var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb2, mod) => function __require() {
  return mod || (0, cb2[__getOwnPropNames(cb2)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all2) => {
  for (var name2 in all2)
    __defProp(target, name2, { get: all2[name2], enumerable: true });
};
var __copyProps = (to, from2, except, desc) => {
  if (from2 && typeof from2 === "object" || typeof from2 === "function") {
    for (let key2 of __getOwnPropNames(from2))
      if (!__hasOwnProp.call(to, key2) && key2 !== except)
        __defProp(to, key2, { get: () => from2[key2], enumerable: !(desc = __getOwnPropDesc(from2, key2)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/tinycolor2/tinycolor.js
var require_tinycolor = __commonJS({
  "node_modules/tinycolor2/tinycolor.js"(exports, module) {
    (function(Math2) {
      var trimLeft = /^\s+/, trimRight = /\s+$/, tinyCounter = 0, mathRound = Math2.round, mathMin = Math2.min, mathMax = Math2.max, mathRandom = Math2.random;
      function tinycolor11(color, opts) {
        color = color ? color : "";
        opts = opts || {};
        if (color instanceof tinycolor11) {
          return color;
        }
        if (!(this instanceof tinycolor11)) {
          return new tinycolor11(color, opts);
        }
        var rgb = inputToRGB(color);
        this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = mathRound(100 * this._a) / 100, this._format = opts.format || rgb.format;
        this._gradientType = opts.gradientType;
        if (this._r < 1) {
          this._r = mathRound(this._r);
        }
        if (this._g < 1) {
          this._g = mathRound(this._g);
        }
        if (this._b < 1) {
          this._b = mathRound(this._b);
        }
        this._ok = rgb.ok;
        this._tc_id = tinyCounter++;
      }
      tinycolor11.prototype = {
        isDark: function() {
          return this.getBrightness() < 128;
        },
        isLight: function() {
          return !this.isDark();
        },
        isValid: function() {
          return this._ok;
        },
        getOriginalInput: function() {
          return this._originalInput;
        },
        getFormat: function() {
          return this._format;
        },
        getAlpha: function() {
          return this._a;
        },
        getBrightness: function() {
          var rgb = this.toRgb();
          return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1e3;
        },
        getLuminance: function() {
          var rgb = this.toRgb();
          var RsRGB, GsRGB, BsRGB, R2, G, B;
          RsRGB = rgb.r / 255;
          GsRGB = rgb.g / 255;
          BsRGB = rgb.b / 255;
          if (RsRGB <= 0.03928) {
            R2 = RsRGB / 12.92;
          } else {
            R2 = Math2.pow((RsRGB + 0.055) / 1.055, 2.4);
          }
          if (GsRGB <= 0.03928) {
            G = GsRGB / 12.92;
          } else {
            G = Math2.pow((GsRGB + 0.055) / 1.055, 2.4);
          }
          if (BsRGB <= 0.03928) {
            B = BsRGB / 12.92;
          } else {
            B = Math2.pow((BsRGB + 0.055) / 1.055, 2.4);
          }
          return 0.2126 * R2 + 0.7152 * G + 0.0722 * B;
        },
        setAlpha: function(value2) {
          this._a = boundAlpha(value2);
          this._roundA = mathRound(100 * this._a) / 100;
          return this;
        },
        toHsv: function() {
          var hsv = rgbToHsv(this._r, this._g, this._b);
          return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
        },
        toHsvString: function() {
          var hsv = rgbToHsv(this._r, this._g, this._b);
          var h3 = mathRound(hsv.h * 360), s3 = mathRound(hsv.s * 100), v3 = mathRound(hsv.v * 100);
          return this._a == 1 ? "hsv(" + h3 + ", " + s3 + "%, " + v3 + "%)" : "hsva(" + h3 + ", " + s3 + "%, " + v3 + "%, " + this._roundA + ")";
        },
        toHsl: function() {
          var hsl = rgbToHsl(this._r, this._g, this._b);
          return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
        },
        toHslString: function() {
          var hsl = rgbToHsl(this._r, this._g, this._b);
          var h3 = mathRound(hsl.h * 360), s3 = mathRound(hsl.s * 100), l3 = mathRound(hsl.l * 100);
          return this._a == 1 ? "hsl(" + h3 + ", " + s3 + "%, " + l3 + "%)" : "hsla(" + h3 + ", " + s3 + "%, " + l3 + "%, " + this._roundA + ")";
        },
        toHex: function(allow3Char) {
          return rgbToHex(this._r, this._g, this._b, allow3Char);
        },
        toHexString: function(allow3Char) {
          return "#" + this.toHex(allow3Char);
        },
        toHex8: function(allow4Char) {
          return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
        },
        toHex8String: function(allow4Char) {
          return "#" + this.toHex8(allow4Char);
        },
        toRgb: function() {
          return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
        },
        toRgbString: function() {
          return this._a == 1 ? "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
        },
        toPercentageRgb: function() {
          return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
        },
        toPercentageRgbString: function() {
          return this._a == 1 ? "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
        },
        toName: function() {
          if (this._a === 0) {
            return "transparent";
          }
          if (this._a < 1) {
            return false;
          }
          return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
        },
        toFilter: function(secondColor) {
          var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a);
          var secondHex8String = hex8String;
          var gradientType = this._gradientType ? "GradientType = 1, " : "";
          if (secondColor) {
            var s3 = tinycolor11(secondColor);
            secondHex8String = "#" + rgbaToArgbHex(s3._r, s3._g, s3._b, s3._a);
          }
          return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")";
        },
        toString: function(format2) {
          var formatSet = !!format2;
          format2 = format2 || this._format;
          var formattedString = false;
          var hasAlpha = this._a < 1 && this._a >= 0;
          var needsAlphaFormat = !formatSet && hasAlpha && (format2 === "hex" || format2 === "hex6" || format2 === "hex3" || format2 === "hex4" || format2 === "hex8" || format2 === "name");
          if (needsAlphaFormat) {
            if (format2 === "name" && this._a === 0) {
              return this.toName();
            }
            return this.toRgbString();
          }
          if (format2 === "rgb") {
            formattedString = this.toRgbString();
          }
          if (format2 === "prgb") {
            formattedString = this.toPercentageRgbString();
          }
          if (format2 === "hex" || format2 === "hex6") {
            formattedString = this.toHexString();
          }
          if (format2 === "hex3") {
            formattedString = this.toHexString(true);
          }
          if (format2 === "hex4") {
            formattedString = this.toHex8String(true);
          }
          if (format2 === "hex8") {
            formattedString = this.toHex8String();
          }
          if (format2 === "name") {
            formattedString = this.toName();
          }
          if (format2 === "hsl") {
            formattedString = this.toHslString();
          }
          if (format2 === "hsv") {
            formattedString = this.toHsvString();
          }
          return formattedString || this.toHexString();
        },
        clone: function() {
          return tinycolor11(this.toString());
        },
        _applyModification: function(fn, args) {
          var color = fn.apply(null, [this].concat([].slice.call(args)));
          this._r = color._r;
          this._g = color._g;
          this._b = color._b;
          this.setAlpha(color._a);
          return this;
        },
        lighten: function() {
          return this._applyModification(lighten, arguments);
        },
        brighten: function() {
          return this._applyModification(brighten, arguments);
        },
        darken: function() {
          return this._applyModification(darken, arguments);
        },
        desaturate: function() {
          return this._applyModification(desaturate, arguments);
        },
        saturate: function() {
          return this._applyModification(saturate, arguments);
        },
        greyscale: function() {
          return this._applyModification(greyscale, arguments);
        },
        spin: function() {
          return this._applyModification(spin, arguments);
        },
        _applyCombination: function(fn, args) {
          return fn.apply(null, [this].concat([].slice.call(args)));
        },
        analogous: function() {
          return this._applyCombination(analogous, arguments);
        },
        complement: function() {
          return this._applyCombination(complement, arguments);
        },
        monochromatic: function() {
          return this._applyCombination(monochromatic, arguments);
        },
        splitcomplement: function() {
          return this._applyCombination(splitcomplement, arguments);
        },
        triad: function() {
          return this._applyCombination(triad, arguments);
        },
        tetrad: function() {
          return this._applyCombination(tetrad, arguments);
        }
      };
      tinycolor11.fromRatio = function(color, opts) {
        if (typeof color == "object") {
          var newColor = {};
          for (var i3 in color) {
            if (color.hasOwnProperty(i3)) {
              if (i3 === "a") {
                newColor[i3] = color[i3];
              } else {
                newColor[i3] = convertToPercentage(color[i3]);
              }
            }
          }
          color = newColor;
        }
        return tinycolor11(color, opts);
      };
      function inputToRGB(color) {
        var rgb = { r: 0, g: 0, b: 0 };
        var a3 = 1;
        var s3 = null;
        var v3 = null;
        var l3 = null;
        var ok = false;
        var format2 = false;
        if (typeof color == "string") {
          color = stringInputToObject(color);
        }
        if (typeof color == "object") {
          if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format2 = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s3 = convertToPercentage(color.s);
            v3 = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s3, v3);
            ok = true;
            format2 = "hsv";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s3 = convertToPercentage(color.s);
            l3 = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s3, l3);
            ok = true;
            format2 = "hsl";
          }
          if (color.hasOwnProperty("a")) {
            a3 = color.a;
          }
        }
        a3 = boundAlpha(a3);
        return {
          ok,
          format: color.format || format2,
          r: mathMin(255, mathMax(rgb.r, 0)),
          g: mathMin(255, mathMax(rgb.g, 0)),
          b: mathMin(255, mathMax(rgb.b, 0)),
          a: a3
        };
      }
      function rgbToRgb(r3, g3, b3) {
        return {
          r: bound01(r3, 255) * 255,
          g: bound01(g3, 255) * 255,
          b: bound01(b3, 255) * 255
        };
      }
      function rgbToHsl(r3, g3, b3) {
        r3 = bound01(r3, 255);
        g3 = bound01(g3, 255);
        b3 = bound01(b3, 255);
        var max3 = mathMax(r3, g3, b3), min3 = mathMin(r3, g3, b3);
        var h3, s3, l3 = (max3 + min3) / 2;
        if (max3 == min3) {
          h3 = s3 = 0;
        } else {
          var d3 = max3 - min3;
          s3 = l3 > 0.5 ? d3 / (2 - max3 - min3) : d3 / (max3 + min3);
          switch (max3) {
            case r3:
              h3 = (g3 - b3) / d3 + (g3 < b3 ? 6 : 0);
              break;
            case g3:
              h3 = (b3 - r3) / d3 + 2;
              break;
            case b3:
              h3 = (r3 - g3) / d3 + 4;
              break;
          }
          h3 /= 6;
        }
        return { h: h3, s: s3, l: l3 };
      }
      function hslToRgb(h3, s3, l3) {
        var r3, g3, b3;
        h3 = bound01(h3, 360);
        s3 = bound01(s3, 100);
        l3 = bound01(l3, 100);
        function hue2rgb(p5, q2, t3) {
          if (t3 < 0) t3 += 1;
          if (t3 > 1) t3 -= 1;
          if (t3 < 1 / 6) return p5 + (q2 - p5) * 6 * t3;
          if (t3 < 1 / 2) return q2;
          if (t3 < 2 / 3) return p5 + (q2 - p5) * (2 / 3 - t3) * 6;
          return p5;
        }
        if (s3 === 0) {
          r3 = g3 = b3 = l3;
        } else {
          var q = l3 < 0.5 ? l3 * (1 + s3) : l3 + s3 - l3 * s3;
          var p4 = 2 * l3 - q;
          r3 = hue2rgb(p4, q, h3 + 1 / 3);
          g3 = hue2rgb(p4, q, h3);
          b3 = hue2rgb(p4, q, h3 - 1 / 3);
        }
        return { r: r3 * 255, g: g3 * 255, b: b3 * 255 };
      }
      function rgbToHsv(r3, g3, b3) {
        r3 = bound01(r3, 255);
        g3 = bound01(g3, 255);
        b3 = bound01(b3, 255);
        var max3 = mathMax(r3, g3, b3), min3 = mathMin(r3, g3, b3);
        var h3, s3, v3 = max3;
        var d3 = max3 - min3;
        s3 = max3 === 0 ? 0 : d3 / max3;
        if (max3 == min3) {
          h3 = 0;
        } else {
          switch (max3) {
            case r3:
              h3 = (g3 - b3) / d3 + (g3 < b3 ? 6 : 0);
              break;
            case g3:
              h3 = (b3 - r3) / d3 + 2;
              break;
            case b3:
              h3 = (r3 - g3) / d3 + 4;
              break;
          }
          h3 /= 6;
        }
        return { h: h3, s: s3, v: v3 };
      }
      function hsvToRgb(h3, s3, v3) {
        h3 = bound01(h3, 360) * 6;
        s3 = bound01(s3, 100);
        v3 = bound01(v3, 100);
        var i3 = Math2.floor(h3), f3 = h3 - i3, p4 = v3 * (1 - s3), q = v3 * (1 - f3 * s3), t3 = v3 * (1 - (1 - f3) * s3), mod = i3 % 6, r3 = [v3, q, p4, p4, t3, v3][mod], g3 = [t3, v3, v3, q, p4, p4][mod], b3 = [p4, p4, t3, v3, v3, q][mod];
        return { r: r3 * 255, g: g3 * 255, b: b3 * 255 };
      }
      function rgbToHex(r3, g3, b3, allow3Char) {
        var hex = [
          pad2(mathRound(r3).toString(16)),
          pad2(mathRound(g3).toString(16)),
          pad2(mathRound(b3).toString(16))
        ];
        if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
          return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
        }
        return hex.join("");
      }
      function rgbaToHex(r3, g3, b3, a3, allow4Char) {
        var hex = [
          pad2(mathRound(r3).toString(16)),
          pad2(mathRound(g3).toString(16)),
          pad2(mathRound(b3).toString(16)),
          pad2(convertDecimalToHex(a3))
        ];
        if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
          return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
        }
        return hex.join("");
      }
      function rgbaToArgbHex(r3, g3, b3, a3) {
        var hex = [
          pad2(convertDecimalToHex(a3)),
          pad2(mathRound(r3).toString(16)),
          pad2(mathRound(g3).toString(16)),
          pad2(mathRound(b3).toString(16))
        ];
        return hex.join("");
      }
      tinycolor11.equals = function(color1, color2) {
        if (!color1 || !color2) {
          return false;
        }
        return tinycolor11(color1).toRgbString() == tinycolor11(color2).toRgbString();
      };
      tinycolor11.random = function() {
        return tinycolor11.fromRatio({
          r: mathRandom(),
          g: mathRandom(),
          b: mathRandom()
        });
      };
      function desaturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor11(color).toHsl();
        hsl.s -= amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor11(hsl);
      }
      function saturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor11(color).toHsl();
        hsl.s += amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor11(hsl);
      }
      function greyscale(color) {
        return tinycolor11(color).desaturate(100);
      }
      function lighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor11(color).toHsl();
        hsl.l += amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor11(hsl);
      }
      function brighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var rgb = tinycolor11(color).toRgb();
        rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * -(amount / 100))));
        rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * -(amount / 100))));
        rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * -(amount / 100))));
        return tinycolor11(rgb);
      }
      function darken(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor11(color).toHsl();
        hsl.l -= amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor11(hsl);
      }
      function spin(color, amount) {
        var hsl = tinycolor11(color).toHsl();
        var hue = (hsl.h + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor11(hsl);
      }
      function complement(color) {
        var hsl = tinycolor11(color).toHsl();
        hsl.h = (hsl.h + 180) % 360;
        return tinycolor11(hsl);
      }
      function triad(color) {
        var hsl = tinycolor11(color).toHsl();
        var h3 = hsl.h;
        return [
          tinycolor11(color),
          tinycolor11({ h: (h3 + 120) % 360, s: hsl.s, l: hsl.l }),
          tinycolor11({ h: (h3 + 240) % 360, s: hsl.s, l: hsl.l })
        ];
      }
      function tetrad(color) {
        var hsl = tinycolor11(color).toHsl();
        var h3 = hsl.h;
        return [
          tinycolor11(color),
          tinycolor11({ h: (h3 + 90) % 360, s: hsl.s, l: hsl.l }),
          tinycolor11({ h: (h3 + 180) % 360, s: hsl.s, l: hsl.l }),
          tinycolor11({ h: (h3 + 270) % 360, s: hsl.s, l: hsl.l })
        ];
      }
      function splitcomplement(color) {
        var hsl = tinycolor11(color).toHsl();
        var h3 = hsl.h;
        return [
          tinycolor11(color),
          tinycolor11({ h: (h3 + 72) % 360, s: hsl.s, l: hsl.l }),
          tinycolor11({ h: (h3 + 216) % 360, s: hsl.s, l: hsl.l })
        ];
      }
      function analogous(color, results2, slices) {
        results2 = results2 || 6;
        slices = slices || 30;
        var hsl = tinycolor11(color).toHsl();
        var part = 360 / slices;
        var ret = [tinycolor11(color)];
        for (hsl.h = (hsl.h - (part * results2 >> 1) + 720) % 360; --results2; ) {
          hsl.h = (hsl.h + part) % 360;
          ret.push(tinycolor11(hsl));
        }
        return ret;
      }
      function monochromatic(color, results2) {
        results2 = results2 || 6;
        var hsv = tinycolor11(color).toHsv();
        var h3 = hsv.h, s3 = hsv.s, v3 = hsv.v;
        var ret = [];
        var modification = 1 / results2;
        while (results2--) {
          ret.push(tinycolor11({ h: h3, s: s3, v: v3 }));
          v3 = (v3 + modification) % 1;
        }
        return ret;
      }
      tinycolor11.mix = function(color1, color2, amount) {
        amount = amount === 0 ? 0 : amount || 50;
        var rgb1 = tinycolor11(color1).toRgb();
        var rgb2 = tinycolor11(color2).toRgb();
        var p4 = amount / 100;
        var rgba = {
          r: (rgb2.r - rgb1.r) * p4 + rgb1.r,
          g: (rgb2.g - rgb1.g) * p4 + rgb1.g,
          b: (rgb2.b - rgb1.b) * p4 + rgb1.b,
          a: (rgb2.a - rgb1.a) * p4 + rgb1.a
        };
        return tinycolor11(rgba);
      };
      tinycolor11.readability = function(color1, color2) {
        var c1 = tinycolor11(color1);
        var c22 = tinycolor11(color2);
        return (Math2.max(c1.getLuminance(), c22.getLuminance()) + 0.05) / (Math2.min(c1.getLuminance(), c22.getLuminance()) + 0.05);
      };
      tinycolor11.isReadable = function(color1, color2, wcag2) {
        var readability = tinycolor11.readability(color1, color2);
        var wcag2Parms, out;
        out = false;
        wcag2Parms = validateWCAG2Parms(wcag2);
        switch (wcag2Parms.level + wcag2Parms.size) {
          case "AAsmall":
          case "AAAlarge":
            out = readability >= 4.5;
            break;
          case "AAlarge":
            out = readability >= 3;
            break;
          case "AAAsmall":
            out = readability >= 7;
            break;
        }
        return out;
      };
      tinycolor11.mostReadable = function(baseColor2, colorList, args) {
        var bestColor = null;
        var bestScore = 0;
        var readability;
        var includeFallbackColors, level, size4;
        args = args || {};
        includeFallbackColors = args.includeFallbackColors;
        level = args.level;
        size4 = args.size;
        for (var i3 = 0; i3 < colorList.length; i3++) {
          readability = tinycolor11.readability(baseColor2, colorList[i3]);
          if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor11(colorList[i3]);
          }
        }
        if (tinycolor11.isReadable(baseColor2, bestColor, { "level": level, "size": size4 }) || !includeFallbackColors) {
          return bestColor;
        } else {
          args.includeFallbackColors = false;
          return tinycolor11.mostReadable(baseColor2, ["#fff", "#000"], args);
        }
      };
      var names = tinycolor11.names = {
        aliceblue: "f0f8ff",
        antiquewhite: "faebd7",
        aqua: "0ff",
        aquamarine: "7fffd4",
        azure: "f0ffff",
        beige: "f5f5dc",
        bisque: "ffe4c4",
        black: "000",
        blanchedalmond: "ffebcd",
        blue: "00f",
        blueviolet: "8a2be2",
        brown: "a52a2a",
        burlywood: "deb887",
        burntsienna: "ea7e5d",
        cadetblue: "5f9ea0",
        chartreuse: "7fff00",
        chocolate: "d2691e",
        coral: "ff7f50",
        cornflowerblue: "6495ed",
        cornsilk: "fff8dc",
        crimson: "dc143c",
        cyan: "0ff",
        darkblue: "00008b",
        darkcyan: "008b8b",
        darkgoldenrod: "b8860b",
        darkgray: "a9a9a9",
        darkgreen: "006400",
        darkgrey: "a9a9a9",
        darkkhaki: "bdb76b",
        darkmagenta: "8b008b",
        darkolivegreen: "556b2f",
        darkorange: "ff8c00",
        darkorchid: "9932cc",
        darkred: "8b0000",
        darksalmon: "e9967a",
        darkseagreen: "8fbc8f",
        darkslateblue: "483d8b",
        darkslategray: "2f4f4f",
        darkslategrey: "2f4f4f",
        darkturquoise: "00ced1",
        darkviolet: "9400d3",
        deeppink: "ff1493",
        deepskyblue: "00bfff",
        dimgray: "696969",
        dimgrey: "696969",
        dodgerblue: "1e90ff",
        firebrick: "b22222",
        floralwhite: "fffaf0",
        forestgreen: "228b22",
        fuchsia: "f0f",
        gainsboro: "dcdcdc",
        ghostwhite: "f8f8ff",
        gold: "ffd700",
        goldenrod: "daa520",
        gray: "808080",
        green: "008000",
        greenyellow: "adff2f",
        grey: "808080",
        honeydew: "f0fff0",
        hotpink: "ff69b4",
        indianred: "cd5c5c",
        indigo: "4b0082",
        ivory: "fffff0",
        khaki: "f0e68c",
        lavender: "e6e6fa",
        lavenderblush: "fff0f5",
        lawngreen: "7cfc00",
        lemonchiffon: "fffacd",
        lightblue: "add8e6",
        lightcoral: "f08080",
        lightcyan: "e0ffff",
        lightgoldenrodyellow: "fafad2",
        lightgray: "d3d3d3",
        lightgreen: "90ee90",
        lightgrey: "d3d3d3",
        lightpink: "ffb6c1",
        lightsalmon: "ffa07a",
        lightseagreen: "20b2aa",
        lightskyblue: "87cefa",
        lightslategray: "789",
        lightslategrey: "789",
        lightsteelblue: "b0c4de",
        lightyellow: "ffffe0",
        lime: "0f0",
        limegreen: "32cd32",
        linen: "faf0e6",
        magenta: "f0f",
        maroon: "800000",
        mediumaquamarine: "66cdaa",
        mediumblue: "0000cd",
        mediumorchid: "ba55d3",
        mediumpurple: "9370db",
        mediumseagreen: "3cb371",
        mediumslateblue: "7b68ee",
        mediumspringgreen: "00fa9a",
        mediumturquoise: "48d1cc",
        mediumvioletred: "c71585",
        midnightblue: "191970",
        mintcream: "f5fffa",
        mistyrose: "ffe4e1",
        moccasin: "ffe4b5",
        navajowhite: "ffdead",
        navy: "000080",
        oldlace: "fdf5e6",
        olive: "808000",
        olivedrab: "6b8e23",
        orange: "ffa500",
        orangered: "ff4500",
        orchid: "da70d6",
        palegoldenrod: "eee8aa",
        palegreen: "98fb98",
        paleturquoise: "afeeee",
        palevioletred: "db7093",
        papayawhip: "ffefd5",
        peachpuff: "ffdab9",
        peru: "cd853f",
        pink: "ffc0cb",
        plum: "dda0dd",
        powderblue: "b0e0e6",
        purple: "800080",
        rebeccapurple: "663399",
        red: "f00",
        rosybrown: "bc8f8f",
        royalblue: "4169e1",
        saddlebrown: "8b4513",
        salmon: "fa8072",
        sandybrown: "f4a460",
        seagreen: "2e8b57",
        seashell: "fff5ee",
        sienna: "a0522d",
        silver: "c0c0c0",
        skyblue: "87ceeb",
        slateblue: "6a5acd",
        slategray: "708090",
        slategrey: "708090",
        snow: "fffafa",
        springgreen: "00ff7f",
        steelblue: "4682b4",
        tan: "d2b48c",
        teal: "008080",
        thistle: "d8bfd8",
        tomato: "ff6347",
        turquoise: "40e0d0",
        violet: "ee82ee",
        wheat: "f5deb3",
        white: "fff",
        whitesmoke: "f5f5f5",
        yellow: "ff0",
        yellowgreen: "9acd32"
      };
      var hexNames = tinycolor11.hexNames = flip(names);
      function flip(o3) {
        var flipped = {};
        for (var i3 in o3) {
          if (o3.hasOwnProperty(i3)) {
            flipped[o3[i3]] = i3;
          }
        }
        return flipped;
      }
      function boundAlpha(a3) {
        a3 = parseFloat(a3);
        if (isNaN(a3) || a3 < 0 || a3 > 1) {
          a3 = 1;
        }
        return a3;
      }
      function bound01(n4, max3) {
        if (isOnePointZero(n4)) {
          n4 = "100%";
        }
        var processPercent = isPercentage(n4);
        n4 = mathMin(max3, mathMax(0, parseFloat(n4)));
        if (processPercent) {
          n4 = parseInt(n4 * max3, 10) / 100;
        }
        if (Math2.abs(n4 - max3) < 1e-6) {
          return 1;
        }
        return n4 % max3 / parseFloat(max3);
      }
      function clamp01(val) {
        return mathMin(1, mathMax(0, val));
      }
      function parseIntFromHex(val) {
        return parseInt(val, 16);
      }
      function isOnePointZero(n4) {
        return typeof n4 == "string" && n4.indexOf(".") != -1 && parseFloat(n4) === 1;
      }
      function isPercentage(n4) {
        return typeof n4 === "string" && n4.indexOf("%") != -1;
      }
      function pad2(c3) {
        return c3.length == 1 ? "0" + c3 : "" + c3;
      }
      function convertToPercentage(n4) {
        if (n4 <= 1) {
          n4 = n4 * 100 + "%";
        }
        return n4;
      }
      function convertDecimalToHex(d3) {
        return Math2.round(parseFloat(d3) * 255).toString(16);
      }
      function convertHexToDecimal(h3) {
        return parseIntFromHex(h3) / 255;
      }
      var matchers = function() {
        var CSS_INTEGER = "[-\\+]?\\d+%?";
        var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
        var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
        var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        return {
          CSS_UNIT: new RegExp(CSS_UNIT),
          rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
          rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
          hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
          hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
          hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
          hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
          hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
          hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
          hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
          hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
        };
      }();
      function isValidCSSUnit(color) {
        return !!matchers.CSS_UNIT.exec(color);
      }
      function stringInputToObject(color) {
        color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
        var named = false;
        if (names[color]) {
          color = names[color];
          named = true;
        } else if (color == "transparent") {
          return { r: 0, g: 0, b: 0, a: 0, format: "name" };
        }
        var match2;
        if (match2 = matchers.rgb.exec(color)) {
          return { r: match2[1], g: match2[2], b: match2[3] };
        }
        if (match2 = matchers.rgba.exec(color)) {
          return { r: match2[1], g: match2[2], b: match2[3], a: match2[4] };
        }
        if (match2 = matchers.hsl.exec(color)) {
          return { h: match2[1], s: match2[2], l: match2[3] };
        }
        if (match2 = matchers.hsla.exec(color)) {
          return { h: match2[1], s: match2[2], l: match2[3], a: match2[4] };
        }
        if (match2 = matchers.hsv.exec(color)) {
          return { h: match2[1], s: match2[2], v: match2[3] };
        }
        if (match2 = matchers.hsva.exec(color)) {
          return { h: match2[1], s: match2[2], v: match2[3], a: match2[4] };
        }
        if (match2 = matchers.hex8.exec(color)) {
          return {
            r: parseIntFromHex(match2[1]),
            g: parseIntFromHex(match2[2]),
            b: parseIntFromHex(match2[3]),
            a: convertHexToDecimal(match2[4]),
            format: named ? "name" : "hex8"
          };
        }
        if (match2 = matchers.hex6.exec(color)) {
          return {
            r: parseIntFromHex(match2[1]),
            g: parseIntFromHex(match2[2]),
            b: parseIntFromHex(match2[3]),
            format: named ? "name" : "hex"
          };
        }
        if (match2 = matchers.hex4.exec(color)) {
          return {
            r: parseIntFromHex(match2[1] + "" + match2[1]),
            g: parseIntFromHex(match2[2] + "" + match2[2]),
            b: parseIntFromHex(match2[3] + "" + match2[3]),
            a: convertHexToDecimal(match2[4] + "" + match2[4]),
            format: named ? "name" : "hex8"
          };
        }
        if (match2 = matchers.hex3.exec(color)) {
          return {
            r: parseIntFromHex(match2[1] + "" + match2[1]),
            g: parseIntFromHex(match2[2] + "" + match2[2]),
            b: parseIntFromHex(match2[3] + "" + match2[3]),
            format: named ? "name" : "hex"
          };
        }
        return false;
      }
      function validateWCAG2Parms(parms) {
        var level, size4;
        parms = parms || { "level": "AA", "size": "small" };
        level = (parms.level || "AA").toUpperCase();
        size4 = (parms.size || "small").toLowerCase();
        if (level !== "AA" && level !== "AAA") {
          level = "AA";
        }
        if (size4 !== "small" && size4 !== "large") {
          size4 = "small";
        }
        return { "level": level, "size": size4 };
      }
      if (typeof module !== "undefined" && module.exports) {
        module.exports = tinycolor11;
      } else if (typeof define === "function" && define.amd) {
        define(function() {
          return tinycolor11;
        });
      } else {
        window.tinycolor = tinycolor11;
      }
    })(Math);
  }
});

// public/app/config/icons.js
var icons_exports = {};
__export(icons_exports, {
  availableIconAliases: () => availableIconAliases,
  availableIcons: () => availableIcons,
  iconClass: () => iconClass
});
function iconClass(input) {
  if (!input) {
    return "";
  }
  if (availableIconAliases[input]) {
    input = availableIconAliases[input];
  }
  if (input.substr(0, 3) === "bi-") {
    return input;
  }
  if (input.substr(0, 4) === "kfi-") {
    return "kfi " + input;
  }
  if (input.substr(0, 3) === "fa-") {
    return "fa " + input;
  }
  return "fa fa-" + input;
}
var availableIcons, availableIconAliases;
var init_icons = __esm({
  "public/app/config/icons.js"() {
    availableIcons = [
      "comments",
      "road",
      "anchor",
      "rocket",
      "line-chart",
      "bolt",
      "bomb",
      "flask",
      "globe",
      "leaf",
      "lock",
      "magic",
      "magnet",
      "paw",
      "retweet",
      "unlock",
      "alarm",
      "asterisk",
      "at",
      "award",
      "bag",
      "ban",
      "bank",
      "bar-chart",
      "gant",
      "basket",
      "battery",
      "bell",
      "bicycle",
      "binoculars",
      "birthday-cake",
      "text",
      "book",
      "bookmarks",
      "box",
      "braces",
      "bricks",
      "suitcase",
      "broadcast",
      "brush",
      "bucket",
      "bug",
      "buildings",
      "bullseye",
      "calculator",
      "calendar",
      "calendar-check",
      "camera",
      "camera-video",
      "shopping-cart",
      "cash",
      "check",
      "checkbox",
      "clipboard",
      "clock",
      "cloud",
      "rain",
      "code",
      "coin",
      "compass",
      "cone",
      "controller",
      "cpu",
      "credit-card",
      "cup",
      "bitcoin",
      "dollar",
      "euro",
      "diargram",
      "dice",
      "display",
      "door",
      "droplet",
      "earbuds",
      "whiteboard",
      "envelope",
      "danger",
      "exclamation-triangle",
      "eye",
      "files",
      "film",
      "flag",
      "flower",
      "folder",
      "gear",
      "gem",
      "gift",
      "grid",
      "hammer",
      "hash",
      "hdd",
      "headset",
      "heart",
      "hourglass",
      "house",
      "image",
      "inbox",
      "info-circle",
      "joystick",
      "key",
      "life-preserver",
      "lightbulb",
      "link",
      "map",
      "megaphone",
      "mic",
      "moon",
      "music-note",
      "newspaper",
      "question-circle",
      "palette",
      "paperclip",
      "pause",
      "pencil",
      "people",
      "person",
      "pie-chart",
      "piggy-bank",
      "pin",
      "play",
      "plug",
      "power",
      "printer",
      "puzzle",
      "receipt",
      "recycle",
      "rss",
      "scissors",
      "server",
      "shield",
      "shop",
      "signpost",
      "snow",
      "speedometer",
      "stack",
      "star",
      "stars",
      "stoplights",
      "stopwatch",
      "sun",
      "sunglasses",
      "tags",
      "telephone",
      "terminal",
      "thermometer",
      "tools",
      "trash",
      "tree",
      "trophy",
      "truck",
      "umbrella",
      "sound",
      "watch",
      "wifi",
      "wind",
      "wrench",
      "kanban",
      "timeline",
      "form",
      "play-circle"
    ];
    availableIconAliases = {
      // Font Awesome 4
      "comments": "fa-comments",
      "road": "fa-road",
      "anchor": "fa-anchor",
      "ban": "fa-ban",
      "birthday-cake": "fa-birthday-cake",
      "bolt": "fa-bolt",
      "bomb": "fa-bomb",
      "flask": "fa-flask",
      "globe": "fa-globe",
      "leaf": "fa-leaf",
      "lock": "fa-lock",
      "magic": "fa-magic",
      "magnet": "fa-magnet",
      "paw": "fa-paw",
      "rocket": "fa-rocket",
      "retweet": "fa-retweet",
      "unlock": "fa-unlock",
      // Bootstrap Icons
      "alarm": "bi-alarm-fill",
      "asterisk": "bi-asterisk",
      "at": "bi-at",
      "award": "bi-award-fill",
      "bag": "bi-bag",
      "bank": "bi-bank2",
      "bar-chart": "bi-bar-chart-fill",
      "gant": "bi-bar-chart-steps",
      "basket": "bi-basket-fill",
      "battery": "bi-battery-full",
      "bell": "bi-bell-fill",
      "bicycle": "bi-bicycle",
      "binoculars": "bi-binoculars-fill",
      "text": "bi-blockquote-left",
      "book": "bi-book",
      "bookmarks": "bi-bookmarks",
      "box": "bi-box",
      "braces": "bi-braces",
      "bricks": "bi-bricks",
      "suitcase": "bi-briefcase-fill",
      "broadcast": "bi-broadcast",
      "brush": "bi-brush-fill",
      "bucket": "bi-bucket-fill",
      "bug": "bi-bug-fill",
      "buildings": "bi-building",
      "bullseye": "bi-bullseye",
      "calculator": "bi-calculator",
      "calendar": "bi-calendar",
      "calendar-check": "bi-calendar2-check",
      "camera": "bi-camera-fill",
      "camera-video": "bi-camera-reels-fill",
      "shopping-cart": "bi-cart",
      "cash": "bi-cash-coin",
      "check": "bi-check2",
      "checkbox": "bi-check2-square",
      "clipboard": "bi-clipboard",
      "clock": "bi-clock",
      "cloud": "bi-cloud-fill",
      "rain": "bi-cloud-rain-heavy-fill",
      "code": "bi-code-slash",
      "coin": "bi-coin",
      "compass": "bi-compass",
      "cone": "bi-cone-striped",
      "controller": "bi-controller",
      "cpu": "bi-cpu-fill",
      "credit-card": "bi-credit-card",
      "cup": "bi-cup-straw",
      "bitcoin": "bi-currency-bitcoin",
      "dollar": "bi-currency-dollar",
      "euro": "bi-currency-euro",
      "diargram": "bi-diagram-3-fill",
      "dice": "bi-dice-6",
      "display": "bi-display",
      "door": "bi-door-closed",
      "droplet": "bi-droplet-fill",
      "earbuds": "bi-earbuds",
      "whiteboard": "bi-easel",
      "envelope": "bi-envelope",
      "danger": "bi-exclamation-diamond-fill",
      "exclamation-triangle": "bi-exclamation-triangle-fill",
      "eye": "bi-eye",
      "files": "bi-files",
      "film": "bi-film",
      "flag": "bi-flag",
      "flower": "bi-flower1",
      "folder": "bi-folder",
      "gear": "bi-gear-fill",
      "gem": "bi-gem",
      "gift": "bi-gift",
      "grid": "bi-grid-3x3-gap-fill",
      "line-chart": "bi-graph-up",
      "hammer": "bi-hammer",
      "hash": "bi-hash",
      "hdd": "bi-hdd",
      "headset": "bi-headset",
      "heart": "bi-heart-fill",
      "hourglass": "bi-hourglass-split",
      "house": "bi-house-fill",
      "image": "bi-image",
      "inbox": "bi-inbox-fill",
      "info-circle": "bi-info-circle-fill",
      "joystick": "bi-joystick",
      "key": "bi-key",
      "life-preserver": "bi-life-preserver",
      "lightbulb": "bi-lightbulb",
      "link": "bi-link",
      "map": "bi-map-fill",
      "megaphone": "bi-megaphone",
      "mic": "bi-mic",
      "moon": "bi-moon",
      "music-note": "bi-music-note-beamed",
      "newspaper": "bi-newspaper",
      "question-circle": "bi-question-circle-fill",
      "palette": "bi-palette",
      "paperclip": "bi-paperclip",
      "pause": "bi-pause-fill",
      "pencil": "bi-pencil-fill",
      "people": "bi-people-fill",
      "person": "bi-person-fill",
      "pie-chart": "bi-pie-chart-fill",
      "piggy-bank": "bi-piggy-bank",
      "pin": "bi-pin-angle-fill",
      "play": "bi-play-fill",
      "plug": "bi-plug-fill",
      "power": "bi-power",
      "printer": "bi-printer",
      "puzzle": "bi-puzzle-fill",
      "receipt": "bi-receipt",
      "recycle": "bi-recycle",
      "rss": "bi-rss-fill",
      "scissors": "bi-scissors",
      "server": "bi-server",
      "shield": "bi-shield-shaded",
      "shop": "bi-shop",
      "signpost": "bi-signpost-2-fill",
      "snow": "bi-snow",
      "speedometer": "bi-speedometer",
      "stack": "bi-stack",
      "star": "bi-star-fill",
      "stars": "bi-stars",
      "stoplights": "bi-stoplights-fill",
      "stopwatch": "bi-stopwatch",
      "sun": "bi-sun-fill",
      "sunglasses": "bi-sunglasses",
      "tags": "bi-tags",
      "telephone": "bi-telephone-fill",
      "terminal": "bi-terminal",
      "thermometer": "bi-thermometer-half",
      "tools": "bi-tools",
      "trash": "fa-trash",
      "tree": "bi-tree-fill",
      "trophy": "bi-trophy-fill",
      "truck": "bi-truck",
      "umbrella": "bi-umbrella-fill",
      "sound": "bi-volume-up-fill",
      "watch": "bi-watch",
      "wifi": "bi-wifi",
      "wind": "bi-wind",
      "wrench": "bi-wrench",
      // aliases
      "life-ring": "bi-life-preserver",
      "calendar-check-o": "bi-calendar2-check",
      "dashboard": "bi-speedometer",
      "check-square-o": "bi-check2-square",
      "times": "fa-times",
      // view modes
      "kanban": "kfi-kanban",
      "timeline": "kfi-timeline",
      "form": "kfi-form",
      // automations
      "play-circle": "bi-play-circle"
    };
  }
});

// node_modules/core-js/internals/global.js
var require_global = __commonJS({
  "node_modules/core-js/internals/global.js"(exports, module) {
    var check = function(it2) {
      return it2 && it2.Math == Math && it2;
    };
    module.exports = // eslint-disable-next-line es-x/no-global-this -- safe
    check(typeof globalThis == "object" && globalThis) || check(typeof window == "object" && window) || // eslint-disable-next-line no-restricted-globals -- safe
    check(typeof self == "object" && self) || check(typeof global == "object" && global) || // eslint-disable-next-line no-new-func -- fallback
    /* @__PURE__ */ function() {
      return this;
    }() || Function("return this")();
  }
});

// node_modules/core-js/internals/is-pure.js
var require_is_pure = __commonJS({
  "node_modules/core-js/internals/is-pure.js"(exports, module) {
    module.exports = false;
  }
});

// node_modules/core-js/internals/define-global-property.js
var require_define_global_property = __commonJS({
  "node_modules/core-js/internals/define-global-property.js"(exports, module) {
    var global5 = require_global();
    var defineProperty3 = Object.defineProperty;
    module.exports = function(key2, value2) {
      try {
        defineProperty3(global5, key2, { value: value2, configurable: true, writable: true });
      } catch (error2) {
        global5[key2] = value2;
      }
      return value2;
    };
  }
});

// node_modules/core-js/internals/shared-store.js
var require_shared_store = __commonJS({
  "node_modules/core-js/internals/shared-store.js"(exports, module) {
    var global5 = require_global();
    var defineGlobalProperty = require_define_global_property();
    var SHARED = "__core-js_shared__";
    var store2 = global5[SHARED] || defineGlobalProperty(SHARED, {});
    module.exports = store2;
  }
});

// node_modules/core-js/internals/shared.js
var require_shared = __commonJS({
  "node_modules/core-js/internals/shared.js"(exports, module) {
    var IS_PURE = require_is_pure();
    var store2 = require_shared_store();
    (module.exports = function(key2, value2) {
      return store2[key2] || (store2[key2] = value2 !== void 0 ? value2 : {});
    })("versions", []).push({
      version: "3.25.1",
      mode: IS_PURE ? "pure" : "global",
      copyright: "\xA9 2014-2022 Denis Pushkarev (zloirock.ru)",
      license: "https://github.com/zloirock/core-js/blob/v3.25.1/LICENSE",
      source: "https://github.com/zloirock/core-js"
    });
  }
});

// node_modules/core-js/internals/fails.js
var require_fails = __commonJS({
  "node_modules/core-js/internals/fails.js"(exports, module) {
    module.exports = function(exec) {
      try {
        return !!exec();
      } catch (error2) {
        return true;
      }
    };
  }
});

// node_modules/core-js/internals/function-bind-native.js
var require_function_bind_native = __commonJS({
  "node_modules/core-js/internals/function-bind-native.js"(exports, module) {
    var fails2 = require_fails();
    module.exports = !fails2(function() {
      var test2 = function() {
      }.bind();
      return typeof test2 != "function" || test2.hasOwnProperty("prototype");
    });
  }
});

// node_modules/core-js/internals/function-uncurry-this.js
var require_function_uncurry_this = __commonJS({
  "node_modules/core-js/internals/function-uncurry-this.js"(exports, module) {
    var NATIVE_BIND = require_function_bind_native();
    var FunctionPrototype2 = Function.prototype;
    var bind2 = FunctionPrototype2.bind;
    var call3 = FunctionPrototype2.call;
    var uncurryThis3 = NATIVE_BIND && bind2.bind(call3, call3);
    module.exports = NATIVE_BIND ? function(fn) {
      return fn && uncurryThis3(fn);
    } : function(fn) {
      return fn && function() {
        return call3.apply(fn, arguments);
      };
    };
  }
});

// node_modules/core-js/internals/is-null-or-undefined.js
var require_is_null_or_undefined = __commonJS({
  "node_modules/core-js/internals/is-null-or-undefined.js"(exports, module) {
    module.exports = function(it2) {
      return it2 === null || it2 === void 0;
    };
  }
});

// node_modules/core-js/internals/require-object-coercible.js
var require_require_object_coercible = __commonJS({
  "node_modules/core-js/internals/require-object-coercible.js"(exports, module) {
    var isNullOrUndefined3 = require_is_null_or_undefined();
    var $TypeError = TypeError;
    module.exports = function(it2) {
      if (isNullOrUndefined3(it2)) throw $TypeError("Can't call method on " + it2);
      return it2;
    };
  }
});

// node_modules/core-js/internals/to-object.js
var require_to_object = __commonJS({
  "node_modules/core-js/internals/to-object.js"(exports, module) {
    var requireObjectCoercible3 = require_require_object_coercible();
    var $Object = Object;
    module.exports = function(argument) {
      return $Object(requireObjectCoercible3(argument));
    };
  }
});

// node_modules/core-js/internals/has-own-property.js
var require_has_own_property = __commonJS({
  "node_modules/core-js/internals/has-own-property.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var toObject = require_to_object();
    var hasOwnProperty5 = uncurryThis3({}.hasOwnProperty);
    module.exports = Object.hasOwn || function hasOwn(it2, key2) {
      return hasOwnProperty5(toObject(it2), key2);
    };
  }
});

// node_modules/core-js/internals/uid.js
var require_uid = __commonJS({
  "node_modules/core-js/internals/uid.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var id = 0;
    var postfix = Math.random();
    var toString9 = uncurryThis3(1 .toString);
    module.exports = function(key2) {
      return "Symbol(" + (key2 === void 0 ? "" : key2) + ")_" + toString9(++id + postfix, 36);
    };
  }
});

// node_modules/core-js/internals/is-callable.js
var require_is_callable = __commonJS({
  "node_modules/core-js/internals/is-callable.js"(exports, module) {
    module.exports = function(argument) {
      return typeof argument == "function";
    };
  }
});

// node_modules/core-js/internals/get-built-in.js
var require_get_built_in = __commonJS({
  "node_modules/core-js/internals/get-built-in.js"(exports, module) {
    var global5 = require_global();
    var isCallable2 = require_is_callable();
    var aFunction = function(argument) {
      return isCallable2(argument) ? argument : void 0;
    };
    module.exports = function(namespace, method) {
      return arguments.length < 2 ? aFunction(global5[namespace]) : global5[namespace] && global5[namespace][method];
    };
  }
});

// node_modules/core-js/internals/engine-user-agent.js
var require_engine_user_agent = __commonJS({
  "node_modules/core-js/internals/engine-user-agent.js"(exports, module) {
    var getBuiltIn = require_get_built_in();
    module.exports = getBuiltIn("navigator", "userAgent") || "";
  }
});

// node_modules/core-js/internals/engine-v8-version.js
var require_engine_v8_version = __commonJS({
  "node_modules/core-js/internals/engine-v8-version.js"(exports, module) {
    var global5 = require_global();
    var userAgent = require_engine_user_agent();
    var process3 = global5.process;
    var Deno = global5.Deno;
    var versions = process3 && process3.versions || Deno && Deno.version;
    var v8 = versions && versions.v8;
    var match2;
    var version;
    if (v8) {
      match2 = v8.split(".");
      version = match2[0] > 0 && match2[0] < 4 ? 1 : +(match2[0] + match2[1]);
    }
    if (!version && userAgent) {
      match2 = userAgent.match(/Edge\/(\d+)/);
      if (!match2 || match2[1] >= 74) {
        match2 = userAgent.match(/Chrome\/(\d+)/);
        if (match2) version = +match2[1];
      }
    }
    module.exports = version;
  }
});

// node_modules/core-js/internals/symbol-constructor-detection.js
var require_symbol_constructor_detection = __commonJS({
  "node_modules/core-js/internals/symbol-constructor-detection.js"(exports, module) {
    var V8_VERSION = require_engine_v8_version();
    var fails2 = require_fails();
    module.exports = !!Object.getOwnPropertySymbols && !fails2(function() {
      var symbol = Symbol();
      return !String(symbol) || !(Object(symbol) instanceof Symbol) || // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
      !Symbol.sham && V8_VERSION && V8_VERSION < 41;
    });
  }
});

// node_modules/core-js/internals/use-symbol-as-uid.js
var require_use_symbol_as_uid = __commonJS({
  "node_modules/core-js/internals/use-symbol-as-uid.js"(exports, module) {
    var NATIVE_SYMBOL = require_symbol_constructor_detection();
    module.exports = NATIVE_SYMBOL && !Symbol.sham && typeof Symbol.iterator == "symbol";
  }
});

// node_modules/core-js/internals/well-known-symbol.js
var require_well_known_symbol = __commonJS({
  "node_modules/core-js/internals/well-known-symbol.js"(exports, module) {
    var global5 = require_global();
    var shared = require_shared();
    var hasOwn = require_has_own_property();
    var uid = require_uid();
    var NATIVE_SYMBOL = require_symbol_constructor_detection();
    var USE_SYMBOL_AS_UID = require_use_symbol_as_uid();
    var WellKnownSymbolsStore = shared("wks");
    var Symbol2 = global5.Symbol;
    var symbolFor = Symbol2 && Symbol2["for"];
    var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol2 : Symbol2 && Symbol2.withoutSetter || uid;
    module.exports = function(name2) {
      if (!hasOwn(WellKnownSymbolsStore, name2) || !(NATIVE_SYMBOL || typeof WellKnownSymbolsStore[name2] == "string")) {
        var description = "Symbol." + name2;
        if (NATIVE_SYMBOL && hasOwn(Symbol2, name2)) {
          WellKnownSymbolsStore[name2] = Symbol2[name2];
        } else if (USE_SYMBOL_AS_UID && symbolFor) {
          WellKnownSymbolsStore[name2] = symbolFor(description);
        } else {
          WellKnownSymbolsStore[name2] = createWellKnownSymbol(description);
        }
      }
      return WellKnownSymbolsStore[name2];
    };
  }
});

// node_modules/core-js/internals/to-string-tag-support.js
var require_to_string_tag_support = __commonJS({
  "node_modules/core-js/internals/to-string-tag-support.js"(exports, module) {
    var wellKnownSymbol3 = require_well_known_symbol();
    var TO_STRING_TAG2 = wellKnownSymbol3("toStringTag");
    var test2 = {};
    test2[TO_STRING_TAG2] = "z";
    module.exports = String(test2) === "[object z]";
  }
});

// node_modules/core-js/internals/descriptors.js
var require_descriptors = __commonJS({
  "node_modules/core-js/internals/descriptors.js"(exports, module) {
    var fails2 = require_fails();
    module.exports = !fails2(function() {
      return Object.defineProperty({}, 1, { get: function() {
        return 7;
      } })[1] != 7;
    });
  }
});

// node_modules/core-js/internals/is-object.js
var require_is_object = __commonJS({
  "node_modules/core-js/internals/is-object.js"(exports, module) {
    var isCallable2 = require_is_callable();
    var documentAll = typeof document == "object" && document.all;
    var SPECIAL_DOCUMENT_ALL = typeof documentAll == "undefined" && documentAll !== void 0;
    module.exports = SPECIAL_DOCUMENT_ALL ? function(it2) {
      return typeof it2 == "object" ? it2 !== null : isCallable2(it2) || it2 === documentAll;
    } : function(it2) {
      return typeof it2 == "object" ? it2 !== null : isCallable2(it2);
    };
  }
});

// node_modules/core-js/internals/document-create-element.js
var require_document_create_element = __commonJS({
  "node_modules/core-js/internals/document-create-element.js"(exports, module) {
    var global5 = require_global();
    var isObject7 = require_is_object();
    var document2 = global5.document;
    var EXISTS = isObject7(document2) && isObject7(document2.createElement);
    module.exports = function(it2) {
      return EXISTS ? document2.createElement(it2) : {};
    };
  }
});

// node_modules/core-js/internals/ie8-dom-define.js
var require_ie8_dom_define = __commonJS({
  "node_modules/core-js/internals/ie8-dom-define.js"(exports, module) {
    var DESCRIPTORS2 = require_descriptors();
    var fails2 = require_fails();
    var createElement2 = require_document_create_element();
    module.exports = !DESCRIPTORS2 && !fails2(function() {
      return Object.defineProperty(createElement2("div"), "a", {
        get: function() {
          return 7;
        }
      }).a != 7;
    });
  }
});

// node_modules/core-js/internals/v8-prototype-define-bug.js
var require_v8_prototype_define_bug = __commonJS({
  "node_modules/core-js/internals/v8-prototype-define-bug.js"(exports, module) {
    var DESCRIPTORS2 = require_descriptors();
    var fails2 = require_fails();
    module.exports = DESCRIPTORS2 && fails2(function() {
      return Object.defineProperty(function() {
      }, "prototype", {
        value: 42,
        writable: false
      }).prototype != 42;
    });
  }
});

// node_modules/core-js/internals/an-object.js
var require_an_object = __commonJS({
  "node_modules/core-js/internals/an-object.js"(exports, module) {
    var isObject7 = require_is_object();
    var $String = String;
    var $TypeError = TypeError;
    module.exports = function(argument) {
      if (isObject7(argument)) return argument;
      throw $TypeError($String(argument) + " is not an object");
    };
  }
});

// node_modules/core-js/internals/function-call.js
var require_function_call = __commonJS({
  "node_modules/core-js/internals/function-call.js"(exports, module) {
    var NATIVE_BIND = require_function_bind_native();
    var call3 = Function.prototype.call;
    module.exports = NATIVE_BIND ? call3.bind(call3) : function() {
      return call3.apply(call3, arguments);
    };
  }
});

// node_modules/core-js/internals/object-is-prototype-of.js
var require_object_is_prototype_of = __commonJS({
  "node_modules/core-js/internals/object-is-prototype-of.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    module.exports = uncurryThis3({}.isPrototypeOf);
  }
});

// node_modules/core-js/internals/is-symbol.js
var require_is_symbol = __commonJS({
  "node_modules/core-js/internals/is-symbol.js"(exports, module) {
    var getBuiltIn = require_get_built_in();
    var isCallable2 = require_is_callable();
    var isPrototypeOf = require_object_is_prototype_of();
    var USE_SYMBOL_AS_UID = require_use_symbol_as_uid();
    var $Object = Object;
    module.exports = USE_SYMBOL_AS_UID ? function(it2) {
      return typeof it2 == "symbol";
    } : function(it2) {
      var $Symbol = getBuiltIn("Symbol");
      return isCallable2($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it2));
    };
  }
});

// node_modules/core-js/internals/try-to-string.js
var require_try_to_string = __commonJS({
  "node_modules/core-js/internals/try-to-string.js"(exports, module) {
    var $String = String;
    module.exports = function(argument) {
      try {
        return $String(argument);
      } catch (error2) {
        return "Object";
      }
    };
  }
});

// node_modules/core-js/internals/a-callable.js
var require_a_callable = __commonJS({
  "node_modules/core-js/internals/a-callable.js"(exports, module) {
    var isCallable2 = require_is_callable();
    var tryToString = require_try_to_string();
    var $TypeError = TypeError;
    module.exports = function(argument) {
      if (isCallable2(argument)) return argument;
      throw $TypeError(tryToString(argument) + " is not a function");
    };
  }
});

// node_modules/core-js/internals/get-method.js
var require_get_method = __commonJS({
  "node_modules/core-js/internals/get-method.js"(exports, module) {
    var aCallable = require_a_callable();
    var isNullOrUndefined3 = require_is_null_or_undefined();
    module.exports = function(V2, P3) {
      var func = V2[P3];
      return isNullOrUndefined3(func) ? void 0 : aCallable(func);
    };
  }
});

// node_modules/core-js/internals/ordinary-to-primitive.js
var require_ordinary_to_primitive = __commonJS({
  "node_modules/core-js/internals/ordinary-to-primitive.js"(exports, module) {
    var call3 = require_function_call();
    var isCallable2 = require_is_callable();
    var isObject7 = require_is_object();
    var $TypeError = TypeError;
    module.exports = function(input, pref) {
      var fn, val;
      if (pref === "string" && isCallable2(fn = input.toString) && !isObject7(val = call3(fn, input))) return val;
      if (isCallable2(fn = input.valueOf) && !isObject7(val = call3(fn, input))) return val;
      if (pref !== "string" && isCallable2(fn = input.toString) && !isObject7(val = call3(fn, input))) return val;
      throw $TypeError("Can't convert object to primitive value");
    };
  }
});

// node_modules/core-js/internals/to-primitive.js
var require_to_primitive = __commonJS({
  "node_modules/core-js/internals/to-primitive.js"(exports, module) {
    var call3 = require_function_call();
    var isObject7 = require_is_object();
    var isSymbol = require_is_symbol();
    var getMethod3 = require_get_method();
    var ordinaryToPrimitive = require_ordinary_to_primitive();
    var wellKnownSymbol3 = require_well_known_symbol();
    var $TypeError = TypeError;
    var TO_PRIMITIVE = wellKnownSymbol3("toPrimitive");
    module.exports = function(input, pref) {
      if (!isObject7(input) || isSymbol(input)) return input;
      var exoticToPrim = getMethod3(input, TO_PRIMITIVE);
      var result2;
      if (exoticToPrim) {
        if (pref === void 0) pref = "default";
        result2 = call3(exoticToPrim, input, pref);
        if (!isObject7(result2) || isSymbol(result2)) return result2;
        throw $TypeError("Can't convert object to primitive value");
      }
      if (pref === void 0) pref = "number";
      return ordinaryToPrimitive(input, pref);
    };
  }
});

// node_modules/core-js/internals/to-property-key.js
var require_to_property_key = __commonJS({
  "node_modules/core-js/internals/to-property-key.js"(exports, module) {
    var toPrimitive = require_to_primitive();
    var isSymbol = require_is_symbol();
    module.exports = function(argument) {
      var key2 = toPrimitive(argument, "string");
      return isSymbol(key2) ? key2 : key2 + "";
    };
  }
});

// node_modules/core-js/internals/object-define-property.js
var require_object_define_property = __commonJS({
  "node_modules/core-js/internals/object-define-property.js"(exports) {
    var DESCRIPTORS2 = require_descriptors();
    var IE8_DOM_DEFINE = require_ie8_dom_define();
    var V8_PROTOTYPE_DEFINE_BUG = require_v8_prototype_define_bug();
    var anObject3 = require_an_object();
    var toPropertyKey = require_to_property_key();
    var $TypeError = TypeError;
    var $defineProperty = Object.defineProperty;
    var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
    var ENUMERABLE = "enumerable";
    var CONFIGURABLE = "configurable";
    var WRITABLE = "writable";
    exports.f = DESCRIPTORS2 ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty3(O4, P3, Attributes) {
      anObject3(O4);
      P3 = toPropertyKey(P3);
      anObject3(Attributes);
      if (typeof O4 === "function" && P3 === "prototype" && "value" in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
        var current = $getOwnPropertyDescriptor(O4, P3);
        if (current && current[WRITABLE]) {
          O4[P3] = Attributes.value;
          Attributes = {
            configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
            enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
            writable: false
          };
        }
      }
      return $defineProperty(O4, P3, Attributes);
    } : $defineProperty : function defineProperty3(O4, P3, Attributes) {
      anObject3(O4);
      P3 = toPropertyKey(P3);
      anObject3(Attributes);
      if (IE8_DOM_DEFINE) try {
        return $defineProperty(O4, P3, Attributes);
      } catch (error2) {
      }
      if ("get" in Attributes || "set" in Attributes) throw $TypeError("Accessors not supported");
      if ("value" in Attributes) O4[P3] = Attributes.value;
      return O4;
    };
  }
});

// node_modules/core-js/internals/function-name.js
var require_function_name = __commonJS({
  "node_modules/core-js/internals/function-name.js"(exports, module) {
    var DESCRIPTORS2 = require_descriptors();
    var hasOwn = require_has_own_property();
    var FunctionPrototype2 = Function.prototype;
    var getDescriptor = DESCRIPTORS2 && Object.getOwnPropertyDescriptor;
    var EXISTS = hasOwn(FunctionPrototype2, "name");
    var PROPER = EXISTS && function something() {
    }.name === "something";
    var CONFIGURABLE = EXISTS && (!DESCRIPTORS2 || DESCRIPTORS2 && getDescriptor(FunctionPrototype2, "name").configurable);
    module.exports = {
      EXISTS,
      PROPER,
      CONFIGURABLE
    };
  }
});

// node_modules/core-js/internals/inspect-source.js
var require_inspect_source = __commonJS({
  "node_modules/core-js/internals/inspect-source.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var isCallable2 = require_is_callable();
    var store2 = require_shared_store();
    var functionToString2 = uncurryThis3(Function.toString);
    if (!isCallable2(store2.inspectSource)) {
      store2.inspectSource = function(it2) {
        return functionToString2(it2);
      };
    }
    module.exports = store2.inspectSource;
  }
});

// node_modules/core-js/internals/weak-map-basic-detection.js
var require_weak_map_basic_detection = __commonJS({
  "node_modules/core-js/internals/weak-map-basic-detection.js"(exports, module) {
    var global5 = require_global();
    var isCallable2 = require_is_callable();
    var WeakMap2 = global5.WeakMap;
    module.exports = isCallable2(WeakMap2) && /native code/.test(String(WeakMap2));
  }
});

// node_modules/core-js/internals/create-property-descriptor.js
var require_create_property_descriptor = __commonJS({
  "node_modules/core-js/internals/create-property-descriptor.js"(exports, module) {
    module.exports = function(bitmap, value2) {
      return {
        enumerable: !(bitmap & 1),
        configurable: !(bitmap & 2),
        writable: !(bitmap & 4),
        value: value2
      };
    };
  }
});

// node_modules/core-js/internals/create-non-enumerable-property.js
var require_create_non_enumerable_property = __commonJS({
  "node_modules/core-js/internals/create-non-enumerable-property.js"(exports, module) {
    var DESCRIPTORS2 = require_descriptors();
    var definePropertyModule = require_object_define_property();
    var createPropertyDescriptor = require_create_property_descriptor();
    module.exports = DESCRIPTORS2 ? function(object2, key2, value2) {
      return definePropertyModule.f(object2, key2, createPropertyDescriptor(1, value2));
    } : function(object2, key2, value2) {
      object2[key2] = value2;
      return object2;
    };
  }
});

// node_modules/core-js/internals/shared-key.js
var require_shared_key = __commonJS({
  "node_modules/core-js/internals/shared-key.js"(exports, module) {
    var shared = require_shared();
    var uid = require_uid();
    var keys5 = shared("keys");
    module.exports = function(key2) {
      return keys5[key2] || (keys5[key2] = uid(key2));
    };
  }
});

// node_modules/core-js/internals/hidden-keys.js
var require_hidden_keys = __commonJS({
  "node_modules/core-js/internals/hidden-keys.js"(exports, module) {
    module.exports = {};
  }
});

// node_modules/core-js/internals/internal-state.js
var require_internal_state = __commonJS({
  "node_modules/core-js/internals/internal-state.js"(exports, module) {
    var NATIVE_WEAK_MAP = require_weak_map_basic_detection();
    var global5 = require_global();
    var uncurryThis3 = require_function_uncurry_this();
    var isObject7 = require_is_object();
    var createNonEnumerableProperty3 = require_create_non_enumerable_property();
    var hasOwn = require_has_own_property();
    var shared = require_shared_store();
    var sharedKey = require_shared_key();
    var hiddenKeys = require_hidden_keys();
    var OBJECT_ALREADY_INITIALIZED = "Object already initialized";
    var TypeError2 = global5.TypeError;
    var WeakMap2 = global5.WeakMap;
    var set4;
    var get7;
    var has4;
    var enforce = function(it2) {
      return has4(it2) ? get7(it2) : set4(it2, {});
    };
    var getterFor = function(TYPE2) {
      return function(it2) {
        var state;
        if (!isObject7(it2) || (state = get7(it2)).type !== TYPE2) {
          throw TypeError2("Incompatible receiver, " + TYPE2 + " required");
        }
        return state;
      };
    };
    if (NATIVE_WEAK_MAP || shared.state) {
      store2 = shared.state || (shared.state = new WeakMap2());
      wmget = uncurryThis3(store2.get);
      wmhas = uncurryThis3(store2.has);
      wmset = uncurryThis3(store2.set);
      set4 = function(it2, metadata) {
        if (wmhas(store2, it2)) throw TypeError2(OBJECT_ALREADY_INITIALIZED);
        metadata.facade = it2;
        wmset(store2, it2, metadata);
        return metadata;
      };
      get7 = function(it2) {
        return wmget(store2, it2) || {};
      };
      has4 = function(it2) {
        return wmhas(store2, it2);
      };
    } else {
      STATE = sharedKey("state");
      hiddenKeys[STATE] = true;
      set4 = function(it2, metadata) {
        if (hasOwn(it2, STATE)) throw TypeError2(OBJECT_ALREADY_INITIALIZED);
        metadata.facade = it2;
        createNonEnumerableProperty3(it2, STATE, metadata);
        return metadata;
      };
      get7 = function(it2) {
        return hasOwn(it2, STATE) ? it2[STATE] : {};
      };
      has4 = function(it2) {
        return hasOwn(it2, STATE);
      };
    }
    var store2;
    var wmget;
    var wmhas;
    var wmset;
    var STATE;
    module.exports = {
      set: set4,
      get: get7,
      has: has4,
      enforce,
      getterFor
    };
  }
});

// node_modules/core-js/internals/make-built-in.js
var require_make_built_in = __commonJS({
  "node_modules/core-js/internals/make-built-in.js"(exports, module) {
    var fails2 = require_fails();
    var isCallable2 = require_is_callable();
    var hasOwn = require_has_own_property();
    var DESCRIPTORS2 = require_descriptors();
    var CONFIGURABLE_FUNCTION_NAME = require_function_name().CONFIGURABLE;
    var inspectSource = require_inspect_source();
    var InternalStateModule2 = require_internal_state();
    var enforceInternalState = InternalStateModule2.enforce;
    var getInternalState2 = InternalStateModule2.get;
    var defineProperty3 = Object.defineProperty;
    var CONFIGURABLE_LENGTH = DESCRIPTORS2 && !fails2(function() {
      return defineProperty3(function() {
      }, "length", { value: 8 }).length !== 8;
    });
    var TEMPLATE = String(String).split("String");
    var makeBuiltIn = module.exports = function(value2, name2, options2) {
      if (String(name2).slice(0, 7) === "Symbol(") {
        name2 = "[" + String(name2).replace(/^Symbol\(([^)]*)\)/, "$1") + "]";
      }
      if (options2 && options2.getter) name2 = "get " + name2;
      if (options2 && options2.setter) name2 = "set " + name2;
      if (!hasOwn(value2, "name") || CONFIGURABLE_FUNCTION_NAME && value2.name !== name2) {
        if (DESCRIPTORS2) defineProperty3(value2, "name", { value: name2, configurable: true });
        else value2.name = name2;
      }
      if (CONFIGURABLE_LENGTH && options2 && hasOwn(options2, "arity") && value2.length !== options2.arity) {
        defineProperty3(value2, "length", { value: options2.arity });
      }
      try {
        if (options2 && hasOwn(options2, "constructor") && options2.constructor) {
          if (DESCRIPTORS2) defineProperty3(value2, "prototype", { writable: false });
        } else if (value2.prototype) value2.prototype = void 0;
      } catch (error2) {
      }
      var state = enforceInternalState(value2);
      if (!hasOwn(state, "source")) {
        state.source = TEMPLATE.join(typeof name2 == "string" ? name2 : "");
      }
      return value2;
    };
    Function.prototype.toString = makeBuiltIn(function toString9() {
      return isCallable2(this) && getInternalState2(this).source || inspectSource(this);
    }, "toString");
  }
});

// node_modules/core-js/internals/define-built-in.js
var require_define_built_in = __commonJS({
  "node_modules/core-js/internals/define-built-in.js"(exports, module) {
    var isCallable2 = require_is_callable();
    var definePropertyModule = require_object_define_property();
    var makeBuiltIn = require_make_built_in();
    var defineGlobalProperty = require_define_global_property();
    module.exports = function(O4, key2, value2, options2) {
      if (!options2) options2 = {};
      var simple = options2.enumerable;
      var name2 = options2.name !== void 0 ? options2.name : key2;
      if (isCallable2(value2)) makeBuiltIn(value2, name2, options2);
      if (options2.global) {
        if (simple) O4[key2] = value2;
        else defineGlobalProperty(key2, value2);
      } else {
        try {
          if (!options2.unsafe) delete O4[key2];
          else if (O4[key2]) simple = true;
        } catch (error2) {
        }
        if (simple) O4[key2] = value2;
        else definePropertyModule.f(O4, key2, {
          value: value2,
          enumerable: false,
          configurable: !options2.nonConfigurable,
          writable: !options2.nonWritable
        });
      }
      return O4;
    };
  }
});

// node_modules/core-js/internals/classof-raw.js
var require_classof_raw = __commonJS({
  "node_modules/core-js/internals/classof-raw.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var toString9 = uncurryThis3({}.toString);
    var stringSlice2 = uncurryThis3("".slice);
    module.exports = function(it2) {
      return stringSlice2(toString9(it2), 8, -1);
    };
  }
});

// node_modules/core-js/internals/classof.js
var require_classof = __commonJS({
  "node_modules/core-js/internals/classof.js"(exports, module) {
    var TO_STRING_TAG_SUPPORT2 = require_to_string_tag_support();
    var isCallable2 = require_is_callable();
    var classofRaw = require_classof_raw();
    var wellKnownSymbol3 = require_well_known_symbol();
    var TO_STRING_TAG2 = wellKnownSymbol3("toStringTag");
    var $Object = Object;
    var CORRECT_ARGUMENTS = classofRaw(/* @__PURE__ */ function() {
      return arguments;
    }()) == "Arguments";
    var tryGet = function(it2, key2) {
      try {
        return it2[key2];
      } catch (error2) {
      }
    };
    module.exports = TO_STRING_TAG_SUPPORT2 ? classofRaw : function(it2) {
      var O4, tag, result2;
      return it2 === void 0 ? "Undefined" : it2 === null ? "Null" : typeof (tag = tryGet(O4 = $Object(it2), TO_STRING_TAG2)) == "string" ? tag : CORRECT_ARGUMENTS ? classofRaw(O4) : (result2 = classofRaw(O4)) == "Object" && isCallable2(O4.callee) ? "Arguments" : result2;
    };
  }
});

// node_modules/core-js/internals/object-to-string.js
var require_object_to_string = __commonJS({
  "node_modules/core-js/internals/object-to-string.js"(exports, module) {
    "use strict";
    var TO_STRING_TAG_SUPPORT2 = require_to_string_tag_support();
    var classof = require_classof();
    module.exports = TO_STRING_TAG_SUPPORT2 ? {}.toString : function toString9() {
      return "[object " + classof(this) + "]";
    };
  }
});

// node_modules/core-js/internals/dom-iterables.js
var require_dom_iterables = __commonJS({
  "node_modules/core-js/internals/dom-iterables.js"(exports, module) {
    module.exports = {
      CSSRuleList: 0,
      CSSStyleDeclaration: 0,
      CSSValueList: 0,
      ClientRectList: 0,
      DOMRectList: 0,
      DOMStringList: 0,
      DOMTokenList: 1,
      DataTransferItemList: 0,
      FileList: 0,
      HTMLAllCollection: 0,
      HTMLCollection: 0,
      HTMLFormElement: 0,
      HTMLSelectElement: 0,
      MediaList: 0,
      MimeTypeArray: 0,
      NamedNodeMap: 0,
      NodeList: 1,
      PaintRequestList: 0,
      Plugin: 0,
      PluginArray: 0,
      SVGLengthList: 0,
      SVGNumberList: 0,
      SVGPathSegList: 0,
      SVGPointList: 0,
      SVGStringList: 0,
      SVGTransformList: 0,
      SourceBufferList: 0,
      StyleSheetList: 0,
      TextTrackCueList: 0,
      TextTrackList: 0,
      TouchList: 0
    };
  }
});

// node_modules/core-js/internals/dom-token-list-prototype.js
var require_dom_token_list_prototype = __commonJS({
  "node_modules/core-js/internals/dom-token-list-prototype.js"(exports, module) {
    var documentCreateElement = require_document_create_element();
    var classList2 = documentCreateElement("span").classList;
    var DOMTokenListPrototype3 = classList2 && classList2.constructor && classList2.constructor.prototype;
    module.exports = DOMTokenListPrototype3 === Object.prototype ? void 0 : DOMTokenListPrototype3;
  }
});

// node_modules/core-js/internals/function-bind-context.js
var require_function_bind_context = __commonJS({
  "node_modules/core-js/internals/function-bind-context.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var aCallable = require_a_callable();
    var NATIVE_BIND = require_function_bind_native();
    var bind2 = uncurryThis3(uncurryThis3.bind);
    module.exports = function(fn, that) {
      aCallable(fn);
      return that === void 0 ? fn : NATIVE_BIND ? bind2(fn, that) : function() {
        return fn.apply(that, arguments);
      };
    };
  }
});

// node_modules/core-js/internals/indexed-object.js
var require_indexed_object = __commonJS({
  "node_modules/core-js/internals/indexed-object.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var fails2 = require_fails();
    var classof = require_classof_raw();
    var $Object = Object;
    var split3 = uncurryThis3("".split);
    module.exports = fails2(function() {
      return !$Object("z").propertyIsEnumerable(0);
    }) ? function(it2) {
      return classof(it2) == "String" ? split3(it2, "") : $Object(it2);
    } : $Object;
  }
});

// node_modules/core-js/internals/math-trunc.js
var require_math_trunc = __commonJS({
  "node_modules/core-js/internals/math-trunc.js"(exports, module) {
    var ceil = Math.ceil;
    var floor2 = Math.floor;
    module.exports = Math.trunc || function trunc(x3) {
      var n4 = +x3;
      return (n4 > 0 ? floor2 : ceil)(n4);
    };
  }
});

// node_modules/core-js/internals/to-integer-or-infinity.js
var require_to_integer_or_infinity = __commonJS({
  "node_modules/core-js/internals/to-integer-or-infinity.js"(exports, module) {
    var trunc = require_math_trunc();
    module.exports = function(argument) {
      var number3 = +argument;
      return number3 !== number3 || number3 === 0 ? 0 : trunc(number3);
    };
  }
});

// node_modules/core-js/internals/to-length.js
var require_to_length = __commonJS({
  "node_modules/core-js/internals/to-length.js"(exports, module) {
    var toIntegerOrInfinity2 = require_to_integer_or_infinity();
    var min3 = Math.min;
    module.exports = function(argument) {
      return argument > 0 ? min3(toIntegerOrInfinity2(argument), 9007199254740991) : 0;
    };
  }
});

// node_modules/core-js/internals/length-of-array-like.js
var require_length_of_array_like = __commonJS({
  "node_modules/core-js/internals/length-of-array-like.js"(exports, module) {
    var toLength3 = require_to_length();
    module.exports = function(obj) {
      return toLength3(obj.length);
    };
  }
});

// node_modules/core-js/internals/is-array.js
var require_is_array = __commonJS({
  "node_modules/core-js/internals/is-array.js"(exports, module) {
    var classof = require_classof_raw();
    module.exports = Array.isArray || function isArray3(argument) {
      return classof(argument) == "Array";
    };
  }
});

// node_modules/core-js/internals/is-constructor.js
var require_is_constructor = __commonJS({
  "node_modules/core-js/internals/is-constructor.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var fails2 = require_fails();
    var isCallable2 = require_is_callable();
    var classof = require_classof();
    var getBuiltIn = require_get_built_in();
    var inspectSource = require_inspect_source();
    var noop5 = function() {
    };
    var empty4 = [];
    var construct = getBuiltIn("Reflect", "construct");
    var constructorRegExp = /^\s*(?:class|function)\b/;
    var exec = uncurryThis3(constructorRegExp.exec);
    var INCORRECT_TO_STRING = !constructorRegExp.exec(noop5);
    var isConstructorModern = function isConstructor(argument) {
      if (!isCallable2(argument)) return false;
      try {
        construct(noop5, empty4, argument);
        return true;
      } catch (error2) {
        return false;
      }
    };
    var isConstructorLegacy = function isConstructor(argument) {
      if (!isCallable2(argument)) return false;
      switch (classof(argument)) {
        case "AsyncFunction":
        case "GeneratorFunction":
        case "AsyncGeneratorFunction":
          return false;
      }
      try {
        return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
      } catch (error2) {
        return true;
      }
    };
    isConstructorLegacy.sham = true;
    module.exports = !construct || fails2(function() {
      var called;
      return isConstructorModern(isConstructorModern.call) || !isConstructorModern(Object) || !isConstructorModern(function() {
        called = true;
      }) || called;
    }) ? isConstructorLegacy : isConstructorModern;
  }
});

// node_modules/core-js/internals/array-species-constructor.js
var require_array_species_constructor = __commonJS({
  "node_modules/core-js/internals/array-species-constructor.js"(exports, module) {
    var isArray3 = require_is_array();
    var isConstructor = require_is_constructor();
    var isObject7 = require_is_object();
    var wellKnownSymbol3 = require_well_known_symbol();
    var SPECIES = wellKnownSymbol3("species");
    var $Array = Array;
    module.exports = function(originalArray) {
      var C3;
      if (isArray3(originalArray)) {
        C3 = originalArray.constructor;
        if (isConstructor(C3) && (C3 === $Array || isArray3(C3.prototype))) C3 = void 0;
        else if (isObject7(C3)) {
          C3 = C3[SPECIES];
          if (C3 === null) C3 = void 0;
        }
      }
      return C3 === void 0 ? $Array : C3;
    };
  }
});

// node_modules/core-js/internals/array-species-create.js
var require_array_species_create = __commonJS({
  "node_modules/core-js/internals/array-species-create.js"(exports, module) {
    var arraySpeciesConstructor = require_array_species_constructor();
    module.exports = function(originalArray, length) {
      return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
    };
  }
});

// node_modules/core-js/internals/array-iteration.js
var require_array_iteration = __commonJS({
  "node_modules/core-js/internals/array-iteration.js"(exports, module) {
    var bind2 = require_function_bind_context();
    var uncurryThis3 = require_function_uncurry_this();
    var IndexedObject = require_indexed_object();
    var toObject = require_to_object();
    var lengthOfArrayLike = require_length_of_array_like();
    var arraySpeciesCreate = require_array_species_create();
    var push3 = uncurryThis3([].push);
    var createMethod = function(TYPE2) {
      var IS_MAP = TYPE2 == 1;
      var IS_FILTER = TYPE2 == 2;
      var IS_SOME = TYPE2 == 3;
      var IS_EVERY = TYPE2 == 4;
      var IS_FIND_INDEX = TYPE2 == 6;
      var IS_FILTER_REJECT = TYPE2 == 7;
      var NO_HOLES = TYPE2 == 5 || IS_FIND_INDEX;
      return function($this, callbackfn, that, specificCreate) {
        var O4 = toObject($this);
        var self2 = IndexedObject(O4);
        var boundFunction = bind2(callbackfn, that);
        var length = lengthOfArrayLike(self2);
        var index2 = 0;
        var create6 = specificCreate || arraySpeciesCreate;
        var target = IS_MAP ? create6($this, length) : IS_FILTER || IS_FILTER_REJECT ? create6($this, 0) : void 0;
        var value2, result2;
        for (; length > index2; index2++) if (NO_HOLES || index2 in self2) {
          value2 = self2[index2];
          result2 = boundFunction(value2, index2, O4);
          if (TYPE2) {
            if (IS_MAP) target[index2] = result2;
            else if (result2) switch (TYPE2) {
              case 3:
                return true;
              // some
              case 5:
                return value2;
              // find
              case 6:
                return index2;
              // findIndex
              case 2:
                push3(target, value2);
            }
            else switch (TYPE2) {
              case 4:
                return false;
              // every
              case 7:
                push3(target, value2);
            }
          }
        }
        return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
      };
    };
    module.exports = {
      // `Array.prototype.forEach` method
      // https://tc39.es/ecma262/#sec-array.prototype.foreach
      forEach: createMethod(0),
      // `Array.prototype.map` method
      // https://tc39.es/ecma262/#sec-array.prototype.map
      map: createMethod(1),
      // `Array.prototype.filter` method
      // https://tc39.es/ecma262/#sec-array.prototype.filter
      filter: createMethod(2),
      // `Array.prototype.some` method
      // https://tc39.es/ecma262/#sec-array.prototype.some
      some: createMethod(3),
      // `Array.prototype.every` method
      // https://tc39.es/ecma262/#sec-array.prototype.every
      every: createMethod(4),
      // `Array.prototype.find` method
      // https://tc39.es/ecma262/#sec-array.prototype.find
      find: createMethod(5),
      // `Array.prototype.findIndex` method
      // https://tc39.es/ecma262/#sec-array.prototype.findIndex
      findIndex: createMethod(6),
      // `Array.prototype.filterReject` method
      // https://github.com/tc39/proposal-array-filtering
      filterReject: createMethod(7)
    };
  }
});

// node_modules/core-js/internals/array-method-is-strict.js
var require_array_method_is_strict = __commonJS({
  "node_modules/core-js/internals/array-method-is-strict.js"(exports, module) {
    "use strict";
    var fails2 = require_fails();
    module.exports = function(METHOD_NAME, argument) {
      var method = [][METHOD_NAME];
      return !!method && fails2(function() {
        method.call(null, argument || function() {
          return 1;
        }, 1);
      });
    };
  }
});

// node_modules/core-js/internals/array-for-each.js
var require_array_for_each = __commonJS({
  "node_modules/core-js/internals/array-for-each.js"(exports, module) {
    "use strict";
    var $forEach = require_array_iteration().forEach;
    var arrayMethodIsStrict2 = require_array_method_is_strict();
    var STRICT_METHOD2 = arrayMethodIsStrict2("forEach");
    module.exports = !STRICT_METHOD2 ? function forEach4(callbackfn) {
      return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : void 0);
    } : [].forEach;
  }
});

// node_modules/can-use-dom/index.js
var require_can_use_dom = __commonJS({
  "node_modules/can-use-dom/index.js"(exports, module) {
    var canUseDOM2 = !!(typeof window !== "undefined" && window.document && window.document.createElement);
    module.exports = canUseDOM2;
  }
});

// node_modules/core-js/internals/object-property-is-enumerable.js
var require_object_property_is_enumerable = __commonJS({
  "node_modules/core-js/internals/object-property-is-enumerable.js"(exports) {
    "use strict";
    var $propertyIsEnumerable = {}.propertyIsEnumerable;
    var getOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
    var NASHORN_BUG = getOwnPropertyDescriptor2 && !$propertyIsEnumerable.call({ 1: 2 }, 1);
    exports.f = NASHORN_BUG ? function propertyIsEnumerable2(V2) {
      var descriptor = getOwnPropertyDescriptor2(this, V2);
      return !!descriptor && descriptor.enumerable;
    } : $propertyIsEnumerable;
  }
});

// node_modules/core-js/internals/to-indexed-object.js
var require_to_indexed_object = __commonJS({
  "node_modules/core-js/internals/to-indexed-object.js"(exports, module) {
    var IndexedObject = require_indexed_object();
    var requireObjectCoercible3 = require_require_object_coercible();
    module.exports = function(it2) {
      return IndexedObject(requireObjectCoercible3(it2));
    };
  }
});

// node_modules/core-js/internals/object-get-own-property-descriptor.js
var require_object_get_own_property_descriptor = __commonJS({
  "node_modules/core-js/internals/object-get-own-property-descriptor.js"(exports) {
    var DESCRIPTORS2 = require_descriptors();
    var call3 = require_function_call();
    var propertyIsEnumerableModule = require_object_property_is_enumerable();
    var createPropertyDescriptor = require_create_property_descriptor();
    var toIndexedObject = require_to_indexed_object();
    var toPropertyKey = require_to_property_key();
    var hasOwn = require_has_own_property();
    var IE8_DOM_DEFINE = require_ie8_dom_define();
    var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
    exports.f = DESCRIPTORS2 ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor2(O4, P3) {
      O4 = toIndexedObject(O4);
      P3 = toPropertyKey(P3);
      if (IE8_DOM_DEFINE) try {
        return $getOwnPropertyDescriptor(O4, P3);
      } catch (error2) {
      }
      if (hasOwn(O4, P3)) return createPropertyDescriptor(!call3(propertyIsEnumerableModule.f, O4, P3), O4[P3]);
    };
  }
});

// node_modules/core-js/internals/to-absolute-index.js
var require_to_absolute_index = __commonJS({
  "node_modules/core-js/internals/to-absolute-index.js"(exports, module) {
    var toIntegerOrInfinity2 = require_to_integer_or_infinity();
    var max3 = Math.max;
    var min3 = Math.min;
    module.exports = function(index2, length) {
      var integer = toIntegerOrInfinity2(index2);
      return integer < 0 ? max3(integer + length, 0) : min3(integer, length);
    };
  }
});

// node_modules/core-js/internals/array-includes.js
var require_array_includes = __commonJS({
  "node_modules/core-js/internals/array-includes.js"(exports, module) {
    var toIndexedObject = require_to_indexed_object();
    var toAbsoluteIndex = require_to_absolute_index();
    var lengthOfArrayLike = require_length_of_array_like();
    var createMethod = function(IS_INCLUDES) {
      return function($this, el2, fromIndex) {
        var O4 = toIndexedObject($this);
        var length = lengthOfArrayLike(O4);
        var index2 = toAbsoluteIndex(fromIndex, length);
        var value2;
        if (IS_INCLUDES && el2 != el2) while (length > index2) {
          value2 = O4[index2++];
          if (value2 != value2) return true;
        }
        else for (; length > index2; index2++) {
          if ((IS_INCLUDES || index2 in O4) && O4[index2] === el2) return IS_INCLUDES || index2 || 0;
        }
        return !IS_INCLUDES && -1;
      };
    };
    module.exports = {
      // `Array.prototype.includes` method
      // https://tc39.es/ecma262/#sec-array.prototype.includes
      includes: createMethod(true),
      // `Array.prototype.indexOf` method
      // https://tc39.es/ecma262/#sec-array.prototype.indexof
      indexOf: createMethod(false)
    };
  }
});

// node_modules/core-js/internals/object-keys-internal.js
var require_object_keys_internal = __commonJS({
  "node_modules/core-js/internals/object-keys-internal.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var hasOwn = require_has_own_property();
    var toIndexedObject = require_to_indexed_object();
    var indexOf = require_array_includes().indexOf;
    var hiddenKeys = require_hidden_keys();
    var push3 = uncurryThis3([].push);
    module.exports = function(object2, names) {
      var O4 = toIndexedObject(object2);
      var i3 = 0;
      var result2 = [];
      var key2;
      for (key2 in O4) !hasOwn(hiddenKeys, key2) && hasOwn(O4, key2) && push3(result2, key2);
      while (names.length > i3) if (hasOwn(O4, key2 = names[i3++])) {
        ~indexOf(result2, key2) || push3(result2, key2);
      }
      return result2;
    };
  }
});

// node_modules/core-js/internals/enum-bug-keys.js
var require_enum_bug_keys = __commonJS({
  "node_modules/core-js/internals/enum-bug-keys.js"(exports, module) {
    module.exports = [
      "constructor",
      "hasOwnProperty",
      "isPrototypeOf",
      "propertyIsEnumerable",
      "toLocaleString",
      "toString",
      "valueOf"
    ];
  }
});

// node_modules/core-js/internals/object-get-own-property-names.js
var require_object_get_own_property_names = __commonJS({
  "node_modules/core-js/internals/object-get-own-property-names.js"(exports) {
    var internalObjectKeys = require_object_keys_internal();
    var enumBugKeys = require_enum_bug_keys();
    var hiddenKeys = enumBugKeys.concat("length", "prototype");
    exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames2(O4) {
      return internalObjectKeys(O4, hiddenKeys);
    };
  }
});

// node_modules/core-js/internals/object-get-own-property-symbols.js
var require_object_get_own_property_symbols = __commonJS({
  "node_modules/core-js/internals/object-get-own-property-symbols.js"(exports) {
    exports.f = Object.getOwnPropertySymbols;
  }
});

// node_modules/core-js/internals/own-keys.js
var require_own_keys = __commonJS({
  "node_modules/core-js/internals/own-keys.js"(exports, module) {
    var getBuiltIn = require_get_built_in();
    var uncurryThis3 = require_function_uncurry_this();
    var getOwnPropertyNamesModule = require_object_get_own_property_names();
    var getOwnPropertySymbolsModule = require_object_get_own_property_symbols();
    var anObject3 = require_an_object();
    var concat2 = uncurryThis3([].concat);
    module.exports = getBuiltIn("Reflect", "ownKeys") || function ownKeys2(it2) {
      var keys5 = getOwnPropertyNamesModule.f(anObject3(it2));
      var getOwnPropertySymbols2 = getOwnPropertySymbolsModule.f;
      return getOwnPropertySymbols2 ? concat2(keys5, getOwnPropertySymbols2(it2)) : keys5;
    };
  }
});

// node_modules/core-js/internals/copy-constructor-properties.js
var require_copy_constructor_properties = __commonJS({
  "node_modules/core-js/internals/copy-constructor-properties.js"(exports, module) {
    var hasOwn = require_has_own_property();
    var ownKeys2 = require_own_keys();
    var getOwnPropertyDescriptorModule = require_object_get_own_property_descriptor();
    var definePropertyModule = require_object_define_property();
    module.exports = function(target, source, exceptions) {
      var keys5 = ownKeys2(source);
      var defineProperty3 = definePropertyModule.f;
      var getOwnPropertyDescriptor2 = getOwnPropertyDescriptorModule.f;
      for (var i3 = 0; i3 < keys5.length; i3++) {
        var key2 = keys5[i3];
        if (!hasOwn(target, key2) && !(exceptions && hasOwn(exceptions, key2))) {
          defineProperty3(target, key2, getOwnPropertyDescriptor2(source, key2));
        }
      }
    };
  }
});

// node_modules/core-js/internals/is-forced.js
var require_is_forced = __commonJS({
  "node_modules/core-js/internals/is-forced.js"(exports, module) {
    var fails2 = require_fails();
    var isCallable2 = require_is_callable();
    var replacement = /#|\.prototype\./;
    var isForced = function(feature, detection) {
      var value2 = data2[normalize5(feature)];
      return value2 == POLYFILL ? true : value2 == NATIVE ? false : isCallable2(detection) ? fails2(detection) : !!detection;
    };
    var normalize5 = isForced.normalize = function(string3) {
      return String(string3).replace(replacement, ".").toLowerCase();
    };
    var data2 = isForced.data = {};
    var NATIVE = isForced.NATIVE = "N";
    var POLYFILL = isForced.POLYFILL = "P";
    module.exports = isForced;
  }
});

// node_modules/core-js/internals/export.js
var require_export = __commonJS({
  "node_modules/core-js/internals/export.js"(exports, module) {
    var global5 = require_global();
    var getOwnPropertyDescriptor2 = require_object_get_own_property_descriptor().f;
    var createNonEnumerableProperty3 = require_create_non_enumerable_property();
    var defineBuiltIn2 = require_define_built_in();
    var defineGlobalProperty = require_define_global_property();
    var copyConstructorProperties = require_copy_constructor_properties();
    var isForced = require_is_forced();
    module.exports = function(options2, source) {
      var TARGET = options2.target;
      var GLOBAL = options2.global;
      var STATIC = options2.stat;
      var FORCED, target, key2, targetProperty, sourceProperty, descriptor;
      if (GLOBAL) {
        target = global5;
      } else if (STATIC) {
        target = global5[TARGET] || defineGlobalProperty(TARGET, {});
      } else {
        target = (global5[TARGET] || {}).prototype;
      }
      if (target) for (key2 in source) {
        sourceProperty = source[key2];
        if (options2.dontCallGetSet) {
          descriptor = getOwnPropertyDescriptor2(target, key2);
          targetProperty = descriptor && descriptor.value;
        } else targetProperty = target[key2];
        FORCED = isForced(GLOBAL ? key2 : TARGET + (STATIC ? "." : "#") + key2, options2.forced);
        if (!FORCED && targetProperty !== void 0) {
          if (typeof sourceProperty == typeof targetProperty) continue;
          copyConstructorProperties(sourceProperty, targetProperty);
        }
        if (options2.sham || targetProperty && targetProperty.sham) {
          createNonEnumerableProperty3(sourceProperty, "sham", true);
        }
        defineBuiltIn2(target, key2, sourceProperty, options2);
      }
    };
  }
});

// node_modules/core-js/internals/to-string.js
var require_to_string = __commonJS({
  "node_modules/core-js/internals/to-string.js"(exports, module) {
    var classof = require_classof();
    var $String = String;
    module.exports = function(argument) {
      if (classof(argument) === "Symbol") throw TypeError("Cannot convert a Symbol value to a string");
      return $String(argument);
    };
  }
});

// node_modules/core-js/internals/whitespaces.js
var require_whitespaces = __commonJS({
  "node_modules/core-js/internals/whitespaces.js"(exports, module) {
    module.exports = "	\n\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF";
  }
});

// node_modules/core-js/internals/string-trim.js
var require_string_trim = __commonJS({
  "node_modules/core-js/internals/string-trim.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var requireObjectCoercible3 = require_require_object_coercible();
    var toString9 = require_to_string();
    var whitespaces = require_whitespaces();
    var replace4 = uncurryThis3("".replace);
    var whitespace2 = "[" + whitespaces + "]";
    var ltrim = RegExp("^" + whitespace2 + whitespace2 + "*");
    var rtrim2 = RegExp(whitespace2 + whitespace2 + "*$");
    var createMethod = function(TYPE2) {
      return function($this) {
        var string3 = toString9(requireObjectCoercible3($this));
        if (TYPE2 & 1) string3 = replace4(string3, ltrim, "");
        if (TYPE2 & 2) string3 = replace4(string3, rtrim2, "");
        return string3;
      };
    };
    module.exports = {
      // `String.prototype.{ trimLeft, trimStart }` methods
      // https://tc39.es/ecma262/#sec-string.prototype.trimstart
      start: createMethod(1),
      // `String.prototype.{ trimRight, trimEnd }` methods
      // https://tc39.es/ecma262/#sec-string.prototype.trimend
      end: createMethod(2),
      // `String.prototype.trim` method
      // https://tc39.es/ecma262/#sec-string.prototype.trim
      trim: createMethod(3)
    };
  }
});

// node_modules/core-js/internals/number-parse-int.js
var require_number_parse_int = __commonJS({
  "node_modules/core-js/internals/number-parse-int.js"(exports, module) {
    var global5 = require_global();
    var fails2 = require_fails();
    var uncurryThis3 = require_function_uncurry_this();
    var toString9 = require_to_string();
    var trim = require_string_trim().trim;
    var whitespaces = require_whitespaces();
    var $parseInt2 = global5.parseInt;
    var Symbol2 = global5.Symbol;
    var ITERATOR2 = Symbol2 && Symbol2.iterator;
    var hex = /^[+-]?0x/i;
    var exec = uncurryThis3(hex.exec);
    var FORCED = $parseInt2(whitespaces + "08") !== 8 || $parseInt2(whitespaces + "0x16") !== 22 || ITERATOR2 && !fails2(function() {
      $parseInt2(Object(ITERATOR2));
    });
    module.exports = FORCED ? function parseInt2(string3, radix) {
      var S2 = trim(toString9(string3));
      return $parseInt2(S2, radix >>> 0 || (exec(hex, S2) ? 16 : 10));
    } : $parseInt2;
  }
});

// node_modules/core-js/internals/object-keys.js
var require_object_keys = __commonJS({
  "node_modules/core-js/internals/object-keys.js"(exports, module) {
    var internalObjectKeys = require_object_keys_internal();
    var enumBugKeys = require_enum_bug_keys();
    module.exports = Object.keys || function keys5(O4) {
      return internalObjectKeys(O4, enumBugKeys);
    };
  }
});

// node_modules/core-js/internals/object-assign.js
var require_object_assign = __commonJS({
  "node_modules/core-js/internals/object-assign.js"(exports, module) {
    "use strict";
    var DESCRIPTORS2 = require_descriptors();
    var uncurryThis3 = require_function_uncurry_this();
    var call3 = require_function_call();
    var fails2 = require_fails();
    var objectKeys = require_object_keys();
    var getOwnPropertySymbolsModule = require_object_get_own_property_symbols();
    var propertyIsEnumerableModule = require_object_property_is_enumerable();
    var toObject = require_to_object();
    var IndexedObject = require_indexed_object();
    var $assign = Object.assign;
    var defineProperty3 = Object.defineProperty;
    var concat2 = uncurryThis3([].concat);
    module.exports = !$assign || fails2(function() {
      if (DESCRIPTORS2 && $assign({ b: 1 }, $assign(defineProperty3({}, "a", {
        enumerable: true,
        get: function() {
          defineProperty3(this, "b", {
            value: 3,
            enumerable: false
          });
        }
      }), { b: 2 })).b !== 1) return true;
      var A4 = {};
      var B = {};
      var symbol = Symbol();
      var alphabet = "abcdefghijklmnopqrst";
      A4[symbol] = 7;
      alphabet.split("").forEach(function(chr) {
        B[chr] = chr;
      });
      return $assign({}, A4)[symbol] != 7 || objectKeys($assign({}, B)).join("") != alphabet;
    }) ? function assign6(target, source) {
      var T3 = toObject(target);
      var argumentsLength = arguments.length;
      var index2 = 1;
      var getOwnPropertySymbols2 = getOwnPropertySymbolsModule.f;
      var propertyIsEnumerable2 = propertyIsEnumerableModule.f;
      while (argumentsLength > index2) {
        var S2 = IndexedObject(arguments[index2++]);
        var keys5 = getOwnPropertySymbols2 ? concat2(objectKeys(S2), getOwnPropertySymbols2(S2)) : objectKeys(S2);
        var length = keys5.length;
        var j = 0;
        var key2;
        while (length > j) {
          key2 = keys5[j++];
          if (!DESCRIPTORS2 || call3(propertyIsEnumerable2, S2, key2)) T3[key2] = S2[key2];
        }
      }
      return T3;
    } : $assign;
  }
});

// node_modules/core-js/internals/array-method-has-species-support.js
var require_array_method_has_species_support = __commonJS({
  "node_modules/core-js/internals/array-method-has-species-support.js"(exports, module) {
    var fails2 = require_fails();
    var wellKnownSymbol3 = require_well_known_symbol();
    var V8_VERSION = require_engine_v8_version();
    var SPECIES = wellKnownSymbol3("species");
    module.exports = function(METHOD_NAME) {
      return V8_VERSION >= 51 || !fails2(function() {
        var array = [];
        var constructor = array.constructor = {};
        constructor[SPECIES] = function() {
          return { foo: 1 };
        };
        return array[METHOD_NAME](Boolean).foo !== 1;
      });
    };
  }
});

// node_modules/core-js/internals/object-define-properties.js
var require_object_define_properties = __commonJS({
  "node_modules/core-js/internals/object-define-properties.js"(exports) {
    var DESCRIPTORS2 = require_descriptors();
    var V8_PROTOTYPE_DEFINE_BUG = require_v8_prototype_define_bug();
    var definePropertyModule = require_object_define_property();
    var anObject3 = require_an_object();
    var toIndexedObject = require_to_indexed_object();
    var objectKeys = require_object_keys();
    exports.f = DESCRIPTORS2 && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O4, Properties2) {
      anObject3(O4);
      var props2 = toIndexedObject(Properties2);
      var keys5 = objectKeys(Properties2);
      var length = keys5.length;
      var index2 = 0;
      var key2;
      while (length > index2) definePropertyModule.f(O4, key2 = keys5[index2++], props2[key2]);
      return O4;
    };
  }
});

// node_modules/core-js/internals/html.js
var require_html = __commonJS({
  "node_modules/core-js/internals/html.js"(exports, module) {
    var getBuiltIn = require_get_built_in();
    module.exports = getBuiltIn("document", "documentElement");
  }
});

// node_modules/core-js/internals/object-create.js
var require_object_create = __commonJS({
  "node_modules/core-js/internals/object-create.js"(exports, module) {
    var anObject3 = require_an_object();
    var definePropertiesModule = require_object_define_properties();
    var enumBugKeys = require_enum_bug_keys();
    var hiddenKeys = require_hidden_keys();
    var html5 = require_html();
    var documentCreateElement = require_document_create_element();
    var sharedKey = require_shared_key();
    var GT = ">";
    var LT = "<";
    var PROTOTYPE = "prototype";
    var SCRIPT = "script";
    var IE_PROTO = sharedKey("IE_PROTO");
    var EmptyConstructor = function() {
    };
    var scriptTag = function(content2) {
      return LT + SCRIPT + GT + content2 + LT + "/" + SCRIPT + GT;
    };
    var NullProtoObjectViaActiveX = function(activeXDocument2) {
      activeXDocument2.write(scriptTag(""));
      activeXDocument2.close();
      var temp = activeXDocument2.parentWindow.Object;
      activeXDocument2 = null;
      return temp;
    };
    var NullProtoObjectViaIFrame = function() {
      var iframe = documentCreateElement("iframe");
      var JS = "java" + SCRIPT + ":";
      var iframeDocument;
      iframe.style.display = "none";
      html5.appendChild(iframe);
      iframe.src = String(JS);
      iframeDocument = iframe.contentWindow.document;
      iframeDocument.open();
      iframeDocument.write(scriptTag("document.F=Object"));
      iframeDocument.close();
      return iframeDocument.F;
    };
    var activeXDocument;
    var NullProtoObject = function() {
      try {
        activeXDocument = new ActiveXObject("htmlfile");
      } catch (error2) {
      }
      NullProtoObject = typeof document != "undefined" ? document.domain && activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame() : NullProtoObjectViaActiveX(activeXDocument);
      var length = enumBugKeys.length;
      while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
      return NullProtoObject();
    };
    hiddenKeys[IE_PROTO] = true;
    module.exports = Object.create || function create6(O4, Properties2) {
      var result2;
      if (O4 !== null) {
        EmptyConstructor[PROTOTYPE] = anObject3(O4);
        result2 = new EmptyConstructor();
        EmptyConstructor[PROTOTYPE] = null;
        result2[IE_PROTO] = O4;
      } else result2 = NullProtoObject();
      return Properties2 === void 0 ? result2 : definePropertiesModule.f(result2, Properties2);
    };
  }
});

// node_modules/core-js/internals/add-to-unscopables.js
var require_add_to_unscopables = __commonJS({
  "node_modules/core-js/internals/add-to-unscopables.js"(exports, module) {
    var wellKnownSymbol3 = require_well_known_symbol();
    var create6 = require_object_create();
    var defineProperty3 = require_object_define_property().f;
    var UNSCOPABLES = wellKnownSymbol3("unscopables");
    var ArrayPrototype = Array.prototype;
    if (ArrayPrototype[UNSCOPABLES] == void 0) {
      defineProperty3(ArrayPrototype, UNSCOPABLES, {
        configurable: true,
        value: create6(null)
      });
    }
    module.exports = function(key2) {
      ArrayPrototype[UNSCOPABLES][key2] = true;
    };
  }
});

// node_modules/core-js/internals/iterators.js
var require_iterators = __commonJS({
  "node_modules/core-js/internals/iterators.js"(exports, module) {
    module.exports = {};
  }
});

// node_modules/core-js/internals/correct-prototype-getter.js
var require_correct_prototype_getter = __commonJS({
  "node_modules/core-js/internals/correct-prototype-getter.js"(exports, module) {
    var fails2 = require_fails();
    module.exports = !fails2(function() {
      function F2() {
      }
      F2.prototype.constructor = null;
      return Object.getPrototypeOf(new F2()) !== F2.prototype;
    });
  }
});

// node_modules/core-js/internals/object-get-prototype-of.js
var require_object_get_prototype_of = __commonJS({
  "node_modules/core-js/internals/object-get-prototype-of.js"(exports, module) {
    var hasOwn = require_has_own_property();
    var isCallable2 = require_is_callable();
    var toObject = require_to_object();
    var sharedKey = require_shared_key();
    var CORRECT_PROTOTYPE_GETTER = require_correct_prototype_getter();
    var IE_PROTO = sharedKey("IE_PROTO");
    var $Object = Object;
    var ObjectPrototype = $Object.prototype;
    module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function(O4) {
      var object2 = toObject(O4);
      if (hasOwn(object2, IE_PROTO)) return object2[IE_PROTO];
      var constructor = object2.constructor;
      if (isCallable2(constructor) && object2 instanceof constructor) {
        return constructor.prototype;
      }
      return object2 instanceof $Object ? ObjectPrototype : null;
    };
  }
});

// node_modules/core-js/internals/iterators-core.js
var require_iterators_core = __commonJS({
  "node_modules/core-js/internals/iterators-core.js"(exports, module) {
    "use strict";
    var fails2 = require_fails();
    var isCallable2 = require_is_callable();
    var isObject7 = require_is_object();
    var create6 = require_object_create();
    var getPrototypeOf2 = require_object_get_prototype_of();
    var defineBuiltIn2 = require_define_built_in();
    var wellKnownSymbol3 = require_well_known_symbol();
    var IS_PURE = require_is_pure();
    var ITERATOR2 = wellKnownSymbol3("iterator");
    var BUGGY_SAFARI_ITERATORS = false;
    var IteratorPrototype;
    var PrototypeOfArrayIteratorPrototype;
    var arrayIterator;
    if ([].keys) {
      arrayIterator = [].keys();
      if (!("next" in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
      else {
        PrototypeOfArrayIteratorPrototype = getPrototypeOf2(getPrototypeOf2(arrayIterator));
        if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
      }
    }
    var NEW_ITERATOR_PROTOTYPE = !isObject7(IteratorPrototype) || fails2(function() {
      var test2 = {};
      return IteratorPrototype[ITERATOR2].call(test2) !== test2;
    });
    if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
    else if (IS_PURE) IteratorPrototype = create6(IteratorPrototype);
    if (!isCallable2(IteratorPrototype[ITERATOR2])) {
      defineBuiltIn2(IteratorPrototype, ITERATOR2, function() {
        return this;
      });
    }
    module.exports = {
      IteratorPrototype,
      BUGGY_SAFARI_ITERATORS
    };
  }
});

// node_modules/core-js/internals/set-to-string-tag.js
var require_set_to_string_tag = __commonJS({
  "node_modules/core-js/internals/set-to-string-tag.js"(exports, module) {
    var defineProperty3 = require_object_define_property().f;
    var hasOwn = require_has_own_property();
    var wellKnownSymbol3 = require_well_known_symbol();
    var TO_STRING_TAG2 = wellKnownSymbol3("toStringTag");
    module.exports = function(target, TAG, STATIC) {
      if (target && !STATIC) target = target.prototype;
      if (target && !hasOwn(target, TO_STRING_TAG2)) {
        defineProperty3(target, TO_STRING_TAG2, { configurable: true, value: TAG });
      }
    };
  }
});

// node_modules/core-js/internals/iterator-create-constructor.js
var require_iterator_create_constructor = __commonJS({
  "node_modules/core-js/internals/iterator-create-constructor.js"(exports, module) {
    "use strict";
    var IteratorPrototype = require_iterators_core().IteratorPrototype;
    var create6 = require_object_create();
    var createPropertyDescriptor = require_create_property_descriptor();
    var setToStringTag = require_set_to_string_tag();
    var Iterators = require_iterators();
    var returnThis = function() {
      return this;
    };
    module.exports = function(IteratorConstructor, NAME2, next2, ENUMERABLE_NEXT) {
      var TO_STRING_TAG2 = NAME2 + " Iterator";
      IteratorConstructor.prototype = create6(IteratorPrototype, { next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next2) });
      setToStringTag(IteratorConstructor, TO_STRING_TAG2, false, true);
      Iterators[TO_STRING_TAG2] = returnThis;
      return IteratorConstructor;
    };
  }
});

// node_modules/core-js/internals/a-possible-prototype.js
var require_a_possible_prototype = __commonJS({
  "node_modules/core-js/internals/a-possible-prototype.js"(exports, module) {
    var isCallable2 = require_is_callable();
    var $String = String;
    var $TypeError = TypeError;
    module.exports = function(argument) {
      if (typeof argument == "object" || isCallable2(argument)) return argument;
      throw $TypeError("Can't set " + $String(argument) + " as a prototype");
    };
  }
});

// node_modules/core-js/internals/object-set-prototype-of.js
var require_object_set_prototype_of = __commonJS({
  "node_modules/core-js/internals/object-set-prototype-of.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var anObject3 = require_an_object();
    var aPossiblePrototype = require_a_possible_prototype();
    module.exports = Object.setPrototypeOf || ("__proto__" in {} ? function() {
      var CORRECT_SETTER = false;
      var test2 = {};
      var setter;
      try {
        setter = uncurryThis3(Object.getOwnPropertyDescriptor(Object.prototype, "__proto__").set);
        setter(test2, []);
        CORRECT_SETTER = test2 instanceof Array;
      } catch (error2) {
      }
      return function setPrototypeOf(O4, proto) {
        anObject3(O4);
        aPossiblePrototype(proto);
        if (CORRECT_SETTER) setter(O4, proto);
        else O4.__proto__ = proto;
        return O4;
      };
    }() : void 0);
  }
});

// node_modules/core-js/internals/iterator-define.js
var require_iterator_define = __commonJS({
  "node_modules/core-js/internals/iterator-define.js"(exports, module) {
    "use strict";
    var $6 = require_export();
    var call3 = require_function_call();
    var IS_PURE = require_is_pure();
    var FunctionName = require_function_name();
    var isCallable2 = require_is_callable();
    var createIteratorConstructor = require_iterator_create_constructor();
    var getPrototypeOf2 = require_object_get_prototype_of();
    var setPrototypeOf = require_object_set_prototype_of();
    var setToStringTag = require_set_to_string_tag();
    var createNonEnumerableProperty3 = require_create_non_enumerable_property();
    var defineBuiltIn2 = require_define_built_in();
    var wellKnownSymbol3 = require_well_known_symbol();
    var Iterators = require_iterators();
    var IteratorsCore = require_iterators_core();
    var PROPER_FUNCTION_NAME = FunctionName.PROPER;
    var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE;
    var IteratorPrototype = IteratorsCore.IteratorPrototype;
    var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
    var ITERATOR2 = wellKnownSymbol3("iterator");
    var KEYS = "keys";
    var VALUES = "values";
    var ENTRIES = "entries";
    var returnThis = function() {
      return this;
    };
    module.exports = function(Iterable, NAME2, IteratorConstructor, next2, DEFAULT, IS_SET, FORCED) {
      createIteratorConstructor(IteratorConstructor, NAME2, next2);
      var getIterationMethod = function(KIND) {
        if (KIND === DEFAULT && defaultIterator) return defaultIterator;
        if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
        switch (KIND) {
          case KEYS:
            return function keys5() {
              return new IteratorConstructor(this, KIND);
            };
          case VALUES:
            return function values2() {
              return new IteratorConstructor(this, KIND);
            };
          case ENTRIES:
            return function entries2() {
              return new IteratorConstructor(this, KIND);
            };
        }
        return function() {
          return new IteratorConstructor(this);
        };
      };
      var TO_STRING_TAG2 = NAME2 + " Iterator";
      var INCORRECT_VALUES_NAME = false;
      var IterablePrototype = Iterable.prototype;
      var nativeIterator = IterablePrototype[ITERATOR2] || IterablePrototype["@@iterator"] || DEFAULT && IterablePrototype[DEFAULT];
      var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
      var anyNativeIterator = NAME2 == "Array" ? IterablePrototype.entries || nativeIterator : nativeIterator;
      var CurrentIteratorPrototype, methods, KEY;
      if (anyNativeIterator) {
        CurrentIteratorPrototype = getPrototypeOf2(anyNativeIterator.call(new Iterable()));
        if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
          if (!IS_PURE && getPrototypeOf2(CurrentIteratorPrototype) !== IteratorPrototype) {
            if (setPrototypeOf) {
              setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
            } else if (!isCallable2(CurrentIteratorPrototype[ITERATOR2])) {
              defineBuiltIn2(CurrentIteratorPrototype, ITERATOR2, returnThis);
            }
          }
          setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG2, true, true);
          if (IS_PURE) Iterators[TO_STRING_TAG2] = returnThis;
        }
      }
      if (PROPER_FUNCTION_NAME && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
        if (!IS_PURE && CONFIGURABLE_FUNCTION_NAME) {
          createNonEnumerableProperty3(IterablePrototype, "name", VALUES);
        } else {
          INCORRECT_VALUES_NAME = true;
          defaultIterator = function values2() {
            return call3(nativeIterator, this);
          };
        }
      }
      if (DEFAULT) {
        methods = {
          values: getIterationMethod(VALUES),
          keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
          entries: getIterationMethod(ENTRIES)
        };
        if (FORCED) for (KEY in methods) {
          if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
            defineBuiltIn2(IterablePrototype, KEY, methods[KEY]);
          }
        }
        else $6({ target: NAME2, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
      }
      if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR2] !== defaultIterator) {
        defineBuiltIn2(IterablePrototype, ITERATOR2, defaultIterator, { name: DEFAULT });
      }
      Iterators[NAME2] = defaultIterator;
      return methods;
    };
  }
});

// node_modules/core-js/internals/create-iter-result-object.js
var require_create_iter_result_object = __commonJS({
  "node_modules/core-js/internals/create-iter-result-object.js"(exports, module) {
    module.exports = function(value2, done) {
      return { value: value2, done };
    };
  }
});

// node_modules/core-js/modules/es.array.iterator.js
var require_es_array_iterator = __commonJS({
  "node_modules/core-js/modules/es.array.iterator.js"(exports, module) {
    "use strict";
    var toIndexedObject = require_to_indexed_object();
    var addToUnscopables = require_add_to_unscopables();
    var Iterators = require_iterators();
    var InternalStateModule2 = require_internal_state();
    var defineProperty3 = require_object_define_property().f;
    var defineIterator2 = require_iterator_define();
    var createIterResultObject2 = require_create_iter_result_object();
    var IS_PURE = require_is_pure();
    var DESCRIPTORS2 = require_descriptors();
    var ARRAY_ITERATOR = "Array Iterator";
    var setInternalState2 = InternalStateModule2.set;
    var getInternalState2 = InternalStateModule2.getterFor(ARRAY_ITERATOR);
    module.exports = defineIterator2(Array, "Array", function(iterated, kind) {
      setInternalState2(this, {
        type: ARRAY_ITERATOR,
        target: toIndexedObject(iterated),
        // target
        index: 0,
        // next index
        kind
        // kind
      });
    }, function() {
      var state = getInternalState2(this);
      var target = state.target;
      var kind = state.kind;
      var index2 = state.index++;
      if (!target || index2 >= target.length) {
        state.target = void 0;
        return createIterResultObject2(void 0, true);
      }
      if (kind == "keys") return createIterResultObject2(index2, false);
      if (kind == "values") return createIterResultObject2(target[index2], false);
      return createIterResultObject2([index2, target[index2]], false);
    }, "values");
    var values2 = Iterators.Arguments = Iterators.Array;
    addToUnscopables("keys");
    addToUnscopables("values");
    addToUnscopables("entries");
    if (!IS_PURE && DESCRIPTORS2 && values2.name !== "values") try {
      defineProperty3(values2, "name", { value: "values" });
    } catch (error2) {
    }
  }
});

// node_modules/core-js/internals/string-multibyte.js
var require_string_multibyte = __commonJS({
  "node_modules/core-js/internals/string-multibyte.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var toIntegerOrInfinity2 = require_to_integer_or_infinity();
    var toString9 = require_to_string();
    var requireObjectCoercible3 = require_require_object_coercible();
    var charAt2 = uncurryThis3("".charAt);
    var charCodeAt = uncurryThis3("".charCodeAt);
    var stringSlice2 = uncurryThis3("".slice);
    var createMethod = function(CONVERT_TO_STRING) {
      return function($this, pos) {
        var S2 = toString9(requireObjectCoercible3($this));
        var position = toIntegerOrInfinity2(pos);
        var size4 = S2.length;
        var first2, second;
        if (position < 0 || position >= size4) return CONVERT_TO_STRING ? "" : void 0;
        first2 = charCodeAt(S2, position);
        return first2 < 55296 || first2 > 56319 || position + 1 === size4 || (second = charCodeAt(S2, position + 1)) < 56320 || second > 57343 ? CONVERT_TO_STRING ? charAt2(S2, position) : first2 : CONVERT_TO_STRING ? stringSlice2(S2, position, position + 2) : (first2 - 55296 << 10) + (second - 56320) + 65536;
      };
    };
    module.exports = {
      // `String.prototype.codePointAt` method
      // https://tc39.es/ecma262/#sec-string.prototype.codepointat
      codeAt: createMethod(false),
      // `String.prototype.at` method
      // https://github.com/mathiasbynens/String.prototype.at
      charAt: createMethod(true)
    };
  }
});

// node_modules/core-js/internals/define-built-ins.js
var require_define_built_ins = __commonJS({
  "node_modules/core-js/internals/define-built-ins.js"(exports, module) {
    var defineBuiltIn2 = require_define_built_in();
    module.exports = function(target, src, options2) {
      for (var key2 in src) defineBuiltIn2(target, key2, src[key2], options2);
      return target;
    };
  }
});

// node_modules/core-js/internals/create-property.js
var require_create_property = __commonJS({
  "node_modules/core-js/internals/create-property.js"(exports, module) {
    "use strict";
    var toPropertyKey = require_to_property_key();
    var definePropertyModule = require_object_define_property();
    var createPropertyDescriptor = require_create_property_descriptor();
    module.exports = function(object2, key2, value2) {
      var propertyKey = toPropertyKey(key2);
      if (propertyKey in object2) definePropertyModule.f(object2, propertyKey, createPropertyDescriptor(0, value2));
      else object2[propertyKey] = value2;
    };
  }
});

// node_modules/core-js/internals/array-slice-simple.js
var require_array_slice_simple = __commonJS({
  "node_modules/core-js/internals/array-slice-simple.js"(exports, module) {
    var toAbsoluteIndex = require_to_absolute_index();
    var lengthOfArrayLike = require_length_of_array_like();
    var createProperty = require_create_property();
    var $Array = Array;
    var max3 = Math.max;
    module.exports = function(O4, start, end) {
      var length = lengthOfArrayLike(O4);
      var k2 = toAbsoluteIndex(start, length);
      var fin = toAbsoluteIndex(end === void 0 ? length : end, length);
      var result2 = $Array(max3(fin - k2, 0));
      for (var n4 = 0; k2 < fin; k2++, n4++) createProperty(result2, n4, O4[k2]);
      result2.length = n4;
      return result2;
    };
  }
});

// node_modules/core-js/internals/object-get-own-property-names-external.js
var require_object_get_own_property_names_external = __commonJS({
  "node_modules/core-js/internals/object-get-own-property-names-external.js"(exports, module) {
    var classof = require_classof_raw();
    var toIndexedObject = require_to_indexed_object();
    var $getOwnPropertyNames = require_object_get_own_property_names().f;
    var arraySlice = require_array_slice_simple();
    var windowNames = typeof window == "object" && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [];
    var getWindowNames = function(it2) {
      try {
        return $getOwnPropertyNames(it2);
      } catch (error2) {
        return arraySlice(windowNames);
      }
    };
    module.exports.f = function getOwnPropertyNames2(it2) {
      return windowNames && classof(it2) == "Window" ? getWindowNames(it2) : $getOwnPropertyNames(toIndexedObject(it2));
    };
  }
});

// node_modules/core-js/internals/array-buffer-non-extensible.js
var require_array_buffer_non_extensible = __commonJS({
  "node_modules/core-js/internals/array-buffer-non-extensible.js"(exports, module) {
    var fails2 = require_fails();
    module.exports = fails2(function() {
      if (typeof ArrayBuffer == "function") {
        var buffer = new ArrayBuffer(8);
        if (Object.isExtensible(buffer)) Object.defineProperty(buffer, "a", { value: 8 });
      }
    });
  }
});

// node_modules/core-js/internals/object-is-extensible.js
var require_object_is_extensible = __commonJS({
  "node_modules/core-js/internals/object-is-extensible.js"(exports, module) {
    var fails2 = require_fails();
    var isObject7 = require_is_object();
    var classof = require_classof_raw();
    var ARRAY_BUFFER_NON_EXTENSIBLE = require_array_buffer_non_extensible();
    var $isExtensible = Object.isExtensible;
    var FAILS_ON_PRIMITIVES = fails2(function() {
      $isExtensible(1);
    });
    module.exports = FAILS_ON_PRIMITIVES || ARRAY_BUFFER_NON_EXTENSIBLE ? function isExtensible(it2) {
      if (!isObject7(it2)) return false;
      if (ARRAY_BUFFER_NON_EXTENSIBLE && classof(it2) == "ArrayBuffer") return false;
      return $isExtensible ? $isExtensible(it2) : true;
    } : $isExtensible;
  }
});

// node_modules/core-js/internals/freezing.js
var require_freezing = __commonJS({
  "node_modules/core-js/internals/freezing.js"(exports, module) {
    var fails2 = require_fails();
    module.exports = !fails2(function() {
      return Object.isExtensible(Object.preventExtensions({}));
    });
  }
});

// node_modules/core-js/internals/internal-metadata.js
var require_internal_metadata = __commonJS({
  "node_modules/core-js/internals/internal-metadata.js"(exports, module) {
    var $6 = require_export();
    var uncurryThis3 = require_function_uncurry_this();
    var hiddenKeys = require_hidden_keys();
    var isObject7 = require_is_object();
    var hasOwn = require_has_own_property();
    var defineProperty3 = require_object_define_property().f;
    var getOwnPropertyNamesModule = require_object_get_own_property_names();
    var getOwnPropertyNamesExternalModule = require_object_get_own_property_names_external();
    var isExtensible = require_object_is_extensible();
    var uid = require_uid();
    var FREEZING = require_freezing();
    var REQUIRED = false;
    var METADATA = uid("meta");
    var id = 0;
    var setMetadata = function(it2) {
      defineProperty3(it2, METADATA, { value: {
        objectID: "O" + id++,
        // object ID
        weakData: {}
        // weak collections IDs
      } });
    };
    var fastKey = function(it2, create6) {
      if (!isObject7(it2)) return typeof it2 == "symbol" ? it2 : (typeof it2 == "string" ? "S" : "P") + it2;
      if (!hasOwn(it2, METADATA)) {
        if (!isExtensible(it2)) return "F";
        if (!create6) return "E";
        setMetadata(it2);
      }
      return it2[METADATA].objectID;
    };
    var getWeakData = function(it2, create6) {
      if (!hasOwn(it2, METADATA)) {
        if (!isExtensible(it2)) return true;
        if (!create6) return false;
        setMetadata(it2);
      }
      return it2[METADATA].weakData;
    };
    var onFreeze = function(it2) {
      if (FREEZING && REQUIRED && isExtensible(it2) && !hasOwn(it2, METADATA)) setMetadata(it2);
      return it2;
    };
    var enable = function() {
      meta2.enable = function() {
      };
      REQUIRED = true;
      var getOwnPropertyNames2 = getOwnPropertyNamesModule.f;
      var splice = uncurryThis3([].splice);
      var test2 = {};
      test2[METADATA] = 1;
      if (getOwnPropertyNames2(test2).length) {
        getOwnPropertyNamesModule.f = function(it2) {
          var result2 = getOwnPropertyNames2(it2);
          for (var i3 = 0, length = result2.length; i3 < length; i3++) {
            if (result2[i3] === METADATA) {
              splice(result2, i3, 1);
              break;
            }
          }
          return result2;
        };
        $6({ target: "Object", stat: true, forced: true }, {
          getOwnPropertyNames: getOwnPropertyNamesExternalModule.f
        });
      }
    };
    var meta2 = module.exports = {
      enable,
      fastKey,
      getWeakData,
      onFreeze
    };
    hiddenKeys[METADATA] = true;
  }
});

// node_modules/core-js/internals/is-array-iterator-method.js
var require_is_array_iterator_method = __commonJS({
  "node_modules/core-js/internals/is-array-iterator-method.js"(exports, module) {
    var wellKnownSymbol3 = require_well_known_symbol();
    var Iterators = require_iterators();
    var ITERATOR2 = wellKnownSymbol3("iterator");
    var ArrayPrototype = Array.prototype;
    module.exports = function(it2) {
      return it2 !== void 0 && (Iterators.Array === it2 || ArrayPrototype[ITERATOR2] === it2);
    };
  }
});

// node_modules/core-js/internals/get-iterator-method.js
var require_get_iterator_method = __commonJS({
  "node_modules/core-js/internals/get-iterator-method.js"(exports, module) {
    var classof = require_classof();
    var getMethod3 = require_get_method();
    var isNullOrUndefined3 = require_is_null_or_undefined();
    var Iterators = require_iterators();
    var wellKnownSymbol3 = require_well_known_symbol();
    var ITERATOR2 = wellKnownSymbol3("iterator");
    module.exports = function(it2) {
      if (!isNullOrUndefined3(it2)) return getMethod3(it2, ITERATOR2) || getMethod3(it2, "@@iterator") || Iterators[classof(it2)];
    };
  }
});

// node_modules/core-js/internals/get-iterator.js
var require_get_iterator = __commonJS({
  "node_modules/core-js/internals/get-iterator.js"(exports, module) {
    var call3 = require_function_call();
    var aCallable = require_a_callable();
    var anObject3 = require_an_object();
    var tryToString = require_try_to_string();
    var getIteratorMethod = require_get_iterator_method();
    var $TypeError = TypeError;
    module.exports = function(argument, usingIterator) {
      var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
      if (aCallable(iteratorMethod)) return anObject3(call3(iteratorMethod, argument));
      throw $TypeError(tryToString(argument) + " is not iterable");
    };
  }
});

// node_modules/core-js/internals/iterator-close.js
var require_iterator_close = __commonJS({
  "node_modules/core-js/internals/iterator-close.js"(exports, module) {
    var call3 = require_function_call();
    var anObject3 = require_an_object();
    var getMethod3 = require_get_method();
    module.exports = function(iterator, kind, value2) {
      var innerResult, innerError;
      anObject3(iterator);
      try {
        innerResult = getMethod3(iterator, "return");
        if (!innerResult) {
          if (kind === "throw") throw value2;
          return value2;
        }
        innerResult = call3(innerResult, iterator);
      } catch (error2) {
        innerError = true;
        innerResult = error2;
      }
      if (kind === "throw") throw value2;
      if (innerError) throw innerResult;
      anObject3(innerResult);
      return value2;
    };
  }
});

// node_modules/core-js/internals/iterate.js
var require_iterate = __commonJS({
  "node_modules/core-js/internals/iterate.js"(exports, module) {
    var bind2 = require_function_bind_context();
    var call3 = require_function_call();
    var anObject3 = require_an_object();
    var tryToString = require_try_to_string();
    var isArrayIteratorMethod = require_is_array_iterator_method();
    var lengthOfArrayLike = require_length_of_array_like();
    var isPrototypeOf = require_object_is_prototype_of();
    var getIterator = require_get_iterator();
    var getIteratorMethod = require_get_iterator_method();
    var iteratorClose = require_iterator_close();
    var $TypeError = TypeError;
    var Result = function(stopped, result2) {
      this.stopped = stopped;
      this.result = result2;
    };
    var ResultPrototype = Result.prototype;
    module.exports = function(iterable, unboundFunction, options2) {
      var that = options2 && options2.that;
      var AS_ENTRIES = !!(options2 && options2.AS_ENTRIES);
      var IS_RECORD = !!(options2 && options2.IS_RECORD);
      var IS_ITERATOR = !!(options2 && options2.IS_ITERATOR);
      var INTERRUPTED = !!(options2 && options2.INTERRUPTED);
      var fn = bind2(unboundFunction, that);
      var iterator, iterFn, index2, length, result2, next2, step2;
      var stop = function(condition) {
        if (iterator) iteratorClose(iterator, "normal", condition);
        return new Result(true, condition);
      };
      var callFn = function(value2) {
        if (AS_ENTRIES) {
          anObject3(value2);
          return INTERRUPTED ? fn(value2[0], value2[1], stop) : fn(value2[0], value2[1]);
        }
        return INTERRUPTED ? fn(value2, stop) : fn(value2);
      };
      if (IS_RECORD) {
        iterator = iterable.iterator;
      } else if (IS_ITERATOR) {
        iterator = iterable;
      } else {
        iterFn = getIteratorMethod(iterable);
        if (!iterFn) throw $TypeError(tryToString(iterable) + " is not iterable");
        if (isArrayIteratorMethod(iterFn)) {
          for (index2 = 0, length = lengthOfArrayLike(iterable); length > index2; index2++) {
            result2 = callFn(iterable[index2]);
            if (result2 && isPrototypeOf(ResultPrototype, result2)) return result2;
          }
          return new Result(false);
        }
        iterator = getIterator(iterable, iterFn);
      }
      next2 = IS_RECORD ? iterable.next : iterator.next;
      while (!(step2 = call3(next2, iterator)).done) {
        try {
          result2 = callFn(step2.value);
        } catch (error2) {
          iteratorClose(iterator, "throw", error2);
        }
        if (typeof result2 == "object" && result2 && isPrototypeOf(ResultPrototype, result2)) return result2;
      }
      return new Result(false);
    };
  }
});

// node_modules/core-js/internals/an-instance.js
var require_an_instance = __commonJS({
  "node_modules/core-js/internals/an-instance.js"(exports, module) {
    var isPrototypeOf = require_object_is_prototype_of();
    var $TypeError = TypeError;
    module.exports = function(it2, Prototype) {
      if (isPrototypeOf(Prototype, it2)) return it2;
      throw $TypeError("Incorrect invocation");
    };
  }
});

// node_modules/core-js/internals/check-correctness-of-iteration.js
var require_check_correctness_of_iteration = __commonJS({
  "node_modules/core-js/internals/check-correctness-of-iteration.js"(exports, module) {
    var wellKnownSymbol3 = require_well_known_symbol();
    var ITERATOR2 = wellKnownSymbol3("iterator");
    var SAFE_CLOSING = false;
    try {
      called = 0;
      iteratorWithReturn = {
        next: function() {
          return { done: !!called++ };
        },
        "return": function() {
          SAFE_CLOSING = true;
        }
      };
      iteratorWithReturn[ITERATOR2] = function() {
        return this;
      };
      Array.from(iteratorWithReturn, function() {
        throw 2;
      });
    } catch (error2) {
    }
    var called;
    var iteratorWithReturn;
    module.exports = function(exec, SKIP_CLOSING) {
      if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
      var ITERATION_SUPPORT = false;
      try {
        var object2 = {};
        object2[ITERATOR2] = function() {
          return {
            next: function() {
              return { done: ITERATION_SUPPORT = true };
            }
          };
        };
        exec(object2);
      } catch (error2) {
      }
      return ITERATION_SUPPORT;
    };
  }
});

// node_modules/core-js/internals/inherit-if-required.js
var require_inherit_if_required = __commonJS({
  "node_modules/core-js/internals/inherit-if-required.js"(exports, module) {
    var isCallable2 = require_is_callable();
    var isObject7 = require_is_object();
    var setPrototypeOf = require_object_set_prototype_of();
    module.exports = function($this, dummy, Wrapper) {
      var NewTarget, NewTargetPrototype;
      if (
        // it can work only with native `setPrototypeOf`
        setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
        isCallable2(NewTarget = dummy.constructor) && NewTarget !== Wrapper && isObject7(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype
      ) setPrototypeOf($this, NewTargetPrototype);
      return $this;
    };
  }
});

// node_modules/core-js/internals/collection.js
var require_collection = __commonJS({
  "node_modules/core-js/internals/collection.js"(exports, module) {
    "use strict";
    var $6 = require_export();
    var global5 = require_global();
    var uncurryThis3 = require_function_uncurry_this();
    var isForced = require_is_forced();
    var defineBuiltIn2 = require_define_built_in();
    var InternalMetadataModule = require_internal_metadata();
    var iterate = require_iterate();
    var anInstance = require_an_instance();
    var isCallable2 = require_is_callable();
    var isNullOrUndefined3 = require_is_null_or_undefined();
    var isObject7 = require_is_object();
    var fails2 = require_fails();
    var checkCorrectnessOfIteration = require_check_correctness_of_iteration();
    var setToStringTag = require_set_to_string_tag();
    var inheritIfRequired = require_inherit_if_required();
    module.exports = function(CONSTRUCTOR_NAME, wrapper, common) {
      var IS_MAP = CONSTRUCTOR_NAME.indexOf("Map") !== -1;
      var IS_WEAK = CONSTRUCTOR_NAME.indexOf("Weak") !== -1;
      var ADDER = IS_MAP ? "set" : "add";
      var NativeConstructor = global5[CONSTRUCTOR_NAME];
      var NativePrototype = NativeConstructor && NativeConstructor.prototype;
      var Constructor = NativeConstructor;
      var exported = {};
      var fixMethod = function(KEY) {
        var uncurriedNativeMethod = uncurryThis3(NativePrototype[KEY]);
        defineBuiltIn2(
          NativePrototype,
          KEY,
          KEY == "add" ? function add4(value2) {
            uncurriedNativeMethod(this, value2 === 0 ? 0 : value2);
            return this;
          } : KEY == "delete" ? function(key2) {
            return IS_WEAK && !isObject7(key2) ? false : uncurriedNativeMethod(this, key2 === 0 ? 0 : key2);
          } : KEY == "get" ? function get7(key2) {
            return IS_WEAK && !isObject7(key2) ? void 0 : uncurriedNativeMethod(this, key2 === 0 ? 0 : key2);
          } : KEY == "has" ? function has4(key2) {
            return IS_WEAK && !isObject7(key2) ? false : uncurriedNativeMethod(this, key2 === 0 ? 0 : key2);
          } : function set4(key2, value2) {
            uncurriedNativeMethod(this, key2 === 0 ? 0 : key2, value2);
            return this;
          }
        );
      };
      var REPLACE2 = isForced(
        CONSTRUCTOR_NAME,
        !isCallable2(NativeConstructor) || !(IS_WEAK || NativePrototype.forEach && !fails2(function() {
          new NativeConstructor().entries().next();
        }))
      );
      if (REPLACE2) {
        Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
        InternalMetadataModule.enable();
      } else if (isForced(CONSTRUCTOR_NAME, true)) {
        var instance = new Constructor();
        var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
        var THROWS_ON_PRIMITIVES = fails2(function() {
          instance.has(1);
        });
        var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function(iterable) {
          new NativeConstructor(iterable);
        });
        var BUGGY_ZERO = !IS_WEAK && fails2(function() {
          var $instance = new NativeConstructor();
          var index2 = 5;
          while (index2--) $instance[ADDER](index2, index2);
          return !$instance.has(-0);
        });
        if (!ACCEPT_ITERABLES) {
          Constructor = wrapper(function(dummy, iterable) {
            anInstance(dummy, NativePrototype);
            var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor);
            if (!isNullOrUndefined3(iterable)) iterate(iterable, that[ADDER], { that, AS_ENTRIES: IS_MAP });
            return that;
          });
          Constructor.prototype = NativePrototype;
          NativePrototype.constructor = Constructor;
        }
        if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
          fixMethod("delete");
          fixMethod("has");
          IS_MAP && fixMethod("get");
        }
        if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
        if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;
      }
      exported[CONSTRUCTOR_NAME] = Constructor;
      $6({ global: true, constructor: true, forced: Constructor != NativeConstructor }, exported);
      setToStringTag(Constructor, CONSTRUCTOR_NAME);
      if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
      return Constructor;
    };
  }
});

// node_modules/core-js/internals/collection-weak.js
var require_collection_weak = __commonJS({
  "node_modules/core-js/internals/collection-weak.js"(exports, module) {
    "use strict";
    var uncurryThis3 = require_function_uncurry_this();
    var defineBuiltIns = require_define_built_ins();
    var getWeakData = require_internal_metadata().getWeakData;
    var anInstance = require_an_instance();
    var anObject3 = require_an_object();
    var isNullOrUndefined3 = require_is_null_or_undefined();
    var isObject7 = require_is_object();
    var iterate = require_iterate();
    var ArrayIterationModule = require_array_iteration();
    var hasOwn = require_has_own_property();
    var InternalStateModule2 = require_internal_state();
    var setInternalState2 = InternalStateModule2.set;
    var internalStateGetterFor = InternalStateModule2.getterFor;
    var find4 = ArrayIterationModule.find;
    var findIndex = ArrayIterationModule.findIndex;
    var splice = uncurryThis3([].splice);
    var id = 0;
    var uncaughtFrozenStore = function(store2) {
      return store2.frozen || (store2.frozen = new UncaughtFrozenStore());
    };
    var UncaughtFrozenStore = function() {
      this.entries = [];
    };
    var findUncaughtFrozen = function(store2, key2) {
      return find4(store2.entries, function(it2) {
        return it2[0] === key2;
      });
    };
    UncaughtFrozenStore.prototype = {
      get: function(key2) {
        var entry = findUncaughtFrozen(this, key2);
        if (entry) return entry[1];
      },
      has: function(key2) {
        return !!findUncaughtFrozen(this, key2);
      },
      set: function(key2, value2) {
        var entry = findUncaughtFrozen(this, key2);
        if (entry) entry[1] = value2;
        else this.entries.push([key2, value2]);
      },
      "delete": function(key2) {
        var index2 = findIndex(this.entries, function(it2) {
          return it2[0] === key2;
        });
        if (~index2) splice(this.entries, index2, 1);
        return !!~index2;
      }
    };
    module.exports = {
      getConstructor: function(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
        var Constructor = wrapper(function(that, iterable) {
          anInstance(that, Prototype);
          setInternalState2(that, {
            type: CONSTRUCTOR_NAME,
            id: id++,
            frozen: void 0
          });
          if (!isNullOrUndefined3(iterable)) iterate(iterable, that[ADDER], { that, AS_ENTRIES: IS_MAP });
        });
        var Prototype = Constructor.prototype;
        var getInternalState2 = internalStateGetterFor(CONSTRUCTOR_NAME);
        var define2 = function(that, key2, value2) {
          var state = getInternalState2(that);
          var data2 = getWeakData(anObject3(key2), true);
          if (data2 === true) uncaughtFrozenStore(state).set(key2, value2);
          else data2[state.id] = value2;
          return that;
        };
        defineBuiltIns(Prototype, {
          // `{ WeakMap, WeakSet }.prototype.delete(key)` methods
          // https://tc39.es/ecma262/#sec-weakmap.prototype.delete
          // https://tc39.es/ecma262/#sec-weakset.prototype.delete
          "delete": function(key2) {
            var state = getInternalState2(this);
            if (!isObject7(key2)) return false;
            var data2 = getWeakData(key2);
            if (data2 === true) return uncaughtFrozenStore(state)["delete"](key2);
            return data2 && hasOwn(data2, state.id) && delete data2[state.id];
          },
          // `{ WeakMap, WeakSet }.prototype.has(key)` methods
          // https://tc39.es/ecma262/#sec-weakmap.prototype.has
          // https://tc39.es/ecma262/#sec-weakset.prototype.has
          has: function has4(key2) {
            var state = getInternalState2(this);
            if (!isObject7(key2)) return false;
            var data2 = getWeakData(key2);
            if (data2 === true) return uncaughtFrozenStore(state).has(key2);
            return data2 && hasOwn(data2, state.id);
          }
        });
        defineBuiltIns(Prototype, IS_MAP ? {
          // `WeakMap.prototype.get(key)` method
          // https://tc39.es/ecma262/#sec-weakmap.prototype.get
          get: function get7(key2) {
            var state = getInternalState2(this);
            if (isObject7(key2)) {
              var data2 = getWeakData(key2);
              if (data2 === true) return uncaughtFrozenStore(state).get(key2);
              return data2 ? data2[state.id] : void 0;
            }
          },
          // `WeakMap.prototype.set(key, value)` method
          // https://tc39.es/ecma262/#sec-weakmap.prototype.set
          set: function set4(key2, value2) {
            return define2(this, key2, value2);
          }
        } : {
          // `WeakSet.prototype.add(value)` method
          // https://tc39.es/ecma262/#sec-weakset.prototype.add
          add: function add4(value2) {
            return define2(this, value2, true);
          }
        });
        return Constructor;
      }
    };
  }
});

// node_modules/core-js/modules/es.weak-map.constructor.js
var require_es_weak_map_constructor = __commonJS({
  "node_modules/core-js/modules/es.weak-map.constructor.js"() {
    "use strict";
    var global5 = require_global();
    var uncurryThis3 = require_function_uncurry_this();
    var defineBuiltIns = require_define_built_ins();
    var InternalMetadataModule = require_internal_metadata();
    var collection = require_collection();
    var collectionWeak = require_collection_weak();
    var isObject7 = require_is_object();
    var isExtensible = require_object_is_extensible();
    var enforceInternalState = require_internal_state().enforce;
    var NATIVE_WEAK_MAP = require_weak_map_basic_detection();
    var IS_IE11 = !global5.ActiveXObject && "ActiveXObject" in global5;
    var InternalWeakMap;
    var wrapper = function(init) {
      return function WeakMap2() {
        return init(this, arguments.length ? arguments[0] : void 0);
      };
    };
    var $WeakMap = collection("WeakMap", wrapper, collectionWeak);
    if (NATIVE_WEAK_MAP && IS_IE11) {
      InternalWeakMap = collectionWeak.getConstructor(wrapper, "WeakMap", true);
      InternalMetadataModule.enable();
      WeakMapPrototype = $WeakMap.prototype;
      nativeDelete = uncurryThis3(WeakMapPrototype["delete"]);
      nativeHas = uncurryThis3(WeakMapPrototype.has);
      nativeGet = uncurryThis3(WeakMapPrototype.get);
      nativeSet = uncurryThis3(WeakMapPrototype.set);
      defineBuiltIns(WeakMapPrototype, {
        "delete": function(key2) {
          if (isObject7(key2) && !isExtensible(key2)) {
            var state = enforceInternalState(this);
            if (!state.frozen) state.frozen = new InternalWeakMap();
            return nativeDelete(this, key2) || state.frozen["delete"](key2);
          }
          return nativeDelete(this, key2);
        },
        has: function has4(key2) {
          if (isObject7(key2) && !isExtensible(key2)) {
            var state = enforceInternalState(this);
            if (!state.frozen) state.frozen = new InternalWeakMap();
            return nativeHas(this, key2) || state.frozen.has(key2);
          }
          return nativeHas(this, key2);
        },
        get: function get7(key2) {
          if (isObject7(key2) && !isExtensible(key2)) {
            var state = enforceInternalState(this);
            if (!state.frozen) state.frozen = new InternalWeakMap();
            return nativeHas(this, key2) ? nativeGet(this, key2) : state.frozen.get(key2);
          }
          return nativeGet(this, key2);
        },
        set: function set4(key2, value2) {
          if (isObject7(key2) && !isExtensible(key2)) {
            var state = enforceInternalState(this);
            if (!state.frozen) state.frozen = new InternalWeakMap();
            nativeHas(this, key2) ? nativeSet(this, key2, value2) : state.frozen.set(key2, value2);
          } else nativeSet(this, key2, value2);
          return this;
        }
      });
    }
    var WeakMapPrototype;
    var nativeDelete;
    var nativeHas;
    var nativeGet;
    var nativeSet;
  }
});

// node_modules/lodash.throttle/index.js
var require_lodash = __commonJS({
  "node_modules/lodash.throttle/index.js"(exports, module) {
    var FUNC_ERROR_TEXT = "Expected a function";
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root3 = freeGlobal || freeSelf || Function("return this")();
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    var now = function() {
      return root3.Date.now();
    };
    function debounce4(func, wait, options2) {
      var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject7(options2)) {
        leading = !!options2.leading;
        maxing = "maxWait" in options2;
        maxWait = maxing ? nativeMax(toNumber(options2.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options2 ? !!options2.trailing : trailing;
      }
      function invokeFunc(time3) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time3;
        result2 = func.apply(thisArg, args);
        return result2;
      }
      function leadingEdge(time3) {
        lastInvokeTime = time3;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time3) : result2;
      }
      function remainingWait(time3) {
        var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, result3 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result3, maxWait - timeSinceLastInvoke) : result3;
      }
      function shouldInvoke(time3) {
        var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time3 = now();
        if (shouldInvoke(time3)) {
          return trailingEdge(time3);
        }
        timerId = setTimeout(timerExpired, remainingWait(time3));
      }
      function trailingEdge(time3) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time3);
        }
        lastArgs = lastThis = void 0;
        return result2;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush() {
        return timerId === void 0 ? result2 : trailingEdge(now());
      }
      function debounced() {
        var time3 = now(), isInvoking = shouldInvoke(time3);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time3;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result2;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    function throttle3(func, wait, options2) {
      var leading = true, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject7(options2)) {
        leading = "leading" in options2 ? !!options2.leading : leading;
        trailing = "trailing" in options2 ? !!options2.trailing : trailing;
      }
      return debounce4(func, wait, {
        "leading": leading,
        "maxWait": wait,
        "trailing": trailing
      });
    }
    function isObject7(value2) {
      var type = typeof value2;
      return !!value2 && (type == "object" || type == "function");
    }
    function isObjectLike(value2) {
      return !!value2 && typeof value2 == "object";
    }
    function isSymbol(value2) {
      return typeof value2 == "symbol" || isObjectLike(value2) && objectToString.call(value2) == symbolTag;
    }
    function toNumber(value2) {
      if (typeof value2 == "number") {
        return value2;
      }
      if (isSymbol(value2)) {
        return NAN;
      }
      if (isObject7(value2)) {
        var other = typeof value2.valueOf == "function" ? value2.valueOf() : value2;
        value2 = isObject7(other) ? other + "" : other;
      }
      if (typeof value2 != "string") {
        return value2 === 0 ? value2 : +value2;
      }
      value2 = value2.replace(reTrim, "");
      var isBinary = reIsBinary.test(value2);
      return isBinary || reIsOctal.test(value2) ? freeParseInt(value2.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value2) ? NAN : +value2;
    }
    module.exports = throttle3;
  }
});

// node_modules/lodash.debounce/index.js
var require_lodash2 = __commonJS({
  "node_modules/lodash.debounce/index.js"(exports, module) {
    var FUNC_ERROR_TEXT = "Expected a function";
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root3 = freeGlobal || freeSelf || Function("return this")();
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    var now = function() {
      return root3.Date.now();
    };
    function debounce4(func, wait, options2) {
      var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject7(options2)) {
        leading = !!options2.leading;
        maxing = "maxWait" in options2;
        maxWait = maxing ? nativeMax(toNumber(options2.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options2 ? !!options2.trailing : trailing;
      }
      function invokeFunc(time3) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time3;
        result2 = func.apply(thisArg, args);
        return result2;
      }
      function leadingEdge(time3) {
        lastInvokeTime = time3;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time3) : result2;
      }
      function remainingWait(time3) {
        var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime, result3 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result3, maxWait - timeSinceLastInvoke) : result3;
      }
      function shouldInvoke(time3) {
        var timeSinceLastCall = time3 - lastCallTime, timeSinceLastInvoke = time3 - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time3 = now();
        if (shouldInvoke(time3)) {
          return trailingEdge(time3);
        }
        timerId = setTimeout(timerExpired, remainingWait(time3));
      }
      function trailingEdge(time3) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time3);
        }
        lastArgs = lastThis = void 0;
        return result2;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush() {
        return timerId === void 0 ? result2 : trailingEdge(now());
      }
      function debounced() {
        var time3 = now(), isInvoking = shouldInvoke(time3);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time3;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result2;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    function isObject7(value2) {
      var type = typeof value2;
      return !!value2 && (type == "object" || type == "function");
    }
    function isObjectLike(value2) {
      return !!value2 && typeof value2 == "object";
    }
    function isSymbol(value2) {
      return typeof value2 == "symbol" || isObjectLike(value2) && objectToString.call(value2) == symbolTag;
    }
    function toNumber(value2) {
      if (typeof value2 == "number") {
        return value2;
      }
      if (isSymbol(value2)) {
        return NAN;
      }
      if (isObject7(value2)) {
        var other = typeof value2.valueOf == "function" ? value2.valueOf() : value2;
        value2 = isObject7(other) ? other + "" : other;
      }
      if (typeof value2 != "string") {
        return value2 === 0 ? value2 : +value2;
      }
      value2 = value2.replace(reTrim, "");
      var isBinary = reIsBinary.test(value2);
      return isBinary || reIsOctal.test(value2) ? freeParseInt(value2.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value2) ? NAN : +value2;
    }
    module.exports = debounce4;
  }
});

// node_modules/lodash.memoize/index.js
var require_lodash3 = __commonJS({
  "node_modules/lodash.memoize/index.js"(exports, module) {
    var FUNC_ERROR_TEXT = "Expected a function";
    var HASH_UNDEFINED = "__lodash_hash_undefined__";
    var funcTag = "[object Function]";
    var genTag = "[object GeneratorFunction]";
    var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
    var reIsHostCtor = /^\[object .+?Constructor\]$/;
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root3 = freeGlobal || freeSelf || Function("return this")();
    function getValue2(object2, key2) {
      return object2 == null ? void 0 : object2[key2];
    }
    function isHostObject(value2) {
      var result2 = false;
      if (value2 != null && typeof value2.toString != "function") {
        try {
          result2 = !!(value2 + "");
        } catch (e3) {
        }
      }
      return result2;
    }
    var arrayProto = Array.prototype;
    var funcProto = Function.prototype;
    var objectProto = Object.prototype;
    var coreJsData = root3["__core-js_shared__"];
    var maskSrcKey = function() {
      var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
      return uid ? "Symbol(src)_1." + uid : "";
    }();
    var funcToString = funcProto.toString;
    var hasOwnProperty5 = objectProto.hasOwnProperty;
    var objectToString = objectProto.toString;
    var reIsNative = RegExp(
      "^" + funcToString.call(hasOwnProperty5).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
    );
    var splice = arrayProto.splice;
    var Map2 = getNative(root3, "Map");
    var nativeCreate2 = getNative(Object, "create");
    function Hash(entries2) {
      var index2 = -1, length = entries2 ? entries2.length : 0;
      this.clear();
      while (++index2 < length) {
        var entry = entries2[index2];
        this.set(entry[0], entry[1]);
      }
    }
    function hashClear() {
      this.__data__ = nativeCreate2 ? nativeCreate2(null) : {};
    }
    function hashDelete(key2) {
      return this.has(key2) && delete this.__data__[key2];
    }
    function hashGet(key2) {
      var data2 = this.__data__;
      if (nativeCreate2) {
        var result2 = data2[key2];
        return result2 === HASH_UNDEFINED ? void 0 : result2;
      }
      return hasOwnProperty5.call(data2, key2) ? data2[key2] : void 0;
    }
    function hashHas(key2) {
      var data2 = this.__data__;
      return nativeCreate2 ? data2[key2] !== void 0 : hasOwnProperty5.call(data2, key2);
    }
    function hashSet(key2, value2) {
      var data2 = this.__data__;
      data2[key2] = nativeCreate2 && value2 === void 0 ? HASH_UNDEFINED : value2;
      return this;
    }
    Hash.prototype.clear = hashClear;
    Hash.prototype["delete"] = hashDelete;
    Hash.prototype.get = hashGet;
    Hash.prototype.has = hashHas;
    Hash.prototype.set = hashSet;
    function ListCache(entries2) {
      var index2 = -1, length = entries2 ? entries2.length : 0;
      this.clear();
      while (++index2 < length) {
        var entry = entries2[index2];
        this.set(entry[0], entry[1]);
      }
    }
    function listCacheClear() {
      this.__data__ = [];
    }
    function listCacheDelete(key2) {
      var data2 = this.__data__, index2 = assocIndexOf(data2, key2);
      if (index2 < 0) {
        return false;
      }
      var lastIndex = data2.length - 1;
      if (index2 == lastIndex) {
        data2.pop();
      } else {
        splice.call(data2, index2, 1);
      }
      return true;
    }
    function listCacheGet(key2) {
      var data2 = this.__data__, index2 = assocIndexOf(data2, key2);
      return index2 < 0 ? void 0 : data2[index2][1];
    }
    function listCacheHas(key2) {
      return assocIndexOf(this.__data__, key2) > -1;
    }
    function listCacheSet(key2, value2) {
      var data2 = this.__data__, index2 = assocIndexOf(data2, key2);
      if (index2 < 0) {
        data2.push([key2, value2]);
      } else {
        data2[index2][1] = value2;
      }
      return this;
    }
    ListCache.prototype.clear = listCacheClear;
    ListCache.prototype["delete"] = listCacheDelete;
    ListCache.prototype.get = listCacheGet;
    ListCache.prototype.has = listCacheHas;
    ListCache.prototype.set = listCacheSet;
    function MapCache(entries2) {
      var index2 = -1, length = entries2 ? entries2.length : 0;
      this.clear();
      while (++index2 < length) {
        var entry = entries2[index2];
        this.set(entry[0], entry[1]);
      }
    }
    function mapCacheClear() {
      this.__data__ = {
        "hash": new Hash(),
        "map": new (Map2 || ListCache)(),
        "string": new Hash()
      };
    }
    function mapCacheDelete(key2) {
      return getMapData(this, key2)["delete"](key2);
    }
    function mapCacheGet(key2) {
      return getMapData(this, key2).get(key2);
    }
    function mapCacheHas(key2) {
      return getMapData(this, key2).has(key2);
    }
    function mapCacheSet(key2, value2) {
      getMapData(this, key2).set(key2, value2);
      return this;
    }
    MapCache.prototype.clear = mapCacheClear;
    MapCache.prototype["delete"] = mapCacheDelete;
    MapCache.prototype.get = mapCacheGet;
    MapCache.prototype.has = mapCacheHas;
    MapCache.prototype.set = mapCacheSet;
    function assocIndexOf(array, key2) {
      var length = array.length;
      while (length--) {
        if (eq2(array[length][0], key2)) {
          return length;
        }
      }
      return -1;
    }
    function baseIsNative(value2) {
      if (!isObject7(value2) || isMasked(value2)) {
        return false;
      }
      var pattern2 = isFunction4(value2) || isHostObject(value2) ? reIsNative : reIsHostCtor;
      return pattern2.test(toSource(value2));
    }
    function getMapData(map5, key2) {
      var data2 = map5.__data__;
      return isKeyable(key2) ? data2[typeof key2 == "string" ? "string" : "hash"] : data2.map;
    }
    function getNative(object2, key2) {
      var value2 = getValue2(object2, key2);
      return baseIsNative(value2) ? value2 : void 0;
    }
    function isKeyable(value2) {
      var type = typeof value2;
      return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value2 !== "__proto__" : value2 === null;
    }
    function isMasked(func) {
      return !!maskSrcKey && maskSrcKey in func;
    }
    function toSource(func) {
      if (func != null) {
        try {
          return funcToString.call(func);
        } catch (e3) {
        }
        try {
          return func + "";
        } catch (e3) {
        }
      }
      return "";
    }
    function memoize4(func, resolver) {
      if (typeof func != "function" || resolver && typeof resolver != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      var memoized = function() {
        var args = arguments, key2 = resolver ? resolver.apply(this, args) : args[0], cache5 = memoized.cache;
        if (cache5.has(key2)) {
          return cache5.get(key2);
        }
        var result2 = func.apply(this, args);
        memoized.cache = cache5.set(key2, result2);
        return result2;
      };
      memoized.cache = new (memoize4.Cache || MapCache)();
      return memoized;
    }
    memoize4.Cache = MapCache;
    function eq2(value2, other) {
      return value2 === other || value2 !== value2 && other !== other;
    }
    function isFunction4(value2) {
      var tag = isObject7(value2) ? objectToString.call(value2) : "";
      return tag == funcTag || tag == genTag;
    }
    function isObject7(value2) {
      var type = typeof value2;
      return !!value2 && (type == "object" || type == "function");
    }
    module.exports = memoize4;
  }
});

// node_modules/core-js/internals/array-reduce.js
var require_array_reduce = __commonJS({
  "node_modules/core-js/internals/array-reduce.js"(exports, module) {
    var aCallable = require_a_callable();
    var toObject = require_to_object();
    var IndexedObject = require_indexed_object();
    var lengthOfArrayLike = require_length_of_array_like();
    var $TypeError = TypeError;
    var createMethod = function(IS_RIGHT) {
      return function(that, callbackfn, argumentsLength, memo) {
        aCallable(callbackfn);
        var O4 = toObject(that);
        var self2 = IndexedObject(O4);
        var length = lengthOfArrayLike(O4);
        var index2 = IS_RIGHT ? length - 1 : 0;
        var i3 = IS_RIGHT ? -1 : 1;
        if (argumentsLength < 2) while (true) {
          if (index2 in self2) {
            memo = self2[index2];
            index2 += i3;
            break;
          }
          index2 += i3;
          if (IS_RIGHT ? index2 < 0 : length <= index2) {
            throw $TypeError("Reduce of empty array with no initial value");
          }
        }
        for (; IS_RIGHT ? index2 >= 0 : length > index2; index2 += i3) if (index2 in self2) {
          memo = callbackfn(memo, self2[index2], index2, O4);
        }
        return memo;
      };
    };
    module.exports = {
      // `Array.prototype.reduce` method
      // https://tc39.es/ecma262/#sec-array.prototype.reduce
      left: createMethod(false),
      // `Array.prototype.reduceRight` method
      // https://tc39.es/ecma262/#sec-array.prototype.reduceright
      right: createMethod(true)
    };
  }
});

// node_modules/core-js/internals/engine-is-node.js
var require_engine_is_node = __commonJS({
  "node_modules/core-js/internals/engine-is-node.js"(exports, module) {
    var classof = require_classof_raw();
    var global5 = require_global();
    module.exports = classof(global5.process) == "process";
  }
});

// node_modules/core-js/internals/regexp-flags.js
var require_regexp_flags = __commonJS({
  "node_modules/core-js/internals/regexp-flags.js"(exports, module) {
    "use strict";
    var anObject3 = require_an_object();
    module.exports = function() {
      var that = anObject3(this);
      var result2 = "";
      if (that.hasIndices) result2 += "d";
      if (that.global) result2 += "g";
      if (that.ignoreCase) result2 += "i";
      if (that.multiline) result2 += "m";
      if (that.dotAll) result2 += "s";
      if (that.unicode) result2 += "u";
      if (that.unicodeSets) result2 += "v";
      if (that.sticky) result2 += "y";
      return result2;
    };
  }
});

// node_modules/core-js/internals/regexp-sticky-helpers.js
var require_regexp_sticky_helpers = __commonJS({
  "node_modules/core-js/internals/regexp-sticky-helpers.js"(exports, module) {
    var fails2 = require_fails();
    var global5 = require_global();
    var $RegExp = global5.RegExp;
    var UNSUPPORTED_Y = fails2(function() {
      var re2 = $RegExp("a", "y");
      re2.lastIndex = 2;
      return re2.exec("abcd") != null;
    });
    var MISSED_STICKY = UNSUPPORTED_Y || fails2(function() {
      return !$RegExp("a", "y").sticky;
    });
    var BROKEN_CARET = UNSUPPORTED_Y || fails2(function() {
      var re2 = $RegExp("^r", "gy");
      re2.lastIndex = 2;
      return re2.exec("str") != null;
    });
    module.exports = {
      BROKEN_CARET,
      MISSED_STICKY,
      UNSUPPORTED_Y
    };
  }
});

// node_modules/core-js/internals/regexp-unsupported-dot-all.js
var require_regexp_unsupported_dot_all = __commonJS({
  "node_modules/core-js/internals/regexp-unsupported-dot-all.js"(exports, module) {
    var fails2 = require_fails();
    var global5 = require_global();
    var $RegExp = global5.RegExp;
    module.exports = fails2(function() {
      var re2 = $RegExp(".", "s");
      return !(re2.dotAll && re2.exec("\n") && re2.flags === "s");
    });
  }
});

// node_modules/core-js/internals/regexp-unsupported-ncg.js
var require_regexp_unsupported_ncg = __commonJS({
  "node_modules/core-js/internals/regexp-unsupported-ncg.js"(exports, module) {
    var fails2 = require_fails();
    var global5 = require_global();
    var $RegExp = global5.RegExp;
    module.exports = fails2(function() {
      var re2 = $RegExp("(?<a>b)", "g");
      return re2.exec("b").groups.a !== "b" || "b".replace(re2, "$<a>c") !== "bc";
    });
  }
});

// node_modules/core-js/internals/regexp-exec.js
var require_regexp_exec = __commonJS({
  "node_modules/core-js/internals/regexp-exec.js"(exports, module) {
    "use strict";
    var call3 = require_function_call();
    var uncurryThis3 = require_function_uncurry_this();
    var toString9 = require_to_string();
    var regexpFlags = require_regexp_flags();
    var stickyHelpers = require_regexp_sticky_helpers();
    var shared = require_shared();
    var create6 = require_object_create();
    var getInternalState2 = require_internal_state().get;
    var UNSUPPORTED_DOT_ALL = require_regexp_unsupported_dot_all();
    var UNSUPPORTED_NCG = require_regexp_unsupported_ncg();
    var nativeReplace = shared("native-string-replace", String.prototype.replace);
    var nativeExec = RegExp.prototype.exec;
    var patchedExec = nativeExec;
    var charAt2 = uncurryThis3("".charAt);
    var indexOf = uncurryThis3("".indexOf);
    var replace4 = uncurryThis3("".replace);
    var stringSlice2 = uncurryThis3("".slice);
    var UPDATES_LAST_INDEX_WRONG = function() {
      var re1 = /a/;
      var re2 = /b*/g;
      call3(nativeExec, re1, "a");
      call3(nativeExec, re2, "a");
      return re1.lastIndex !== 0 || re2.lastIndex !== 0;
    }();
    var UNSUPPORTED_Y = stickyHelpers.BROKEN_CARET;
    var NPCG_INCLUDED = /()??/.exec("")[1] !== void 0;
    var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y || UNSUPPORTED_DOT_ALL || UNSUPPORTED_NCG;
    if (PATCH) {
      patchedExec = function exec(string3) {
        var re2 = this;
        var state = getInternalState2(re2);
        var str = toString9(string3);
        var raw2 = state.raw;
        var result2, reCopy, lastIndex, match2, i3, object2, group2;
        if (raw2) {
          raw2.lastIndex = re2.lastIndex;
          result2 = call3(patchedExec, raw2, str);
          re2.lastIndex = raw2.lastIndex;
          return result2;
        }
        var groups = state.groups;
        var sticky = UNSUPPORTED_Y && re2.sticky;
        var flags = call3(regexpFlags, re2);
        var source = re2.source;
        var charsAdded = 0;
        var strCopy = str;
        if (sticky) {
          flags = replace4(flags, "y", "");
          if (indexOf(flags, "g") === -1) {
            flags += "g";
          }
          strCopy = stringSlice2(str, re2.lastIndex);
          if (re2.lastIndex > 0 && (!re2.multiline || re2.multiline && charAt2(str, re2.lastIndex - 1) !== "\n")) {
            source = "(?: " + source + ")";
            strCopy = " " + strCopy;
            charsAdded++;
          }
          reCopy = new RegExp("^(?:" + source + ")", flags);
        }
        if (NPCG_INCLUDED) {
          reCopy = new RegExp("^" + source + "$(?!\\s)", flags);
        }
        if (UPDATES_LAST_INDEX_WRONG) lastIndex = re2.lastIndex;
        match2 = call3(nativeExec, sticky ? reCopy : re2, strCopy);
        if (sticky) {
          if (match2) {
            match2.input = stringSlice2(match2.input, charsAdded);
            match2[0] = stringSlice2(match2[0], charsAdded);
            match2.index = re2.lastIndex;
            re2.lastIndex += match2[0].length;
          } else re2.lastIndex = 0;
        } else if (UPDATES_LAST_INDEX_WRONG && match2) {
          re2.lastIndex = re2.global ? match2.index + match2[0].length : lastIndex;
        }
        if (NPCG_INCLUDED && match2 && match2.length > 1) {
          call3(nativeReplace, match2[0], reCopy, function() {
            for (i3 = 1; i3 < arguments.length - 2; i3++) {
              if (arguments[i3] === void 0) match2[i3] = void 0;
            }
          });
        }
        if (match2 && groups) {
          match2.groups = object2 = create6(null);
          for (i3 = 0; i3 < groups.length; i3++) {
            group2 = groups[i3];
            object2[group2[0]] = match2[group2[1]];
          }
        }
        return match2;
      };
    }
    module.exports = patchedExec;
  }
});

// node_modules/core-js/modules/es.regexp.exec.js
var require_es_regexp_exec = __commonJS({
  "node_modules/core-js/modules/es.regexp.exec.js"() {
    "use strict";
    var $6 = require_export();
    var exec = require_regexp_exec();
    $6({ target: "RegExp", proto: true, forced: /./.exec !== exec }, {
      exec
    });
  }
});

// node_modules/core-js/internals/fix-regexp-well-known-symbol-logic.js
var require_fix_regexp_well_known_symbol_logic = __commonJS({
  "node_modules/core-js/internals/fix-regexp-well-known-symbol-logic.js"(exports, module) {
    "use strict";
    require_es_regexp_exec();
    var uncurryThis3 = require_function_uncurry_this();
    var defineBuiltIn2 = require_define_built_in();
    var regexpExec = require_regexp_exec();
    var fails2 = require_fails();
    var wellKnownSymbol3 = require_well_known_symbol();
    var createNonEnumerableProperty3 = require_create_non_enumerable_property();
    var SPECIES = wellKnownSymbol3("species");
    var RegExpPrototype = RegExp.prototype;
    module.exports = function(KEY, exec, FORCED, SHAM) {
      var SYMBOL = wellKnownSymbol3(KEY);
      var DELEGATES_TO_SYMBOL = !fails2(function() {
        var O4 = {};
        O4[SYMBOL] = function() {
          return 7;
        };
        return ""[KEY](O4) != 7;
      });
      var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails2(function() {
        var execCalled = false;
        var re2 = /a/;
        if (KEY === "split") {
          re2 = {};
          re2.constructor = {};
          re2.constructor[SPECIES] = function() {
            return re2;
          };
          re2.flags = "";
          re2[SYMBOL] = /./[SYMBOL];
        }
        re2.exec = function() {
          execCalled = true;
          return null;
        };
        re2[SYMBOL]("");
        return !execCalled;
      });
      if (!DELEGATES_TO_SYMBOL || !DELEGATES_TO_EXEC || FORCED) {
        var uncurriedNativeRegExpMethod = uncurryThis3(/./[SYMBOL]);
        var methods = exec(SYMBOL, ""[KEY], function(nativeMethod, regexp, str, arg2, forceStringMethod) {
          var uncurriedNativeMethod = uncurryThis3(nativeMethod);
          var $exec = regexp.exec;
          if ($exec === regexpExec || $exec === RegExpPrototype.exec) {
            if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
              return { done: true, value: uncurriedNativeRegExpMethod(regexp, str, arg2) };
            }
            return { done: true, value: uncurriedNativeMethod(str, regexp, arg2) };
          }
          return { done: false };
        });
        defineBuiltIn2(String.prototype, KEY, methods[0]);
        defineBuiltIn2(RegExpPrototype, SYMBOL, methods[1]);
      }
      if (SHAM) createNonEnumerableProperty3(RegExpPrototype[SYMBOL], "sham", true);
    };
  }
});

// node_modules/core-js/internals/advance-string-index.js
var require_advance_string_index = __commonJS({
  "node_modules/core-js/internals/advance-string-index.js"(exports, module) {
    "use strict";
    var charAt2 = require_string_multibyte().charAt;
    module.exports = function(S2, index2, unicode) {
      return index2 + (unicode ? charAt2(S2, index2).length : 1);
    };
  }
});

// node_modules/core-js/internals/regexp-exec-abstract.js
var require_regexp_exec_abstract = __commonJS({
  "node_modules/core-js/internals/regexp-exec-abstract.js"(exports, module) {
    var call3 = require_function_call();
    var anObject3 = require_an_object();
    var isCallable2 = require_is_callable();
    var classof = require_classof_raw();
    var regexpExec = require_regexp_exec();
    var $TypeError = TypeError;
    module.exports = function(R2, S2) {
      var exec = R2.exec;
      if (isCallable2(exec)) {
        var result2 = call3(exec, R2, S2);
        if (result2 !== null) anObject3(result2);
        return result2;
      }
      if (classof(R2) === "RegExp") return call3(regexpExec, R2, S2);
      throw $TypeError("RegExp#exec called on incompatible receiver");
    };
  }
});

// node_modules/core-js/internals/function-apply.js
var require_function_apply = __commonJS({
  "node_modules/core-js/internals/function-apply.js"(exports, module) {
    var NATIVE_BIND = require_function_bind_native();
    var FunctionPrototype2 = Function.prototype;
    var apply3 = FunctionPrototype2.apply;
    var call3 = FunctionPrototype2.call;
    module.exports = typeof Reflect == "object" && Reflect.apply || (NATIVE_BIND ? call3.bind(apply3) : function() {
      return call3.apply(apply3, arguments);
    });
  }
});

// node_modules/core-js/internals/get-substitution.js
var require_get_substitution = __commonJS({
  "node_modules/core-js/internals/get-substitution.js"(exports, module) {
    var uncurryThis3 = require_function_uncurry_this();
    var toObject = require_to_object();
    var floor2 = Math.floor;
    var charAt2 = uncurryThis3("".charAt);
    var replace4 = uncurryThis3("".replace);
    var stringSlice2 = uncurryThis3("".slice);
    var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d{1,2}|<[^>]*>)/g;
    var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d{1,2})/g;
    module.exports = function(matched, str, position, captures, namedCaptures, replacement) {
      var tailPos = position + matched.length;
      var m3 = captures.length;
      var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
      if (namedCaptures !== void 0) {
        namedCaptures = toObject(namedCaptures);
        symbols = SUBSTITUTION_SYMBOLS;
      }
      return replace4(replacement, symbols, function(match2, ch) {
        var capture;
        switch (charAt2(ch, 0)) {
          case "$":
            return "$";
          case "&":
            return matched;
          case "`":
            return stringSlice2(str, 0, position);
          case "'":
            return stringSlice2(str, tailPos);
          case "<":
            capture = namedCaptures[stringSlice2(ch, 1, -1)];
            break;
          default:
            var n4 = +ch;
            if (n4 === 0) return match2;
            if (n4 > m3) {
              var f3 = floor2(n4 / 10);
              if (f3 === 0) return match2;
              if (f3 <= m3) return captures[f3 - 1] === void 0 ? charAt2(ch, 1) : captures[f3 - 1] + charAt2(ch, 1);
              return match2;
            }
            capture = captures[n4 - 1];
        }
        return capture === void 0 ? "" : capture;
      });
    };
  }
});

// node_modules/dompurify/dist/purify.js
var require_purify = __commonJS({
  "node_modules/dompurify/dist/purify.js"(exports, module) {
    (function(global5, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global5 = typeof globalThis !== "undefined" ? globalThis : global5 || self, global5.DOMPurify = factory());
    })(exports, function() {
      "use strict";
      function _typeof(obj) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) {
          return typeof obj2;
        } : function(obj2) {
          return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
        }, _typeof(obj);
      }
      function _setPrototypeOf(o3, p4) {
        _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o4, p5) {
          o4.__proto__ = p5;
          return o4;
        };
        return _setPrototypeOf(o3, p4);
      }
      function _isNativeReflectConstruct() {
        if (typeof Reflect === "undefined" || !Reflect.construct) return false;
        if (Reflect.construct.sham) return false;
        if (typeof Proxy === "function") return true;
        try {
          Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
          }));
          return true;
        } catch (e3) {
          return false;
        }
      }
      function _construct(Parent, args, Class) {
        if (_isNativeReflectConstruct()) {
          _construct = Reflect.construct;
        } else {
          _construct = function _construct2(Parent2, args2, Class2) {
            var a3 = [null];
            a3.push.apply(a3, args2);
            var Constructor = Function.bind.apply(Parent2, a3);
            var instance = new Constructor();
            if (Class2) _setPrototypeOf(instance, Class2.prototype);
            return instance;
          };
        }
        return _construct.apply(null, arguments);
      }
      function _toConsumableArray(arr) {
        return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
      }
      function _arrayWithoutHoles(arr) {
        if (Array.isArray(arr)) return _arrayLikeToArray(arr);
      }
      function _iterableToArray(iter) {
        if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
      }
      function _unsupportedIterableToArray(o3, minLen) {
        if (!o3) return;
        if (typeof o3 === "string") return _arrayLikeToArray(o3, minLen);
        var n4 = Object.prototype.toString.call(o3).slice(8, -1);
        if (n4 === "Object" && o3.constructor) n4 = o3.constructor.name;
        if (n4 === "Map" || n4 === "Set") return Array.from(o3);
        if (n4 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n4)) return _arrayLikeToArray(o3, minLen);
      }
      function _arrayLikeToArray(arr, len) {
        if (len == null || len > arr.length) len = arr.length;
        for (var i3 = 0, arr2 = new Array(len); i3 < len; i3++) arr2[i3] = arr[i3];
        return arr2;
      }
      function _nonIterableSpread() {
        throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
      }
      var hasOwnProperty5 = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf2 = Object.getPrototypeOf, getOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
      var freeze2 = Object.freeze, seal = Object.seal, create6 = Object.create;
      var _ref = typeof Reflect !== "undefined" && Reflect, apply3 = _ref.apply, construct = _ref.construct;
      if (!apply3) {
        apply3 = function apply4(fun, thisValue, args) {
          return fun.apply(thisValue, args);
        };
      }
      if (!freeze2) {
        freeze2 = function freeze3(x3) {
          return x3;
        };
      }
      if (!seal) {
        seal = function seal2(x3) {
          return x3;
        };
      }
      if (!construct) {
        construct = function construct2(Func, args) {
          return _construct(Func, _toConsumableArray(args));
        };
      }
      var arrayForEach = unapply(Array.prototype.forEach);
      var arrayPop = unapply(Array.prototype.pop);
      var arrayPush = unapply(Array.prototype.push);
      var stringToLowerCase = unapply(String.prototype.toLowerCase);
      var stringToString = unapply(String.prototype.toString);
      var stringMatch = unapply(String.prototype.match);
      var stringReplace = unapply(String.prototype.replace);
      var stringIndexOf2 = unapply(String.prototype.indexOf);
      var stringTrim = unapply(String.prototype.trim);
      var regExpTest = unapply(RegExp.prototype.test);
      var typeErrorCreate = unconstruct(TypeError);
      function unapply(func) {
        return function(thisArg) {
          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
          }
          return apply3(func, thisArg, args);
        };
      }
      function unconstruct(func) {
        return function() {
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          return construct(func, args);
        };
      }
      function addToSet(set4, array, transformCaseFunc) {
        transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
        if (setPrototypeOf) {
          setPrototypeOf(set4, null);
        }
        var l3 = array.length;
        while (l3--) {
          var element2 = array[l3];
          if (typeof element2 === "string") {
            var lcElement = transformCaseFunc(element2);
            if (lcElement !== element2) {
              if (!isFrozen(array)) {
                array[l3] = lcElement;
              }
              element2 = lcElement;
            }
          }
          set4[element2] = true;
        }
        return set4;
      }
      function clone3(object2) {
        var newObject = create6(null);
        var property2;
        for (property2 in object2) {
          if (apply3(hasOwnProperty5, object2, [property2]) === true) {
            newObject[property2] = object2[property2];
          }
        }
        return newObject;
      }
      function lookupGetter(object2, prop2) {
        while (object2 !== null) {
          var desc = getOwnPropertyDescriptor2(object2, prop2);
          if (desc) {
            if (desc.get) {
              return unapply(desc.get);
            }
            if (typeof desc.value === "function") {
              return unapply(desc.value);
            }
          }
          object2 = getPrototypeOf2(object2);
        }
        function fallbackValue(element2) {
          console.warn("fallback value for", element2);
          return null;
        }
        return fallbackValue;
      }
      var html$1 = freeze2(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]);
      var svg$1 = freeze2(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]);
      var svgFilters = freeze2(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]);
      var svgDisallowed = freeze2(["animate", "color-profile", "cursor", "discard", "fedropshadow", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]);
      var mathMl$1 = freeze2(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover"]);
      var mathMlDisallowed = freeze2(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]);
      var text3 = freeze2(["#text"]);
      var html5 = freeze2(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "xmlns", "slot"]);
      var svg4 = freeze2(["accent-height", "accumulate", "additive", "alignment-baseline", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]);
      var mathMl = freeze2(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]);
      var xml2 = freeze2(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]);
      var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
      var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
      var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
      var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
      var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
      var IS_ALLOWED_URI = seal(
        /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
        // eslint-disable-line no-useless-escape
      );
      var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
      var ATTR_WHITESPACE = seal(
        /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
        // eslint-disable-line no-control-regex
      );
      var DOCTYPE_NAME = seal(/^html$/i);
      var getGlobal = function getGlobal2() {
        return typeof window === "undefined" ? null : window;
      };
      var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, document2) {
        if (_typeof(trustedTypes) !== "object" || typeof trustedTypes.createPolicy !== "function") {
          return null;
        }
        var suffix = null;
        var ATTR_NAME = "data-tt-policy-suffix";
        if (document2.currentScript && document2.currentScript.hasAttribute(ATTR_NAME)) {
          suffix = document2.currentScript.getAttribute(ATTR_NAME);
        }
        var policyName = "dompurify" + (suffix ? "#" + suffix : "");
        try {
          return trustedTypes.createPolicy(policyName, {
            createHTML: function createHTML(html6) {
              return html6;
            },
            createScriptURL: function createScriptURL(scriptUrl) {
              return scriptUrl;
            }
          });
        } catch (_5) {
          console.warn("TrustedTypes policy " + policyName + " could not be created.");
          return null;
        }
      };
      function createDOMPurify() {
        var window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
        var DOMPurify3 = function DOMPurify4(root3) {
          return createDOMPurify(root3);
        };
        DOMPurify3.version = "2.4.3";
        DOMPurify3.removed = [];
        if (!window2 || !window2.document || window2.document.nodeType !== 9) {
          DOMPurify3.isSupported = false;
          return DOMPurify3;
        }
        var originalDocument = window2.document;
        var document2 = window2.document;
        var DocumentFragment2 = window2.DocumentFragment, HTMLTemplateElement = window2.HTMLTemplateElement, Node3 = window2.Node, Element2 = window2.Element, NodeFilter = window2.NodeFilter, _window$NamedNodeMap = window2.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window2.NamedNodeMap || window2.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window2.HTMLFormElement, DOMParser2 = window2.DOMParser, trustedTypes = window2.trustedTypes;
        var ElementPrototype = Element2.prototype;
        var cloneNode = lookupGetter(ElementPrototype, "cloneNode");
        var getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
        var getChildNodes = lookupGetter(ElementPrototype, "childNodes");
        var getParentNode = lookupGetter(ElementPrototype, "parentNode");
        if (typeof HTMLTemplateElement === "function") {
          var template3 = document2.createElement("template");
          if (template3.content && template3.content.ownerDocument) {
            document2 = template3.content.ownerDocument;
          }
        }
        var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
        var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML("") : "";
        var _document = document2, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
        var importNode = originalDocument.importNode;
        var documentMode = {};
        try {
          documentMode = clone3(document2).documentMode ? document2.documentMode : {};
        } catch (_5) {
        }
        var hooks = {};
        DOMPurify3.isSupported = typeof getParentNode === "function" && implementation && typeof implementation.createHTMLDocument !== "undefined" && documentMode !== 9;
        var MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, TMPLIT_EXPR$1 = TMPLIT_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
        var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
        var ALLOWED_TAGS = null;
        var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text3)));
        var ALLOWED_ATTR = null;
        var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html5), _toConsumableArray(svg4), _toConsumableArray(mathMl), _toConsumableArray(xml2)));
        var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
          tagNameCheck: {
            writable: true,
            configurable: false,
            enumerable: true,
            value: null
          },
          attributeNameCheck: {
            writable: true,
            configurable: false,
            enumerable: true,
            value: null
          },
          allowCustomizedBuiltInElements: {
            writable: true,
            configurable: false,
            enumerable: true,
            value: false
          }
        }));
        var FORBID_TAGS = null;
        var FORBID_ATTR = null;
        var ALLOW_ARIA_ATTR = true;
        var ALLOW_DATA_ATTR = true;
        var ALLOW_UNKNOWN_PROTOCOLS = false;
        var SAFE_FOR_TEMPLATES = false;
        var WHOLE_DOCUMENT = false;
        var SET_CONFIG = false;
        var FORCE_BODY = false;
        var RETURN_DOM = false;
        var RETURN_DOM_FRAGMENT = false;
        var RETURN_TRUSTED_TYPE = false;
        var SANITIZE_DOM = true;
        var SANITIZE_NAMED_PROPS = false;
        var SANITIZE_NAMED_PROPS_PREFIX = "user-content-";
        var KEEP_CONTENT = true;
        var IN_PLACE = false;
        var USE_PROFILES = {};
        var FORBID_CONTENTS = null;
        var DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
        var DATA_URI_TAGS = null;
        var DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
        var URI_SAFE_ATTRIBUTES = null;
        var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
        var MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
        var SVG_NAMESPACE2 = "http://www.w3.org/2000/svg";
        var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
        var NAMESPACE = HTML_NAMESPACE;
        var IS_EMPTY_INPUT = false;
        var ALLOWED_NAMESPACES = null;
        var DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE2, HTML_NAMESPACE], stringToString);
        var PARSER_MEDIA_TYPE;
        var SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"];
        var DEFAULT_PARSER_MEDIA_TYPE = "text/html";
        var transformCaseFunc;
        var CONFIG = null;
        var formElement = document2.createElement("form");
        var isRegexOrFunction = function isRegexOrFunction2(testValue) {
          return testValue instanceof RegExp || testValue instanceof Function;
        };
        var _parseConfig = function _parseConfig2(cfg) {
          if (CONFIG && CONFIG === cfg) {
            return;
          }
          if (!cfg || _typeof(cfg) !== "object") {
            cfg = {};
          }
          cfg = clone3(cfg);
          PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
          SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
          transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase;
          ALLOWED_TAGS = "ALLOWED_TAGS" in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
          ALLOWED_ATTR = "ALLOWED_ATTR" in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
          ALLOWED_NAMESPACES = "ALLOWED_NAMESPACES" in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
          URI_SAFE_ATTRIBUTES = "ADD_URI_SAFE_ATTR" in cfg ? addToSet(
            clone3(DEFAULT_URI_SAFE_ATTRIBUTES),
            // eslint-disable-line indent
            cfg.ADD_URI_SAFE_ATTR,
            // eslint-disable-line indent
            transformCaseFunc
            // eslint-disable-line indent
          ) : DEFAULT_URI_SAFE_ATTRIBUTES;
          DATA_URI_TAGS = "ADD_DATA_URI_TAGS" in cfg ? addToSet(
            clone3(DEFAULT_DATA_URI_TAGS),
            // eslint-disable-line indent
            cfg.ADD_DATA_URI_TAGS,
            // eslint-disable-line indent
            transformCaseFunc
            // eslint-disable-line indent
          ) : DEFAULT_DATA_URI_TAGS;
          FORBID_CONTENTS = "FORBID_CONTENTS" in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
          FORBID_TAGS = "FORBID_TAGS" in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
          FORBID_ATTR = "FORBID_ATTR" in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
          USE_PROFILES = "USE_PROFILES" in cfg ? cfg.USE_PROFILES : false;
          ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
          ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
          ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
          SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
          WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
          RETURN_DOM = cfg.RETURN_DOM || false;
          RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
          RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
          FORCE_BODY = cfg.FORCE_BODY || false;
          SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
          SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false;
          KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
          IN_PLACE = cfg.IN_PLACE || false;
          IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
          NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
          if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
            CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
          }
          if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
            CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
          }
          if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") {
            CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
          }
          if (SAFE_FOR_TEMPLATES) {
            ALLOW_DATA_ATTR = false;
          }
          if (RETURN_DOM_FRAGMENT) {
            RETURN_DOM = true;
          }
          if (USE_PROFILES) {
            ALLOWED_TAGS = addToSet({}, _toConsumableArray(text3));
            ALLOWED_ATTR = [];
            if (USE_PROFILES.html === true) {
              addToSet(ALLOWED_TAGS, html$1);
              addToSet(ALLOWED_ATTR, html5);
            }
            if (USE_PROFILES.svg === true) {
              addToSet(ALLOWED_TAGS, svg$1);
              addToSet(ALLOWED_ATTR, svg4);
              addToSet(ALLOWED_ATTR, xml2);
            }
            if (USE_PROFILES.svgFilters === true) {
              addToSet(ALLOWED_TAGS, svgFilters);
              addToSet(ALLOWED_ATTR, svg4);
              addToSet(ALLOWED_ATTR, xml2);
            }
            if (USE_PROFILES.mathMl === true) {
              addToSet(ALLOWED_TAGS, mathMl$1);
              addToSet(ALLOWED_ATTR, mathMl);
              addToSet(ALLOWED_ATTR, xml2);
            }
          }
          if (cfg.ADD_TAGS) {
            if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
              ALLOWED_TAGS = clone3(ALLOWED_TAGS);
            }
            addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
          }
          if (cfg.ADD_ATTR) {
            if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
              ALLOWED_ATTR = clone3(ALLOWED_ATTR);
            }
            addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
          }
          if (cfg.ADD_URI_SAFE_ATTR) {
            addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
          }
          if (cfg.FORBID_CONTENTS) {
            if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
              FORBID_CONTENTS = clone3(FORBID_CONTENTS);
            }
            addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
          }
          if (KEEP_CONTENT) {
            ALLOWED_TAGS["#text"] = true;
          }
          if (WHOLE_DOCUMENT) {
            addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
          }
          if (ALLOWED_TAGS.table) {
            addToSet(ALLOWED_TAGS, ["tbody"]);
            delete FORBID_TAGS.tbody;
          }
          if (freeze2) {
            freeze2(cfg);
          }
          CONFIG = cfg;
        };
        var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
        var HTML_INTEGRATION_POINTS = addToSet({}, ["foreignobject", "desc", "title", "annotation-xml"]);
        var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]);
        var ALL_SVG_TAGS = addToSet({}, svg$1);
        addToSet(ALL_SVG_TAGS, svgFilters);
        addToSet(ALL_SVG_TAGS, svgDisallowed);
        var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
        addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
        var _checkValidNamespace = function _checkValidNamespace2(element2) {
          var parent = getParentNode(element2);
          if (!parent || !parent.tagName) {
            parent = {
              namespaceURI: NAMESPACE,
              tagName: "template"
            };
          }
          var tagName = stringToLowerCase(element2.tagName);
          var parentTagName = stringToLowerCase(parent.tagName);
          if (!ALLOWED_NAMESPACES[element2.namespaceURI]) {
            return false;
          }
          if (element2.namespaceURI === SVG_NAMESPACE2) {
            if (parent.namespaceURI === HTML_NAMESPACE) {
              return tagName === "svg";
            }
            if (parent.namespaceURI === MATHML_NAMESPACE) {
              return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
            }
            return Boolean(ALL_SVG_TAGS[tagName]);
          }
          if (element2.namespaceURI === MATHML_NAMESPACE) {
            if (parent.namespaceURI === HTML_NAMESPACE) {
              return tagName === "math";
            }
            if (parent.namespaceURI === SVG_NAMESPACE2) {
              return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
            }
            return Boolean(ALL_MATHML_TAGS[tagName]);
          }
          if (element2.namespaceURI === HTML_NAMESPACE) {
            if (parent.namespaceURI === SVG_NAMESPACE2 && !HTML_INTEGRATION_POINTS[parentTagName]) {
              return false;
            }
            if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
              return false;
            }
            return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
          }
          if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element2.namespaceURI]) {
            return true;
          }
          return false;
        };
        var _forceRemove = function _forceRemove2(node) {
          arrayPush(DOMPurify3.removed, {
            element: node
          });
          try {
            node.parentNode.removeChild(node);
          } catch (_5) {
            try {
              node.outerHTML = emptyHTML;
            } catch (_6) {
              node.remove();
            }
          }
        };
        var _removeAttribute = function _removeAttribute2(name2, node) {
          try {
            arrayPush(DOMPurify3.removed, {
              attribute: node.getAttributeNode(name2),
              from: node
            });
          } catch (_5) {
            arrayPush(DOMPurify3.removed, {
              attribute: null,
              from: node
            });
          }
          node.removeAttribute(name2);
          if (name2 === "is" && !ALLOWED_ATTR[name2]) {
            if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
              try {
                _forceRemove(node);
              } catch (_5) {
              }
            } else {
              try {
                node.setAttribute(name2, "");
              } catch (_5) {
              }
            }
          }
        };
        var _initDocument = function _initDocument2(dirty) {
          var doc4;
          var leadingWhitespace;
          if (FORCE_BODY) {
            dirty = "<remove></remove>" + dirty;
          } else {
            var matches3 = stringMatch(dirty, /^[\r\n\t ]+/);
            leadingWhitespace = matches3 && matches3[0];
          }
          if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) {
            dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + "</body></html>";
          }
          var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
          if (NAMESPACE === HTML_NAMESPACE) {
            try {
              doc4 = new DOMParser2().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
            } catch (_5) {
            }
          }
          if (!doc4 || !doc4.documentElement) {
            doc4 = implementation.createDocument(NAMESPACE, "template", null);
            try {
              doc4.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
            } catch (_5) {
            }
          }
          var body3 = doc4.body || doc4.documentElement;
          if (dirty && leadingWhitespace) {
            body3.insertBefore(document2.createTextNode(leadingWhitespace), body3.childNodes[0] || null);
          }
          if (NAMESPACE === HTML_NAMESPACE) {
            return getElementsByTagName.call(doc4, WHOLE_DOCUMENT ? "html" : "body")[0];
          }
          return WHOLE_DOCUMENT ? doc4.documentElement : body3;
        };
        var _createIterator = function _createIterator2(root3) {
          return createNodeIterator.call(
            root3.ownerDocument || root3,
            root3,
            // eslint-disable-next-line no-bitwise
            NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT,
            null,
            false
          );
        };
        var _isClobbered = function _isClobbered2(elm) {
          return elm instanceof HTMLFormElement && (typeof elm.nodeName !== "string" || typeof elm.textContent !== "string" || typeof elm.removeChild !== "function" || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== "function" || typeof elm.setAttribute !== "function" || typeof elm.namespaceURI !== "string" || typeof elm.insertBefore !== "function" || typeof elm.hasChildNodes !== "function");
        };
        var _isNode = function _isNode2(object2) {
          return _typeof(Node3) === "object" ? object2 instanceof Node3 : object2 && _typeof(object2) === "object" && typeof object2.nodeType === "number" && typeof object2.nodeName === "string";
        };
        var _executeHook = function _executeHook2(entryPoint, currentNode, data2) {
          if (!hooks[entryPoint]) {
            return;
          }
          arrayForEach(hooks[entryPoint], function(hook) {
            hook.call(DOMPurify3, currentNode, data2, CONFIG);
          });
        };
        var _sanitizeElements = function _sanitizeElements2(currentNode) {
          var content2;
          _executeHook("beforeSanitizeElements", currentNode, null);
          if (_isClobbered(currentNode)) {
            _forceRemove(currentNode);
            return true;
          }
          if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
            _forceRemove(currentNode);
            return true;
          }
          var tagName = transformCaseFunc(currentNode.nodeName);
          _executeHook("uponSanitizeElement", currentNode, {
            tagName,
            allowedTags: ALLOWED_TAGS
          });
          if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
            _forceRemove(currentNode);
            return true;
          }
          if (tagName === "select" && regExpTest(/<template/i, currentNode.innerHTML)) {
            _forceRemove(currentNode);
            return true;
          }
          if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
            if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
              if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
              if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
            }
            if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
              var parentNode2 = getParentNode(currentNode) || currentNode.parentNode;
              var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
              if (childNodes && parentNode2) {
                var childCount = childNodes.length;
                for (var i3 = childCount - 1; i3 >= 0; --i3) {
                  parentNode2.insertBefore(cloneNode(childNodes[i3], true), getNextSibling(currentNode));
                }
              }
            }
            _forceRemove(currentNode);
            return true;
          }
          if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
            _forceRemove(currentNode);
            return true;
          }
          if ((tagName === "noscript" || tagName === "noembed") && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
            _forceRemove(currentNode);
            return true;
          }
          if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
            content2 = currentNode.textContent;
            content2 = stringReplace(content2, MUSTACHE_EXPR$1, " ");
            content2 = stringReplace(content2, ERB_EXPR$1, " ");
            content2 = stringReplace(content2, TMPLIT_EXPR$1, " ");
            if (currentNode.textContent !== content2) {
              arrayPush(DOMPurify3.removed, {
                element: currentNode.cloneNode()
              });
              currentNode.textContent = content2;
            }
          }
          _executeHook("afterSanitizeElements", currentNode, null);
          return false;
        };
        var _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value2) {
          if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value2 in document2 || value2 in formElement)) {
            return false;
          }
          if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ;
          else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ;
          else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
            if (
              // First condition does a very basic check if a) it's basically a valid custom element tagname AND
              // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
              // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
              _basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
              // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
              lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value2) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value2))
            ) ;
            else {
              return false;
            }
          } else if (URI_SAFE_ATTRIBUTES[lcName]) ;
          else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value2, ATTR_WHITESPACE$1, ""))) ;
          else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf2(value2, "data:") === 0 && DATA_URI_TAGS[lcTag]) ;
          else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value2, ATTR_WHITESPACE$1, ""))) ;
          else if (!value2) ;
          else {
            return false;
          }
          return true;
        };
        var _basicCustomElementTest = function _basicCustomElementTest2(tagName) {
          return tagName.indexOf("-") > 0;
        };
        var _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
          var attr;
          var value2;
          var lcName;
          var l3;
          _executeHook("beforeSanitizeAttributes", currentNode, null);
          var attributes = currentNode.attributes;
          if (!attributes) {
            return;
          }
          var hookEvent = {
            attrName: "",
            attrValue: "",
            keepAttr: true,
            allowedAttributes: ALLOWED_ATTR
          };
          l3 = attributes.length;
          while (l3--) {
            attr = attributes[l3];
            var _attr = attr, name2 = _attr.name, namespaceURI = _attr.namespaceURI;
            value2 = name2 === "value" ? attr.value : stringTrim(attr.value);
            lcName = transformCaseFunc(name2);
            hookEvent.attrName = lcName;
            hookEvent.attrValue = value2;
            hookEvent.keepAttr = true;
            hookEvent.forceKeepAttr = void 0;
            _executeHook("uponSanitizeAttribute", currentNode, hookEvent);
            value2 = hookEvent.attrValue;
            if (hookEvent.forceKeepAttr) {
              continue;
            }
            _removeAttribute(name2, currentNode);
            if (!hookEvent.keepAttr) {
              continue;
            }
            if (regExpTest(/\/>/i, value2)) {
              _removeAttribute(name2, currentNode);
              continue;
            }
            if (SAFE_FOR_TEMPLATES) {
              value2 = stringReplace(value2, MUSTACHE_EXPR$1, " ");
              value2 = stringReplace(value2, ERB_EXPR$1, " ");
              value2 = stringReplace(value2, TMPLIT_EXPR$1, " ");
            }
            var lcTag = transformCaseFunc(currentNode.nodeName);
            if (!_isValidAttribute(lcTag, lcName, value2)) {
              continue;
            }
            if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) {
              _removeAttribute(name2, currentNode);
              value2 = SANITIZE_NAMED_PROPS_PREFIX + value2;
            }
            if (trustedTypesPolicy && _typeof(trustedTypes) === "object" && typeof trustedTypes.getAttributeType === "function") {
              if (namespaceURI) ;
              else {
                switch (trustedTypes.getAttributeType(lcTag, lcName)) {
                  case "TrustedHTML":
                    value2 = trustedTypesPolicy.createHTML(value2);
                    break;
                  case "TrustedScriptURL":
                    value2 = trustedTypesPolicy.createScriptURL(value2);
                    break;
                }
              }
            }
            try {
              if (namespaceURI) {
                currentNode.setAttributeNS(namespaceURI, name2, value2);
              } else {
                currentNode.setAttribute(name2, value2);
              }
              arrayPop(DOMPurify3.removed);
            } catch (_5) {
            }
          }
          _executeHook("afterSanitizeAttributes", currentNode, null);
        };
        var _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
          var shadowNode;
          var shadowIterator = _createIterator(fragment);
          _executeHook("beforeSanitizeShadowDOM", fragment, null);
          while (shadowNode = shadowIterator.nextNode()) {
            _executeHook("uponSanitizeShadowNode", shadowNode, null);
            if (_sanitizeElements(shadowNode)) {
              continue;
            }
            if (shadowNode.content instanceof DocumentFragment2) {
              _sanitizeShadowDOM2(shadowNode.content);
            }
            _sanitizeAttributes(shadowNode);
          }
          _executeHook("afterSanitizeShadowDOM", fragment, null);
        };
        DOMPurify3.sanitize = function(dirty) {
          var cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
          var body3;
          var importedNode;
          var currentNode;
          var oldNode;
          var returnNode;
          IS_EMPTY_INPUT = !dirty;
          if (IS_EMPTY_INPUT) {
            dirty = "<!-->";
          }
          if (typeof dirty !== "string" && !_isNode(dirty)) {
            if (typeof dirty.toString !== "function") {
              throw typeErrorCreate("toString is not a function");
            } else {
              dirty = dirty.toString();
              if (typeof dirty !== "string") {
                throw typeErrorCreate("dirty is not a string, aborting");
              }
            }
          }
          if (!DOMPurify3.isSupported) {
            if (_typeof(window2.toStaticHTML) === "object" || typeof window2.toStaticHTML === "function") {
              if (typeof dirty === "string") {
                return window2.toStaticHTML(dirty);
              }
              if (_isNode(dirty)) {
                return window2.toStaticHTML(dirty.outerHTML);
              }
            }
            return dirty;
          }
          if (!SET_CONFIG) {
            _parseConfig(cfg);
          }
          DOMPurify3.removed = [];
          if (typeof dirty === "string") {
            IN_PLACE = false;
          }
          if (IN_PLACE) {
            if (dirty.nodeName) {
              var tagName = transformCaseFunc(dirty.nodeName);
              if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
                throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place");
              }
            }
          } else if (dirty instanceof Node3) {
            body3 = _initDocument("<!---->");
            importedNode = body3.ownerDocument.importNode(dirty, true);
            if (importedNode.nodeType === 1 && importedNode.nodeName === "BODY") {
              body3 = importedNode;
            } else if (importedNode.nodeName === "HTML") {
              body3 = importedNode;
            } else {
              body3.appendChild(importedNode);
            }
          } else {
            if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
            dirty.indexOf("<") === -1) {
              return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
            }
            body3 = _initDocument(dirty);
            if (!body3) {
              return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
            }
          }
          if (body3 && FORCE_BODY) {
            _forceRemove(body3.firstChild);
          }
          var nodeIterator = _createIterator(IN_PLACE ? dirty : body3);
          while (currentNode = nodeIterator.nextNode()) {
            if (currentNode.nodeType === 3 && currentNode === oldNode) {
              continue;
            }
            if (_sanitizeElements(currentNode)) {
              continue;
            }
            if (currentNode.content instanceof DocumentFragment2) {
              _sanitizeShadowDOM(currentNode.content);
            }
            _sanitizeAttributes(currentNode);
            oldNode = currentNode;
          }
          oldNode = null;
          if (IN_PLACE) {
            return dirty;
          }
          if (RETURN_DOM) {
            if (RETURN_DOM_FRAGMENT) {
              returnNode = createDocumentFragment.call(body3.ownerDocument);
              while (body3.firstChild) {
                returnNode.appendChild(body3.firstChild);
              }
            } else {
              returnNode = body3;
            }
            if (ALLOWED_ATTR.shadowroot) {
              returnNode = importNode.call(originalDocument, returnNode, true);
            }
            return returnNode;
          }
          var serializedHTML = WHOLE_DOCUMENT ? body3.outerHTML : body3.innerHTML;
          if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body3.ownerDocument && body3.ownerDocument.doctype && body3.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body3.ownerDocument.doctype.name)) {
            serializedHTML = "<!DOCTYPE " + body3.ownerDocument.doctype.name + ">\n" + serializedHTML;
          }
          if (SAFE_FOR_TEMPLATES) {
            serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, " ");
            serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, " ");
            serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR$1, " ");
          }
          return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
        };
        DOMPurify3.setConfig = function(cfg) {
          _parseConfig(cfg);
          SET_CONFIG = true;
        };
        DOMPurify3.clearConfig = function() {
          CONFIG = null;
          SET_CONFIG = false;
        };
        DOMPurify3.isValidAttribute = function(tag, attr, value2) {
          if (!CONFIG) {
            _parseConfig({});
          }
          var lcTag = transformCaseFunc(tag);
          var lcName = transformCaseFunc(attr);
          return _isValidAttribute(lcTag, lcName, value2);
        };
        DOMPurify3.addHook = function(entryPoint, hookFunction) {
          if (typeof hookFunction !== "function") {
            return;
          }
          hooks[entryPoint] = hooks[entryPoint] || [];
          arrayPush(hooks[entryPoint], hookFunction);
        };
        DOMPurify3.removeHook = function(entryPoint) {
          if (hooks[entryPoint]) {
            return arrayPop(hooks[entryPoint]);
          }
        };
        DOMPurify3.removeHooks = function(entryPoint) {
          if (hooks[entryPoint]) {
            hooks[entryPoint] = [];
          }
        };
        DOMPurify3.removeAllHooks = function() {
          hooks = {};
        };
        return DOMPurify3;
      }
      var purify = createDOMPurify();
      return purify;
    });
  }
});

// node_modules/html2canvas/dist/html2canvas.js
var require_html2canvas = __commonJS({
  "node_modules/html2canvas/dist/html2canvas.js"(exports, module) {
    (function(global5, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global5 = typeof globalThis !== "undefined" ? globalThis : global5 || self, global5.html2canvas = factory());
    })(exports, function() {
      "use strict";
      var extendStatics = function(d3, b3) {
        extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
          d4.__proto__ = b4;
        } || function(d4, b4) {
          for (var p4 in b4) if (Object.prototype.hasOwnProperty.call(b4, p4)) d4[p4] = b4[p4];
        };
        return extendStatics(d3, b3);
      };
      function __extends(d3, b3) {
        if (typeof b3 !== "function" && b3 !== null)
          throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
        extendStatics(d3, b3);
        function __2() {
          this.constructor = d3;
        }
        d3.prototype = b3 === null ? Object.create(b3) : (__2.prototype = b3.prototype, new __2());
      }
      var __assign = function() {
        __assign = Object.assign || function __assign2(t3) {
          for (var s3, i4 = 1, n4 = arguments.length; i4 < n4; i4++) {
            s3 = arguments[i4];
            for (var p4 in s3) if (Object.prototype.hasOwnProperty.call(s3, p4)) t3[p4] = s3[p4];
          }
          return t3;
        };
        return __assign.apply(this, arguments);
      };
      function __awaiter(thisArg, _arguments, P3, generator) {
        function adopt(value2) {
          return value2 instanceof P3 ? value2 : new P3(function(resolve2) {
            resolve2(value2);
          });
        }
        return new (P3 || (P3 = Promise))(function(resolve2, reject2) {
          function fulfilled(value2) {
            try {
              step2(generator.next(value2));
            } catch (e4) {
              reject2(e4);
            }
          }
          function rejected(value2) {
            try {
              step2(generator["throw"](value2));
            } catch (e4) {
              reject2(e4);
            }
          }
          function step2(result2) {
            result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
          }
          step2((generator = generator.apply(thisArg, _arguments || [])).next());
        });
      }
      function __generator(thisArg, body3) {
        var _5 = { label: 0, sent: function() {
          if (t3[0] & 1) throw t3[1];
          return t3[1];
        }, trys: [], ops: [] }, f4, y3, t3, g3;
        return g3 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() {
          return this;
        }), g3;
        function verb(n4) {
          return function(v3) {
            return step2([n4, v3]);
          };
        }
        function step2(op) {
          if (f4) throw new TypeError("Generator is already executing.");
          while (_5) try {
            if (f4 = 1, y3 && (t3 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t3 = y3["return"]) && t3.call(y3), 0) : y3.next) && !(t3 = t3.call(y3, op[1])).done) return t3;
            if (y3 = 0, t3) op = [op[0] & 2, t3.value];
            switch (op[0]) {
              case 0:
              case 1:
                t3 = op;
                break;
              case 4:
                _5.label++;
                return { value: op[1], done: false };
              case 5:
                _5.label++;
                y3 = op[1];
                op = [0];
                continue;
              case 7:
                op = _5.ops.pop();
                _5.trys.pop();
                continue;
              default:
                if (!(t3 = _5.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                  _5 = 0;
                  continue;
                }
                if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
                  _5.label = op[1];
                  break;
                }
                if (op[0] === 6 && _5.label < t3[1]) {
                  _5.label = t3[1];
                  t3 = op;
                  break;
                }
                if (t3 && _5.label < t3[2]) {
                  _5.label = t3[2];
                  _5.ops.push(op);
                  break;
                }
                if (t3[2]) _5.ops.pop();
                _5.trys.pop();
                continue;
            }
            op = body3.call(thisArg, _5);
          } catch (e4) {
            op = [6, e4];
            y3 = 0;
          } finally {
            f4 = t3 = 0;
          }
          if (op[0] & 5) throw op[1];
          return { value: op[0] ? op[1] : void 0, done: true };
        }
      }
      function __spreadArray(to, from2, pack2) {
        if (pack2 || arguments.length === 2) for (var i4 = 0, l3 = from2.length, ar; i4 < l3; i4++) {
          if (ar || !(i4 in from2)) {
            if (!ar) ar = Array.prototype.slice.call(from2, 0, i4);
            ar[i4] = from2[i4];
          }
        }
        return to.concat(ar || from2);
      }
      var Bounds2 = (
        /** @class */
        function() {
          function Bounds3(left, top2, width, height) {
            this.left = left;
            this.top = top2;
            this.width = width;
            this.height = height;
          }
          Bounds3.prototype.add = function(x3, y3, w3, h3) {
            return new Bounds3(this.left + x3, this.top + y3, this.width + w3, this.height + h3);
          };
          Bounds3.fromClientRect = function(context, clientRect2) {
            return new Bounds3(clientRect2.left + context.windowBounds.left, clientRect2.top + context.windowBounds.top, clientRect2.width, clientRect2.height);
          };
          Bounds3.fromDOMRectList = function(context, domRectList) {
            var domRect = Array.from(domRectList).find(function(rect) {
              return rect.width !== 0;
            });
            return domRect ? new Bounds3(domRect.left + context.windowBounds.left, domRect.top + context.windowBounds.top, domRect.width, domRect.height) : Bounds3.EMPTY;
          };
          Bounds3.EMPTY = new Bounds3(0, 0, 0, 0);
          return Bounds3;
        }()
      );
      var parseBounds = function(context, node) {
        return Bounds2.fromClientRect(context, node.getBoundingClientRect());
      };
      var parseDocumentSize = function(document2) {
        var body3 = document2.body;
        var documentElement = document2.documentElement;
        if (!body3 || !documentElement) {
          throw new Error("Unable to get document size");
        }
        var width = Math.max(Math.max(body3.scrollWidth, documentElement.scrollWidth), Math.max(body3.offsetWidth, documentElement.offsetWidth), Math.max(body3.clientWidth, documentElement.clientWidth));
        var height = Math.max(Math.max(body3.scrollHeight, documentElement.scrollHeight), Math.max(body3.offsetHeight, documentElement.offsetHeight), Math.max(body3.clientHeight, documentElement.clientHeight));
        return new Bounds2(0, 0, width, height);
      };
      var toCodePoints$1 = function(str) {
        var codePoints = [];
        var i4 = 0;
        var length = str.length;
        while (i4 < length) {
          var value2 = str.charCodeAt(i4++);
          if (value2 >= 55296 && value2 <= 56319 && i4 < length) {
            var extra = str.charCodeAt(i4++);
            if ((extra & 64512) === 56320) {
              codePoints.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
            } else {
              codePoints.push(value2);
              i4--;
            }
          } else {
            codePoints.push(value2);
          }
        }
        return codePoints;
      };
      var fromCodePoint$1 = function() {
        var codePoints = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          codePoints[_i] = arguments[_i];
        }
        if (String.fromCodePoint) {
          return String.fromCodePoint.apply(String, codePoints);
        }
        var length = codePoints.length;
        if (!length) {
          return "";
        }
        var codeUnits = [];
        var index2 = -1;
        var result2 = "";
        while (++index2 < length) {
          var codePoint = codePoints[index2];
          if (codePoint <= 65535) {
            codeUnits.push(codePoint);
          } else {
            codePoint -= 65536;
            codeUnits.push((codePoint >> 10) + 55296, codePoint % 1024 + 56320);
          }
          if (index2 + 1 === length || codeUnits.length > 16384) {
            result2 += String.fromCharCode.apply(String, codeUnits);
            codeUnits.length = 0;
          }
        }
        return result2;
      };
      var chars$2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var lookup$2 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
      for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
        lookup$2[chars$2.charCodeAt(i$2)] = i$2;
      }
      var chars$1$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var lookup$1$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
      for (var i$1$1 = 0; i$1$1 < chars$1$1.length; i$1$1++) {
        lookup$1$1[chars$1$1.charCodeAt(i$1$1)] = i$1$1;
      }
      var decode$1 = function(base642) {
        var bufferLength = base642.length * 0.75, len = base642.length, i4, p4 = 0, encoded1, encoded2, encoded3, encoded4;
        if (base642[base642.length - 1] === "=") {
          bufferLength--;
          if (base642[base642.length - 2] === "=") {
            bufferLength--;
          }
        }
        var buffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined" && typeof Uint8Array.prototype.slice !== "undefined" ? new ArrayBuffer(bufferLength) : new Array(bufferLength);
        var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
        for (i4 = 0; i4 < len; i4 += 4) {
          encoded1 = lookup$1$1[base642.charCodeAt(i4)];
          encoded2 = lookup$1$1[base642.charCodeAt(i4 + 1)];
          encoded3 = lookup$1$1[base642.charCodeAt(i4 + 2)];
          encoded4 = lookup$1$1[base642.charCodeAt(i4 + 3)];
          bytes[p4++] = encoded1 << 2 | encoded2 >> 4;
          bytes[p4++] = (encoded2 & 15) << 4 | encoded3 >> 2;
          bytes[p4++] = (encoded3 & 3) << 6 | encoded4 & 63;
        }
        return buffer;
      };
      var polyUint16Array$1 = function(buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i4 = 0; i4 < length; i4 += 2) {
          bytes.push(buffer[i4 + 1] << 8 | buffer[i4]);
        }
        return bytes;
      };
      var polyUint32Array$1 = function(buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i4 = 0; i4 < length; i4 += 4) {
          bytes.push(buffer[i4 + 3] << 24 | buffer[i4 + 2] << 16 | buffer[i4 + 1] << 8 | buffer[i4]);
        }
        return bytes;
      };
      var UTRIE2_SHIFT_2$1 = 5;
      var UTRIE2_SHIFT_1$1 = 6 + 5;
      var UTRIE2_INDEX_SHIFT$1 = 2;
      var UTRIE2_SHIFT_1_2$1 = UTRIE2_SHIFT_1$1 - UTRIE2_SHIFT_2$1;
      var UTRIE2_LSCP_INDEX_2_OFFSET$1 = 65536 >> UTRIE2_SHIFT_2$1;
      var UTRIE2_DATA_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_2$1;
      var UTRIE2_DATA_MASK$1 = UTRIE2_DATA_BLOCK_LENGTH$1 - 1;
      var UTRIE2_LSCP_INDEX_2_LENGTH$1 = 1024 >> UTRIE2_SHIFT_2$1;
      var UTRIE2_INDEX_2_BMP_LENGTH$1 = UTRIE2_LSCP_INDEX_2_OFFSET$1 + UTRIE2_LSCP_INDEX_2_LENGTH$1;
      var UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 = UTRIE2_INDEX_2_BMP_LENGTH$1;
      var UTRIE2_UTF8_2B_INDEX_2_LENGTH$1 = 2048 >> 6;
      var UTRIE2_INDEX_1_OFFSET$1 = UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 + UTRIE2_UTF8_2B_INDEX_2_LENGTH$1;
      var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 = 65536 >> UTRIE2_SHIFT_1$1;
      var UTRIE2_INDEX_2_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_1_2$1;
      var UTRIE2_INDEX_2_MASK$1 = UTRIE2_INDEX_2_BLOCK_LENGTH$1 - 1;
      var slice16$1 = function(view, start, end) {
        if (view.slice) {
          return view.slice(start, end);
        }
        return new Uint16Array(Array.prototype.slice.call(view, start, end));
      };
      var slice32$1 = function(view, start, end) {
        if (view.slice) {
          return view.slice(start, end);
        }
        return new Uint32Array(Array.prototype.slice.call(view, start, end));
      };
      var createTrieFromBase64$1 = function(base642, _byteLength) {
        var buffer = decode$1(base642);
        var view32 = Array.isArray(buffer) ? polyUint32Array$1(buffer) : new Uint32Array(buffer);
        var view16 = Array.isArray(buffer) ? polyUint16Array$1(buffer) : new Uint16Array(buffer);
        var headerLength = 24;
        var index2 = slice16$1(view16, headerLength / 2, view32[4] / 2);
        var data2 = view32[5] === 2 ? slice16$1(view16, (headerLength + view32[4]) / 2) : slice32$1(view32, Math.ceil((headerLength + view32[4]) / 4));
        return new Trie$1(view32[0], view32[1], view32[2], view32[3], index2, data2);
      };
      var Trie$1 = (
        /** @class */
        function() {
          function Trie2(initialValue, errorValue, highStart, highValueIndex, index2, data2) {
            this.initialValue = initialValue;
            this.errorValue = errorValue;
            this.highStart = highStart;
            this.highValueIndex = highValueIndex;
            this.index = index2;
            this.data = data2;
          }
          Trie2.prototype.get = function(codePoint) {
            var ix;
            if (codePoint >= 0) {
              if (codePoint < 55296 || codePoint > 56319 && codePoint <= 65535) {
                ix = this.index[codePoint >> UTRIE2_SHIFT_2$1];
                ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
                return this.data[ix];
              }
              if (codePoint <= 65535) {
                ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET$1 + (codePoint - 55296 >> UTRIE2_SHIFT_2$1)];
                ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
                return this.data[ix];
              }
              if (codePoint < this.highStart) {
                ix = UTRIE2_INDEX_1_OFFSET$1 - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 + (codePoint >> UTRIE2_SHIFT_1$1);
                ix = this.index[ix];
                ix += codePoint >> UTRIE2_SHIFT_2$1 & UTRIE2_INDEX_2_MASK$1;
                ix = this.index[ix];
                ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
                return this.data[ix];
              }
              if (codePoint <= 1114111) {
                return this.data[this.highValueIndex];
              }
            }
            return this.errorValue;
          };
          return Trie2;
        }()
      );
      var chars$3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var lookup$3 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
      for (var i$3 = 0; i$3 < chars$3.length; i$3++) {
        lookup$3[chars$3.charCodeAt(i$3)] = i$3;
      }
      var base64$1 = " ";
      var LETTER_NUMBER_MODIFIER = 50;
      var BK = 1;
      var CR$1 = 2;
      var LF$1 = 3;
      var CM = 4;
      var NL = 5;
      var WJ = 7;
      var ZW = 8;
      var GL = 9;
      var SP = 10;
      var ZWJ$1 = 11;
      var B2 = 12;
      var BA = 13;
      var BB = 14;
      var HY = 15;
      var CB = 16;
      var CL = 17;
      var CP = 18;
      var EX = 19;
      var IN = 20;
      var NS = 21;
      var OP = 22;
      var QU = 23;
      var IS = 24;
      var NU = 25;
      var PO = 26;
      var PR = 27;
      var SY = 28;
      var AI = 29;
      var AL = 30;
      var CJ = 31;
      var EB = 32;
      var EM = 33;
      var H2 = 34;
      var H3 = 35;
      var HL = 36;
      var ID = 37;
      var JL = 38;
      var JV = 39;
      var JT = 40;
      var RI$1 = 41;
      var SA = 42;
      var XX = 43;
      var ea_OP = [9001, 65288];
      var BREAK_MANDATORY = "!";
      var BREAK_NOT_ALLOWED$1 = "\xD7";
      var BREAK_ALLOWED$1 = "\xF7";
      var UnicodeTrie$1 = createTrieFromBase64$1(base64$1);
      var ALPHABETICS = [AL, HL];
      var HARD_LINE_BREAKS = [BK, CR$1, LF$1, NL];
      var SPACE$1 = [SP, ZW];
      var PREFIX_POSTFIX = [PR, PO];
      var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE$1);
      var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3];
      var HYPHEN = [HY, BA];
      var codePointsToCharacterClasses = function(codePoints, lineBreak2) {
        if (lineBreak2 === void 0) {
          lineBreak2 = "strict";
        }
        var types2 = [];
        var indices = [];
        var categories = [];
        codePoints.forEach(function(codePoint, index2) {
          var classType = UnicodeTrie$1.get(codePoint);
          if (classType > LETTER_NUMBER_MODIFIER) {
            categories.push(true);
            classType -= LETTER_NUMBER_MODIFIER;
          } else {
            categories.push(false);
          }
          if (["normal", "auto", "loose"].indexOf(lineBreak2) !== -1) {
            if ([8208, 8211, 12316, 12448].indexOf(codePoint) !== -1) {
              indices.push(index2);
              return types2.push(CB);
            }
          }
          if (classType === CM || classType === ZWJ$1) {
            if (index2 === 0) {
              indices.push(index2);
              return types2.push(AL);
            }
            var prev = types2[index2 - 1];
            if (LINE_BREAKS.indexOf(prev) === -1) {
              indices.push(indices[index2 - 1]);
              return types2.push(prev);
            }
            indices.push(index2);
            return types2.push(AL);
          }
          indices.push(index2);
          if (classType === CJ) {
            return types2.push(lineBreak2 === "strict" ? NS : ID);
          }
          if (classType === SA) {
            return types2.push(AL);
          }
          if (classType === AI) {
            return types2.push(AL);
          }
          if (classType === XX) {
            if (codePoint >= 131072 && codePoint <= 196605 || codePoint >= 196608 && codePoint <= 262141) {
              return types2.push(ID);
            } else {
              return types2.push(AL);
            }
          }
          types2.push(classType);
        });
        return [indices, types2, categories];
      };
      var isAdjacentWithSpaceIgnored = function(a4, b3, currentIndex, classTypes) {
        var current = classTypes[currentIndex];
        if (Array.isArray(a4) ? a4.indexOf(current) !== -1 : a4 === current) {
          var i4 = currentIndex;
          while (i4 <= classTypes.length) {
            i4++;
            var next2 = classTypes[i4];
            if (next2 === b3) {
              return true;
            }
            if (next2 !== SP) {
              break;
            }
          }
        }
        if (current === SP) {
          var i4 = currentIndex;
          while (i4 > 0) {
            i4--;
            var prev = classTypes[i4];
            if (Array.isArray(a4) ? a4.indexOf(prev) !== -1 : a4 === prev) {
              var n4 = currentIndex;
              while (n4 <= classTypes.length) {
                n4++;
                var next2 = classTypes[n4];
                if (next2 === b3) {
                  return true;
                }
                if (next2 !== SP) {
                  break;
                }
              }
            }
            if (prev !== SP) {
              break;
            }
          }
        }
        return false;
      };
      var previousNonSpaceClassType = function(currentIndex, classTypes) {
        var i4 = currentIndex;
        while (i4 >= 0) {
          var type = classTypes[i4];
          if (type === SP) {
            i4--;
          } else {
            return type;
          }
        }
        return 0;
      };
      var _lineBreakAtIndex = function(codePoints, classTypes, indicies, index2, forbiddenBreaks) {
        if (indicies[index2] === 0) {
          return BREAK_NOT_ALLOWED$1;
        }
        var currentIndex = index2 - 1;
        if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) {
          return BREAK_NOT_ALLOWED$1;
        }
        var beforeIndex = currentIndex - 1;
        var afterIndex = currentIndex + 1;
        var current = classTypes[currentIndex];
        var before2 = beforeIndex >= 0 ? classTypes[beforeIndex] : 0;
        var next2 = classTypes[afterIndex];
        if (current === CR$1 && next2 === LF$1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (HARD_LINE_BREAKS.indexOf(current) !== -1) {
          return BREAK_MANDATORY;
        }
        if (HARD_LINE_BREAKS.indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (SPACE$1.indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) {
          return BREAK_ALLOWED$1;
        }
        if (UnicodeTrie$1.get(codePoints[currentIndex]) === ZWJ$1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if ((current === EB || current === EM) && UnicodeTrie$1.get(codePoints[afterIndex]) === ZWJ$1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === WJ || next2 === WJ) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === GL) {
          return BREAK_NOT_ALLOWED$1;
        }
        if ([SP, BA, HY].indexOf(current) === -1 && next2 === GL) {
          return BREAK_NOT_ALLOWED$1;
        }
        if ([CL, CP, EX, IS, SY].indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (previousNonSpaceClassType(currentIndex, classTypes) === OP) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === SP) {
          return BREAK_ALLOWED$1;
        }
        if (current === QU || next2 === QU) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (next2 === CB || current === CB) {
          return BREAK_ALLOWED$1;
        }
        if ([BA, HY, NS].indexOf(next2) !== -1 || current === BB) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (before2 === HL && HYPHEN.indexOf(current) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === SY && next2 === HL) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (next2 === IN) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (ALPHABETICS.indexOf(next2) !== -1 && current === NU || ALPHABETICS.indexOf(current) !== -1 && next2 === NU) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === PR && [ID, EB, EM].indexOf(next2) !== -1 || [ID, EB, EM].indexOf(current) !== -1 && next2 === PO) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next2) !== -1 || PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (
          // (PR | PO) × ( OP | HY )? NU
          [PR, PO].indexOf(current) !== -1 && (next2 === NU || [OP, HY].indexOf(next2) !== -1 && classTypes[afterIndex + 1] === NU) || // ( OP | HY ) × NU
          [OP, HY].indexOf(current) !== -1 && next2 === NU || // NU ×	(NU | SY | IS)
          current === NU && [NU, SY, IS].indexOf(next2) !== -1
        ) {
          return BREAK_NOT_ALLOWED$1;
        }
        if ([NU, SY, IS, CL, CP].indexOf(next2) !== -1) {
          var prevIndex = currentIndex;
          while (prevIndex >= 0) {
            var type = classTypes[prevIndex];
            if (type === NU) {
              return BREAK_NOT_ALLOWED$1;
            } else if ([SY, IS].indexOf(type) !== -1) {
              prevIndex--;
            } else {
              break;
            }
          }
        }
        if ([PR, PO].indexOf(next2) !== -1) {
          var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex;
          while (prevIndex >= 0) {
            var type = classTypes[prevIndex];
            if (type === NU) {
              return BREAK_NOT_ALLOWED$1;
            } else if ([SY, IS].indexOf(type) !== -1) {
              prevIndex--;
            } else {
              break;
            }
          }
        }
        if (JL === current && [JL, JV, H2, H3].indexOf(next2) !== -1 || [JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next2) !== -1 || [JT, H3].indexOf(current) !== -1 && next2 === JT) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next2) !== -1 || KOREAN_SYLLABLE_BLOCK.indexOf(next2) !== -1 && current === PR) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === IS && ALPHABETICS.indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (ALPHABETICS.concat(NU).indexOf(current) !== -1 && next2 === OP && ea_OP.indexOf(codePoints[afterIndex]) === -1 || ALPHABETICS.concat(NU).indexOf(next2) !== -1 && current === CP) {
          return BREAK_NOT_ALLOWED$1;
        }
        if (current === RI$1 && next2 === RI$1) {
          var i4 = indicies[currentIndex];
          var count = 1;
          while (i4 > 0) {
            i4--;
            if (classTypes[i4] === RI$1) {
              count++;
            } else {
              break;
            }
          }
          if (count % 2 !== 0) {
            return BREAK_NOT_ALLOWED$1;
          }
        }
        if (current === EB && next2 === EM) {
          return BREAK_NOT_ALLOWED$1;
        }
        return BREAK_ALLOWED$1;
      };
      var cssFormattedClasses = function(codePoints, options2) {
        if (!options2) {
          options2 = { lineBreak: "normal", wordBreak: "normal" };
        }
        var _a4 = codePointsToCharacterClasses(codePoints, options2.lineBreak), indicies = _a4[0], classTypes = _a4[1], isLetterNumber = _a4[2];
        if (options2.wordBreak === "break-all" || options2.wordBreak === "break-word") {
          classTypes = classTypes.map(function(type) {
            return [NU, AL, SA].indexOf(type) !== -1 ? ID : type;
          });
        }
        var forbiddenBreakpoints = options2.wordBreak === "keep-all" ? isLetterNumber.map(function(letterNumber, i4) {
          return letterNumber && codePoints[i4] >= 19968 && codePoints[i4] <= 40959;
        }) : void 0;
        return [indicies, classTypes, forbiddenBreakpoints];
      };
      var Break2 = (
        /** @class */
        function() {
          function Break3(codePoints, lineBreak2, start, end) {
            this.codePoints = codePoints;
            this.required = lineBreak2 === BREAK_MANDATORY;
            this.start = start;
            this.end = end;
          }
          Break3.prototype.slice = function() {
            return fromCodePoint$1.apply(void 0, this.codePoints.slice(this.start, this.end));
          };
          return Break3;
        }()
      );
      var LineBreaker = function(str, options2) {
        var codePoints = toCodePoints$1(str);
        var _a4 = cssFormattedClasses(codePoints, options2), indicies = _a4[0], classTypes = _a4[1], forbiddenBreakpoints = _a4[2];
        var length = codePoints.length;
        var lastEnd = 0;
        var nextIndex = 0;
        return {
          next: function() {
            if (nextIndex >= length) {
              return { done: true, value: null };
            }
            var lineBreak2 = BREAK_NOT_ALLOWED$1;
            while (nextIndex < length && (lineBreak2 = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) === BREAK_NOT_ALLOWED$1) {
            }
            if (lineBreak2 !== BREAK_NOT_ALLOWED$1 || nextIndex === length) {
              var value2 = new Break2(codePoints, lineBreak2, lastEnd, nextIndex);
              lastEnd = nextIndex;
              return { value: value2, done: false };
            }
            return { done: true, value: null };
          }
        };
      };
      var FLAG_UNRESTRICTED = 1 << 0;
      var FLAG_ID = 1 << 1;
      var FLAG_INTEGER = 1 << 2;
      var FLAG_NUMBER = 1 << 3;
      var LINE_FEED = 10;
      var SOLIDUS = 47;
      var REVERSE_SOLIDUS = 92;
      var CHARACTER_TABULATION = 9;
      var SPACE = 32;
      var QUOTATION_MARK = 34;
      var EQUALS_SIGN = 61;
      var NUMBER_SIGN = 35;
      var DOLLAR_SIGN = 36;
      var PERCENTAGE_SIGN = 37;
      var APOSTROPHE2 = 39;
      var LEFT_PARENTHESIS = 40;
      var RIGHT_PARENTHESIS = 41;
      var LOW_LINE = 95;
      var HYPHEN_MINUS = 45;
      var EXCLAMATION_MARK = 33;
      var LESS_THAN_SIGN = 60;
      var GREATER_THAN_SIGN = 62;
      var COMMERCIAL_AT = 64;
      var LEFT_SQUARE_BRACKET = 91;
      var RIGHT_SQUARE_BRACKET = 93;
      var CIRCUMFLEX_ACCENT = 61;
      var LEFT_CURLY_BRACKET = 123;
      var QUESTION_MARK = 63;
      var RIGHT_CURLY_BRACKET = 125;
      var VERTICAL_LINE = 124;
      var TILDE = 126;
      var CONTROL = 128;
      var REPLACEMENT_CHARACTER = 65533;
      var ASTERISK = 42;
      var PLUS_SIGN = 43;
      var COMMA = 44;
      var COLON = 58;
      var SEMICOLON = 59;
      var FULL_STOP = 46;
      var NULL = 0;
      var BACKSPACE = 8;
      var LINE_TABULATION = 11;
      var SHIFT_OUT = 14;
      var INFORMATION_SEPARATOR_ONE = 31;
      var DELETE = 127;
      var EOF = -1;
      var ZERO = 48;
      var a3 = 97;
      var e3 = 101;
      var f3 = 102;
      var u3 = 117;
      var z2 = 122;
      var A4 = 65;
      var E3 = 69;
      var F2 = 70;
      var U = 85;
      var Z = 90;
      var isDigit = function(codePoint) {
        return codePoint >= ZERO && codePoint <= 57;
      };
      var isSurrogateCodePoint = function(codePoint) {
        return codePoint >= 55296 && codePoint <= 57343;
      };
      var isHex = function(codePoint) {
        return isDigit(codePoint) || codePoint >= A4 && codePoint <= F2 || codePoint >= a3 && codePoint <= f3;
      };
      var isLowerCaseLetter = function(codePoint) {
        return codePoint >= a3 && codePoint <= z2;
      };
      var isUpperCaseLetter = function(codePoint) {
        return codePoint >= A4 && codePoint <= Z;
      };
      var isLetter2 = function(codePoint) {
        return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint);
      };
      var isNonASCIICodePoint = function(codePoint) {
        return codePoint >= CONTROL;
      };
      var isWhiteSpace2 = function(codePoint) {
        return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE;
      };
      var isNameStartCodePoint = function(codePoint) {
        return isLetter2(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE;
      };
      var isNameCodePoint = function(codePoint) {
        return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS;
      };
      var isNonPrintableCodePoint = function(codePoint) {
        return codePoint >= NULL && codePoint <= BACKSPACE || codePoint === LINE_TABULATION || codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE || codePoint === DELETE;
      };
      var isValidEscape = function(c1, c22) {
        if (c1 !== REVERSE_SOLIDUS) {
          return false;
        }
        return c22 !== LINE_FEED;
      };
      var isIdentifierStart = function(c1, c22, c3) {
        if (c1 === HYPHEN_MINUS) {
          return isNameStartCodePoint(c22) || isValidEscape(c22, c3);
        } else if (isNameStartCodePoint(c1)) {
          return true;
        } else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c22)) {
          return true;
        }
        return false;
      };
      var isNumberStart = function(c1, c22, c3) {
        if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
          if (isDigit(c22)) {
            return true;
          }
          return c22 === FULL_STOP && isDigit(c3);
        }
        if (c1 === FULL_STOP) {
          return isDigit(c22);
        }
        return isDigit(c1);
      };
      var stringToNumber = function(codePoints) {
        var c3 = 0;
        var sign = 1;
        if (codePoints[c3] === PLUS_SIGN || codePoints[c3] === HYPHEN_MINUS) {
          if (codePoints[c3] === HYPHEN_MINUS) {
            sign = -1;
          }
          c3++;
        }
        var integers = [];
        while (isDigit(codePoints[c3])) {
          integers.push(codePoints[c3++]);
        }
        var int3 = integers.length ? parseInt(fromCodePoint$1.apply(void 0, integers), 10) : 0;
        if (codePoints[c3] === FULL_STOP) {
          c3++;
        }
        var fraction = [];
        while (isDigit(codePoints[c3])) {
          fraction.push(codePoints[c3++]);
        }
        var fracd = fraction.length;
        var frac = fracd ? parseInt(fromCodePoint$1.apply(void 0, fraction), 10) : 0;
        if (codePoints[c3] === E3 || codePoints[c3] === e3) {
          c3++;
        }
        var expsign = 1;
        if (codePoints[c3] === PLUS_SIGN || codePoints[c3] === HYPHEN_MINUS) {
          if (codePoints[c3] === HYPHEN_MINUS) {
            expsign = -1;
          }
          c3++;
        }
        var exponent = [];
        while (isDigit(codePoints[c3])) {
          exponent.push(codePoints[c3++]);
        }
        var exp = exponent.length ? parseInt(fromCodePoint$1.apply(void 0, exponent), 10) : 0;
        return sign * (int3 + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp);
      };
      var LEFT_PARENTHESIS_TOKEN = {
        type: 2
        /* LEFT_PARENTHESIS_TOKEN */
      };
      var RIGHT_PARENTHESIS_TOKEN = {
        type: 3
        /* RIGHT_PARENTHESIS_TOKEN */
      };
      var COMMA_TOKEN = {
        type: 4
        /* COMMA_TOKEN */
      };
      var SUFFIX_MATCH_TOKEN = {
        type: 13
        /* SUFFIX_MATCH_TOKEN */
      };
      var PREFIX_MATCH_TOKEN = {
        type: 8
        /* PREFIX_MATCH_TOKEN */
      };
      var COLUMN_TOKEN = {
        type: 21
        /* COLUMN_TOKEN */
      };
      var DASH_MATCH_TOKEN = {
        type: 9
        /* DASH_MATCH_TOKEN */
      };
      var INCLUDE_MATCH_TOKEN = {
        type: 10
        /* INCLUDE_MATCH_TOKEN */
      };
      var LEFT_CURLY_BRACKET_TOKEN = {
        type: 11
        /* LEFT_CURLY_BRACKET_TOKEN */
      };
      var RIGHT_CURLY_BRACKET_TOKEN = {
        type: 12
        /* RIGHT_CURLY_BRACKET_TOKEN */
      };
      var SUBSTRING_MATCH_TOKEN = {
        type: 14
        /* SUBSTRING_MATCH_TOKEN */
      };
      var BAD_URL_TOKEN = {
        type: 23
        /* BAD_URL_TOKEN */
      };
      var BAD_STRING_TOKEN = {
        type: 1
        /* BAD_STRING_TOKEN */
      };
      var CDO_TOKEN = {
        type: 25
        /* CDO_TOKEN */
      };
      var CDC_TOKEN = {
        type: 24
        /* CDC_TOKEN */
      };
      var COLON_TOKEN = {
        type: 26
        /* COLON_TOKEN */
      };
      var SEMICOLON_TOKEN = {
        type: 27
        /* SEMICOLON_TOKEN */
      };
      var LEFT_SQUARE_BRACKET_TOKEN = {
        type: 28
        /* LEFT_SQUARE_BRACKET_TOKEN */
      };
      var RIGHT_SQUARE_BRACKET_TOKEN = {
        type: 29
        /* RIGHT_SQUARE_BRACKET_TOKEN */
      };
      var WHITESPACE_TOKEN = {
        type: 31
        /* WHITESPACE_TOKEN */
      };
      var EOF_TOKEN = {
        type: 32
        /* EOF_TOKEN */
      };
      var Tokenizer2 = (
        /** @class */
        function() {
          function Tokenizer3() {
            this._value = [];
          }
          Tokenizer3.prototype.write = function(chunk2) {
            this._value = this._value.concat(toCodePoints$1(chunk2));
          };
          Tokenizer3.prototype.read = function() {
            var tokens = [];
            var token = this.consumeToken();
            while (token !== EOF_TOKEN) {
              tokens.push(token);
              token = this.consumeToken();
            }
            return tokens;
          };
          Tokenizer3.prototype.consumeToken = function() {
            var codePoint = this.consumeCodePoint();
            switch (codePoint) {
              case QUOTATION_MARK:
                return this.consumeStringToken(QUOTATION_MARK);
              case NUMBER_SIGN:
                var c1 = this.peekCodePoint(0);
                var c22 = this.peekCodePoint(1);
                var c3 = this.peekCodePoint(2);
                if (isNameCodePoint(c1) || isValidEscape(c22, c3)) {
                  var flags = isIdentifierStart(c1, c22, c3) ? FLAG_ID : FLAG_UNRESTRICTED;
                  var value2 = this.consumeName();
                  return { type: 5, value: value2, flags };
                }
                break;
              case DOLLAR_SIGN:
                if (this.peekCodePoint(0) === EQUALS_SIGN) {
                  this.consumeCodePoint();
                  return SUFFIX_MATCH_TOKEN;
                }
                break;
              case APOSTROPHE2:
                return this.consumeStringToken(APOSTROPHE2);
              case LEFT_PARENTHESIS:
                return LEFT_PARENTHESIS_TOKEN;
              case RIGHT_PARENTHESIS:
                return RIGHT_PARENTHESIS_TOKEN;
              case ASTERISK:
                if (this.peekCodePoint(0) === EQUALS_SIGN) {
                  this.consumeCodePoint();
                  return SUBSTRING_MATCH_TOKEN;
                }
                break;
              case PLUS_SIGN:
                if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
                  this.reconsumeCodePoint(codePoint);
                  return this.consumeNumericToken();
                }
                break;
              case COMMA:
                return COMMA_TOKEN;
              case HYPHEN_MINUS:
                var e1 = codePoint;
                var e22 = this.peekCodePoint(0);
                var e32 = this.peekCodePoint(1);
                if (isNumberStart(e1, e22, e32)) {
                  this.reconsumeCodePoint(codePoint);
                  return this.consumeNumericToken();
                }
                if (isIdentifierStart(e1, e22, e32)) {
                  this.reconsumeCodePoint(codePoint);
                  return this.consumeIdentLikeToken();
                }
                if (e22 === HYPHEN_MINUS && e32 === GREATER_THAN_SIGN) {
                  this.consumeCodePoint();
                  this.consumeCodePoint();
                  return CDC_TOKEN;
                }
                break;
              case FULL_STOP:
                if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
                  this.reconsumeCodePoint(codePoint);
                  return this.consumeNumericToken();
                }
                break;
              case SOLIDUS:
                if (this.peekCodePoint(0) === ASTERISK) {
                  this.consumeCodePoint();
                  while (true) {
                    var c4 = this.consumeCodePoint();
                    if (c4 === ASTERISK) {
                      c4 = this.consumeCodePoint();
                      if (c4 === SOLIDUS) {
                        return this.consumeToken();
                      }
                    }
                    if (c4 === EOF) {
                      return this.consumeToken();
                    }
                  }
                }
                break;
              case COLON:
                return COLON_TOKEN;
              case SEMICOLON:
                return SEMICOLON_TOKEN;
              case LESS_THAN_SIGN:
                if (this.peekCodePoint(0) === EXCLAMATION_MARK && this.peekCodePoint(1) === HYPHEN_MINUS && this.peekCodePoint(2) === HYPHEN_MINUS) {
                  this.consumeCodePoint();
                  this.consumeCodePoint();
                  return CDO_TOKEN;
                }
                break;
              case COMMERCIAL_AT:
                var a1 = this.peekCodePoint(0);
                var a22 = this.peekCodePoint(1);
                var a32 = this.peekCodePoint(2);
                if (isIdentifierStart(a1, a22, a32)) {
                  var value2 = this.consumeName();
                  return { type: 7, value: value2 };
                }
                break;
              case LEFT_SQUARE_BRACKET:
                return LEFT_SQUARE_BRACKET_TOKEN;
              case REVERSE_SOLIDUS:
                if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                  this.reconsumeCodePoint(codePoint);
                  return this.consumeIdentLikeToken();
                }
                break;
              case RIGHT_SQUARE_BRACKET:
                return RIGHT_SQUARE_BRACKET_TOKEN;
              case CIRCUMFLEX_ACCENT:
                if (this.peekCodePoint(0) === EQUALS_SIGN) {
                  this.consumeCodePoint();
                  return PREFIX_MATCH_TOKEN;
                }
                break;
              case LEFT_CURLY_BRACKET:
                return LEFT_CURLY_BRACKET_TOKEN;
              case RIGHT_CURLY_BRACKET:
                return RIGHT_CURLY_BRACKET_TOKEN;
              case u3:
              case U:
                var u1 = this.peekCodePoint(0);
                var u22 = this.peekCodePoint(1);
                if (u1 === PLUS_SIGN && (isHex(u22) || u22 === QUESTION_MARK)) {
                  this.consumeCodePoint();
                  this.consumeUnicodeRangeToken();
                }
                this.reconsumeCodePoint(codePoint);
                return this.consumeIdentLikeToken();
              case VERTICAL_LINE:
                if (this.peekCodePoint(0) === EQUALS_SIGN) {
                  this.consumeCodePoint();
                  return DASH_MATCH_TOKEN;
                }
                if (this.peekCodePoint(0) === VERTICAL_LINE) {
                  this.consumeCodePoint();
                  return COLUMN_TOKEN;
                }
                break;
              case TILDE:
                if (this.peekCodePoint(0) === EQUALS_SIGN) {
                  this.consumeCodePoint();
                  return INCLUDE_MATCH_TOKEN;
                }
                break;
              case EOF:
                return EOF_TOKEN;
            }
            if (isWhiteSpace2(codePoint)) {
              this.consumeWhiteSpace();
              return WHITESPACE_TOKEN;
            }
            if (isDigit(codePoint)) {
              this.reconsumeCodePoint(codePoint);
              return this.consumeNumericToken();
            }
            if (isNameStartCodePoint(codePoint)) {
              this.reconsumeCodePoint(codePoint);
              return this.consumeIdentLikeToken();
            }
            return { type: 6, value: fromCodePoint$1(codePoint) };
          };
          Tokenizer3.prototype.consumeCodePoint = function() {
            var value2 = this._value.shift();
            return typeof value2 === "undefined" ? -1 : value2;
          };
          Tokenizer3.prototype.reconsumeCodePoint = function(codePoint) {
            this._value.unshift(codePoint);
          };
          Tokenizer3.prototype.peekCodePoint = function(delta) {
            if (delta >= this._value.length) {
              return -1;
            }
            return this._value[delta];
          };
          Tokenizer3.prototype.consumeUnicodeRangeToken = function() {
            var digits = [];
            var codePoint = this.consumeCodePoint();
            while (isHex(codePoint) && digits.length < 6) {
              digits.push(codePoint);
              codePoint = this.consumeCodePoint();
            }
            var questionMarks = false;
            while (codePoint === QUESTION_MARK && digits.length < 6) {
              digits.push(codePoint);
              codePoint = this.consumeCodePoint();
              questionMarks = true;
            }
            if (questionMarks) {
              var start_1 = parseInt(fromCodePoint$1.apply(void 0, digits.map(function(digit) {
                return digit === QUESTION_MARK ? ZERO : digit;
              })), 16);
              var end = parseInt(fromCodePoint$1.apply(void 0, digits.map(function(digit) {
                return digit === QUESTION_MARK ? F2 : digit;
              })), 16);
              return { type: 30, start: start_1, end };
            }
            var start = parseInt(fromCodePoint$1.apply(void 0, digits), 16);
            if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) {
              this.consumeCodePoint();
              codePoint = this.consumeCodePoint();
              var endDigits = [];
              while (isHex(codePoint) && endDigits.length < 6) {
                endDigits.push(codePoint);
                codePoint = this.consumeCodePoint();
              }
              var end = parseInt(fromCodePoint$1.apply(void 0, endDigits), 16);
              return { type: 30, start, end };
            } else {
              return { type: 30, start, end: start };
            }
          };
          Tokenizer3.prototype.consumeIdentLikeToken = function() {
            var value2 = this.consumeName();
            if (value2.toLowerCase() === "url" && this.peekCodePoint(0) === LEFT_PARENTHESIS) {
              this.consumeCodePoint();
              return this.consumeUrlToken();
            } else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) {
              this.consumeCodePoint();
              return { type: 19, value: value2 };
            }
            return { type: 20, value: value2 };
          };
          Tokenizer3.prototype.consumeUrlToken = function() {
            var value2 = [];
            this.consumeWhiteSpace();
            if (this.peekCodePoint(0) === EOF) {
              return { type: 22, value: "" };
            }
            var next2 = this.peekCodePoint(0);
            if (next2 === APOSTROPHE2 || next2 === QUOTATION_MARK) {
              var stringToken = this.consumeStringToken(this.consumeCodePoint());
              if (stringToken.type === 0) {
                this.consumeWhiteSpace();
                if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
                  this.consumeCodePoint();
                  return { type: 22, value: stringToken.value };
                }
              }
              this.consumeBadUrlRemnants();
              return BAD_URL_TOKEN;
            }
            while (true) {
              var codePoint = this.consumeCodePoint();
              if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) {
                return { type: 22, value: fromCodePoint$1.apply(void 0, value2) };
              } else if (isWhiteSpace2(codePoint)) {
                this.consumeWhiteSpace();
                if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
                  this.consumeCodePoint();
                  return { type: 22, value: fromCodePoint$1.apply(void 0, value2) };
                }
                this.consumeBadUrlRemnants();
                return BAD_URL_TOKEN;
              } else if (codePoint === QUOTATION_MARK || codePoint === APOSTROPHE2 || codePoint === LEFT_PARENTHESIS || isNonPrintableCodePoint(codePoint)) {
                this.consumeBadUrlRemnants();
                return BAD_URL_TOKEN;
              } else if (codePoint === REVERSE_SOLIDUS) {
                if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                  value2.push(this.consumeEscapedCodePoint());
                } else {
                  this.consumeBadUrlRemnants();
                  return BAD_URL_TOKEN;
                }
              } else {
                value2.push(codePoint);
              }
            }
          };
          Tokenizer3.prototype.consumeWhiteSpace = function() {
            while (isWhiteSpace2(this.peekCodePoint(0))) {
              this.consumeCodePoint();
            }
          };
          Tokenizer3.prototype.consumeBadUrlRemnants = function() {
            while (true) {
              var codePoint = this.consumeCodePoint();
              if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) {
                return;
              }
              if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                this.consumeEscapedCodePoint();
              }
            }
          };
          Tokenizer3.prototype.consumeStringSlice = function(count) {
            var SLICE_STACK_SIZE = 5e4;
            var value2 = "";
            while (count > 0) {
              var amount = Math.min(SLICE_STACK_SIZE, count);
              value2 += fromCodePoint$1.apply(void 0, this._value.splice(0, amount));
              count -= amount;
            }
            this._value.shift();
            return value2;
          };
          Tokenizer3.prototype.consumeStringToken = function(endingCodePoint) {
            var value2 = "";
            var i4 = 0;
            do {
              var codePoint = this._value[i4];
              if (codePoint === EOF || codePoint === void 0 || codePoint === endingCodePoint) {
                value2 += this.consumeStringSlice(i4);
                return { type: 0, value: value2 };
              }
              if (codePoint === LINE_FEED) {
                this._value.splice(0, i4);
                return BAD_STRING_TOKEN;
              }
              if (codePoint === REVERSE_SOLIDUS) {
                var next2 = this._value[i4 + 1];
                if (next2 !== EOF && next2 !== void 0) {
                  if (next2 === LINE_FEED) {
                    value2 += this.consumeStringSlice(i4);
                    i4 = -1;
                    this._value.shift();
                  } else if (isValidEscape(codePoint, next2)) {
                    value2 += this.consumeStringSlice(i4);
                    value2 += fromCodePoint$1(this.consumeEscapedCodePoint());
                    i4 = -1;
                  }
                }
              }
              i4++;
            } while (true);
          };
          Tokenizer3.prototype.consumeNumber = function() {
            var repr = [];
            var type = FLAG_INTEGER;
            var c1 = this.peekCodePoint(0);
            if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
              repr.push(this.consumeCodePoint());
            }
            while (isDigit(this.peekCodePoint(0))) {
              repr.push(this.consumeCodePoint());
            }
            c1 = this.peekCodePoint(0);
            var c22 = this.peekCodePoint(1);
            if (c1 === FULL_STOP && isDigit(c22)) {
              repr.push(this.consumeCodePoint(), this.consumeCodePoint());
              type = FLAG_NUMBER;
              while (isDigit(this.peekCodePoint(0))) {
                repr.push(this.consumeCodePoint());
              }
            }
            c1 = this.peekCodePoint(0);
            c22 = this.peekCodePoint(1);
            var c3 = this.peekCodePoint(2);
            if ((c1 === E3 || c1 === e3) && ((c22 === PLUS_SIGN || c22 === HYPHEN_MINUS) && isDigit(c3) || isDigit(c22))) {
              repr.push(this.consumeCodePoint(), this.consumeCodePoint());
              type = FLAG_NUMBER;
              while (isDigit(this.peekCodePoint(0))) {
                repr.push(this.consumeCodePoint());
              }
            }
            return [stringToNumber(repr), type];
          };
          Tokenizer3.prototype.consumeNumericToken = function() {
            var _a4 = this.consumeNumber(), number3 = _a4[0], flags = _a4[1];
            var c1 = this.peekCodePoint(0);
            var c22 = this.peekCodePoint(1);
            var c3 = this.peekCodePoint(2);
            if (isIdentifierStart(c1, c22, c3)) {
              var unit = this.consumeName();
              return { type: 15, number: number3, flags, unit };
            }
            if (c1 === PERCENTAGE_SIGN) {
              this.consumeCodePoint();
              return { type: 16, number: number3, flags };
            }
            return { type: 17, number: number3, flags };
          };
          Tokenizer3.prototype.consumeEscapedCodePoint = function() {
            var codePoint = this.consumeCodePoint();
            if (isHex(codePoint)) {
              var hex = fromCodePoint$1(codePoint);
              while (isHex(this.peekCodePoint(0)) && hex.length < 6) {
                hex += fromCodePoint$1(this.consumeCodePoint());
              }
              if (isWhiteSpace2(this.peekCodePoint(0))) {
                this.consumeCodePoint();
              }
              var hexCodePoint = parseInt(hex, 16);
              if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 1114111) {
                return REPLACEMENT_CHARACTER;
              }
              return hexCodePoint;
            }
            if (codePoint === EOF) {
              return REPLACEMENT_CHARACTER;
            }
            return codePoint;
          };
          Tokenizer3.prototype.consumeName = function() {
            var result2 = "";
            while (true) {
              var codePoint = this.consumeCodePoint();
              if (isNameCodePoint(codePoint)) {
                result2 += fromCodePoint$1(codePoint);
              } else if (isValidEscape(codePoint, this.peekCodePoint(0))) {
                result2 += fromCodePoint$1(this.consumeEscapedCodePoint());
              } else {
                this.reconsumeCodePoint(codePoint);
                return result2;
              }
            }
          };
          return Tokenizer3;
        }()
      );
      var Parser4 = (
        /** @class */
        function() {
          function Parser5(tokens) {
            this._tokens = tokens;
          }
          Parser5.create = function(value2) {
            var tokenizer = new Tokenizer2();
            tokenizer.write(value2);
            return new Parser5(tokenizer.read());
          };
          Parser5.parseValue = function(value2) {
            return Parser5.create(value2).parseComponentValue();
          };
          Parser5.parseValues = function(value2) {
            return Parser5.create(value2).parseComponentValues();
          };
          Parser5.prototype.parseComponentValue = function() {
            var token = this.consumeToken();
            while (token.type === 31) {
              token = this.consumeToken();
            }
            if (token.type === 32) {
              throw new SyntaxError("Error parsing CSS component value, unexpected EOF");
            }
            this.reconsumeToken(token);
            var value2 = this.consumeComponentValue();
            do {
              token = this.consumeToken();
            } while (token.type === 31);
            if (token.type === 32) {
              return value2;
            }
            throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one");
          };
          Parser5.prototype.parseComponentValues = function() {
            var values2 = [];
            while (true) {
              var value2 = this.consumeComponentValue();
              if (value2.type === 32) {
                return values2;
              }
              values2.push(value2);
              values2.push();
            }
          };
          Parser5.prototype.consumeComponentValue = function() {
            var token = this.consumeToken();
            switch (token.type) {
              case 11:
              case 28:
              case 2:
                return this.consumeSimpleBlock(token.type);
              case 19:
                return this.consumeFunction(token);
            }
            return token;
          };
          Parser5.prototype.consumeSimpleBlock = function(type) {
            var block3 = { type, values: [] };
            var token = this.consumeToken();
            while (true) {
              if (token.type === 32 || isEndingTokenFor(token, type)) {
                return block3;
              }
              this.reconsumeToken(token);
              block3.values.push(this.consumeComponentValue());
              token = this.consumeToken();
            }
          };
          Parser5.prototype.consumeFunction = function(functionToken) {
            var cssFunction = {
              name: functionToken.value,
              values: [],
              type: 18
              /* FUNCTION */
            };
            while (true) {
              var token = this.consumeToken();
              if (token.type === 32 || token.type === 3) {
                return cssFunction;
              }
              this.reconsumeToken(token);
              cssFunction.values.push(this.consumeComponentValue());
            }
          };
          Parser5.prototype.consumeToken = function() {
            var token = this._tokens.shift();
            return typeof token === "undefined" ? EOF_TOKEN : token;
          };
          Parser5.prototype.reconsumeToken = function(token) {
            this._tokens.unshift(token);
          };
          return Parser5;
        }()
      );
      var isDimensionToken = function(token) {
        return token.type === 15;
      };
      var isNumberToken = function(token) {
        return token.type === 17;
      };
      var isIdentToken = function(token) {
        return token.type === 20;
      };
      var isStringToken = function(token) {
        return token.type === 0;
      };
      var isIdentWithValue = function(token, value2) {
        return isIdentToken(token) && token.value === value2;
      };
      var nonWhiteSpace = function(token) {
        return token.type !== 31;
      };
      var nonFunctionArgSeparator = function(token) {
        return token.type !== 31 && token.type !== 4;
      };
      var parseFunctionArgs = function(tokens) {
        var args = [];
        var arg = [];
        tokens.forEach(function(token) {
          if (token.type === 4) {
            if (arg.length === 0) {
              throw new Error("Error parsing function args, zero tokens for arg");
            }
            args.push(arg);
            arg = [];
            return;
          }
          if (token.type !== 31) {
            arg.push(token);
          }
        });
        if (arg.length) {
          args.push(arg);
        }
        return args;
      };
      var isEndingTokenFor = function(token, type) {
        if (type === 11 && token.type === 12) {
          return true;
        }
        if (type === 28 && token.type === 29) {
          return true;
        }
        return type === 2 && token.type === 3;
      };
      var isLength = function(token) {
        return token.type === 17 || token.type === 15;
      };
      var isLengthPercentage = function(token) {
        return token.type === 16 || isLength(token);
      };
      var parseLengthPercentageTuple = function(tokens) {
        return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]];
      };
      var ZERO_LENGTH = {
        type: 17,
        number: 0,
        flags: FLAG_INTEGER
      };
      var FIFTY_PERCENT = {
        type: 16,
        number: 50,
        flags: FLAG_INTEGER
      };
      var HUNDRED_PERCENT = {
        type: 16,
        number: 100,
        flags: FLAG_INTEGER
      };
      var getAbsoluteValueForTuple = function(tuple, width, height) {
        var x3 = tuple[0], y3 = tuple[1];
        return [getAbsoluteValue(x3, width), getAbsoluteValue(typeof y3 !== "undefined" ? y3 : x3, height)];
      };
      var getAbsoluteValue = function(token, parent) {
        if (token.type === 16) {
          return token.number / 100 * parent;
        }
        if (isDimensionToken(token)) {
          switch (token.unit) {
            case "rem":
            case "em":
              return 16 * token.number;
            // TODO use correct font-size
            case "px":
            default:
              return token.number;
          }
        }
        return token.number;
      };
      var DEG = "deg";
      var GRAD = "grad";
      var RAD = "rad";
      var TURN = "turn";
      var angle = {
        name: "angle",
        parse: function(_context, value2) {
          if (value2.type === 15) {
            switch (value2.unit) {
              case DEG:
                return Math.PI * value2.number / 180;
              case GRAD:
                return Math.PI / 200 * value2.number;
              case RAD:
                return value2.number;
              case TURN:
                return Math.PI * 2 * value2.number;
            }
          }
          throw new Error("Unsupported angle type");
        }
      };
      var isAngle = function(value2) {
        if (value2.type === 15) {
          if (value2.unit === DEG || value2.unit === GRAD || value2.unit === RAD || value2.unit === TURN) {
            return true;
          }
        }
        return false;
      };
      var parseNamedSide = function(tokens) {
        var sideOrCorner = tokens.filter(isIdentToken).map(function(ident) {
          return ident.value;
        }).join(" ");
        switch (sideOrCorner) {
          case "to bottom right":
          case "to right bottom":
          case "left top":
          case "top left":
            return [ZERO_LENGTH, ZERO_LENGTH];
          case "to top":
          case "bottom":
            return deg(0);
          case "to bottom left":
          case "to left bottom":
          case "right top":
          case "top right":
            return [ZERO_LENGTH, HUNDRED_PERCENT];
          case "to right":
          case "left":
            return deg(90);
          case "to top left":
          case "to left top":
          case "right bottom":
          case "bottom right":
            return [HUNDRED_PERCENT, HUNDRED_PERCENT];
          case "to bottom":
          case "top":
            return deg(180);
          case "to top right":
          case "to right top":
          case "left bottom":
          case "bottom left":
            return [HUNDRED_PERCENT, ZERO_LENGTH];
          case "to left":
          case "right":
            return deg(270);
        }
        return 0;
      };
      var deg = function(deg2) {
        return Math.PI * deg2 / 180;
      };
      var color$1 = {
        name: "color",
        parse: function(context, value2) {
          if (value2.type === 18) {
            var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value2.name];
            if (typeof colorFunction === "undefined") {
              throw new Error('Attempting to parse an unsupported color function "' + value2.name + '"');
            }
            return colorFunction(context, value2.values);
          }
          if (value2.type === 5) {
            if (value2.value.length === 3) {
              var r3 = value2.value.substring(0, 1);
              var g3 = value2.value.substring(1, 2);
              var b3 = value2.value.substring(2, 3);
              return pack(parseInt(r3 + r3, 16), parseInt(g3 + g3, 16), parseInt(b3 + b3, 16), 1);
            }
            if (value2.value.length === 4) {
              var r3 = value2.value.substring(0, 1);
              var g3 = value2.value.substring(1, 2);
              var b3 = value2.value.substring(2, 3);
              var a4 = value2.value.substring(3, 4);
              return pack(parseInt(r3 + r3, 16), parseInt(g3 + g3, 16), parseInt(b3 + b3, 16), parseInt(a4 + a4, 16) / 255);
            }
            if (value2.value.length === 6) {
              var r3 = value2.value.substring(0, 2);
              var g3 = value2.value.substring(2, 4);
              var b3 = value2.value.substring(4, 6);
              return pack(parseInt(r3, 16), parseInt(g3, 16), parseInt(b3, 16), 1);
            }
            if (value2.value.length === 8) {
              var r3 = value2.value.substring(0, 2);
              var g3 = value2.value.substring(2, 4);
              var b3 = value2.value.substring(4, 6);
              var a4 = value2.value.substring(6, 8);
              return pack(parseInt(r3, 16), parseInt(g3, 16), parseInt(b3, 16), parseInt(a4, 16) / 255);
            }
          }
          if (value2.type === 20) {
            var namedColor = COLORS[value2.value.toUpperCase()];
            if (typeof namedColor !== "undefined") {
              return namedColor;
            }
          }
          return COLORS.TRANSPARENT;
        }
      };
      var isTransparent = function(color2) {
        return (255 & color2) === 0;
      };
      var asString = function(color2) {
        var alpha = 255 & color2;
        var blue = 255 & color2 >> 8;
        var green = 255 & color2 >> 16;
        var red = 255 & color2 >> 24;
        return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")";
      };
      var pack = function(r3, g3, b3, a4) {
        return (r3 << 24 | g3 << 16 | b3 << 8 | Math.round(a4 * 255) << 0) >>> 0;
      };
      var getTokenColorValue = function(token, i4) {
        if (token.type === 17) {
          return token.number;
        }
        if (token.type === 16) {
          var max3 = i4 === 3 ? 1 : 255;
          return i4 === 3 ? token.number / 100 * max3 : Math.round(token.number / 100 * max3);
        }
        return 0;
      };
      var rgb = function(_context, args) {
        var tokens = args.filter(nonFunctionArgSeparator);
        if (tokens.length === 3) {
          var _a4 = tokens.map(getTokenColorValue), r3 = _a4[0], g3 = _a4[1], b3 = _a4[2];
          return pack(r3, g3, b3, 1);
        }
        if (tokens.length === 4) {
          var _b = tokens.map(getTokenColorValue), r3 = _b[0], g3 = _b[1], b3 = _b[2], a4 = _b[3];
          return pack(r3, g3, b3, a4);
        }
        return 0;
      };
      function hue2rgb(t1, t22, hue) {
        if (hue < 0) {
          hue += 1;
        }
        if (hue >= 1) {
          hue -= 1;
        }
        if (hue < 1 / 6) {
          return (t22 - t1) * hue * 6 + t1;
        } else if (hue < 1 / 2) {
          return t22;
        } else if (hue < 2 / 3) {
          return (t22 - t1) * 6 * (2 / 3 - hue) + t1;
        } else {
          return t1;
        }
      }
      var hsl = function(context, args) {
        var tokens = args.filter(nonFunctionArgSeparator);
        var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3];
        var h3 = (hue.type === 17 ? deg(hue.number) : angle.parse(context, hue)) / (Math.PI * 2);
        var s3 = isLengthPercentage(saturation) ? saturation.number / 100 : 0;
        var l3 = isLengthPercentage(lightness) ? lightness.number / 100 : 0;
        var a4 = typeof alpha !== "undefined" && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1;
        if (s3 === 0) {
          return pack(l3 * 255, l3 * 255, l3 * 255, 1);
        }
        var t22 = l3 <= 0.5 ? l3 * (s3 + 1) : l3 + s3 - l3 * s3;
        var t1 = l3 * 2 - t22;
        var r3 = hue2rgb(t1, t22, h3 + 1 / 3);
        var g3 = hue2rgb(t1, t22, h3);
        var b3 = hue2rgb(t1, t22, h3 - 1 / 3);
        return pack(r3 * 255, g3 * 255, b3 * 255, a4);
      };
      var SUPPORTED_COLOR_FUNCTIONS = {
        hsl,
        hsla: hsl,
        rgb,
        rgba: rgb
      };
      var parseColor2 = function(context, value2) {
        return color$1.parse(context, Parser4.create(value2).parseComponentValue());
      };
      var COLORS = {
        ALICEBLUE: 4042850303,
        ANTIQUEWHITE: 4209760255,
        AQUA: 16777215,
        AQUAMARINE: 2147472639,
        AZURE: 4043309055,
        BEIGE: 4126530815,
        BISQUE: 4293182719,
        BLACK: 255,
        BLANCHEDALMOND: 4293643775,
        BLUE: 65535,
        BLUEVIOLET: 2318131967,
        BROWN: 2771004159,
        BURLYWOOD: 3736635391,
        CADETBLUE: 1604231423,
        CHARTREUSE: 2147418367,
        CHOCOLATE: 3530104575,
        CORAL: 4286533887,
        CORNFLOWERBLUE: 1687547391,
        CORNSILK: 4294499583,
        CRIMSON: 3692313855,
        CYAN: 16777215,
        DARKBLUE: 35839,
        DARKCYAN: 9145343,
        DARKGOLDENROD: 3095837695,
        DARKGRAY: 2846468607,
        DARKGREEN: 6553855,
        DARKGREY: 2846468607,
        DARKKHAKI: 3182914559,
        DARKMAGENTA: 2332068863,
        DARKOLIVEGREEN: 1433087999,
        DARKORANGE: 4287365375,
        DARKORCHID: 2570243327,
        DARKRED: 2332033279,
        DARKSALMON: 3918953215,
        DARKSEAGREEN: 2411499519,
        DARKSLATEBLUE: 1211993087,
        DARKSLATEGRAY: 793726975,
        DARKSLATEGREY: 793726975,
        DARKTURQUOISE: 13554175,
        DARKVIOLET: 2483082239,
        DEEPPINK: 4279538687,
        DEEPSKYBLUE: 12582911,
        DIMGRAY: 1768516095,
        DIMGREY: 1768516095,
        DODGERBLUE: 512819199,
        FIREBRICK: 2988581631,
        FLORALWHITE: 4294635775,
        FORESTGREEN: 579543807,
        FUCHSIA: 4278255615,
        GAINSBORO: 3705462015,
        GHOSTWHITE: 4177068031,
        GOLD: 4292280575,
        GOLDENROD: 3668254975,
        GRAY: 2155905279,
        GREEN: 8388863,
        GREENYELLOW: 2919182335,
        GREY: 2155905279,
        HONEYDEW: 4043305215,
        HOTPINK: 4285117695,
        INDIANRED: 3445382399,
        INDIGO: 1258324735,
        IVORY: 4294963455,
        KHAKI: 4041641215,
        LAVENDER: 3873897215,
        LAVENDERBLUSH: 4293981695,
        LAWNGREEN: 2096890111,
        LEMONCHIFFON: 4294626815,
        LIGHTBLUE: 2916673279,
        LIGHTCORAL: 4034953471,
        LIGHTCYAN: 3774873599,
        LIGHTGOLDENRODYELLOW: 4210742015,
        LIGHTGRAY: 3553874943,
        LIGHTGREEN: 2431553791,
        LIGHTGREY: 3553874943,
        LIGHTPINK: 4290167295,
        LIGHTSALMON: 4288707327,
        LIGHTSEAGREEN: 548580095,
        LIGHTSKYBLUE: 2278488831,
        LIGHTSLATEGRAY: 2005441023,
        LIGHTSLATEGREY: 2005441023,
        LIGHTSTEELBLUE: 2965692159,
        LIGHTYELLOW: 4294959359,
        LIME: 16711935,
        LIMEGREEN: 852308735,
        LINEN: 4210091775,
        MAGENTA: 4278255615,
        MAROON: 2147483903,
        MEDIUMAQUAMARINE: 1724754687,
        MEDIUMBLUE: 52735,
        MEDIUMORCHID: 3126187007,
        MEDIUMPURPLE: 2473647103,
        MEDIUMSEAGREEN: 1018393087,
        MEDIUMSLATEBLUE: 2070474495,
        MEDIUMSPRINGGREEN: 16423679,
        MEDIUMTURQUOISE: 1221709055,
        MEDIUMVIOLETRED: 3340076543,
        MIDNIGHTBLUE: 421097727,
        MINTCREAM: 4127193855,
        MISTYROSE: 4293190143,
        MOCCASIN: 4293178879,
        NAVAJOWHITE: 4292783615,
        NAVY: 33023,
        OLDLACE: 4260751103,
        OLIVE: 2155872511,
        OLIVEDRAB: 1804477439,
        ORANGE: 4289003775,
        ORANGERED: 4282712319,
        ORCHID: 3664828159,
        PALEGOLDENROD: 4008225535,
        PALEGREEN: 2566625535,
        PALETURQUOISE: 2951671551,
        PALEVIOLETRED: 3681588223,
        PAPAYAWHIP: 4293907967,
        PEACHPUFF: 4292524543,
        PERU: 3448061951,
        PINK: 4290825215,
        PLUM: 3718307327,
        POWDERBLUE: 2967529215,
        PURPLE: 2147516671,
        REBECCAPURPLE: 1714657791,
        RED: 4278190335,
        ROSYBROWN: 3163525119,
        ROYALBLUE: 1097458175,
        SADDLEBROWN: 2336560127,
        SALMON: 4202722047,
        SANDYBROWN: 4104413439,
        SEAGREEN: 780883967,
        SEASHELL: 4294307583,
        SIENNA: 2689740287,
        SILVER: 3233857791,
        SKYBLUE: 2278484991,
        SLATEBLUE: 1784335871,
        SLATEGRAY: 1887473919,
        SLATEGREY: 1887473919,
        SNOW: 4294638335,
        SPRINGGREEN: 16744447,
        STEELBLUE: 1182971135,
        TAN: 3535047935,
        TEAL: 8421631,
        THISTLE: 3636451583,
        TOMATO: 4284696575,
        TRANSPARENT: 0,
        TURQUOISE: 1088475391,
        VIOLET: 4001558271,
        WHEAT: 4125012991,
        WHITE: 4294967295,
        WHITESMOKE: 4126537215,
        YELLOW: 4294902015,
        YELLOWGREEN: 2597139199
      };
      var backgroundClip = {
        name: "background-clip",
        initialValue: "border-box",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return tokens.map(function(token) {
            if (isIdentToken(token)) {
              switch (token.value) {
                case "padding-box":
                  return 1;
                case "content-box":
                  return 2;
              }
            }
            return 0;
          });
        }
      };
      var backgroundColor = {
        name: "background-color",
        initialValue: "transparent",
        prefix: false,
        type: 3,
        format: "color"
      };
      var parseColorStop = function(context, args) {
        var color2 = color$1.parse(context, args[0]);
        var stop = args[1];
        return stop && isLengthPercentage(stop) ? { color: color2, stop } : { color: color2, stop: null };
      };
      var processColorStops = function(stops, lineLength) {
        var first2 = stops[0];
        var last3 = stops[stops.length - 1];
        if (first2.stop === null) {
          first2.stop = ZERO_LENGTH;
        }
        if (last3.stop === null) {
          last3.stop = HUNDRED_PERCENT;
        }
        var processStops = [];
        var previous = 0;
        for (var i4 = 0; i4 < stops.length; i4++) {
          var stop_1 = stops[i4].stop;
          if (stop_1 !== null) {
            var absoluteValue = getAbsoluteValue(stop_1, lineLength);
            if (absoluteValue > previous) {
              processStops.push(absoluteValue);
            } else {
              processStops.push(previous);
            }
            previous = absoluteValue;
          } else {
            processStops.push(null);
          }
        }
        var gapBegin = null;
        for (var i4 = 0; i4 < processStops.length; i4++) {
          var stop_2 = processStops[i4];
          if (stop_2 === null) {
            if (gapBegin === null) {
              gapBegin = i4;
            }
          } else if (gapBegin !== null) {
            var gapLength = i4 - gapBegin;
            var beforeGap = processStops[gapBegin - 1];
            var gapValue = (stop_2 - beforeGap) / (gapLength + 1);
            for (var g3 = 1; g3 <= gapLength; g3++) {
              processStops[gapBegin + g3 - 1] = gapValue * g3;
            }
            gapBegin = null;
          }
        }
        return stops.map(function(_a4, i5) {
          var color2 = _a4.color;
          return { color: color2, stop: Math.max(Math.min(1, processStops[i5] / lineLength), 0) };
        });
      };
      var getAngleFromCorner = function(corner, width, height) {
        var centerX = width / 2;
        var centerY = height / 2;
        var x3 = getAbsoluteValue(corner[0], width) - centerX;
        var y3 = centerY - getAbsoluteValue(corner[1], height);
        return (Math.atan2(y3, x3) + Math.PI * 2) % (Math.PI * 2);
      };
      var calculateGradientDirection = function(angle2, width, height) {
        var radian = typeof angle2 === "number" ? angle2 : getAngleFromCorner(angle2, width, height);
        var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
        var halfWidth = width / 2;
        var halfHeight = height / 2;
        var halfLineLength = lineLength / 2;
        var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength;
        var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength;
        return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff];
      };
      var distance = function(a4, b3) {
        return Math.sqrt(a4 * a4 + b3 * b3);
      };
      var findCorner = function(width, height, x3, y3, closest) {
        var corners = [
          [0, 0],
          [0, height],
          [width, 0],
          [width, height]
        ];
        return corners.reduce(function(stat, corner) {
          var cx = corner[0], cy = corner[1];
          var d3 = distance(x3 - cx, y3 - cy);
          if (closest ? d3 < stat.optimumDistance : d3 > stat.optimumDistance) {
            return {
              optimumCorner: corner,
              optimumDistance: d3
            };
          }
          return stat;
        }, {
          optimumDistance: closest ? Infinity : -Infinity,
          optimumCorner: null
        }).optimumCorner;
      };
      var calculateRadius = function(gradient, x3, y3, width, height) {
        var rx = 0;
        var ry = 0;
        switch (gradient.size) {
          case 0:
            if (gradient.shape === 0) {
              rx = ry = Math.min(Math.abs(x3), Math.abs(x3 - width), Math.abs(y3), Math.abs(y3 - height));
            } else if (gradient.shape === 1) {
              rx = Math.min(Math.abs(x3), Math.abs(x3 - width));
              ry = Math.min(Math.abs(y3), Math.abs(y3 - height));
            }
            break;
          case 2:
            if (gradient.shape === 0) {
              rx = ry = Math.min(distance(x3, y3), distance(x3, y3 - height), distance(x3 - width, y3), distance(x3 - width, y3 - height));
            } else if (gradient.shape === 1) {
              var c3 = Math.min(Math.abs(y3), Math.abs(y3 - height)) / Math.min(Math.abs(x3), Math.abs(x3 - width));
              var _a4 = findCorner(width, height, x3, y3, true), cx = _a4[0], cy = _a4[1];
              rx = distance(cx - x3, (cy - y3) / c3);
              ry = c3 * rx;
            }
            break;
          case 1:
            if (gradient.shape === 0) {
              rx = ry = Math.max(Math.abs(x3), Math.abs(x3 - width), Math.abs(y3), Math.abs(y3 - height));
            } else if (gradient.shape === 1) {
              rx = Math.max(Math.abs(x3), Math.abs(x3 - width));
              ry = Math.max(Math.abs(y3), Math.abs(y3 - height));
            }
            break;
          case 3:
            if (gradient.shape === 0) {
              rx = ry = Math.max(distance(x3, y3), distance(x3, y3 - height), distance(x3 - width, y3), distance(x3 - width, y3 - height));
            } else if (gradient.shape === 1) {
              var c3 = Math.max(Math.abs(y3), Math.abs(y3 - height)) / Math.max(Math.abs(x3), Math.abs(x3 - width));
              var _b = findCorner(width, height, x3, y3, false), cx = _b[0], cy = _b[1];
              rx = distance(cx - x3, (cy - y3) / c3);
              ry = c3 * rx;
            }
            break;
        }
        if (Array.isArray(gradient.size)) {
          rx = getAbsoluteValue(gradient.size[0], width);
          ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx;
        }
        return [rx, ry];
      };
      var linearGradient = function(context, tokens) {
        var angle$1 = deg(180);
        var stops = [];
        parseFunctionArgs(tokens).forEach(function(arg, i4) {
          if (i4 === 0) {
            var firstToken = arg[0];
            if (firstToken.type === 20 && firstToken.value === "to") {
              angle$1 = parseNamedSide(arg);
              return;
            } else if (isAngle(firstToken)) {
              angle$1 = angle.parse(context, firstToken);
              return;
            }
          }
          var colorStop = parseColorStop(context, arg);
          stops.push(colorStop);
        });
        return {
          angle: angle$1,
          stops,
          type: 1
          /* LINEAR_GRADIENT */
        };
      };
      var prefixLinearGradient = function(context, tokens) {
        var angle$1 = deg(180);
        var stops = [];
        parseFunctionArgs(tokens).forEach(function(arg, i4) {
          if (i4 === 0) {
            var firstToken = arg[0];
            if (firstToken.type === 20 && ["top", "left", "right", "bottom"].indexOf(firstToken.value) !== -1) {
              angle$1 = parseNamedSide(arg);
              return;
            } else if (isAngle(firstToken)) {
              angle$1 = (angle.parse(context, firstToken) + deg(270)) % deg(360);
              return;
            }
          }
          var colorStop = parseColorStop(context, arg);
          stops.push(colorStop);
        });
        return {
          angle: angle$1,
          stops,
          type: 1
          /* LINEAR_GRADIENT */
        };
      };
      var webkitGradient = function(context, tokens) {
        var angle2 = deg(180);
        var stops = [];
        var type = 1;
        var shape = 0;
        var size4 = 3;
        var position2 = [];
        parseFunctionArgs(tokens).forEach(function(arg, i4) {
          var firstToken = arg[0];
          if (i4 === 0) {
            if (isIdentToken(firstToken) && firstToken.value === "linear") {
              type = 1;
              return;
            } else if (isIdentToken(firstToken) && firstToken.value === "radial") {
              type = 2;
              return;
            }
          }
          if (firstToken.type === 18) {
            if (firstToken.name === "from") {
              var color2 = color$1.parse(context, firstToken.values[0]);
              stops.push({ stop: ZERO_LENGTH, color: color2 });
            } else if (firstToken.name === "to") {
              var color2 = color$1.parse(context, firstToken.values[0]);
              stops.push({ stop: HUNDRED_PERCENT, color: color2 });
            } else if (firstToken.name === "color-stop") {
              var values2 = firstToken.values.filter(nonFunctionArgSeparator);
              if (values2.length === 2) {
                var color2 = color$1.parse(context, values2[1]);
                var stop_1 = values2[0];
                if (isNumberToken(stop_1)) {
                  stops.push({
                    stop: { type: 16, number: stop_1.number * 100, flags: stop_1.flags },
                    color: color2
                  });
                }
              }
            }
          }
        });
        return type === 1 ? {
          angle: (angle2 + deg(180)) % deg(360),
          stops,
          type
        } : { size: size4, shape, stops, position: position2, type };
      };
      var CLOSEST_SIDE = "closest-side";
      var FARTHEST_SIDE = "farthest-side";
      var CLOSEST_CORNER = "closest-corner";
      var FARTHEST_CORNER = "farthest-corner";
      var CIRCLE = "circle";
      var ELLIPSE = "ellipse";
      var COVER = "cover";
      var CONTAIN = "contain";
      var radialGradient = function(context, tokens) {
        var shape = 0;
        var size4 = 3;
        var stops = [];
        var position2 = [];
        parseFunctionArgs(tokens).forEach(function(arg, i4) {
          var isColorStop = true;
          if (i4 === 0) {
            var isAtPosition_1 = false;
            isColorStop = arg.reduce(function(acc, token) {
              if (isAtPosition_1) {
                if (isIdentToken(token)) {
                  switch (token.value) {
                    case "center":
                      position2.push(FIFTY_PERCENT);
                      return acc;
                    case "top":
                    case "left":
                      position2.push(ZERO_LENGTH);
                      return acc;
                    case "right":
                    case "bottom":
                      position2.push(HUNDRED_PERCENT);
                      return acc;
                  }
                } else if (isLengthPercentage(token) || isLength(token)) {
                  position2.push(token);
                }
              } else if (isIdentToken(token)) {
                switch (token.value) {
                  case CIRCLE:
                    shape = 0;
                    return false;
                  case ELLIPSE:
                    shape = 1;
                    return false;
                  case "at":
                    isAtPosition_1 = true;
                    return false;
                  case CLOSEST_SIDE:
                    size4 = 0;
                    return false;
                  case COVER:
                  case FARTHEST_SIDE:
                    size4 = 1;
                    return false;
                  case CONTAIN:
                  case CLOSEST_CORNER:
                    size4 = 2;
                    return false;
                  case FARTHEST_CORNER:
                    size4 = 3;
                    return false;
                }
              } else if (isLength(token) || isLengthPercentage(token)) {
                if (!Array.isArray(size4)) {
                  size4 = [];
                }
                size4.push(token);
                return false;
              }
              return acc;
            }, isColorStop);
          }
          if (isColorStop) {
            var colorStop = parseColorStop(context, arg);
            stops.push(colorStop);
          }
        });
        return {
          size: size4,
          shape,
          stops,
          position: position2,
          type: 2
          /* RADIAL_GRADIENT */
        };
      };
      var prefixRadialGradient = function(context, tokens) {
        var shape = 0;
        var size4 = 3;
        var stops = [];
        var position2 = [];
        parseFunctionArgs(tokens).forEach(function(arg, i4) {
          var isColorStop = true;
          if (i4 === 0) {
            isColorStop = arg.reduce(function(acc, token) {
              if (isIdentToken(token)) {
                switch (token.value) {
                  case "center":
                    position2.push(FIFTY_PERCENT);
                    return false;
                  case "top":
                  case "left":
                    position2.push(ZERO_LENGTH);
                    return false;
                  case "right":
                  case "bottom":
                    position2.push(HUNDRED_PERCENT);
                    return false;
                }
              } else if (isLengthPercentage(token) || isLength(token)) {
                position2.push(token);
                return false;
              }
              return acc;
            }, isColorStop);
          } else if (i4 === 1) {
            isColorStop = arg.reduce(function(acc, token) {
              if (isIdentToken(token)) {
                switch (token.value) {
                  case CIRCLE:
                    shape = 0;
                    return false;
                  case ELLIPSE:
                    shape = 1;
                    return false;
                  case CONTAIN:
                  case CLOSEST_SIDE:
                    size4 = 0;
                    return false;
                  case FARTHEST_SIDE:
                    size4 = 1;
                    return false;
                  case CLOSEST_CORNER:
                    size4 = 2;
                    return false;
                  case COVER:
                  case FARTHEST_CORNER:
                    size4 = 3;
                    return false;
                }
              } else if (isLength(token) || isLengthPercentage(token)) {
                if (!Array.isArray(size4)) {
                  size4 = [];
                }
                size4.push(token);
                return false;
              }
              return acc;
            }, isColorStop);
          }
          if (isColorStop) {
            var colorStop = parseColorStop(context, arg);
            stops.push(colorStop);
          }
        });
        return {
          size: size4,
          shape,
          stops,
          position: position2,
          type: 2
          /* RADIAL_GRADIENT */
        };
      };
      var isLinearGradient = function(background) {
        return background.type === 1;
      };
      var isRadialGradient = function(background) {
        return background.type === 2;
      };
      var image2 = {
        name: "image",
        parse: function(context, value2) {
          if (value2.type === 22) {
            var image_1 = {
              url: value2.value,
              type: 0
              /* URL */
            };
            context.cache.addImage(value2.value);
            return image_1;
          }
          if (value2.type === 18) {
            var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value2.name];
            if (typeof imageFunction === "undefined") {
              throw new Error('Attempting to parse an unsupported image function "' + value2.name + '"');
            }
            return imageFunction(context, value2.values);
          }
          throw new Error("Unsupported image type " + value2.type);
        }
      };
      function isSupportedImage(value2) {
        return !(value2.type === 20 && value2.value === "none") && (value2.type !== 18 || !!SUPPORTED_IMAGE_FUNCTIONS[value2.name]);
      }
      var SUPPORTED_IMAGE_FUNCTIONS = {
        "linear-gradient": linearGradient,
        "-moz-linear-gradient": prefixLinearGradient,
        "-ms-linear-gradient": prefixLinearGradient,
        "-o-linear-gradient": prefixLinearGradient,
        "-webkit-linear-gradient": prefixLinearGradient,
        "radial-gradient": radialGradient,
        "-moz-radial-gradient": prefixRadialGradient,
        "-ms-radial-gradient": prefixRadialGradient,
        "-o-radial-gradient": prefixRadialGradient,
        "-webkit-radial-gradient": prefixRadialGradient,
        "-webkit-gradient": webkitGradient
      };
      var backgroundImage = {
        name: "background-image",
        initialValue: "none",
        type: 1,
        prefix: false,
        parse: function(context, tokens) {
          if (tokens.length === 0) {
            return [];
          }
          var first2 = tokens[0];
          if (first2.type === 20 && first2.value === "none") {
            return [];
          }
          return tokens.filter(function(value2) {
            return nonFunctionArgSeparator(value2) && isSupportedImage(value2);
          }).map(function(value2) {
            return image2.parse(context, value2);
          });
        }
      };
      var backgroundOrigin = {
        name: "background-origin",
        initialValue: "border-box",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return tokens.map(function(token) {
            if (isIdentToken(token)) {
              switch (token.value) {
                case "padding-box":
                  return 1;
                case "content-box":
                  return 2;
              }
            }
            return 0;
          });
        }
      };
      var backgroundPosition = {
        name: "background-position",
        initialValue: "0% 0%",
        type: 1,
        prefix: false,
        parse: function(_context, tokens) {
          return parseFunctionArgs(tokens).map(function(values2) {
            return values2.filter(isLengthPercentage);
          }).map(parseLengthPercentageTuple);
        }
      };
      var backgroundRepeat = {
        name: "background-repeat",
        initialValue: "repeat",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return parseFunctionArgs(tokens).map(function(values2) {
            return values2.filter(isIdentToken).map(function(token) {
              return token.value;
            }).join(" ");
          }).map(parseBackgroundRepeat);
        }
      };
      var parseBackgroundRepeat = function(value2) {
        switch (value2) {
          case "no-repeat":
            return 1;
          case "repeat-x":
          case "repeat no-repeat":
            return 2;
          case "repeat-y":
          case "no-repeat repeat":
            return 3;
          case "repeat":
          default:
            return 0;
        }
      };
      var BACKGROUND_SIZE;
      (function(BACKGROUND_SIZE2) {
        BACKGROUND_SIZE2["AUTO"] = "auto";
        BACKGROUND_SIZE2["CONTAIN"] = "contain";
        BACKGROUND_SIZE2["COVER"] = "cover";
      })(BACKGROUND_SIZE || (BACKGROUND_SIZE = {}));
      var backgroundSize = {
        name: "background-size",
        initialValue: "0",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return parseFunctionArgs(tokens).map(function(values2) {
            return values2.filter(isBackgroundSizeInfoToken);
          });
        }
      };
      var isBackgroundSizeInfoToken = function(value2) {
        return isIdentToken(value2) || isLengthPercentage(value2);
      };
      var borderColorForSide = function(side) {
        return {
          name: "border-" + side + "-color",
          initialValue: "transparent",
          prefix: false,
          type: 3,
          format: "color"
        };
      };
      var borderTopColor = borderColorForSide("top");
      var borderRightColor = borderColorForSide("right");
      var borderBottomColor = borderColorForSide("bottom");
      var borderLeftColor = borderColorForSide("left");
      var borderRadiusForSide = function(side) {
        return {
          name: "border-radius-" + side,
          initialValue: "0 0",
          prefix: false,
          type: 1,
          parse: function(_context, tokens) {
            return parseLengthPercentageTuple(tokens.filter(isLengthPercentage));
          }
        };
      };
      var borderTopLeftRadius = borderRadiusForSide("top-left");
      var borderTopRightRadius = borderRadiusForSide("top-right");
      var borderBottomRightRadius = borderRadiusForSide("bottom-right");
      var borderBottomLeftRadius = borderRadiusForSide("bottom-left");
      var borderStyleForSide = function(side) {
        return {
          name: "border-" + side + "-style",
          initialValue: "solid",
          prefix: false,
          type: 2,
          parse: function(_context, style3) {
            switch (style3) {
              case "none":
                return 0;
              case "dashed":
                return 2;
              case "dotted":
                return 3;
              case "double":
                return 4;
            }
            return 1;
          }
        };
      };
      var borderTopStyle = borderStyleForSide("top");
      var borderRightStyle = borderStyleForSide("right");
      var borderBottomStyle = borderStyleForSide("bottom");
      var borderLeftStyle = borderStyleForSide("left");
      var borderWidthForSide = function(side) {
        return {
          name: "border-" + side + "-width",
          initialValue: "0",
          type: 0,
          prefix: false,
          parse: function(_context, token) {
            if (isDimensionToken(token)) {
              return token.number;
            }
            return 0;
          }
        };
      };
      var borderTopWidth = borderWidthForSide("top");
      var borderRightWidth = borderWidthForSide("right");
      var borderBottomWidth = borderWidthForSide("bottom");
      var borderLeftWidth = borderWidthForSide("left");
      var color = {
        name: "color",
        initialValue: "transparent",
        prefix: false,
        type: 3,
        format: "color"
      };
      var direction = {
        name: "direction",
        initialValue: "ltr",
        prefix: false,
        type: 2,
        parse: function(_context, direction2) {
          switch (direction2) {
            case "rtl":
              return 1;
            case "ltr":
            default:
              return 0;
          }
        }
      };
      var display = {
        name: "display",
        initialValue: "inline-block",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return tokens.filter(isIdentToken).reduce(
            function(bit, token) {
              return bit | parseDisplayValue(token.value);
            },
            0
            /* NONE */
          );
        }
      };
      var parseDisplayValue = function(display2) {
        switch (display2) {
          case "block":
          case "-webkit-box":
            return 2;
          case "inline":
            return 4;
          case "run-in":
            return 8;
          case "flow":
            return 16;
          case "flow-root":
            return 32;
          case "table":
            return 64;
          case "flex":
          case "-webkit-flex":
            return 128;
          case "grid":
          case "-ms-grid":
            return 256;
          case "ruby":
            return 512;
          case "subgrid":
            return 1024;
          case "list-item":
            return 2048;
          case "table-row-group":
            return 4096;
          case "table-header-group":
            return 8192;
          case "table-footer-group":
            return 16384;
          case "table-row":
            return 32768;
          case "table-cell":
            return 65536;
          case "table-column-group":
            return 131072;
          case "table-column":
            return 262144;
          case "table-caption":
            return 524288;
          case "ruby-base":
            return 1048576;
          case "ruby-text":
            return 2097152;
          case "ruby-base-container":
            return 4194304;
          case "ruby-text-container":
            return 8388608;
          case "contents":
            return 16777216;
          case "inline-block":
            return 33554432;
          case "inline-list-item":
            return 67108864;
          case "inline-table":
            return 134217728;
          case "inline-flex":
            return 268435456;
          case "inline-grid":
            return 536870912;
        }
        return 0;
      };
      var float3 = {
        name: "float",
        initialValue: "none",
        prefix: false,
        type: 2,
        parse: function(_context, float4) {
          switch (float4) {
            case "left":
              return 1;
            case "right":
              return 2;
            case "inline-start":
              return 3;
            case "inline-end":
              return 4;
          }
          return 0;
        }
      };
      var letterSpacing = {
        name: "letter-spacing",
        initialValue: "0",
        prefix: false,
        type: 0,
        parse: function(_context, token) {
          if (token.type === 20 && token.value === "normal") {
            return 0;
          }
          if (token.type === 17) {
            return token.number;
          }
          if (token.type === 15) {
            return token.number;
          }
          return 0;
        }
      };
      var LINE_BREAK;
      (function(LINE_BREAK2) {
        LINE_BREAK2["NORMAL"] = "normal";
        LINE_BREAK2["STRICT"] = "strict";
      })(LINE_BREAK || (LINE_BREAK = {}));
      var lineBreak = {
        name: "line-break",
        initialValue: "normal",
        prefix: false,
        type: 2,
        parse: function(_context, lineBreak2) {
          switch (lineBreak2) {
            case "strict":
              return LINE_BREAK.STRICT;
            case "normal":
            default:
              return LINE_BREAK.NORMAL;
          }
        }
      };
      var lineHeight = {
        name: "line-height",
        initialValue: "normal",
        prefix: false,
        type: 4
        /* TOKEN_VALUE */
      };
      var computeLineHeight = function(token, fontSize2) {
        if (isIdentToken(token) && token.value === "normal") {
          return 1.2 * fontSize2;
        } else if (token.type === 17) {
          return fontSize2 * token.number;
        } else if (isLengthPercentage(token)) {
          return getAbsoluteValue(token, fontSize2);
        }
        return fontSize2;
      };
      var listStyleImage = {
        name: "list-style-image",
        initialValue: "none",
        type: 0,
        prefix: false,
        parse: function(context, token) {
          if (token.type === 20 && token.value === "none") {
            return null;
          }
          return image2.parse(context, token);
        }
      };
      var listStylePosition = {
        name: "list-style-position",
        initialValue: "outside",
        prefix: false,
        type: 2,
        parse: function(_context, position2) {
          switch (position2) {
            case "inside":
              return 0;
            case "outside":
            default:
              return 1;
          }
        }
      };
      var listStyleType = {
        name: "list-style-type",
        initialValue: "none",
        prefix: false,
        type: 2,
        parse: function(_context, type) {
          switch (type) {
            case "disc":
              return 0;
            case "circle":
              return 1;
            case "square":
              return 2;
            case "decimal":
              return 3;
            case "cjk-decimal":
              return 4;
            case "decimal-leading-zero":
              return 5;
            case "lower-roman":
              return 6;
            case "upper-roman":
              return 7;
            case "lower-greek":
              return 8;
            case "lower-alpha":
              return 9;
            case "upper-alpha":
              return 10;
            case "arabic-indic":
              return 11;
            case "armenian":
              return 12;
            case "bengali":
              return 13;
            case "cambodian":
              return 14;
            case "cjk-earthly-branch":
              return 15;
            case "cjk-heavenly-stem":
              return 16;
            case "cjk-ideographic":
              return 17;
            case "devanagari":
              return 18;
            case "ethiopic-numeric":
              return 19;
            case "georgian":
              return 20;
            case "gujarati":
              return 21;
            case "gurmukhi":
              return 22;
            case "hebrew":
              return 22;
            case "hiragana":
              return 23;
            case "hiragana-iroha":
              return 24;
            case "japanese-formal":
              return 25;
            case "japanese-informal":
              return 26;
            case "kannada":
              return 27;
            case "katakana":
              return 28;
            case "katakana-iroha":
              return 29;
            case "khmer":
              return 30;
            case "korean-hangul-formal":
              return 31;
            case "korean-hanja-formal":
              return 32;
            case "korean-hanja-informal":
              return 33;
            case "lao":
              return 34;
            case "lower-armenian":
              return 35;
            case "malayalam":
              return 36;
            case "mongolian":
              return 37;
            case "myanmar":
              return 38;
            case "oriya":
              return 39;
            case "persian":
              return 40;
            case "simp-chinese-formal":
              return 41;
            case "simp-chinese-informal":
              return 42;
            case "tamil":
              return 43;
            case "telugu":
              return 44;
            case "thai":
              return 45;
            case "tibetan":
              return 46;
            case "trad-chinese-formal":
              return 47;
            case "trad-chinese-informal":
              return 48;
            case "upper-armenian":
              return 49;
            case "disclosure-open":
              return 50;
            case "disclosure-closed":
              return 51;
            case "none":
            default:
              return -1;
          }
        }
      };
      var marginForSide = function(side) {
        return {
          name: "margin-" + side,
          initialValue: "0",
          prefix: false,
          type: 4
          /* TOKEN_VALUE */
        };
      };
      var marginTop = marginForSide("top");
      var marginRight = marginForSide("right");
      var marginBottom = marginForSide("bottom");
      var marginLeft = marginForSide("left");
      var overflow = {
        name: "overflow",
        initialValue: "visible",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return tokens.filter(isIdentToken).map(function(overflow2) {
            switch (overflow2.value) {
              case "hidden":
                return 1;
              case "scroll":
                return 2;
              case "clip":
                return 3;
              case "auto":
                return 4;
              case "visible":
              default:
                return 0;
            }
          });
        }
      };
      var overflowWrap = {
        name: "overflow-wrap",
        initialValue: "normal",
        prefix: false,
        type: 2,
        parse: function(_context, overflow2) {
          switch (overflow2) {
            case "break-word":
              return "break-word";
            case "normal":
            default:
              return "normal";
          }
        }
      };
      var paddingForSide = function(side) {
        return {
          name: "padding-" + side,
          initialValue: "0",
          prefix: false,
          type: 3,
          format: "length-percentage"
        };
      };
      var paddingTop = paddingForSide("top");
      var paddingRight = paddingForSide("right");
      var paddingBottom = paddingForSide("bottom");
      var paddingLeft = paddingForSide("left");
      var textAlign = {
        name: "text-align",
        initialValue: "left",
        prefix: false,
        type: 2,
        parse: function(_context, textAlign2) {
          switch (textAlign2) {
            case "right":
              return 2;
            case "center":
            case "justify":
              return 1;
            case "left":
            default:
              return 0;
          }
        }
      };
      var position = {
        name: "position",
        initialValue: "static",
        prefix: false,
        type: 2,
        parse: function(_context, position2) {
          switch (position2) {
            case "relative":
              return 1;
            case "absolute":
              return 2;
            case "fixed":
              return 3;
            case "sticky":
              return 4;
          }
          return 0;
        }
      };
      var textShadow = {
        name: "text-shadow",
        initialValue: "none",
        type: 1,
        prefix: false,
        parse: function(context, tokens) {
          if (tokens.length === 1 && isIdentWithValue(tokens[0], "none")) {
            return [];
          }
          return parseFunctionArgs(tokens).map(function(values2) {
            var shadow = {
              color: COLORS.TRANSPARENT,
              offsetX: ZERO_LENGTH,
              offsetY: ZERO_LENGTH,
              blur: ZERO_LENGTH
            };
            var c3 = 0;
            for (var i4 = 0; i4 < values2.length; i4++) {
              var token = values2[i4];
              if (isLength(token)) {
                if (c3 === 0) {
                  shadow.offsetX = token;
                } else if (c3 === 1) {
                  shadow.offsetY = token;
                } else {
                  shadow.blur = token;
                }
                c3++;
              } else {
                shadow.color = color$1.parse(context, token);
              }
            }
            return shadow;
          });
        }
      };
      var textTransform = {
        name: "text-transform",
        initialValue: "none",
        prefix: false,
        type: 2,
        parse: function(_context, textTransform2) {
          switch (textTransform2) {
            case "uppercase":
              return 2;
            case "lowercase":
              return 1;
            case "capitalize":
              return 3;
          }
          return 0;
        }
      };
      var transform$1 = {
        name: "transform",
        initialValue: "none",
        prefix: true,
        type: 0,
        parse: function(_context, token) {
          if (token.type === 20 && token.value === "none") {
            return null;
          }
          if (token.type === 18) {
            var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name];
            if (typeof transformFunction === "undefined") {
              throw new Error('Attempting to parse an unsupported transform function "' + token.name + '"');
            }
            return transformFunction(token.values);
          }
          return null;
        }
      };
      var matrix = function(args) {
        var values2 = args.filter(function(arg) {
          return arg.type === 17;
        }).map(function(arg) {
          return arg.number;
        });
        return values2.length === 6 ? values2 : null;
      };
      var matrix3d = function(args) {
        var values2 = args.filter(function(arg) {
          return arg.type === 17;
        }).map(function(arg) {
          return arg.number;
        });
        var a1 = values2[0], b1 = values2[1];
        values2[2];
        values2[3];
        var a22 = values2[4], b22 = values2[5];
        values2[6];
        values2[7];
        values2[8];
        values2[9];
        values2[10];
        values2[11];
        var a4 = values2[12], b4 = values2[13];
        values2[14];
        values2[15];
        return values2.length === 16 ? [a1, b1, a22, b22, a4, b4] : null;
      };
      var SUPPORTED_TRANSFORM_FUNCTIONS = {
        matrix,
        matrix3d
      };
      var DEFAULT_VALUE = {
        type: 16,
        number: 50,
        flags: FLAG_INTEGER
      };
      var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE];
      var transformOrigin = {
        name: "transform-origin",
        initialValue: "50% 50%",
        prefix: true,
        type: 1,
        parse: function(_context, tokens) {
          var origins = tokens.filter(isLengthPercentage);
          if (origins.length !== 2) {
            return DEFAULT;
          }
          return [origins[0], origins[1]];
        }
      };
      var visibility = {
        name: "visible",
        initialValue: "none",
        prefix: false,
        type: 2,
        parse: function(_context, visibility2) {
          switch (visibility2) {
            case "hidden":
              return 1;
            case "collapse":
              return 2;
            case "visible":
            default:
              return 0;
          }
        }
      };
      var WORD_BREAK;
      (function(WORD_BREAK2) {
        WORD_BREAK2["NORMAL"] = "normal";
        WORD_BREAK2["BREAK_ALL"] = "break-all";
        WORD_BREAK2["KEEP_ALL"] = "keep-all";
      })(WORD_BREAK || (WORD_BREAK = {}));
      var wordBreak = {
        name: "word-break",
        initialValue: "normal",
        prefix: false,
        type: 2,
        parse: function(_context, wordBreak2) {
          switch (wordBreak2) {
            case "break-all":
              return WORD_BREAK.BREAK_ALL;
            case "keep-all":
              return WORD_BREAK.KEEP_ALL;
            case "normal":
            default:
              return WORD_BREAK.NORMAL;
          }
        }
      };
      var zIndex = {
        name: "z-index",
        initialValue: "auto",
        prefix: false,
        type: 0,
        parse: function(_context, token) {
          if (token.type === 20) {
            return { auto: true, order: 0 };
          }
          if (isNumberToken(token)) {
            return { auto: false, order: token.number };
          }
          throw new Error("Invalid z-index number parsed");
        }
      };
      var time3 = {
        name: "time",
        parse: function(_context, value2) {
          if (value2.type === 15) {
            switch (value2.unit.toLowerCase()) {
              case "s":
                return 1e3 * value2.number;
              case "ms":
                return value2.number;
            }
          }
          throw new Error("Unsupported time type");
        }
      };
      var opacity = {
        name: "opacity",
        initialValue: "1",
        type: 0,
        prefix: false,
        parse: function(_context, token) {
          if (isNumberToken(token)) {
            return token.number;
          }
          return 1;
        }
      };
      var textDecorationColor = {
        name: "text-decoration-color",
        initialValue: "transparent",
        prefix: false,
        type: 3,
        format: "color"
      };
      var textDecorationLine = {
        name: "text-decoration-line",
        initialValue: "none",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          return tokens.filter(isIdentToken).map(function(token) {
            switch (token.value) {
              case "underline":
                return 1;
              case "overline":
                return 2;
              case "line-through":
                return 3;
              case "none":
                return 4;
            }
            return 0;
          }).filter(function(line) {
            return line !== 0;
          });
        }
      };
      var fontFamily = {
        name: "font-family",
        initialValue: "",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          var accumulator = [];
          var results2 = [];
          tokens.forEach(function(token) {
            switch (token.type) {
              case 20:
              case 0:
                accumulator.push(token.value);
                break;
              case 17:
                accumulator.push(token.number.toString());
                break;
              case 4:
                results2.push(accumulator.join(" "));
                accumulator.length = 0;
                break;
            }
          });
          if (accumulator.length) {
            results2.push(accumulator.join(" "));
          }
          return results2.map(function(result2) {
            return result2.indexOf(" ") === -1 ? result2 : "'" + result2 + "'";
          });
        }
      };
      var fontSize = {
        name: "font-size",
        initialValue: "0",
        prefix: false,
        type: 3,
        format: "length"
      };
      var fontWeight = {
        name: "font-weight",
        initialValue: "normal",
        type: 0,
        prefix: false,
        parse: function(_context, token) {
          if (isNumberToken(token)) {
            return token.number;
          }
          if (isIdentToken(token)) {
            switch (token.value) {
              case "bold":
                return 700;
              case "normal":
              default:
                return 400;
            }
          }
          return 400;
        }
      };
      var fontVariant = {
        name: "font-variant",
        initialValue: "none",
        type: 1,
        prefix: false,
        parse: function(_context, tokens) {
          return tokens.filter(isIdentToken).map(function(token) {
            return token.value;
          });
        }
      };
      var fontStyle = {
        name: "font-style",
        initialValue: "normal",
        prefix: false,
        type: 2,
        parse: function(_context, overflow2) {
          switch (overflow2) {
            case "oblique":
              return "oblique";
            case "italic":
              return "italic";
            case "normal":
            default:
              return "normal";
          }
        }
      };
      var contains4 = function(bit, value2) {
        return (bit & value2) !== 0;
      };
      var content2 = {
        name: "content",
        initialValue: "none",
        type: 1,
        prefix: false,
        parse: function(_context, tokens) {
          if (tokens.length === 0) {
            return [];
          }
          var first2 = tokens[0];
          if (first2.type === 20 && first2.value === "none") {
            return [];
          }
          return tokens;
        }
      };
      var counterIncrement = {
        name: "counter-increment",
        initialValue: "none",
        prefix: true,
        type: 1,
        parse: function(_context, tokens) {
          if (tokens.length === 0) {
            return null;
          }
          var first2 = tokens[0];
          if (first2.type === 20 && first2.value === "none") {
            return null;
          }
          var increments = [];
          var filtered = tokens.filter(nonWhiteSpace);
          for (var i4 = 0; i4 < filtered.length; i4++) {
            var counter3 = filtered[i4];
            var next2 = filtered[i4 + 1];
            if (counter3.type === 20) {
              var increment2 = next2 && isNumberToken(next2) ? next2.number : 1;
              increments.push({ counter: counter3.value, increment: increment2 });
            }
          }
          return increments;
        }
      };
      var counterReset = {
        name: "counter-reset",
        initialValue: "none",
        prefix: true,
        type: 1,
        parse: function(_context, tokens) {
          if (tokens.length === 0) {
            return [];
          }
          var resets = [];
          var filtered = tokens.filter(nonWhiteSpace);
          for (var i4 = 0; i4 < filtered.length; i4++) {
            var counter3 = filtered[i4];
            var next2 = filtered[i4 + 1];
            if (isIdentToken(counter3) && counter3.value !== "none") {
              var reset3 = next2 && isNumberToken(next2) ? next2.number : 0;
              resets.push({ counter: counter3.value, reset: reset3 });
            }
          }
          return resets;
        }
      };
      var duration = {
        name: "duration",
        initialValue: "0s",
        prefix: false,
        type: 1,
        parse: function(context, tokens) {
          return tokens.filter(isDimensionToken).map(function(token) {
            return time3.parse(context, token);
          });
        }
      };
      var quotes = {
        name: "quotes",
        initialValue: "none",
        prefix: true,
        type: 1,
        parse: function(_context, tokens) {
          if (tokens.length === 0) {
            return null;
          }
          var first2 = tokens[0];
          if (first2.type === 20 && first2.value === "none") {
            return null;
          }
          var quotes2 = [];
          var filtered = tokens.filter(isStringToken);
          if (filtered.length % 2 !== 0) {
            return null;
          }
          for (var i4 = 0; i4 < filtered.length; i4 += 2) {
            var open_1 = filtered[i4].value;
            var close_1 = filtered[i4 + 1].value;
            quotes2.push({ open: open_1, close: close_1 });
          }
          return quotes2;
        }
      };
      var getQuote = function(quotes2, depth2, open) {
        if (!quotes2) {
          return "";
        }
        var quote = quotes2[Math.min(depth2, quotes2.length - 1)];
        if (!quote) {
          return "";
        }
        return open ? quote.open : quote.close;
      };
      var boxShadow = {
        name: "box-shadow",
        initialValue: "none",
        type: 1,
        prefix: false,
        parse: function(context, tokens) {
          if (tokens.length === 1 && isIdentWithValue(tokens[0], "none")) {
            return [];
          }
          return parseFunctionArgs(tokens).map(function(values2) {
            var shadow = {
              color: 255,
              offsetX: ZERO_LENGTH,
              offsetY: ZERO_LENGTH,
              blur: ZERO_LENGTH,
              spread: ZERO_LENGTH,
              inset: false
            };
            var c3 = 0;
            for (var i4 = 0; i4 < values2.length; i4++) {
              var token = values2[i4];
              if (isIdentWithValue(token, "inset")) {
                shadow.inset = true;
              } else if (isLength(token)) {
                if (c3 === 0) {
                  shadow.offsetX = token;
                } else if (c3 === 1) {
                  shadow.offsetY = token;
                } else if (c3 === 2) {
                  shadow.blur = token;
                } else {
                  shadow.spread = token;
                }
                c3++;
              } else {
                shadow.color = color$1.parse(context, token);
              }
            }
            return shadow;
          });
        }
      };
      var paintOrder = {
        name: "paint-order",
        initialValue: "normal",
        prefix: false,
        type: 1,
        parse: function(_context, tokens) {
          var DEFAULT_VALUE2 = [
            0,
            1,
            2
            /* MARKERS */
          ];
          var layers = [];
          tokens.filter(isIdentToken).forEach(function(token) {
            switch (token.value) {
              case "stroke":
                layers.push(
                  1
                  /* STROKE */
                );
                break;
              case "fill":
                layers.push(
                  0
                  /* FILL */
                );
                break;
              case "markers":
                layers.push(
                  2
                  /* MARKERS */
                );
                break;
            }
          });
          DEFAULT_VALUE2.forEach(function(value2) {
            if (layers.indexOf(value2) === -1) {
              layers.push(value2);
            }
          });
          return layers;
        }
      };
      var webkitTextStrokeColor = {
        name: "-webkit-text-stroke-color",
        initialValue: "currentcolor",
        prefix: false,
        type: 3,
        format: "color"
      };
      var webkitTextStrokeWidth = {
        name: "-webkit-text-stroke-width",
        initialValue: "0",
        type: 0,
        prefix: false,
        parse: function(_context, token) {
          if (isDimensionToken(token)) {
            return token.number;
          }
          return 0;
        }
      };
      var CSSParsedDeclaration = (
        /** @class */
        function() {
          function CSSParsedDeclaration2(context, declaration2) {
            var _a4, _b;
            this.animationDuration = parse4(context, duration, declaration2.animationDuration);
            this.backgroundClip = parse4(context, backgroundClip, declaration2.backgroundClip);
            this.backgroundColor = parse4(context, backgroundColor, declaration2.backgroundColor);
            this.backgroundImage = parse4(context, backgroundImage, declaration2.backgroundImage);
            this.backgroundOrigin = parse4(context, backgroundOrigin, declaration2.backgroundOrigin);
            this.backgroundPosition = parse4(context, backgroundPosition, declaration2.backgroundPosition);
            this.backgroundRepeat = parse4(context, backgroundRepeat, declaration2.backgroundRepeat);
            this.backgroundSize = parse4(context, backgroundSize, declaration2.backgroundSize);
            this.borderTopColor = parse4(context, borderTopColor, declaration2.borderTopColor);
            this.borderRightColor = parse4(context, borderRightColor, declaration2.borderRightColor);
            this.borderBottomColor = parse4(context, borderBottomColor, declaration2.borderBottomColor);
            this.borderLeftColor = parse4(context, borderLeftColor, declaration2.borderLeftColor);
            this.borderTopLeftRadius = parse4(context, borderTopLeftRadius, declaration2.borderTopLeftRadius);
            this.borderTopRightRadius = parse4(context, borderTopRightRadius, declaration2.borderTopRightRadius);
            this.borderBottomRightRadius = parse4(context, borderBottomRightRadius, declaration2.borderBottomRightRadius);
            this.borderBottomLeftRadius = parse4(context, borderBottomLeftRadius, declaration2.borderBottomLeftRadius);
            this.borderTopStyle = parse4(context, borderTopStyle, declaration2.borderTopStyle);
            this.borderRightStyle = parse4(context, borderRightStyle, declaration2.borderRightStyle);
            this.borderBottomStyle = parse4(context, borderBottomStyle, declaration2.borderBottomStyle);
            this.borderLeftStyle = parse4(context, borderLeftStyle, declaration2.borderLeftStyle);
            this.borderTopWidth = parse4(context, borderTopWidth, declaration2.borderTopWidth);
            this.borderRightWidth = parse4(context, borderRightWidth, declaration2.borderRightWidth);
            this.borderBottomWidth = parse4(context, borderBottomWidth, declaration2.borderBottomWidth);
            this.borderLeftWidth = parse4(context, borderLeftWidth, declaration2.borderLeftWidth);
            this.boxShadow = parse4(context, boxShadow, declaration2.boxShadow);
            this.color = parse4(context, color, declaration2.color);
            this.direction = parse4(context, direction, declaration2.direction);
            this.display = parse4(context, display, declaration2.display);
            this.float = parse4(context, float3, declaration2.cssFloat);
            this.fontFamily = parse4(context, fontFamily, declaration2.fontFamily);
            this.fontSize = parse4(context, fontSize, declaration2.fontSize);
            this.fontStyle = parse4(context, fontStyle, declaration2.fontStyle);
            this.fontVariant = parse4(context, fontVariant, declaration2.fontVariant);
            this.fontWeight = parse4(context, fontWeight, declaration2.fontWeight);
            this.letterSpacing = parse4(context, letterSpacing, declaration2.letterSpacing);
            this.lineBreak = parse4(context, lineBreak, declaration2.lineBreak);
            this.lineHeight = parse4(context, lineHeight, declaration2.lineHeight);
            this.listStyleImage = parse4(context, listStyleImage, declaration2.listStyleImage);
            this.listStylePosition = parse4(context, listStylePosition, declaration2.listStylePosition);
            this.listStyleType = parse4(context, listStyleType, declaration2.listStyleType);
            this.marginTop = parse4(context, marginTop, declaration2.marginTop);
            this.marginRight = parse4(context, marginRight, declaration2.marginRight);
            this.marginBottom = parse4(context, marginBottom, declaration2.marginBottom);
            this.marginLeft = parse4(context, marginLeft, declaration2.marginLeft);
            this.opacity = parse4(context, opacity, declaration2.opacity);
            var overflowTuple = parse4(context, overflow, declaration2.overflow);
            this.overflowX = overflowTuple[0];
            this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0];
            this.overflowWrap = parse4(context, overflowWrap, declaration2.overflowWrap);
            this.paddingTop = parse4(context, paddingTop, declaration2.paddingTop);
            this.paddingRight = parse4(context, paddingRight, declaration2.paddingRight);
            this.paddingBottom = parse4(context, paddingBottom, declaration2.paddingBottom);
            this.paddingLeft = parse4(context, paddingLeft, declaration2.paddingLeft);
            this.paintOrder = parse4(context, paintOrder, declaration2.paintOrder);
            this.position = parse4(context, position, declaration2.position);
            this.textAlign = parse4(context, textAlign, declaration2.textAlign);
            this.textDecorationColor = parse4(context, textDecorationColor, (_a4 = declaration2.textDecorationColor) !== null && _a4 !== void 0 ? _a4 : declaration2.color);
            this.textDecorationLine = parse4(context, textDecorationLine, (_b = declaration2.textDecorationLine) !== null && _b !== void 0 ? _b : declaration2.textDecoration);
            this.textShadow = parse4(context, textShadow, declaration2.textShadow);
            this.textTransform = parse4(context, textTransform, declaration2.textTransform);
            this.transform = parse4(context, transform$1, declaration2.transform);
            this.transformOrigin = parse4(context, transformOrigin, declaration2.transformOrigin);
            this.visibility = parse4(context, visibility, declaration2.visibility);
            this.webkitTextStrokeColor = parse4(context, webkitTextStrokeColor, declaration2.webkitTextStrokeColor);
            this.webkitTextStrokeWidth = parse4(context, webkitTextStrokeWidth, declaration2.webkitTextStrokeWidth);
            this.wordBreak = parse4(context, wordBreak, declaration2.wordBreak);
            this.zIndex = parse4(context, zIndex, declaration2.zIndex);
          }
          CSSParsedDeclaration2.prototype.isVisible = function() {
            return this.display > 0 && this.opacity > 0 && this.visibility === 0;
          };
          CSSParsedDeclaration2.prototype.isTransparent = function() {
            return isTransparent(this.backgroundColor);
          };
          CSSParsedDeclaration2.prototype.isTransformed = function() {
            return this.transform !== null;
          };
          CSSParsedDeclaration2.prototype.isPositioned = function() {
            return this.position !== 0;
          };
          CSSParsedDeclaration2.prototype.isPositionedWithZIndex = function() {
            return this.isPositioned() && !this.zIndex.auto;
          };
          CSSParsedDeclaration2.prototype.isFloating = function() {
            return this.float !== 0;
          };
          CSSParsedDeclaration2.prototype.isInlineLevel = function() {
            return contains4(
              this.display,
              4
              /* INLINE */
            ) || contains4(
              this.display,
              33554432
              /* INLINE_BLOCK */
            ) || contains4(
              this.display,
              268435456
              /* INLINE_FLEX */
            ) || contains4(
              this.display,
              536870912
              /* INLINE_GRID */
            ) || contains4(
              this.display,
              67108864
              /* INLINE_LIST_ITEM */
            ) || contains4(
              this.display,
              134217728
              /* INLINE_TABLE */
            );
          };
          return CSSParsedDeclaration2;
        }()
      );
      var CSSParsedPseudoDeclaration = (
        /** @class */
        /* @__PURE__ */ function() {
          function CSSParsedPseudoDeclaration2(context, declaration2) {
            this.content = parse4(context, content2, declaration2.content);
            this.quotes = parse4(context, quotes, declaration2.quotes);
          }
          return CSSParsedPseudoDeclaration2;
        }()
      );
      var CSSParsedCounterDeclaration = (
        /** @class */
        /* @__PURE__ */ function() {
          function CSSParsedCounterDeclaration2(context, declaration2) {
            this.counterIncrement = parse4(context, counterIncrement, declaration2.counterIncrement);
            this.counterReset = parse4(context, counterReset, declaration2.counterReset);
          }
          return CSSParsedCounterDeclaration2;
        }()
      );
      var parse4 = function(context, descriptor, style3) {
        var tokenizer = new Tokenizer2();
        var value2 = style3 !== null && typeof style3 !== "undefined" ? style3.toString() : descriptor.initialValue;
        tokenizer.write(value2);
        var parser4 = new Parser4(tokenizer.read());
        switch (descriptor.type) {
          case 2:
            var token = parser4.parseComponentValue();
            return descriptor.parse(context, isIdentToken(token) ? token.value : descriptor.initialValue);
          case 0:
            return descriptor.parse(context, parser4.parseComponentValue());
          case 1:
            return descriptor.parse(context, parser4.parseComponentValues());
          case 4:
            return parser4.parseComponentValue();
          case 3:
            switch (descriptor.format) {
              case "angle":
                return angle.parse(context, parser4.parseComponentValue());
              case "color":
                return color$1.parse(context, parser4.parseComponentValue());
              case "image":
                return image2.parse(context, parser4.parseComponentValue());
              case "length":
                var length_1 = parser4.parseComponentValue();
                return isLength(length_1) ? length_1 : ZERO_LENGTH;
              case "length-percentage":
                var value_1 = parser4.parseComponentValue();
                return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH;
              case "time":
                return time3.parse(context, parser4.parseComponentValue());
            }
            break;
        }
      };
      var elementDebuggerAttribute = "data-html2canvas-debug";
      var getElementDebugType = function(element2) {
        var attribute2 = element2.getAttribute(elementDebuggerAttribute);
        switch (attribute2) {
          case "all":
            return 1;
          case "clone":
            return 2;
          case "parse":
            return 3;
          case "render":
            return 4;
          default:
            return 0;
        }
      };
      var isDebugging = function(element2, type) {
        var elementType = getElementDebugType(element2);
        return elementType === 1 || type === elementType;
      };
      var ElementContainer = (
        /** @class */
        /* @__PURE__ */ function() {
          function ElementContainer2(context, element2) {
            this.context = context;
            this.textNodes = [];
            this.elements = [];
            this.flags = 0;
            if (isDebugging(
              element2,
              3
              /* PARSE */
            )) {
              debugger;
            }
            this.styles = new CSSParsedDeclaration(context, window.getComputedStyle(element2, null));
            if (isHTMLElementNode(element2)) {
              if (this.styles.animationDuration.some(function(duration2) {
                return duration2 > 0;
              })) {
                element2.style.animationDuration = "0s";
              }
              if (this.styles.transform !== null) {
                element2.style.transform = "none";
              }
            }
            this.bounds = parseBounds(this.context, element2);
            if (isDebugging(
              element2,
              4
              /* RENDER */
            )) {
              this.flags |= 16;
            }
          }
          return ElementContainer2;
        }()
      );
      var base64 = " ";
      var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var lookup$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
      for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
        lookup$1[chars$1.charCodeAt(i$1)] = i$1;
      }
      var decode3 = function(base642) {
        var bufferLength = base642.length * 0.75, len = base642.length, i4, p4 = 0, encoded1, encoded2, encoded3, encoded4;
        if (base642[base642.length - 1] === "=") {
          bufferLength--;
          if (base642[base642.length - 2] === "=") {
            bufferLength--;
          }
        }
        var buffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined" && typeof Uint8Array.prototype.slice !== "undefined" ? new ArrayBuffer(bufferLength) : new Array(bufferLength);
        var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
        for (i4 = 0; i4 < len; i4 += 4) {
          encoded1 = lookup$1[base642.charCodeAt(i4)];
          encoded2 = lookup$1[base642.charCodeAt(i4 + 1)];
          encoded3 = lookup$1[base642.charCodeAt(i4 + 2)];
          encoded4 = lookup$1[base642.charCodeAt(i4 + 3)];
          bytes[p4++] = encoded1 << 2 | encoded2 >> 4;
          bytes[p4++] = (encoded2 & 15) << 4 | encoded3 >> 2;
          bytes[p4++] = (encoded3 & 3) << 6 | encoded4 & 63;
        }
        return buffer;
      };
      var polyUint16Array = function(buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i4 = 0; i4 < length; i4 += 2) {
          bytes.push(buffer[i4 + 1] << 8 | buffer[i4]);
        }
        return bytes;
      };
      var polyUint32Array = function(buffer) {
        var length = buffer.length;
        var bytes = [];
        for (var i4 = 0; i4 < length; i4 += 4) {
          bytes.push(buffer[i4 + 3] << 24 | buffer[i4 + 2] << 16 | buffer[i4 + 1] << 8 | buffer[i4]);
        }
        return bytes;
      };
      var UTRIE2_SHIFT_2 = 5;
      var UTRIE2_SHIFT_1 = 6 + 5;
      var UTRIE2_INDEX_SHIFT = 2;
      var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2;
      var UTRIE2_LSCP_INDEX_2_OFFSET = 65536 >> UTRIE2_SHIFT_2;
      var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2;
      var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1;
      var UTRIE2_LSCP_INDEX_2_LENGTH = 1024 >> UTRIE2_SHIFT_2;
      var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH;
      var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH;
      var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 2048 >> 6;
      var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH;
      var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 65536 >> UTRIE2_SHIFT_1;
      var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2;
      var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1;
      var slice16 = function(view, start, end) {
        if (view.slice) {
          return view.slice(start, end);
        }
        return new Uint16Array(Array.prototype.slice.call(view, start, end));
      };
      var slice32 = function(view, start, end) {
        if (view.slice) {
          return view.slice(start, end);
        }
        return new Uint32Array(Array.prototype.slice.call(view, start, end));
      };
      var createTrieFromBase64 = function(base642, _byteLength) {
        var buffer = decode3(base642);
        var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer);
        var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer);
        var headerLength = 24;
        var index2 = slice16(view16, headerLength / 2, view32[4] / 2);
        var data2 = view32[5] === 2 ? slice16(view16, (headerLength + view32[4]) / 2) : slice32(view32, Math.ceil((headerLength + view32[4]) / 4));
        return new Trie(view32[0], view32[1], view32[2], view32[3], index2, data2);
      };
      var Trie = (
        /** @class */
        function() {
          function Trie2(initialValue, errorValue, highStart, highValueIndex, index2, data2) {
            this.initialValue = initialValue;
            this.errorValue = errorValue;
            this.highStart = highStart;
            this.highValueIndex = highValueIndex;
            this.index = index2;
            this.data = data2;
          }
          Trie2.prototype.get = function(codePoint) {
            var ix;
            if (codePoint >= 0) {
              if (codePoint < 55296 || codePoint > 56319 && codePoint <= 65535) {
                ix = this.index[codePoint >> UTRIE2_SHIFT_2];
                ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
                return this.data[ix];
              }
              if (codePoint <= 65535) {
                ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + (codePoint - 55296 >> UTRIE2_SHIFT_2)];
                ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
                return this.data[ix];
              }
              if (codePoint < this.highStart) {
                ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1);
                ix = this.index[ix];
                ix += codePoint >> UTRIE2_SHIFT_2 & UTRIE2_INDEX_2_MASK;
                ix = this.index[ix];
                ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
                return this.data[ix];
              }
              if (codePoint <= 1114111) {
                return this.data[this.highValueIndex];
              }
            }
            return this.errorValue;
          };
          return Trie2;
        }()
      );
      var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
      for (var i3 = 0; i3 < chars.length; i3++) {
        lookup[chars.charCodeAt(i3)] = i3;
      }
      var Prepend = 1;
      var CR = 2;
      var LF = 3;
      var Control = 4;
      var Extend = 5;
      var SpacingMark = 7;
      var L5 = 8;
      var V2 = 9;
      var T3 = 10;
      var LV = 11;
      var LVT = 12;
      var ZWJ2 = 13;
      var Extended_Pictographic = 14;
      var RI = 15;
      var toCodePoints = function(str) {
        var codePoints = [];
        var i4 = 0;
        var length = str.length;
        while (i4 < length) {
          var value2 = str.charCodeAt(i4++);
          if (value2 >= 55296 && value2 <= 56319 && i4 < length) {
            var extra = str.charCodeAt(i4++);
            if ((extra & 64512) === 56320) {
              codePoints.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
            } else {
              codePoints.push(value2);
              i4--;
            }
          } else {
            codePoints.push(value2);
          }
        }
        return codePoints;
      };
      var fromCodePoint4 = function() {
        var codePoints = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          codePoints[_i] = arguments[_i];
        }
        if (String.fromCodePoint) {
          return String.fromCodePoint.apply(String, codePoints);
        }
        var length = codePoints.length;
        if (!length) {
          return "";
        }
        var codeUnits = [];
        var index2 = -1;
        var result2 = "";
        while (++index2 < length) {
          var codePoint = codePoints[index2];
          if (codePoint <= 65535) {
            codeUnits.push(codePoint);
          } else {
            codePoint -= 65536;
            codeUnits.push((codePoint >> 10) + 55296, codePoint % 1024 + 56320);
          }
          if (index2 + 1 === length || codeUnits.length > 16384) {
            result2 += String.fromCharCode.apply(String, codeUnits);
            codeUnits.length = 0;
          }
        }
        return result2;
      };
      var UnicodeTrie = createTrieFromBase64(base64);
      var BREAK_NOT_ALLOWED = "\xD7";
      var BREAK_ALLOWED = "\xF7";
      var codePointToClass = function(codePoint) {
        return UnicodeTrie.get(codePoint);
      };
      var _graphemeBreakAtIndex = function(_codePoints, classTypes, index2) {
        var prevIndex = index2 - 2;
        var prev = classTypes[prevIndex];
        var current = classTypes[index2 - 1];
        var next2 = classTypes[index2];
        if (current === CR && next2 === LF) {
          return BREAK_NOT_ALLOWED;
        }
        if (current === CR || current === LF || current === Control) {
          return BREAK_ALLOWED;
        }
        if (next2 === CR || next2 === LF || next2 === Control) {
          return BREAK_ALLOWED;
        }
        if (current === L5 && [L5, V2, LV, LVT].indexOf(next2) !== -1) {
          return BREAK_NOT_ALLOWED;
        }
        if ((current === LV || current === V2) && (next2 === V2 || next2 === T3)) {
          return BREAK_NOT_ALLOWED;
        }
        if ((current === LVT || current === T3) && next2 === T3) {
          return BREAK_NOT_ALLOWED;
        }
        if (next2 === ZWJ2 || next2 === Extend) {
          return BREAK_NOT_ALLOWED;
        }
        if (next2 === SpacingMark) {
          return BREAK_NOT_ALLOWED;
        }
        if (current === Prepend) {
          return BREAK_NOT_ALLOWED;
        }
        if (current === ZWJ2 && next2 === Extended_Pictographic) {
          while (prev === Extend) {
            prev = classTypes[--prevIndex];
          }
          if (prev === Extended_Pictographic) {
            return BREAK_NOT_ALLOWED;
          }
        }
        if (current === RI && next2 === RI) {
          var countRI = 0;
          while (prev === RI) {
            countRI++;
            prev = classTypes[--prevIndex];
          }
          if (countRI % 2 === 0) {
            return BREAK_NOT_ALLOWED;
          }
        }
        return BREAK_ALLOWED;
      };
      var GraphemeBreaker = function(str) {
        var codePoints = toCodePoints(str);
        var length = codePoints.length;
        var index2 = 0;
        var lastEnd = 0;
        var classTypes = codePoints.map(codePointToClass);
        return {
          next: function() {
            if (index2 >= length) {
              return { done: true, value: null };
            }
            var graphemeBreak = BREAK_NOT_ALLOWED;
            while (index2 < length && (graphemeBreak = _graphemeBreakAtIndex(codePoints, classTypes, ++index2)) === BREAK_NOT_ALLOWED) {
            }
            if (graphemeBreak !== BREAK_NOT_ALLOWED || index2 === length) {
              var value2 = fromCodePoint4.apply(null, codePoints.slice(lastEnd, index2));
              lastEnd = index2;
              return { value: value2, done: false };
            }
            return { done: true, value: null };
          }
        };
      };
      var splitGraphemes = function(str) {
        var breaker = GraphemeBreaker(str);
        var graphemes = [];
        var bk;
        while (!(bk = breaker.next()).done) {
          if (bk.value) {
            graphemes.push(bk.value.slice());
          }
        }
        return graphemes;
      };
      var testRangeBounds = function(document2) {
        var TEST_HEIGHT = 123;
        if (document2.createRange) {
          var range2 = document2.createRange();
          if (range2.getBoundingClientRect) {
            var testElement = document2.createElement("boundtest");
            testElement.style.height = TEST_HEIGHT + "px";
            testElement.style.display = "block";
            document2.body.appendChild(testElement);
            range2.selectNode(testElement);
            var rangeBounds = range2.getBoundingClientRect();
            var rangeHeight = Math.round(rangeBounds.height);
            document2.body.removeChild(testElement);
            if (rangeHeight === TEST_HEIGHT) {
              return true;
            }
          }
        }
        return false;
      };
      var testIOSLineBreak = function(document2) {
        var testElement = document2.createElement("boundtest");
        testElement.style.width = "50px";
        testElement.style.display = "block";
        testElement.style.fontSize = "12px";
        testElement.style.letterSpacing = "0px";
        testElement.style.wordSpacing = "0px";
        document2.body.appendChild(testElement);
        var range2 = document2.createRange();
        testElement.innerHTML = typeof "".repeat === "function" ? "&#128104;".repeat(10) : "";
        var node = testElement.firstChild;
        var textList = toCodePoints$1(node.data).map(function(i4) {
          return fromCodePoint$1(i4);
        });
        var offset = 0;
        var prev = {};
        var supports2 = textList.every(function(text3, i4) {
          range2.setStart(node, offset);
          range2.setEnd(node, offset + text3.length);
          var rect = range2.getBoundingClientRect();
          offset += text3.length;
          var boundAhead = rect.x > prev.x || rect.y > prev.y;
          prev = rect;
          if (i4 === 0) {
            return true;
          }
          return boundAhead;
        });
        document2.body.removeChild(testElement);
        return supports2;
      };
      var testCORS = function() {
        return typeof new Image().crossOrigin !== "undefined";
      };
      var testResponseType = function() {
        return typeof new XMLHttpRequest().responseType === "string";
      };
      var testSVG = function(document2) {
        var img = new Image();
        var canvas = document2.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (!ctx) {
          return false;
        }
        img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
        try {
          ctx.drawImage(img, 0, 0);
          canvas.toDataURL();
        } catch (e4) {
          return false;
        }
        return true;
      };
      var isGreenPixel = function(data2) {
        return data2[0] === 0 && data2[1] === 255 && data2[2] === 0 && data2[3] === 255;
      };
      var testForeignObject = function(document2) {
        var canvas = document2.createElement("canvas");
        var size4 = 100;
        canvas.width = size4;
        canvas.height = size4;
        var ctx = canvas.getContext("2d");
        if (!ctx) {
          return Promise.reject(false);
        }
        ctx.fillStyle = "rgb(0, 255, 0)";
        ctx.fillRect(0, 0, size4, size4);
        var img = new Image();
        var greenImageSrc = canvas.toDataURL();
        img.src = greenImageSrc;
        var svg4 = createForeignObjectSVG(size4, size4, 0, 0, img);
        ctx.fillStyle = "red";
        ctx.fillRect(0, 0, size4, size4);
        return loadSerializedSVG$1(svg4).then(function(img2) {
          ctx.drawImage(img2, 0, 0);
          var data2 = ctx.getImageData(0, 0, size4, size4).data;
          ctx.fillStyle = "red";
          ctx.fillRect(0, 0, size4, size4);
          var node = document2.createElement("div");
          node.style.backgroundImage = "url(" + greenImageSrc + ")";
          node.style.height = size4 + "px";
          return isGreenPixel(data2) ? loadSerializedSVG$1(createForeignObjectSVG(size4, size4, 0, 0, node)) : Promise.reject(false);
        }).then(function(img2) {
          ctx.drawImage(img2, 0, 0);
          return isGreenPixel(ctx.getImageData(0, 0, size4, size4).data);
        }).catch(function() {
          return false;
        });
      };
      var createForeignObjectSVG = function(width, height, x3, y3, node) {
        var xmlns2 = "http://www.w3.org/2000/svg";
        var svg4 = document.createElementNS(xmlns2, "svg");
        var foreignObject = document.createElementNS(xmlns2, "foreignObject");
        svg4.setAttributeNS(null, "width", width.toString());
        svg4.setAttributeNS(null, "height", height.toString());
        foreignObject.setAttributeNS(null, "width", "100%");
        foreignObject.setAttributeNS(null, "height", "100%");
        foreignObject.setAttributeNS(null, "x", x3.toString());
        foreignObject.setAttributeNS(null, "y", y3.toString());
        foreignObject.setAttributeNS(null, "externalResourcesRequired", "true");
        svg4.appendChild(foreignObject);
        foreignObject.appendChild(node);
        return svg4;
      };
      var loadSerializedSVG$1 = function(svg4) {
        return new Promise(function(resolve2, reject2) {
          var img = new Image();
          img.onload = function() {
            return resolve2(img);
          };
          img.onerror = reject2;
          img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg4));
        });
      };
      var FEATURES = {
        get SUPPORT_RANGE_BOUNDS() {
          var value2 = testRangeBounds(document);
          Object.defineProperty(FEATURES, "SUPPORT_RANGE_BOUNDS", { value: value2 });
          return value2;
        },
        get SUPPORT_WORD_BREAKING() {
          var value2 = FEATURES.SUPPORT_RANGE_BOUNDS && testIOSLineBreak(document);
          Object.defineProperty(FEATURES, "SUPPORT_WORD_BREAKING", { value: value2 });
          return value2;
        },
        get SUPPORT_SVG_DRAWING() {
          var value2 = testSVG(document);
          Object.defineProperty(FEATURES, "SUPPORT_SVG_DRAWING", { value: value2 });
          return value2;
        },
        get SUPPORT_FOREIGNOBJECT_DRAWING() {
          var value2 = typeof Array.from === "function" && typeof window.fetch === "function" ? testForeignObject(document) : Promise.resolve(false);
          Object.defineProperty(FEATURES, "SUPPORT_FOREIGNOBJECT_DRAWING", { value: value2 });
          return value2;
        },
        get SUPPORT_CORS_IMAGES() {
          var value2 = testCORS();
          Object.defineProperty(FEATURES, "SUPPORT_CORS_IMAGES", { value: value2 });
          return value2;
        },
        get SUPPORT_RESPONSE_TYPE() {
          var value2 = testResponseType();
          Object.defineProperty(FEATURES, "SUPPORT_RESPONSE_TYPE", { value: value2 });
          return value2;
        },
        get SUPPORT_CORS_XHR() {
          var value2 = "withCredentials" in new XMLHttpRequest();
          Object.defineProperty(FEATURES, "SUPPORT_CORS_XHR", { value: value2 });
          return value2;
        },
        get SUPPORT_NATIVE_TEXT_SEGMENTATION() {
          var value2 = !!(typeof Intl !== "undefined" && Intl.Segmenter);
          Object.defineProperty(FEATURES, "SUPPORT_NATIVE_TEXT_SEGMENTATION", { value: value2 });
          return value2;
        }
      };
      var TextBounds = (
        /** @class */
        /* @__PURE__ */ function() {
          function TextBounds2(text3, bounds) {
            this.text = text3;
            this.bounds = bounds;
          }
          return TextBounds2;
        }()
      );
      var parseTextBounds = function(context, value2, styles, node) {
        var textList = breakText(value2, styles);
        var textBounds = [];
        var offset = 0;
        textList.forEach(function(text3) {
          if (styles.textDecorationLine.length || text3.trim().length > 0) {
            if (FEATURES.SUPPORT_RANGE_BOUNDS) {
              var clientRects = createRange(node, offset, text3.length).getClientRects();
              if (clientRects.length > 1) {
                var subSegments = segmentGraphemes(text3);
                var subOffset_1 = 0;
                subSegments.forEach(function(subSegment) {
                  textBounds.push(new TextBounds(subSegment, Bounds2.fromDOMRectList(context, createRange(node, subOffset_1 + offset, subSegment.length).getClientRects())));
                  subOffset_1 += subSegment.length;
                });
              } else {
                textBounds.push(new TextBounds(text3, Bounds2.fromDOMRectList(context, clientRects)));
              }
            } else {
              var replacementNode = node.splitText(text3.length);
              textBounds.push(new TextBounds(text3, getWrapperBounds(context, node)));
              node = replacementNode;
            }
          } else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
            node = node.splitText(text3.length);
          }
          offset += text3.length;
        });
        return textBounds;
      };
      var getWrapperBounds = function(context, node) {
        var ownerDocument2 = node.ownerDocument;
        if (ownerDocument2) {
          var wrapper = ownerDocument2.createElement("html2canvaswrapper");
          wrapper.appendChild(node.cloneNode(true));
          var parentNode2 = node.parentNode;
          if (parentNode2) {
            parentNode2.replaceChild(wrapper, node);
            var bounds = parseBounds(context, wrapper);
            if (wrapper.firstChild) {
              parentNode2.replaceChild(wrapper.firstChild, wrapper);
            }
            return bounds;
          }
        }
        return Bounds2.EMPTY;
      };
      var createRange = function(node, offset, length) {
        var ownerDocument2 = node.ownerDocument;
        if (!ownerDocument2) {
          throw new Error("Node has no owner document");
        }
        var range2 = ownerDocument2.createRange();
        range2.setStart(node, offset);
        range2.setEnd(node, offset + length);
        return range2;
      };
      var segmentGraphemes = function(value2) {
        if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
          var segmenter2 = new Intl.Segmenter(void 0, { granularity: "grapheme" });
          return Array.from(segmenter2.segment(value2)).map(function(segment) {
            return segment.segment;
          });
        }
        return splitGraphemes(value2);
      };
      var segmentWords = function(value2, styles) {
        if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
          var segmenter2 = new Intl.Segmenter(void 0, {
            granularity: "word"
          });
          return Array.from(segmenter2.segment(value2)).map(function(segment) {
            return segment.segment;
          });
        }
        return breakWords(value2, styles);
      };
      var breakText = function(value2, styles) {
        return styles.letterSpacing !== 0 ? segmentGraphemes(value2) : segmentWords(value2, styles);
      };
      var wordSeparators = [32, 160, 4961, 65792, 65793, 4153, 4241];
      var breakWords = function(str, styles) {
        var breaker = LineBreaker(str, {
          lineBreak: styles.lineBreak,
          wordBreak: styles.overflowWrap === "break-word" ? "break-word" : styles.wordBreak
        });
        var words = [];
        var bk;
        var _loop_1 = function() {
          if (bk.value) {
            var value2 = bk.value.slice();
            var codePoints = toCodePoints$1(value2);
            var word_1 = "";
            codePoints.forEach(function(codePoint) {
              if (wordSeparators.indexOf(codePoint) === -1) {
                word_1 += fromCodePoint$1(codePoint);
              } else {
                if (word_1.length) {
                  words.push(word_1);
                }
                words.push(fromCodePoint$1(codePoint));
                word_1 = "";
              }
            });
            if (word_1.length) {
              words.push(word_1);
            }
          }
        };
        while (!(bk = breaker.next()).done) {
          _loop_1();
        }
        return words;
      };
      var TextContainer = (
        /** @class */
        /* @__PURE__ */ function() {
          function TextContainer2(context, node, styles) {
            this.text = transform(node.data, styles.textTransform);
            this.textBounds = parseTextBounds(context, this.text, styles, node);
          }
          return TextContainer2;
        }()
      );
      var transform = function(text3, transform2) {
        switch (transform2) {
          case 1:
            return text3.toLowerCase();
          case 3:
            return text3.replace(CAPITALIZE, capitalize2);
          case 2:
            return text3.toUpperCase();
          default:
            return text3;
        }
      };
      var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
      var capitalize2 = function(m3, p1, p22) {
        if (m3.length > 0) {
          return p1 + p22.toUpperCase();
        }
        return m3;
      };
      var ImageElementContainer = (
        /** @class */
        function(_super) {
          __extends(ImageElementContainer2, _super);
          function ImageElementContainer2(context, img) {
            var _this = _super.call(this, context, img) || this;
            _this.src = img.currentSrc || img.src;
            _this.intrinsicWidth = img.naturalWidth;
            _this.intrinsicHeight = img.naturalHeight;
            _this.context.cache.addImage(_this.src);
            return _this;
          }
          return ImageElementContainer2;
        }(ElementContainer)
      );
      var CanvasElementContainer = (
        /** @class */
        function(_super) {
          __extends(CanvasElementContainer2, _super);
          function CanvasElementContainer2(context, canvas) {
            var _this = _super.call(this, context, canvas) || this;
            _this.canvas = canvas;
            _this.intrinsicWidth = canvas.width;
            _this.intrinsicHeight = canvas.height;
            return _this;
          }
          return CanvasElementContainer2;
        }(ElementContainer)
      );
      var SVGElementContainer = (
        /** @class */
        function(_super) {
          __extends(SVGElementContainer2, _super);
          function SVGElementContainer2(context, img) {
            var _this = _super.call(this, context, img) || this;
            var s3 = new XMLSerializer();
            var bounds = parseBounds(context, img);
            img.setAttribute("width", bounds.width + "px");
            img.setAttribute("height", bounds.height + "px");
            _this.svg = "data:image/svg+xml," + encodeURIComponent(s3.serializeToString(img));
            _this.intrinsicWidth = img.width.baseVal.value;
            _this.intrinsicHeight = img.height.baseVal.value;
            _this.context.cache.addImage(_this.svg);
            return _this;
          }
          return SVGElementContainer2;
        }(ElementContainer)
      );
      var LIElementContainer = (
        /** @class */
        function(_super) {
          __extends(LIElementContainer2, _super);
          function LIElementContainer2(context, element2) {
            var _this = _super.call(this, context, element2) || this;
            _this.value = element2.value;
            return _this;
          }
          return LIElementContainer2;
        }(ElementContainer)
      );
      var OLElementContainer = (
        /** @class */
        function(_super) {
          __extends(OLElementContainer2, _super);
          function OLElementContainer2(context, element2) {
            var _this = _super.call(this, context, element2) || this;
            _this.start = element2.start;
            _this.reversed = typeof element2.reversed === "boolean" && element2.reversed === true;
            return _this;
          }
          return OLElementContainer2;
        }(ElementContainer)
      );
      var CHECKBOX_BORDER_RADIUS = [
        {
          type: 15,
          flags: 0,
          unit: "px",
          number: 3
        }
      ];
      var RADIO_BORDER_RADIUS = [
        {
          type: 16,
          flags: 0,
          number: 50
        }
      ];
      var reformatInputBounds = function(bounds) {
        if (bounds.width > bounds.height) {
          return new Bounds2(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height);
        } else if (bounds.width < bounds.height) {
          return new Bounds2(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width);
        }
        return bounds;
      };
      var getInputValue = function(node) {
        var value2 = node.type === PASSWORD ? new Array(node.value.length + 1).join("\u2022") : node.value;
        return value2.length === 0 ? node.placeholder || "" : value2;
      };
      var CHECKBOX = "checkbox";
      var RADIO = "radio";
      var PASSWORD = "password";
      var INPUT_COLOR = 707406591;
      var InputElementContainer = (
        /** @class */
        function(_super) {
          __extends(InputElementContainer2, _super);
          function InputElementContainer2(context, input) {
            var _this = _super.call(this, context, input) || this;
            _this.type = input.type.toLowerCase();
            _this.checked = input.checked;
            _this.value = getInputValue(input);
            if (_this.type === CHECKBOX || _this.type === RADIO) {
              _this.styles.backgroundColor = 3739148031;
              _this.styles.borderTopColor = _this.styles.borderRightColor = _this.styles.borderBottomColor = _this.styles.borderLeftColor = 2779096575;
              _this.styles.borderTopWidth = _this.styles.borderRightWidth = _this.styles.borderBottomWidth = _this.styles.borderLeftWidth = 1;
              _this.styles.borderTopStyle = _this.styles.borderRightStyle = _this.styles.borderBottomStyle = _this.styles.borderLeftStyle = 1;
              _this.styles.backgroundClip = [
                0
                /* BORDER_BOX */
              ];
              _this.styles.backgroundOrigin = [
                0
                /* BORDER_BOX */
              ];
              _this.bounds = reformatInputBounds(_this.bounds);
            }
            switch (_this.type) {
              case CHECKBOX:
                _this.styles.borderTopRightRadius = _this.styles.borderTopLeftRadius = _this.styles.borderBottomRightRadius = _this.styles.borderBottomLeftRadius = CHECKBOX_BORDER_RADIUS;
                break;
              case RADIO:
                _this.styles.borderTopRightRadius = _this.styles.borderTopLeftRadius = _this.styles.borderBottomRightRadius = _this.styles.borderBottomLeftRadius = RADIO_BORDER_RADIUS;
                break;
            }
            return _this;
          }
          return InputElementContainer2;
        }(ElementContainer)
      );
      var SelectElementContainer = (
        /** @class */
        function(_super) {
          __extends(SelectElementContainer2, _super);
          function SelectElementContainer2(context, element2) {
            var _this = _super.call(this, context, element2) || this;
            var option2 = element2.options[element2.selectedIndex || 0];
            _this.value = option2 ? option2.text || "" : "";
            return _this;
          }
          return SelectElementContainer2;
        }(ElementContainer)
      );
      var TextareaElementContainer = (
        /** @class */
        function(_super) {
          __extends(TextareaElementContainer2, _super);
          function TextareaElementContainer2(context, element2) {
            var _this = _super.call(this, context, element2) || this;
            _this.value = element2.value;
            return _this;
          }
          return TextareaElementContainer2;
        }(ElementContainer)
      );
      var IFrameElementContainer = (
        /** @class */
        function(_super) {
          __extends(IFrameElementContainer2, _super);
          function IFrameElementContainer2(context, iframe) {
            var _this = _super.call(this, context, iframe) || this;
            _this.src = iframe.src;
            _this.width = parseInt(iframe.width, 10) || 0;
            _this.height = parseInt(iframe.height, 10) || 0;
            _this.backgroundColor = _this.styles.backgroundColor;
            try {
              if (iframe.contentWindow && iframe.contentWindow.document && iframe.contentWindow.document.documentElement) {
                _this.tree = parseTree(context, iframe.contentWindow.document.documentElement);
                var documentBackgroundColor = iframe.contentWindow.document.documentElement ? parseColor2(context, getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor) : COLORS.TRANSPARENT;
                var bodyBackgroundColor = iframe.contentWindow.document.body ? parseColor2(context, getComputedStyle(iframe.contentWindow.document.body).backgroundColor) : COLORS.TRANSPARENT;
                _this.backgroundColor = isTransparent(documentBackgroundColor) ? isTransparent(bodyBackgroundColor) ? _this.styles.backgroundColor : bodyBackgroundColor : documentBackgroundColor;
              }
            } catch (e4) {
            }
            return _this;
          }
          return IFrameElementContainer2;
        }(ElementContainer)
      );
      var LIST_OWNERS = ["OL", "UL", "MENU"];
      var parseNodeTree = function(context, node, parent, root3) {
        for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) {
          nextNode = childNode.nextSibling;
          if (isTextNode(childNode) && childNode.data.trim().length > 0) {
            parent.textNodes.push(new TextContainer(context, childNode, parent.styles));
          } else if (isElementNode(childNode)) {
            if (isSlotElement(childNode) && childNode.assignedNodes) {
              childNode.assignedNodes().forEach(function(childNode2) {
                return parseNodeTree(context, childNode2, parent, root3);
              });
            } else {
              var container = createContainer(context, childNode);
              if (container.styles.isVisible()) {
                if (createsRealStackingContext(childNode, container, root3)) {
                  container.flags |= 4;
                } else if (createsStackingContext(container.styles)) {
                  container.flags |= 2;
                }
                if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) {
                  container.flags |= 8;
                }
                parent.elements.push(container);
                childNode.slot;
                if (childNode.shadowRoot) {
                  parseNodeTree(context, childNode.shadowRoot, container, root3);
                } else if (!isTextareaElement(childNode) && !isSVGElement(childNode) && !isSelectElement(childNode)) {
                  parseNodeTree(context, childNode, container, root3);
                }
              }
            }
          }
        }
      };
      var createContainer = function(context, element2) {
        if (isImageElement(element2)) {
          return new ImageElementContainer(context, element2);
        }
        if (isCanvasElement(element2)) {
          return new CanvasElementContainer(context, element2);
        }
        if (isSVGElement(element2)) {
          return new SVGElementContainer(context, element2);
        }
        if (isLIElement(element2)) {
          return new LIElementContainer(context, element2);
        }
        if (isOLElement(element2)) {
          return new OLElementContainer(context, element2);
        }
        if (isInputElement(element2)) {
          return new InputElementContainer(context, element2);
        }
        if (isSelectElement(element2)) {
          return new SelectElementContainer(context, element2);
        }
        if (isTextareaElement(element2)) {
          return new TextareaElementContainer(context, element2);
        }
        if (isIFrameElement(element2)) {
          return new IFrameElementContainer(context, element2);
        }
        return new ElementContainer(context, element2);
      };
      var parseTree = function(context, element2) {
        var container = createContainer(context, element2);
        container.flags |= 4;
        parseNodeTree(context, element2, container, container);
        return container;
      };
      var createsRealStackingContext = function(node, container, root3) {
        return container.styles.isPositionedWithZIndex() || container.styles.opacity < 1 || container.styles.isTransformed() || isBodyElement(node) && root3.styles.isTransparent();
      };
      var createsStackingContext = function(styles) {
        return styles.isPositioned() || styles.isFloating();
      };
      var isTextNode = function(node) {
        return node.nodeType === Node.TEXT_NODE;
      };
      var isElementNode = function(node) {
        return node.nodeType === Node.ELEMENT_NODE;
      };
      var isHTMLElementNode = function(node) {
        return isElementNode(node) && typeof node.style !== "undefined" && !isSVGElementNode(node);
      };
      var isSVGElementNode = function(element2) {
        return typeof element2.className === "object";
      };
      var isLIElement = function(node) {
        return node.tagName === "LI";
      };
      var isOLElement = function(node) {
        return node.tagName === "OL";
      };
      var isInputElement = function(node) {
        return node.tagName === "INPUT";
      };
      var isHTMLElement = function(node) {
        return node.tagName === "HTML";
      };
      var isSVGElement = function(node) {
        return node.tagName === "svg";
      };
      var isBodyElement = function(node) {
        return node.tagName === "BODY";
      };
      var isCanvasElement = function(node) {
        return node.tagName === "CANVAS";
      };
      var isVideoElement = function(node) {
        return node.tagName === "VIDEO";
      };
      var isImageElement = function(node) {
        return node.tagName === "IMG";
      };
      var isIFrameElement = function(node) {
        return node.tagName === "IFRAME";
      };
      var isStyleElement = function(node) {
        return node.tagName === "STYLE";
      };
      var isScriptElement = function(node) {
        return node.tagName === "SCRIPT";
      };
      var isTextareaElement = function(node) {
        return node.tagName === "TEXTAREA";
      };
      var isSelectElement = function(node) {
        return node.tagName === "SELECT";
      };
      var isSlotElement = function(node) {
        return node.tagName === "SLOT";
      };
      var isCustomElement = function(node) {
        return node.tagName.indexOf("-") > 0;
      };
      var CounterState = (
        /** @class */
        function() {
          function CounterState2() {
            this.counters = {};
          }
          CounterState2.prototype.getCounterValue = function(name2) {
            var counter3 = this.counters[name2];
            if (counter3 && counter3.length) {
              return counter3[counter3.length - 1];
            }
            return 1;
          };
          CounterState2.prototype.getCounterValues = function(name2) {
            var counter3 = this.counters[name2];
            return counter3 ? counter3 : [];
          };
          CounterState2.prototype.pop = function(counters) {
            var _this = this;
            counters.forEach(function(counter3) {
              return _this.counters[counter3].pop();
            });
          };
          CounterState2.prototype.parse = function(style3) {
            var _this = this;
            var counterIncrement2 = style3.counterIncrement;
            var counterReset2 = style3.counterReset;
            var canReset = true;
            if (counterIncrement2 !== null) {
              counterIncrement2.forEach(function(entry) {
                var counter3 = _this.counters[entry.counter];
                if (counter3 && entry.increment !== 0) {
                  canReset = false;
                  if (!counter3.length) {
                    counter3.push(1);
                  }
                  counter3[Math.max(0, counter3.length - 1)] += entry.increment;
                }
              });
            }
            var counterNames = [];
            if (canReset) {
              counterReset2.forEach(function(entry) {
                var counter3 = _this.counters[entry.counter];
                counterNames.push(entry.counter);
                if (!counter3) {
                  counter3 = _this.counters[entry.counter] = [];
                }
                counter3.push(entry.reset);
              });
            }
            return counterNames;
          };
          return CounterState2;
        }()
      );
      var ROMAN_UPPER = {
        integers: [1e3, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
        values: ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
      };
      var ARMENIAN = {
        integers: [
          9e3,
          8e3,
          7e3,
          6e3,
          5e3,
          4e3,
          3e3,
          2e3,
          1e3,
          900,
          800,
          700,
          600,
          500,
          400,
          300,
          200,
          100,
          90,
          80,
          70,
          60,
          50,
          40,
          30,
          20,
          10,
          9,
          8,
          7,
          6,
          5,
          4,
          3,
          2,
          1
        ],
        values: [
          "\u0554",
          "\u0553",
          "\u0552",
          "\u0551",
          "\u0550",
          "\u054F",
          "\u054E",
          "\u054D",
          "\u054C",
          "\u054B",
          "\u054A",
          "\u0549",
          "\u0548",
          "\u0547",
          "\u0546",
          "\u0545",
          "\u0544",
          "\u0543",
          "\u0542",
          "\u0541",
          "\u0540",
          "\u053F",
          "\u053E",
          "\u053D",
          "\u053C",
          "\u053B",
          "\u053A",
          "\u0539",
          "\u0538",
          "\u0537",
          "\u0536",
          "\u0535",
          "\u0534",
          "\u0533",
          "\u0532",
          "\u0531"
        ]
      };
      var HEBREW = {
        integers: [
          1e4,
          9e3,
          8e3,
          7e3,
          6e3,
          5e3,
          4e3,
          3e3,
          2e3,
          1e3,
          400,
          300,
          200,
          100,
          90,
          80,
          70,
          60,
          50,
          40,
          30,
          20,
          19,
          18,
          17,
          16,
          15,
          10,
          9,
          8,
          7,
          6,
          5,
          4,
          3,
          2,
          1
        ],
        values: [
          "\u05D9\u05F3",
          "\u05D8\u05F3",
          "\u05D7\u05F3",
          "\u05D6\u05F3",
          "\u05D5\u05F3",
          "\u05D4\u05F3",
          "\u05D3\u05F3",
          "\u05D2\u05F3",
          "\u05D1\u05F3",
          "\u05D0\u05F3",
          "\u05EA",
          "\u05E9",
          "\u05E8",
          "\u05E7",
          "\u05E6",
          "\u05E4",
          "\u05E2",
          "\u05E1",
          "\u05E0",
          "\u05DE",
          "\u05DC",
          "\u05DB",
          "\u05D9\u05D8",
          "\u05D9\u05D7",
          "\u05D9\u05D6",
          "\u05D8\u05D6",
          "\u05D8\u05D5",
          "\u05D9",
          "\u05D8",
          "\u05D7",
          "\u05D6",
          "\u05D5",
          "\u05D4",
          "\u05D3",
          "\u05D2",
          "\u05D1",
          "\u05D0"
        ]
      };
      var GEORGIAN = {
        integers: [
          1e4,
          9e3,
          8e3,
          7e3,
          6e3,
          5e3,
          4e3,
          3e3,
          2e3,
          1e3,
          900,
          800,
          700,
          600,
          500,
          400,
          300,
          200,
          100,
          90,
          80,
          70,
          60,
          50,
          40,
          30,
          20,
          10,
          9,
          8,
          7,
          6,
          5,
          4,
          3,
          2,
          1
        ],
        values: [
          "\u10F5",
          "\u10F0",
          "\u10EF",
          "\u10F4",
          "\u10EE",
          "\u10ED",
          "\u10EC",
          "\u10EB",
          "\u10EA",
          "\u10E9",
          "\u10E8",
          "\u10E7",
          "\u10E6",
          "\u10E5",
          "\u10E4",
          "\u10F3",
          "\u10E2",
          "\u10E1",
          "\u10E0",
          "\u10DF",
          "\u10DE",
          "\u10DD",
          "\u10F2",
          "\u10DC",
          "\u10DB",
          "\u10DA",
          "\u10D9",
          "\u10D8",
          "\u10D7",
          "\u10F1",
          "\u10D6",
          "\u10D5",
          "\u10D4",
          "\u10D3",
          "\u10D2",
          "\u10D1",
          "\u10D0"
        ]
      };
      var createAdditiveCounter = function(value2, min3, max3, symbols, fallback, suffix) {
        if (value2 < min3 || value2 > max3) {
          return createCounterText(value2, fallback, suffix.length > 0);
        }
        return symbols.integers.reduce(function(string3, integer, index2) {
          while (value2 >= integer) {
            value2 -= integer;
            string3 += symbols.values[index2];
          }
          return string3;
        }, "") + suffix;
      };
      var createCounterStyleWithSymbolResolver = function(value2, codePointRangeLength, isNumeric, resolver) {
        var string3 = "";
        do {
          if (!isNumeric) {
            value2--;
          }
          string3 = resolver(value2) + string3;
          value2 /= codePointRangeLength;
        } while (value2 * codePointRangeLength >= codePointRangeLength);
        return string3;
      };
      var createCounterStyleFromRange = function(value2, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) {
        var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1;
        return (value2 < 0 ? "-" : "") + (createCounterStyleWithSymbolResolver(Math.abs(value2), codePointRangeLength, isNumeric, function(codePoint) {
          return fromCodePoint$1(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart);
        }) + suffix);
      };
      var createCounterStyleFromSymbols = function(value2, symbols, suffix) {
        if (suffix === void 0) {
          suffix = ". ";
        }
        var codePointRangeLength = symbols.length;
        return createCounterStyleWithSymbolResolver(Math.abs(value2), codePointRangeLength, false, function(codePoint) {
          return symbols[Math.floor(codePoint % codePointRangeLength)];
        }) + suffix;
      };
      var CJK_ZEROS = 1 << 0;
      var CJK_TEN_COEFFICIENTS = 1 << 1;
      var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2;
      var CJK_HUNDRED_COEFFICIENTS = 1 << 3;
      var createCJKCounter = function(value2, numbers, multipliers, negativeSign, suffix, flags) {
        if (value2 < -9999 || value2 > 9999) {
          return createCounterText(value2, 4, suffix.length > 0);
        }
        var tmp = Math.abs(value2);
        var string3 = suffix;
        if (tmp === 0) {
          return numbers[0] + string3;
        }
        for (var digit = 0; tmp > 0 && digit <= 4; digit++) {
          var coefficient = tmp % 10;
          if (coefficient === 0 && contains4(flags, CJK_ZEROS) && string3 !== "") {
            string3 = numbers[coefficient] + string3;
          } else if (coefficient > 1 || coefficient === 1 && digit === 0 || coefficient === 1 && digit === 1 && contains4(flags, CJK_TEN_COEFFICIENTS) || coefficient === 1 && digit === 1 && contains4(flags, CJK_TEN_HIGH_COEFFICIENTS) && value2 > 100 || coefficient === 1 && digit > 1 && contains4(flags, CJK_HUNDRED_COEFFICIENTS)) {
            string3 = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : "") + string3;
          } else if (coefficient === 1 && digit > 0) {
            string3 = multipliers[digit - 1] + string3;
          }
          tmp = Math.floor(tmp / 10);
        }
        return (value2 < 0 ? negativeSign : "") + string3;
      };
      var CHINESE_INFORMAL_MULTIPLIERS = "\u5341\u767E\u5343\u842C";
      var CHINESE_FORMAL_MULTIPLIERS = "\u62FE\u4F70\u4EDF\u842C";
      var JAPANESE_NEGATIVE = "\u30DE\u30A4\u30CA\u30B9";
      var KOREAN_NEGATIVE = "\uB9C8\uC774\uB108\uC2A4";
      var createCounterText = function(value2, type, appendSuffix) {
        var defaultSuffix = appendSuffix ? ". " : "";
        var cjkSuffix = appendSuffix ? "\u3001" : "";
        var koreanSuffix = appendSuffix ? ", " : "";
        var spaceSuffix = appendSuffix ? " " : "";
        switch (type) {
          case 0:
            return "\u2022" + spaceSuffix;
          case 1:
            return "\u25E6" + spaceSuffix;
          case 2:
            return "\u25FE" + spaceSuffix;
          case 5:
            var string3 = createCounterStyleFromRange(value2, 48, 57, true, defaultSuffix);
            return string3.length < 4 ? "0" + string3 : string3;
          case 4:
            return createCounterStyleFromSymbols(value2, "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D", cjkSuffix);
          case 6:
            return createAdditiveCounter(value2, 1, 3999, ROMAN_UPPER, 3, defaultSuffix).toLowerCase();
          case 7:
            return createAdditiveCounter(value2, 1, 3999, ROMAN_UPPER, 3, defaultSuffix);
          case 8:
            return createCounterStyleFromRange(value2, 945, 969, false, defaultSuffix);
          case 9:
            return createCounterStyleFromRange(value2, 97, 122, false, defaultSuffix);
          case 10:
            return createCounterStyleFromRange(value2, 65, 90, false, defaultSuffix);
          case 11:
            return createCounterStyleFromRange(value2, 1632, 1641, true, defaultSuffix);
          case 12:
          case 49:
            return createAdditiveCounter(value2, 1, 9999, ARMENIAN, 3, defaultSuffix);
          case 35:
            return createAdditiveCounter(value2, 1, 9999, ARMENIAN, 3, defaultSuffix).toLowerCase();
          case 13:
            return createCounterStyleFromRange(value2, 2534, 2543, true, defaultSuffix);
          case 14:
          case 30:
            return createCounterStyleFromRange(value2, 6112, 6121, true, defaultSuffix);
          case 15:
            return createCounterStyleFromSymbols(value2, "\u5B50\u4E11\u5BC5\u536F\u8FB0\u5DF3\u5348\u672A\u7533\u9149\u620C\u4EA5", cjkSuffix);
          case 16:
            return createCounterStyleFromSymbols(value2, "\u7532\u4E59\u4E19\u4E01\u620A\u5DF1\u5E9A\u8F9B\u58EC\u7678", cjkSuffix);
          case 17:
          case 48:
            return createCJKCounter(value2, "\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D", CHINESE_INFORMAL_MULTIPLIERS, "\u8CA0", cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
          case 47:
            return createCJKCounter(value2, "\u96F6\u58F9\u8CB3\u53C3\u8086\u4F0D\u9678\u67D2\u634C\u7396", CHINESE_FORMAL_MULTIPLIERS, "\u8CA0", cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
          case 42:
            return createCJKCounter(value2, "\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D", CHINESE_INFORMAL_MULTIPLIERS, "\u8D1F", cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
          case 41:
            return createCJKCounter(value2, "\u96F6\u58F9\u8D30\u53C1\u8086\u4F0D\u9646\u67D2\u634C\u7396", CHINESE_FORMAL_MULTIPLIERS, "\u8D1F", cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
          case 26:
            return createCJKCounter(value2, "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D", "\u5341\u767E\u5343\u4E07", JAPANESE_NEGATIVE, cjkSuffix, 0);
          case 25:
            return createCJKCounter(value2, "\u96F6\u58F1\u5F10\u53C2\u56DB\u4F0D\u516D\u4E03\u516B\u4E5D", "\u62FE\u767E\u5343\u4E07", JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
          case 31:
            return createCJKCounter(value2, "\uC601\uC77C\uC774\uC0BC\uC0AC\uC624\uC721\uCE60\uD314\uAD6C", "\uC2ED\uBC31\uCC9C\uB9CC", KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
          case 33:
            return createCJKCounter(value2, "\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D", "\u5341\u767E\u5343\u842C", KOREAN_NEGATIVE, koreanSuffix, 0);
          case 32:
            return createCJKCounter(value2, "\u96F6\u58F9\u8CB3\u53C3\u56DB\u4E94\u516D\u4E03\u516B\u4E5D", "\u62FE\u767E\u5343", KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
          case 18:
            return createCounterStyleFromRange(value2, 2406, 2415, true, defaultSuffix);
          case 20:
            return createAdditiveCounter(value2, 1, 19999, GEORGIAN, 3, defaultSuffix);
          case 21:
            return createCounterStyleFromRange(value2, 2790, 2799, true, defaultSuffix);
          case 22:
            return createCounterStyleFromRange(value2, 2662, 2671, true, defaultSuffix);
          case 22:
            return createAdditiveCounter(value2, 1, 10999, HEBREW, 3, defaultSuffix);
          case 23:
            return createCounterStyleFromSymbols(value2, "\u3042\u3044\u3046\u3048\u304A\u304B\u304D\u304F\u3051\u3053\u3055\u3057\u3059\u305B\u305D\u305F\u3061\u3064\u3066\u3068\u306A\u306B\u306C\u306D\u306E\u306F\u3072\u3075\u3078\u307B\u307E\u307F\u3080\u3081\u3082\u3084\u3086\u3088\u3089\u308A\u308B\u308C\u308D\u308F\u3090\u3091\u3092\u3093");
          case 24:
            return createCounterStyleFromSymbols(value2, "\u3044\u308D\u306F\u306B\u307B\u3078\u3068\u3061\u308A\u306C\u308B\u3092\u308F\u304B\u3088\u305F\u308C\u305D\u3064\u306D\u306A\u3089\u3080\u3046\u3090\u306E\u304A\u304F\u3084\u307E\u3051\u3075\u3053\u3048\u3066\u3042\u3055\u304D\u3086\u3081\u307F\u3057\u3091\u3072\u3082\u305B\u3059");
          case 27:
            return createCounterStyleFromRange(value2, 3302, 3311, true, defaultSuffix);
          case 28:
            return createCounterStyleFromSymbols(value2, "\u30A2\u30A4\u30A6\u30A8\u30AA\u30AB\u30AD\u30AF\u30B1\u30B3\u30B5\u30B7\u30B9\u30BB\u30BD\u30BF\u30C1\u30C4\u30C6\u30C8\u30CA\u30CB\u30CC\u30CD\u30CE\u30CF\u30D2\u30D5\u30D8\u30DB\u30DE\u30DF\u30E0\u30E1\u30E2\u30E4\u30E6\u30E8\u30E9\u30EA\u30EB\u30EC\u30ED\u30EF\u30F0\u30F1\u30F2\u30F3", cjkSuffix);
          case 29:
            return createCounterStyleFromSymbols(value2, "\u30A4\u30ED\u30CF\u30CB\u30DB\u30D8\u30C8\u30C1\u30EA\u30CC\u30EB\u30F2\u30EF\u30AB\u30E8\u30BF\u30EC\u30BD\u30C4\u30CD\u30CA\u30E9\u30E0\u30A6\u30F0\u30CE\u30AA\u30AF\u30E4\u30DE\u30B1\u30D5\u30B3\u30A8\u30C6\u30A2\u30B5\u30AD\u30E6\u30E1\u30DF\u30B7\u30F1\u30D2\u30E2\u30BB\u30B9", cjkSuffix);
          case 34:
            return createCounterStyleFromRange(value2, 3792, 3801, true, defaultSuffix);
          case 37:
            return createCounterStyleFromRange(value2, 6160, 6169, true, defaultSuffix);
          case 38:
            return createCounterStyleFromRange(value2, 4160, 4169, true, defaultSuffix);
          case 39:
            return createCounterStyleFromRange(value2, 2918, 2927, true, defaultSuffix);
          case 40:
            return createCounterStyleFromRange(value2, 1776, 1785, true, defaultSuffix);
          case 43:
            return createCounterStyleFromRange(value2, 3046, 3055, true, defaultSuffix);
          case 44:
            return createCounterStyleFromRange(value2, 3174, 3183, true, defaultSuffix);
          case 45:
            return createCounterStyleFromRange(value2, 3664, 3673, true, defaultSuffix);
          case 46:
            return createCounterStyleFromRange(value2, 3872, 3881, true, defaultSuffix);
          case 3:
          default:
            return createCounterStyleFromRange(value2, 48, 57, true, defaultSuffix);
        }
      };
      var IGNORE_ATTRIBUTE = "data-html2canvas-ignore";
      var DocumentCloner = (
        /** @class */
        function() {
          function DocumentCloner2(context, element2, options2) {
            this.context = context;
            this.options = options2;
            this.scrolledElements = [];
            this.referenceElement = element2;
            this.counters = new CounterState();
            this.quoteDepth = 0;
            if (!element2.ownerDocument) {
              throw new Error("Cloned element does not have an owner document");
            }
            this.documentElement = this.cloneNode(element2.ownerDocument.documentElement, false);
          }
          DocumentCloner2.prototype.toIFrame = function(ownerDocument2, windowSize) {
            var _this = this;
            var iframe = createIFrameContainer(ownerDocument2, windowSize);
            if (!iframe.contentWindow) {
              return Promise.reject("Unable to find iframe window");
            }
            var scrollX = ownerDocument2.defaultView.pageXOffset;
            var scrollY = ownerDocument2.defaultView.pageYOffset;
            var cloneWindow = iframe.contentWindow;
            var documentClone = cloneWindow.document;
            var iframeLoad = iframeLoader(iframe).then(function() {
              return __awaiter(_this, void 0, void 0, function() {
                var onclone, referenceElement;
                return __generator(this, function(_a4) {
                  switch (_a4.label) {
                    case 0:
                      this.scrolledElements.forEach(restoreNodeScroll);
                      if (cloneWindow) {
                        cloneWindow.scrollTo(windowSize.left, windowSize.top);
                        if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) && (cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left)) {
                          this.context.logger.warn("Unable to restore scroll position for cloned document");
                          this.context.windowBounds = this.context.windowBounds.add(cloneWindow.scrollX - windowSize.left, cloneWindow.scrollY - windowSize.top, 0, 0);
                        }
                      }
                      onclone = this.options.onclone;
                      referenceElement = this.clonedReferenceElement;
                      if (typeof referenceElement === "undefined") {
                        return [2, Promise.reject("Error finding the " + this.referenceElement.nodeName + " in the cloned document")];
                      }
                      if (!(documentClone.fonts && documentClone.fonts.ready)) return [3, 2];
                      return [4, documentClone.fonts.ready];
                    case 1:
                      _a4.sent();
                      _a4.label = 2;
                    case 2:
                      if (!/(AppleWebKit)/g.test(navigator.userAgent)) return [3, 4];
                      return [4, imagesReady(documentClone)];
                    case 3:
                      _a4.sent();
                      _a4.label = 4;
                    case 4:
                      if (typeof onclone === "function") {
                        return [2, Promise.resolve().then(function() {
                          return onclone(documentClone, referenceElement);
                        }).then(function() {
                          return iframe;
                        })];
                      }
                      return [2, iframe];
                  }
                });
              });
            });
            documentClone.open();
            documentClone.write(serializeDoctype(document.doctype) + "<html></html>");
            restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY);
            documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement);
            documentClone.close();
            return iframeLoad;
          };
          DocumentCloner2.prototype.createElementClone = function(node) {
            if (isDebugging(
              node,
              2
              /* CLONE */
            )) {
              debugger;
            }
            if (isCanvasElement(node)) {
              return this.createCanvasClone(node);
            }
            if (isVideoElement(node)) {
              return this.createVideoClone(node);
            }
            if (isStyleElement(node)) {
              return this.createStyleClone(node);
            }
            var clone3 = node.cloneNode(false);
            if (isImageElement(clone3)) {
              if (isImageElement(node) && node.currentSrc && node.currentSrc !== node.src) {
                clone3.src = node.currentSrc;
                clone3.srcset = "";
              }
              if (clone3.loading === "lazy") {
                clone3.loading = "eager";
              }
            }
            if (isCustomElement(clone3)) {
              return this.createCustomElementClone(clone3);
            }
            return clone3;
          };
          DocumentCloner2.prototype.createCustomElementClone = function(node) {
            var clone3 = document.createElement("html2canvascustomelement");
            copyCSSStyles(node.style, clone3);
            return clone3;
          };
          DocumentCloner2.prototype.createStyleClone = function(node) {
            try {
              var sheet = node.sheet;
              if (sheet && sheet.cssRules) {
                var css = [].slice.call(sheet.cssRules, 0).reduce(function(css2, rule) {
                  if (rule && typeof rule.cssText === "string") {
                    return css2 + rule.cssText;
                  }
                  return css2;
                }, "");
                var style3 = node.cloneNode(false);
                style3.textContent = css;
                return style3;
              }
            } catch (e4) {
              this.context.logger.error("Unable to access cssRules property", e4);
              if (e4.name !== "SecurityError") {
                throw e4;
              }
            }
            return node.cloneNode(false);
          };
          DocumentCloner2.prototype.createCanvasClone = function(canvas) {
            var _a4;
            if (this.options.inlineImages && canvas.ownerDocument) {
              var img = canvas.ownerDocument.createElement("img");
              try {
                img.src = canvas.toDataURL();
                return img;
              } catch (e4) {
                this.context.logger.info("Unable to inline canvas contents, canvas is tainted", canvas);
              }
            }
            var clonedCanvas = canvas.cloneNode(false);
            try {
              clonedCanvas.width = canvas.width;
              clonedCanvas.height = canvas.height;
              var ctx = canvas.getContext("2d");
              var clonedCtx = clonedCanvas.getContext("2d");
              if (clonedCtx) {
                if (!this.options.allowTaint && ctx) {
                  clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
                } else {
                  var gl = (_a4 = canvas.getContext("webgl2")) !== null && _a4 !== void 0 ? _a4 : canvas.getContext("webgl");
                  if (gl) {
                    var attribs = gl.getContextAttributes();
                    if ((attribs === null || attribs === void 0 ? void 0 : attribs.preserveDrawingBuffer) === false) {
                      this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false", canvas);
                    }
                  }
                  clonedCtx.drawImage(canvas, 0, 0);
                }
              }
              return clonedCanvas;
            } catch (e4) {
              this.context.logger.info("Unable to clone canvas as it is tainted", canvas);
            }
            return clonedCanvas;
          };
          DocumentCloner2.prototype.createVideoClone = function(video) {
            var canvas = video.ownerDocument.createElement("canvas");
            canvas.width = video.offsetWidth;
            canvas.height = video.offsetHeight;
            var ctx = canvas.getContext("2d");
            try {
              if (ctx) {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                if (!this.options.allowTaint) {
                  ctx.getImageData(0, 0, canvas.width, canvas.height);
                }
              }
              return canvas;
            } catch (e4) {
              this.context.logger.info("Unable to clone video as it is tainted", video);
            }
            var blankCanvas = video.ownerDocument.createElement("canvas");
            blankCanvas.width = video.offsetWidth;
            blankCanvas.height = video.offsetHeight;
            return blankCanvas;
          };
          DocumentCloner2.prototype.appendChildNode = function(clone3, child, copyStyles2) {
            if (!isElementNode(child) || !isScriptElement(child) && !child.hasAttribute(IGNORE_ATTRIBUTE) && (typeof this.options.ignoreElements !== "function" || !this.options.ignoreElements(child))) {
              if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {
                clone3.appendChild(this.cloneNode(child, copyStyles2));
              }
            }
          };
          DocumentCloner2.prototype.cloneChildNodes = function(node, clone3, copyStyles2) {
            var _this = this;
            for (var child = node.shadowRoot ? node.shadowRoot.firstChild : node.firstChild; child; child = child.nextSibling) {
              if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === "function") {
                var assignedNodes = child.assignedNodes();
                if (assignedNodes.length) {
                  assignedNodes.forEach(function(assignedNode) {
                    return _this.appendChildNode(clone3, assignedNode, copyStyles2);
                  });
                }
              } else {
                this.appendChildNode(clone3, child, copyStyles2);
              }
            }
          };
          DocumentCloner2.prototype.cloneNode = function(node, copyStyles2) {
            if (isTextNode(node)) {
              return document.createTextNode(node.data);
            }
            if (!node.ownerDocument) {
              return node.cloneNode(false);
            }
            var window2 = node.ownerDocument.defaultView;
            if (window2 && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
              var clone3 = this.createElementClone(node);
              clone3.style.transitionProperty = "none";
              var style3 = window2.getComputedStyle(node);
              var styleBefore = window2.getComputedStyle(node, ":before");
              var styleAfter = window2.getComputedStyle(node, ":after");
              if (this.referenceElement === node && isHTMLElementNode(clone3)) {
                this.clonedReferenceElement = clone3;
              }
              if (isBodyElement(clone3)) {
                createPseudoHideStyles(clone3);
              }
              var counters = this.counters.parse(new CSSParsedCounterDeclaration(this.context, style3));
              var before2 = this.resolvePseudoContent(node, clone3, styleBefore, PseudoElementType.BEFORE);
              if (isCustomElement(node)) {
                copyStyles2 = true;
              }
              if (!isVideoElement(node)) {
                this.cloneChildNodes(node, clone3, copyStyles2);
              }
              if (before2) {
                clone3.insertBefore(before2, clone3.firstChild);
              }
              var after2 = this.resolvePseudoContent(node, clone3, styleAfter, PseudoElementType.AFTER);
              if (after2) {
                clone3.appendChild(after2);
              }
              this.counters.pop(counters);
              if (style3 && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node) || copyStyles2) {
                copyCSSStyles(style3, clone3);
              }
              if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
                this.scrolledElements.push([clone3, node.scrollLeft, node.scrollTop]);
              }
              if ((isTextareaElement(node) || isSelectElement(node)) && (isTextareaElement(clone3) || isSelectElement(clone3))) {
                clone3.value = node.value;
              }
              return clone3;
            }
            return node.cloneNode(false);
          };
          DocumentCloner2.prototype.resolvePseudoContent = function(node, clone3, style3, pseudoElt) {
            var _this = this;
            if (!style3) {
              return;
            }
            var value2 = style3.content;
            var document2 = clone3.ownerDocument;
            if (!document2 || !value2 || value2 === "none" || value2 === "-moz-alt-content" || style3.display === "none") {
              return;
            }
            this.counters.parse(new CSSParsedCounterDeclaration(this.context, style3));
            var declaration2 = new CSSParsedPseudoDeclaration(this.context, style3);
            var anonymousReplacedElement = document2.createElement("html2canvaspseudoelement");
            copyCSSStyles(style3, anonymousReplacedElement);
            declaration2.content.forEach(function(token) {
              if (token.type === 0) {
                anonymousReplacedElement.appendChild(document2.createTextNode(token.value));
              } else if (token.type === 22) {
                var img = document2.createElement("img");
                img.src = token.value;
                img.style.opacity = "1";
                anonymousReplacedElement.appendChild(img);
              } else if (token.type === 18) {
                if (token.name === "attr") {
                  var attr = token.values.filter(isIdentToken);
                  if (attr.length) {
                    anonymousReplacedElement.appendChild(document2.createTextNode(node.getAttribute(attr[0].value) || ""));
                  }
                } else if (token.name === "counter") {
                  var _a4 = token.values.filter(nonFunctionArgSeparator), counter3 = _a4[0], counterStyle = _a4[1];
                  if (counter3 && isIdentToken(counter3)) {
                    var counterState = _this.counters.getCounterValue(counter3.value);
                    var counterType = counterStyle && isIdentToken(counterStyle) ? listStyleType.parse(_this.context, counterStyle.value) : 3;
                    anonymousReplacedElement.appendChild(document2.createTextNode(createCounterText(counterState, counterType, false)));
                  }
                } else if (token.name === "counters") {
                  var _b = token.values.filter(nonFunctionArgSeparator), counter3 = _b[0], delim = _b[1], counterStyle = _b[2];
                  if (counter3 && isIdentToken(counter3)) {
                    var counterStates = _this.counters.getCounterValues(counter3.value);
                    var counterType_1 = counterStyle && isIdentToken(counterStyle) ? listStyleType.parse(_this.context, counterStyle.value) : 3;
                    var separator3 = delim && delim.type === 0 ? delim.value : "";
                    var text3 = counterStates.map(function(value3) {
                      return createCounterText(value3, counterType_1, false);
                    }).join(separator3);
                    anonymousReplacedElement.appendChild(document2.createTextNode(text3));
                  }
                } else ;
              } else if (token.type === 20) {
                switch (token.value) {
                  case "open-quote":
                    anonymousReplacedElement.appendChild(document2.createTextNode(getQuote(declaration2.quotes, _this.quoteDepth++, true)));
                    break;
                  case "close-quote":
                    anonymousReplacedElement.appendChild(document2.createTextNode(getQuote(declaration2.quotes, --_this.quoteDepth, false)));
                    break;
                  default:
                    anonymousReplacedElement.appendChild(document2.createTextNode(token.value));
                }
              }
            });
            anonymousReplacedElement.className = PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
            var newClassName = pseudoElt === PseudoElementType.BEFORE ? " " + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE : " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
            if (isSVGElementNode(clone3)) {
              clone3.className.baseValue += newClassName;
            } else {
              clone3.className += newClassName;
            }
            return anonymousReplacedElement;
          };
          DocumentCloner2.destroy = function(container) {
            if (container.parentNode) {
              container.parentNode.removeChild(container);
              return true;
            }
            return false;
          };
          return DocumentCloner2;
        }()
      );
      var PseudoElementType;
      (function(PseudoElementType2) {
        PseudoElementType2[PseudoElementType2["BEFORE"] = 0] = "BEFORE";
        PseudoElementType2[PseudoElementType2["AFTER"] = 1] = "AFTER";
      })(PseudoElementType || (PseudoElementType = {}));
      var createIFrameContainer = function(ownerDocument2, bounds) {
        var cloneIframeContainer = ownerDocument2.createElement("iframe");
        cloneIframeContainer.className = "html2canvas-container";
        cloneIframeContainer.style.visibility = "hidden";
        cloneIframeContainer.style.position = "fixed";
        cloneIframeContainer.style.left = "-10000px";
        cloneIframeContainer.style.top = "0px";
        cloneIframeContainer.style.border = "0";
        cloneIframeContainer.width = bounds.width.toString();
        cloneIframeContainer.height = bounds.height.toString();
        cloneIframeContainer.scrolling = "no";
        cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, "true");
        ownerDocument2.body.appendChild(cloneIframeContainer);
        return cloneIframeContainer;
      };
      var imageReady = function(img) {
        return new Promise(function(resolve2) {
          if (img.complete) {
            resolve2();
            return;
          }
          if (!img.src) {
            resolve2();
            return;
          }
          img.onload = resolve2;
          img.onerror = resolve2;
        });
      };
      var imagesReady = function(document2) {
        return Promise.all([].slice.call(document2.images, 0).map(imageReady));
      };
      var iframeLoader = function(iframe) {
        return new Promise(function(resolve2, reject2) {
          var cloneWindow = iframe.contentWindow;
          if (!cloneWindow) {
            return reject2("No window assigned for iframe");
          }
          var documentClone = cloneWindow.document;
          cloneWindow.onload = iframe.onload = function() {
            cloneWindow.onload = iframe.onload = null;
            var interval = setInterval(function() {
              if (documentClone.body.childNodes.length > 0 && documentClone.readyState === "complete") {
                clearInterval(interval);
                resolve2(iframe);
              }
            }, 50);
          };
        });
      };
      var ignoredStyleProperties = [
        "all",
        "d",
        "content"
        // Safari shows pseudoelements if content is set
      ];
      var copyCSSStyles = function(style3, target) {
        for (var i4 = style3.length - 1; i4 >= 0; i4--) {
          var property2 = style3.item(i4);
          if (ignoredStyleProperties.indexOf(property2) === -1) {
            target.style.setProperty(property2, style3.getPropertyValue(property2));
          }
        }
        return target;
      };
      var serializeDoctype = function(doctype2) {
        var str = "";
        if (doctype2) {
          str += "<!DOCTYPE ";
          if (doctype2.name) {
            str += doctype2.name;
          }
          if (doctype2.internalSubset) {
            str += doctype2.internalSubset;
          }
          if (doctype2.publicId) {
            str += '"' + doctype2.publicId + '"';
          }
          if (doctype2.systemId) {
            str += '"' + doctype2.systemId + '"';
          }
          str += ">";
        }
        return str;
      };
      var restoreOwnerScroll = function(ownerDocument2, x3, y3) {
        if (ownerDocument2 && ownerDocument2.defaultView && (x3 !== ownerDocument2.defaultView.pageXOffset || y3 !== ownerDocument2.defaultView.pageYOffset)) {
          ownerDocument2.defaultView.scrollTo(x3, y3);
        }
      };
      var restoreNodeScroll = function(_a4) {
        var element2 = _a4[0], x3 = _a4[1], y3 = _a4[2];
        element2.scrollLeft = x3;
        element2.scrollTop = y3;
      };
      var PSEUDO_BEFORE = ":before";
      var PSEUDO_AFTER = ":after";
      var PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
      var PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
      var PSEUDO_HIDE_ELEMENT_STYLE = '{\n    content: "" !important;\n    display: none !important;\n}';
      var createPseudoHideStyles = function(body3) {
        createStyles2(body3, "." + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + PSEUDO_BEFORE + PSEUDO_HIDE_ELEMENT_STYLE + "\n         ." + PSEUDO_HIDE_ELEMENT_CLASS_AFTER + PSEUDO_AFTER + PSEUDO_HIDE_ELEMENT_STYLE);
      };
      var createStyles2 = function(body3, styles) {
        var document2 = body3.ownerDocument;
        if (document2) {
          var style3 = document2.createElement("style");
          style3.textContent = styles;
          body3.appendChild(style3);
        }
      };
      var CacheStorage = (
        /** @class */
        function() {
          function CacheStorage2() {
          }
          CacheStorage2.getOrigin = function(url2) {
            var link2 = CacheStorage2._link;
            if (!link2) {
              return "about:blank";
            }
            link2.href = url2;
            link2.href = link2.href;
            return link2.protocol + link2.hostname + link2.port;
          };
          CacheStorage2.isSameOrigin = function(src) {
            return CacheStorage2.getOrigin(src) === CacheStorage2._origin;
          };
          CacheStorage2.setContext = function(window2) {
            CacheStorage2._link = window2.document.createElement("a");
            CacheStorage2._origin = CacheStorage2.getOrigin(window2.location.href);
          };
          CacheStorage2._origin = "about:blank";
          return CacheStorage2;
        }()
      );
      var Cache = (
        /** @class */
        function() {
          function Cache2(context, _options) {
            this.context = context;
            this._options = _options;
            this._cache = {};
          }
          Cache2.prototype.addImage = function(src) {
            var result2 = Promise.resolve();
            if (this.has(src)) {
              return result2;
            }
            if (isBlobImage(src) || isRenderable(src)) {
              (this._cache[src] = this.loadImage(src)).catch(function() {
              });
              return result2;
            }
            return result2;
          };
          Cache2.prototype.match = function(src) {
            return this._cache[src];
          };
          Cache2.prototype.loadImage = function(key2) {
            return __awaiter(this, void 0, void 0, function() {
              var isSameOrigin, useCORS, useProxy, src;
              var _this = this;
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    isSameOrigin = CacheStorage.isSameOrigin(key2);
                    useCORS = !isInlineImage(key2) && this._options.useCORS === true && FEATURES.SUPPORT_CORS_IMAGES && !isSameOrigin;
                    useProxy = !isInlineImage(key2) && !isSameOrigin && !isBlobImage(key2) && typeof this._options.proxy === "string" && FEATURES.SUPPORT_CORS_XHR && !useCORS;
                    if (!isSameOrigin && this._options.allowTaint === false && !isInlineImage(key2) && !isBlobImage(key2) && !useProxy && !useCORS) {
                      return [
                        2
                        /*return*/
                      ];
                    }
                    src = key2;
                    if (!useProxy) return [3, 2];
                    return [4, this.proxy(src)];
                  case 1:
                    src = _a4.sent();
                    _a4.label = 2;
                  case 2:
                    this.context.logger.debug("Added image " + key2.substring(0, 256));
                    return [4, new Promise(function(resolve2, reject2) {
                      var img = new Image();
                      img.onload = function() {
                        return resolve2(img);
                      };
                      img.onerror = reject2;
                      if (isInlineBase64Image(src) || useCORS) {
                        img.crossOrigin = "anonymous";
                      }
                      img.src = src;
                      if (img.complete === true) {
                        setTimeout(function() {
                          return resolve2(img);
                        }, 500);
                      }
                      if (_this._options.imageTimeout > 0) {
                        setTimeout(function() {
                          return reject2("Timed out (" + _this._options.imageTimeout + "ms) loading image");
                        }, _this._options.imageTimeout);
                      }
                    })];
                  case 3:
                    return [2, _a4.sent()];
                }
              });
            });
          };
          Cache2.prototype.has = function(key2) {
            return typeof this._cache[key2] !== "undefined";
          };
          Cache2.prototype.keys = function() {
            return Promise.resolve(Object.keys(this._cache));
          };
          Cache2.prototype.proxy = function(src) {
            var _this = this;
            var proxy = this._options.proxy;
            if (!proxy) {
              throw new Error("No proxy defined");
            }
            var key2 = src.substring(0, 256);
            return new Promise(function(resolve2, reject2) {
              var responseType = FEATURES.SUPPORT_RESPONSE_TYPE ? "blob" : "text";
              var xhr = new XMLHttpRequest();
              xhr.onload = function() {
                if (xhr.status === 200) {
                  if (responseType === "text") {
                    resolve2(xhr.response);
                  } else {
                    var reader_1 = new FileReader();
                    reader_1.addEventListener("load", function() {
                      return resolve2(reader_1.result);
                    }, false);
                    reader_1.addEventListener("error", function(e4) {
                      return reject2(e4);
                    }, false);
                    reader_1.readAsDataURL(xhr.response);
                  }
                } else {
                  reject2("Failed to proxy resource " + key2 + " with status code " + xhr.status);
                }
              };
              xhr.onerror = reject2;
              var queryString = proxy.indexOf("?") > -1 ? "&" : "?";
              xhr.open("GET", "" + proxy + queryString + "url=" + encodeURIComponent(src) + "&responseType=" + responseType);
              if (responseType !== "text" && xhr instanceof XMLHttpRequest) {
                xhr.responseType = responseType;
              }
              if (_this._options.imageTimeout) {
                var timeout_1 = _this._options.imageTimeout;
                xhr.timeout = timeout_1;
                xhr.ontimeout = function() {
                  return reject2("Timed out (" + timeout_1 + "ms) proxying " + key2);
                };
              }
              xhr.send();
            });
          };
          return Cache2;
        }()
      );
      var INLINE_SVG = /^data:image\/svg\+xml/i;
      var INLINE_BASE64 = /^data:image\/.*;base64,/i;
      var INLINE_IMG = /^data:image\/.*/i;
      var isRenderable = function(src) {
        return FEATURES.SUPPORT_SVG_DRAWING || !isSVG2(src);
      };
      var isInlineImage = function(src) {
        return INLINE_IMG.test(src);
      };
      var isInlineBase64Image = function(src) {
        return INLINE_BASE64.test(src);
      };
      var isBlobImage = function(src) {
        return src.substr(0, 4) === "blob";
      };
      var isSVG2 = function(src) {
        return src.substr(-3).toLowerCase() === "svg" || INLINE_SVG.test(src);
      };
      var Vector = (
        /** @class */
        function() {
          function Vector2(x3, y3) {
            this.type = 0;
            this.x = x3;
            this.y = y3;
          }
          Vector2.prototype.add = function(deltaX, deltaY) {
            return new Vector2(this.x + deltaX, this.y + deltaY);
          };
          return Vector2;
        }()
      );
      var lerp = function(a4, b3, t3) {
        return new Vector(a4.x + (b3.x - a4.x) * t3, a4.y + (b3.y - a4.y) * t3);
      };
      var BezierCurve = (
        /** @class */
        function() {
          function BezierCurve2(start, startControl, endControl, end) {
            this.type = 1;
            this.start = start;
            this.startControl = startControl;
            this.endControl = endControl;
            this.end = end;
          }
          BezierCurve2.prototype.subdivide = function(t3, firstHalf) {
            var ab = lerp(this.start, this.startControl, t3);
            var bc = lerp(this.startControl, this.endControl, t3);
            var cd = lerp(this.endControl, this.end, t3);
            var abbc = lerp(ab, bc, t3);
            var bccd = lerp(bc, cd, t3);
            var dest = lerp(abbc, bccd, t3);
            return firstHalf ? new BezierCurve2(this.start, ab, abbc, dest) : new BezierCurve2(dest, bccd, cd, this.end);
          };
          BezierCurve2.prototype.add = function(deltaX, deltaY) {
            return new BezierCurve2(this.start.add(deltaX, deltaY), this.startControl.add(deltaX, deltaY), this.endControl.add(deltaX, deltaY), this.end.add(deltaX, deltaY));
          };
          BezierCurve2.prototype.reverse = function() {
            return new BezierCurve2(this.end, this.endControl, this.startControl, this.start);
          };
          return BezierCurve2;
        }()
      );
      var isBezierCurve = function(path) {
        return path.type === 1;
      };
      var BoundCurves = (
        /** @class */
        /* @__PURE__ */ function() {
          function BoundCurves2(element2) {
            var styles = element2.styles;
            var bounds = element2.bounds;
            var _a4 = getAbsoluteValueForTuple(styles.borderTopLeftRadius, bounds.width, bounds.height), tlh = _a4[0], tlv = _a4[1];
            var _b = getAbsoluteValueForTuple(styles.borderTopRightRadius, bounds.width, bounds.height), trh = _b[0], trv = _b[1];
            var _c = getAbsoluteValueForTuple(styles.borderBottomRightRadius, bounds.width, bounds.height), brh = _c[0], brv = _c[1];
            var _d = getAbsoluteValueForTuple(styles.borderBottomLeftRadius, bounds.width, bounds.height), blh = _d[0], blv = _d[1];
            var factors = [];
            factors.push((tlh + trh) / bounds.width);
            factors.push((blh + brh) / bounds.width);
            factors.push((tlv + blv) / bounds.height);
            factors.push((trv + brv) / bounds.height);
            var maxFactor = Math.max.apply(Math, factors);
            if (maxFactor > 1) {
              tlh /= maxFactor;
              tlv /= maxFactor;
              trh /= maxFactor;
              trv /= maxFactor;
              brh /= maxFactor;
              brv /= maxFactor;
              blh /= maxFactor;
              blv /= maxFactor;
            }
            var topWidth = bounds.width - trh;
            var rightHeight = bounds.height - brv;
            var bottomWidth = bounds.width - brh;
            var leftHeight = bounds.height - blv;
            var borderTopWidth2 = styles.borderTopWidth;
            var borderRightWidth2 = styles.borderRightWidth;
            var borderBottomWidth2 = styles.borderBottomWidth;
            var borderLeftWidth2 = styles.borderLeftWidth;
            var paddingTop2 = getAbsoluteValue(styles.paddingTop, element2.bounds.width);
            var paddingRight2 = getAbsoluteValue(styles.paddingRight, element2.bounds.width);
            var paddingBottom2 = getAbsoluteValue(styles.paddingBottom, element2.bounds.width);
            var paddingLeft2 = getAbsoluteValue(styles.paddingLeft, element2.bounds.width);
            this.topLeftBorderDoubleOuterBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 / 3, bounds.top + borderTopWidth2 / 3, tlh - borderLeftWidth2 / 3, tlv - borderTopWidth2 / 3, CORNER.TOP_LEFT) : new Vector(bounds.left + borderLeftWidth2 / 3, bounds.top + borderTopWidth2 / 3);
            this.topRightBorderDoubleOuterBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth2 / 3, trh - borderRightWidth2 / 3, trv - borderTopWidth2 / 3, CORNER.TOP_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2 / 3, bounds.top + borderTopWidth2 / 3);
            this.bottomRightBorderDoubleOuterBox = brh > 0 || brv > 0 ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth2 / 3, brv - borderBottomWidth2 / 3, CORNER.BOTTOM_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2 / 3, bounds.top + bounds.height - borderBottomWidth2 / 3);
            this.bottomLeftBorderDoubleOuterBox = blh > 0 || blv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 / 3, bounds.top + leftHeight, blh - borderLeftWidth2 / 3, blv - borderBottomWidth2 / 3, CORNER.BOTTOM_LEFT) : new Vector(bounds.left + borderLeftWidth2 / 3, bounds.top + bounds.height - borderBottomWidth2 / 3);
            this.topLeftBorderDoubleInnerBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 * 2 / 3, bounds.top + borderTopWidth2 * 2 / 3, tlh - borderLeftWidth2 * 2 / 3, tlv - borderTopWidth2 * 2 / 3, CORNER.TOP_LEFT) : new Vector(bounds.left + borderLeftWidth2 * 2 / 3, bounds.top + borderTopWidth2 * 2 / 3);
            this.topRightBorderDoubleInnerBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth2 * 2 / 3, trh - borderRightWidth2 * 2 / 3, trv - borderTopWidth2 * 2 / 3, CORNER.TOP_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2 * 2 / 3, bounds.top + borderTopWidth2 * 2 / 3);
            this.bottomRightBorderDoubleInnerBox = brh > 0 || brv > 0 ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth2 * 2 / 3, brv - borderBottomWidth2 * 2 / 3, CORNER.BOTTOM_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2 * 2 / 3, bounds.top + bounds.height - borderBottomWidth2 * 2 / 3);
            this.bottomLeftBorderDoubleInnerBox = blh > 0 || blv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 * 2 / 3, bounds.top + leftHeight, blh - borderLeftWidth2 * 2 / 3, blv - borderBottomWidth2 * 2 / 3, CORNER.BOTTOM_LEFT) : new Vector(bounds.left + borderLeftWidth2 * 2 / 3, bounds.top + bounds.height - borderBottomWidth2 * 2 / 3);
            this.topLeftBorderStroke = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 / 2, bounds.top + borderTopWidth2 / 2, tlh - borderLeftWidth2 / 2, tlv - borderTopWidth2 / 2, CORNER.TOP_LEFT) : new Vector(bounds.left + borderLeftWidth2 / 2, bounds.top + borderTopWidth2 / 2);
            this.topRightBorderStroke = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth2 / 2, trh - borderRightWidth2 / 2, trv - borderTopWidth2 / 2, CORNER.TOP_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2 / 2, bounds.top + borderTopWidth2 / 2);
            this.bottomRightBorderStroke = brh > 0 || brv > 0 ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth2 / 2, brv - borderBottomWidth2 / 2, CORNER.BOTTOM_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2 / 2, bounds.top + bounds.height - borderBottomWidth2 / 2);
            this.bottomLeftBorderStroke = blh > 0 || blv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 / 2, bounds.top + leftHeight, blh - borderLeftWidth2 / 2, blv - borderBottomWidth2 / 2, CORNER.BOTTOM_LEFT) : new Vector(bounds.left + borderLeftWidth2 / 2, bounds.top + bounds.height - borderBottomWidth2 / 2);
            this.topLeftBorderBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT) : new Vector(bounds.left, bounds.top);
            this.topRightBorderBox = trh > 0 || trv > 0 ? getCurvePoints(bounds.left + topWidth, bounds.top, trh, trv, CORNER.TOP_RIGHT) : new Vector(bounds.left + bounds.width, bounds.top);
            this.bottomRightBorderBox = brh > 0 || brv > 0 ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh, brv, CORNER.BOTTOM_RIGHT) : new Vector(bounds.left + bounds.width, bounds.top + bounds.height);
            this.bottomLeftBorderBox = blh > 0 || blv > 0 ? getCurvePoints(bounds.left, bounds.top + leftHeight, blh, blv, CORNER.BOTTOM_LEFT) : new Vector(bounds.left, bounds.top + bounds.height);
            this.topLeftPaddingBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2, bounds.top + borderTopWidth2, Math.max(0, tlh - borderLeftWidth2), Math.max(0, tlv - borderTopWidth2), CORNER.TOP_LEFT) : new Vector(bounds.left + borderLeftWidth2, bounds.top + borderTopWidth2);
            this.topRightPaddingBox = trh > 0 || trv > 0 ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width - borderRightWidth2), bounds.top + borderTopWidth2, topWidth > bounds.width + borderRightWidth2 ? 0 : Math.max(0, trh - borderRightWidth2), Math.max(0, trv - borderTopWidth2), CORNER.TOP_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2, bounds.top + borderTopWidth2);
            this.bottomRightPaddingBox = brh > 0 || brv > 0 ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth2), bounds.top + Math.min(rightHeight, bounds.height - borderBottomWidth2), Math.max(0, brh - borderRightWidth2), Math.max(0, brv - borderBottomWidth2), CORNER.BOTTOM_RIGHT) : new Vector(bounds.left + bounds.width - borderRightWidth2, bounds.top + bounds.height - borderBottomWidth2);
            this.bottomLeftPaddingBox = blh > 0 || blv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2, bounds.top + Math.min(leftHeight, bounds.height - borderBottomWidth2), Math.max(0, blh - borderLeftWidth2), Math.max(0, blv - borderBottomWidth2), CORNER.BOTTOM_LEFT) : new Vector(bounds.left + borderLeftWidth2, bounds.top + bounds.height - borderBottomWidth2);
            this.topLeftContentBox = tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 + paddingLeft2, bounds.top + borderTopWidth2 + paddingTop2, Math.max(0, tlh - (borderLeftWidth2 + paddingLeft2)), Math.max(0, tlv - (borderTopWidth2 + paddingTop2)), CORNER.TOP_LEFT) : new Vector(bounds.left + borderLeftWidth2 + paddingLeft2, bounds.top + borderTopWidth2 + paddingTop2);
            this.topRightContentBox = trh > 0 || trv > 0 ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth2 + paddingLeft2), bounds.top + borderTopWidth2 + paddingTop2, topWidth > bounds.width + borderLeftWidth2 + paddingLeft2 ? 0 : trh - borderLeftWidth2 + paddingLeft2, trv - (borderTopWidth2 + paddingTop2), CORNER.TOP_RIGHT) : new Vector(bounds.left + bounds.width - (borderRightWidth2 + paddingRight2), bounds.top + borderTopWidth2 + paddingTop2);
            this.bottomRightContentBox = brh > 0 || brv > 0 ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - (borderLeftWidth2 + paddingLeft2)), bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth2 + paddingTop2), Math.max(0, brh - (borderRightWidth2 + paddingRight2)), brv - (borderBottomWidth2 + paddingBottom2), CORNER.BOTTOM_RIGHT) : new Vector(bounds.left + bounds.width - (borderRightWidth2 + paddingRight2), bounds.top + bounds.height - (borderBottomWidth2 + paddingBottom2));
            this.bottomLeftContentBox = blh > 0 || blv > 0 ? getCurvePoints(bounds.left + borderLeftWidth2 + paddingLeft2, bounds.top + leftHeight, Math.max(0, blh - (borderLeftWidth2 + paddingLeft2)), blv - (borderBottomWidth2 + paddingBottom2), CORNER.BOTTOM_LEFT) : new Vector(bounds.left + borderLeftWidth2 + paddingLeft2, bounds.top + bounds.height - (borderBottomWidth2 + paddingBottom2));
          }
          return BoundCurves2;
        }()
      );
      var CORNER;
      (function(CORNER2) {
        CORNER2[CORNER2["TOP_LEFT"] = 0] = "TOP_LEFT";
        CORNER2[CORNER2["TOP_RIGHT"] = 1] = "TOP_RIGHT";
        CORNER2[CORNER2["BOTTOM_RIGHT"] = 2] = "BOTTOM_RIGHT";
        CORNER2[CORNER2["BOTTOM_LEFT"] = 3] = "BOTTOM_LEFT";
      })(CORNER || (CORNER = {}));
      var getCurvePoints = function(x3, y3, r1, r22, position2) {
        var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
        var ox = r1 * kappa;
        var oy = r22 * kappa;
        var xm = x3 + r1;
        var ym = y3 + r22;
        switch (position2) {
          case CORNER.TOP_LEFT:
            return new BezierCurve(new Vector(x3, ym), new Vector(x3, ym - oy), new Vector(xm - ox, y3), new Vector(xm, y3));
          case CORNER.TOP_RIGHT:
            return new BezierCurve(new Vector(x3, y3), new Vector(x3 + ox, y3), new Vector(xm, ym - oy), new Vector(xm, ym));
          case CORNER.BOTTOM_RIGHT:
            return new BezierCurve(new Vector(xm, y3), new Vector(xm, y3 + oy), new Vector(x3 + ox, ym), new Vector(x3, ym));
          case CORNER.BOTTOM_LEFT:
          default:
            return new BezierCurve(new Vector(xm, ym), new Vector(xm - ox, ym), new Vector(x3, y3 + oy), new Vector(x3, y3));
        }
      };
      var calculateBorderBoxPath = function(curves) {
        return [curves.topLeftBorderBox, curves.topRightBorderBox, curves.bottomRightBorderBox, curves.bottomLeftBorderBox];
      };
      var calculateContentBoxPath = function(curves) {
        return [
          curves.topLeftContentBox,
          curves.topRightContentBox,
          curves.bottomRightContentBox,
          curves.bottomLeftContentBox
        ];
      };
      var calculatePaddingBoxPath = function(curves) {
        return [
          curves.topLeftPaddingBox,
          curves.topRightPaddingBox,
          curves.bottomRightPaddingBox,
          curves.bottomLeftPaddingBox
        ];
      };
      var TransformEffect = (
        /** @class */
        /* @__PURE__ */ function() {
          function TransformEffect2(offsetX, offsetY, matrix2) {
            this.offsetX = offsetX;
            this.offsetY = offsetY;
            this.matrix = matrix2;
            this.type = 0;
            this.target = 2 | 4;
          }
          return TransformEffect2;
        }()
      );
      var ClipEffect = (
        /** @class */
        /* @__PURE__ */ function() {
          function ClipEffect2(path, target) {
            this.path = path;
            this.target = target;
            this.type = 1;
          }
          return ClipEffect2;
        }()
      );
      var OpacityEffect = (
        /** @class */
        /* @__PURE__ */ function() {
          function OpacityEffect2(opacity2) {
            this.opacity = opacity2;
            this.type = 2;
            this.target = 2 | 4;
          }
          return OpacityEffect2;
        }()
      );
      var isTransformEffect = function(effect2) {
        return effect2.type === 0;
      };
      var isClipEffect = function(effect2) {
        return effect2.type === 1;
      };
      var isOpacityEffect = function(effect2) {
        return effect2.type === 2;
      };
      var equalPath = function(a4, b3) {
        if (a4.length === b3.length) {
          return a4.some(function(v3, i4) {
            return v3 === b3[i4];
          });
        }
        return false;
      };
      var transformPath = function(path, deltaX, deltaY, deltaW, deltaH) {
        return path.map(function(point, index2) {
          switch (index2) {
            case 0:
              return point.add(deltaX, deltaY);
            case 1:
              return point.add(deltaX + deltaW, deltaY);
            case 2:
              return point.add(deltaX + deltaW, deltaY + deltaH);
            case 3:
              return point.add(deltaX, deltaY + deltaH);
          }
          return point;
        });
      };
      var StackingContext = (
        /** @class */
        /* @__PURE__ */ function() {
          function StackingContext2(container) {
            this.element = container;
            this.inlineLevel = [];
            this.nonInlineLevel = [];
            this.negativeZIndex = [];
            this.zeroOrAutoZIndexOrTransformedOrOpacity = [];
            this.positiveZIndex = [];
            this.nonPositionedFloats = [];
            this.nonPositionedInlineLevel = [];
          }
          return StackingContext2;
        }()
      );
      var ElementPaint = (
        /** @class */
        function() {
          function ElementPaint2(container, parent) {
            this.container = container;
            this.parent = parent;
            this.effects = [];
            this.curves = new BoundCurves(this.container);
            if (this.container.styles.opacity < 1) {
              this.effects.push(new OpacityEffect(this.container.styles.opacity));
            }
            if (this.container.styles.transform !== null) {
              var offsetX = this.container.bounds.left + this.container.styles.transformOrigin[0].number;
              var offsetY = this.container.bounds.top + this.container.styles.transformOrigin[1].number;
              var matrix2 = this.container.styles.transform;
              this.effects.push(new TransformEffect(offsetX, offsetY, matrix2));
            }
            if (this.container.styles.overflowX !== 0) {
              var borderBox = calculateBorderBoxPath(this.curves);
              var paddingBox2 = calculatePaddingBoxPath(this.curves);
              if (equalPath(borderBox, paddingBox2)) {
                this.effects.push(new ClipEffect(
                  borderBox,
                  2 | 4
                  /* CONTENT */
                ));
              } else {
                this.effects.push(new ClipEffect(
                  borderBox,
                  2
                  /* BACKGROUND_BORDERS */
                ));
                this.effects.push(new ClipEffect(
                  paddingBox2,
                  4
                  /* CONTENT */
                ));
              }
            }
          }
          ElementPaint2.prototype.getEffects = function(target) {
            var inFlow = [
              2,
              3
              /* FIXED */
            ].indexOf(this.container.styles.position) === -1;
            var parent = this.parent;
            var effects = this.effects.slice(0);
            while (parent) {
              var croplessEffects = parent.effects.filter(function(effect2) {
                return !isClipEffect(effect2);
              });
              if (inFlow || parent.container.styles.position !== 0 || !parent.parent) {
                effects.unshift.apply(effects, croplessEffects);
                inFlow = [
                  2,
                  3
                  /* FIXED */
                ].indexOf(parent.container.styles.position) === -1;
                if (parent.container.styles.overflowX !== 0) {
                  var borderBox = calculateBorderBoxPath(parent.curves);
                  var paddingBox2 = calculatePaddingBoxPath(parent.curves);
                  if (!equalPath(borderBox, paddingBox2)) {
                    effects.unshift(new ClipEffect(
                      paddingBox2,
                      2 | 4
                      /* CONTENT */
                    ));
                  }
                }
              } else {
                effects.unshift.apply(effects, croplessEffects);
              }
              parent = parent.parent;
            }
            return effects.filter(function(effect2) {
              return contains4(effect2.target, target);
            });
          };
          return ElementPaint2;
        }()
      );
      var parseStackTree = function(parent, stackingContext, realStackingContext, listItems) {
        parent.container.elements.forEach(function(child) {
          var treatAsRealStackingContext = contains4(
            child.flags,
            4
            /* CREATES_REAL_STACKING_CONTEXT */
          );
          var createsStackingContext2 = contains4(
            child.flags,
            2
            /* CREATES_STACKING_CONTEXT */
          );
          var paintContainer = new ElementPaint(child, parent);
          if (contains4(
            child.styles.display,
            2048
            /* LIST_ITEM */
          )) {
            listItems.push(paintContainer);
          }
          var listOwnerItems = contains4(
            child.flags,
            8
            /* IS_LIST_OWNER */
          ) ? [] : listItems;
          if (treatAsRealStackingContext || createsStackingContext2) {
            var parentStack = treatAsRealStackingContext || child.styles.isPositioned() ? realStackingContext : stackingContext;
            var stack = new StackingContext(paintContainer);
            if (child.styles.isPositioned() || child.styles.opacity < 1 || child.styles.isTransformed()) {
              var order_1 = child.styles.zIndex.order;
              if (order_1 < 0) {
                var index_1 = 0;
                parentStack.negativeZIndex.some(function(current, i4) {
                  if (order_1 > current.element.container.styles.zIndex.order) {
                    index_1 = i4;
                    return false;
                  } else if (index_1 > 0) {
                    return true;
                  }
                  return false;
                });
                parentStack.negativeZIndex.splice(index_1, 0, stack);
              } else if (order_1 > 0) {
                var index_2 = 0;
                parentStack.positiveZIndex.some(function(current, i4) {
                  if (order_1 >= current.element.container.styles.zIndex.order) {
                    index_2 = i4 + 1;
                    return false;
                  } else if (index_2 > 0) {
                    return true;
                  }
                  return false;
                });
                parentStack.positiveZIndex.splice(index_2, 0, stack);
              } else {
                parentStack.zeroOrAutoZIndexOrTransformedOrOpacity.push(stack);
              }
            } else {
              if (child.styles.isFloating()) {
                parentStack.nonPositionedFloats.push(stack);
              } else {
                parentStack.nonPositionedInlineLevel.push(stack);
              }
            }
            parseStackTree(paintContainer, stack, treatAsRealStackingContext ? stack : realStackingContext, listOwnerItems);
          } else {
            if (child.styles.isInlineLevel()) {
              stackingContext.inlineLevel.push(paintContainer);
            } else {
              stackingContext.nonInlineLevel.push(paintContainer);
            }
            parseStackTree(paintContainer, stackingContext, realStackingContext, listOwnerItems);
          }
          if (contains4(
            child.flags,
            8
            /* IS_LIST_OWNER */
          )) {
            processListItems(child, listOwnerItems);
          }
        });
      };
      var processListItems = function(owner, elements) {
        var numbering = owner instanceof OLElementContainer ? owner.start : 1;
        var reversed = owner instanceof OLElementContainer ? owner.reversed : false;
        for (var i4 = 0; i4 < elements.length; i4++) {
          var item = elements[i4];
          if (item.container instanceof LIElementContainer && typeof item.container.value === "number" && item.container.value !== 0) {
            numbering = item.container.value;
          }
          item.listValue = createCounterText(numbering, item.container.styles.listStyleType, true);
          numbering += reversed ? -1 : 1;
        }
      };
      var parseStackingContexts = function(container) {
        var paintContainer = new ElementPaint(container, null);
        var root3 = new StackingContext(paintContainer);
        var listItems = [];
        parseStackTree(paintContainer, root3, root3, listItems);
        processListItems(paintContainer.container, listItems);
        return root3;
      };
      var parsePathForBorder = function(curves, borderSide) {
        switch (borderSide) {
          case 0:
            return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftPaddingBox, curves.topRightBorderBox, curves.topRightPaddingBox);
          case 1:
            return createPathFromCurves(curves.topRightBorderBox, curves.topRightPaddingBox, curves.bottomRightBorderBox, curves.bottomRightPaddingBox);
          case 2:
            return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox);
          case 3:
          default:
            return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox, curves.topLeftBorderBox, curves.topLeftPaddingBox);
        }
      };
      var parsePathForBorderDoubleOuter = function(curves, borderSide) {
        switch (borderSide) {
          case 0:
            return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftBorderDoubleOuterBox, curves.topRightBorderBox, curves.topRightBorderDoubleOuterBox);
          case 1:
            return createPathFromCurves(curves.topRightBorderBox, curves.topRightBorderDoubleOuterBox, curves.bottomRightBorderBox, curves.bottomRightBorderDoubleOuterBox);
          case 2:
            return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightBorderDoubleOuterBox, curves.bottomLeftBorderBox, curves.bottomLeftBorderDoubleOuterBox);
          case 3:
          default:
            return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftBorderDoubleOuterBox, curves.topLeftBorderBox, curves.topLeftBorderDoubleOuterBox);
        }
      };
      var parsePathForBorderDoubleInner = function(curves, borderSide) {
        switch (borderSide) {
          case 0:
            return createPathFromCurves(curves.topLeftBorderDoubleInnerBox, curves.topLeftPaddingBox, curves.topRightBorderDoubleInnerBox, curves.topRightPaddingBox);
          case 1:
            return createPathFromCurves(curves.topRightBorderDoubleInnerBox, curves.topRightPaddingBox, curves.bottomRightBorderDoubleInnerBox, curves.bottomRightPaddingBox);
          case 2:
            return createPathFromCurves(curves.bottomRightBorderDoubleInnerBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderDoubleInnerBox, curves.bottomLeftPaddingBox);
          case 3:
          default:
            return createPathFromCurves(curves.bottomLeftBorderDoubleInnerBox, curves.bottomLeftPaddingBox, curves.topLeftBorderDoubleInnerBox, curves.topLeftPaddingBox);
        }
      };
      var parsePathForBorderStroke = function(curves, borderSide) {
        switch (borderSide) {
          case 0:
            return createStrokePathFromCurves(curves.topLeftBorderStroke, curves.topRightBorderStroke);
          case 1:
            return createStrokePathFromCurves(curves.topRightBorderStroke, curves.bottomRightBorderStroke);
          case 2:
            return createStrokePathFromCurves(curves.bottomRightBorderStroke, curves.bottomLeftBorderStroke);
          case 3:
          default:
            return createStrokePathFromCurves(curves.bottomLeftBorderStroke, curves.topLeftBorderStroke);
        }
      };
      var createStrokePathFromCurves = function(outer1, outer2) {
        var path = [];
        if (isBezierCurve(outer1)) {
          path.push(outer1.subdivide(0.5, false));
        } else {
          path.push(outer1);
        }
        if (isBezierCurve(outer2)) {
          path.push(outer2.subdivide(0.5, true));
        } else {
          path.push(outer2);
        }
        return path;
      };
      var createPathFromCurves = function(outer1, inner1, outer2, inner2) {
        var path = [];
        if (isBezierCurve(outer1)) {
          path.push(outer1.subdivide(0.5, false));
        } else {
          path.push(outer1);
        }
        if (isBezierCurve(outer2)) {
          path.push(outer2.subdivide(0.5, true));
        } else {
          path.push(outer2);
        }
        if (isBezierCurve(inner2)) {
          path.push(inner2.subdivide(0.5, true).reverse());
        } else {
          path.push(inner2);
        }
        if (isBezierCurve(inner1)) {
          path.push(inner1.subdivide(0.5, false).reverse());
        } else {
          path.push(inner1);
        }
        return path;
      };
      var paddingBox = function(element2) {
        var bounds = element2.bounds;
        var styles = element2.styles;
        return bounds.add(styles.borderLeftWidth, styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth), -(styles.borderTopWidth + styles.borderBottomWidth));
      };
      var contentBox = function(element2) {
        var styles = element2.styles;
        var bounds = element2.bounds;
        var paddingLeft2 = getAbsoluteValue(styles.paddingLeft, bounds.width);
        var paddingRight2 = getAbsoluteValue(styles.paddingRight, bounds.width);
        var paddingTop2 = getAbsoluteValue(styles.paddingTop, bounds.width);
        var paddingBottom2 = getAbsoluteValue(styles.paddingBottom, bounds.width);
        return bounds.add(paddingLeft2 + styles.borderLeftWidth, paddingTop2 + styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth + paddingLeft2 + paddingRight2), -(styles.borderTopWidth + styles.borderBottomWidth + paddingTop2 + paddingBottom2));
      };
      var calculateBackgroundPositioningArea = function(backgroundOrigin2, element2) {
        if (backgroundOrigin2 === 0) {
          return element2.bounds;
        }
        if (backgroundOrigin2 === 2) {
          return contentBox(element2);
        }
        return paddingBox(element2);
      };
      var calculateBackgroundPaintingArea = function(backgroundClip2, element2) {
        if (backgroundClip2 === 0) {
          return element2.bounds;
        }
        if (backgroundClip2 === 2) {
          return contentBox(element2);
        }
        return paddingBox(element2);
      };
      var calculateBackgroundRendering = function(container, index2, intrinsicSize) {
        var backgroundPositioningArea = calculateBackgroundPositioningArea(getBackgroundValueForIndex(container.styles.backgroundOrigin, index2), container);
        var backgroundPaintingArea = calculateBackgroundPaintingArea(getBackgroundValueForIndex(container.styles.backgroundClip, index2), container);
        var backgroundImageSize = calculateBackgroundSize(getBackgroundValueForIndex(container.styles.backgroundSize, index2), intrinsicSize, backgroundPositioningArea);
        var sizeWidth = backgroundImageSize[0], sizeHeight = backgroundImageSize[1];
        var position2 = getAbsoluteValueForTuple(getBackgroundValueForIndex(container.styles.backgroundPosition, index2), backgroundPositioningArea.width - sizeWidth, backgroundPositioningArea.height - sizeHeight);
        var path = calculateBackgroundRepeatPath(getBackgroundValueForIndex(container.styles.backgroundRepeat, index2), position2, backgroundImageSize, backgroundPositioningArea, backgroundPaintingArea);
        var offsetX = Math.round(backgroundPositioningArea.left + position2[0]);
        var offsetY = Math.round(backgroundPositioningArea.top + position2[1]);
        return [path, offsetX, offsetY, sizeWidth, sizeHeight];
      };
      var isAuto = function(token) {
        return isIdentToken(token) && token.value === BACKGROUND_SIZE.AUTO;
      };
      var hasIntrinsicValue = function(value2) {
        return typeof value2 === "number";
      };
      var calculateBackgroundSize = function(size4, _a4, bounds) {
        var intrinsicWidth = _a4[0], intrinsicHeight = _a4[1], intrinsicProportion = _a4[2];
        var first2 = size4[0], second = size4[1];
        if (!first2) {
          return [0, 0];
        }
        if (isLengthPercentage(first2) && second && isLengthPercentage(second)) {
          return [getAbsoluteValue(first2, bounds.width), getAbsoluteValue(second, bounds.height)];
        }
        var hasIntrinsicProportion = hasIntrinsicValue(intrinsicProportion);
        if (isIdentToken(first2) && (first2.value === BACKGROUND_SIZE.CONTAIN || first2.value === BACKGROUND_SIZE.COVER)) {
          if (hasIntrinsicValue(intrinsicProportion)) {
            var targetRatio = bounds.width / bounds.height;
            return targetRatio < intrinsicProportion !== (first2.value === BACKGROUND_SIZE.COVER) ? [bounds.width, bounds.width / intrinsicProportion] : [bounds.height * intrinsicProportion, bounds.height];
          }
          return [bounds.width, bounds.height];
        }
        var hasIntrinsicWidth = hasIntrinsicValue(intrinsicWidth);
        var hasIntrinsicHeight = hasIntrinsicValue(intrinsicHeight);
        var hasIntrinsicDimensions = hasIntrinsicWidth || hasIntrinsicHeight;
        if (isAuto(first2) && (!second || isAuto(second))) {
          if (hasIntrinsicWidth && hasIntrinsicHeight) {
            return [intrinsicWidth, intrinsicHeight];
          }
          if (!hasIntrinsicProportion && !hasIntrinsicDimensions) {
            return [bounds.width, bounds.height];
          }
          if (hasIntrinsicDimensions && hasIntrinsicProportion) {
            var width_1 = hasIntrinsicWidth ? intrinsicWidth : intrinsicHeight * intrinsicProportion;
            var height_1 = hasIntrinsicHeight ? intrinsicHeight : intrinsicWidth / intrinsicProportion;
            return [width_1, height_1];
          }
          var width_2 = hasIntrinsicWidth ? intrinsicWidth : bounds.width;
          var height_2 = hasIntrinsicHeight ? intrinsicHeight : bounds.height;
          return [width_2, height_2];
        }
        if (hasIntrinsicProportion) {
          var width_3 = 0;
          var height_3 = 0;
          if (isLengthPercentage(first2)) {
            width_3 = getAbsoluteValue(first2, bounds.width);
          } else if (isLengthPercentage(second)) {
            height_3 = getAbsoluteValue(second, bounds.height);
          }
          if (isAuto(first2)) {
            width_3 = height_3 * intrinsicProportion;
          } else if (!second || isAuto(second)) {
            height_3 = width_3 / intrinsicProportion;
          }
          return [width_3, height_3];
        }
        var width = null;
        var height = null;
        if (isLengthPercentage(first2)) {
          width = getAbsoluteValue(first2, bounds.width);
        } else if (second && isLengthPercentage(second)) {
          height = getAbsoluteValue(second, bounds.height);
        }
        if (width !== null && (!second || isAuto(second))) {
          height = hasIntrinsicWidth && hasIntrinsicHeight ? width / intrinsicWidth * intrinsicHeight : bounds.height;
        }
        if (height !== null && isAuto(first2)) {
          width = hasIntrinsicWidth && hasIntrinsicHeight ? height / intrinsicHeight * intrinsicWidth : bounds.width;
        }
        if (width !== null && height !== null) {
          return [width, height];
        }
        throw new Error("Unable to calculate background-size for element");
      };
      var getBackgroundValueForIndex = function(values2, index2) {
        var value2 = values2[index2];
        if (typeof value2 === "undefined") {
          return values2[0];
        }
        return value2;
      };
      var calculateBackgroundRepeatPath = function(repeat, _a4, _b, backgroundPositioningArea, backgroundPaintingArea) {
        var x3 = _a4[0], y3 = _a4[1];
        var width = _b[0], height = _b[1];
        switch (repeat) {
          case 2:
            return [
              new Vector(Math.round(backgroundPositioningArea.left), Math.round(backgroundPositioningArea.top + y3)),
              new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(backgroundPositioningArea.top + y3)),
              new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(height + backgroundPositioningArea.top + y3)),
              new Vector(Math.round(backgroundPositioningArea.left), Math.round(height + backgroundPositioningArea.top + y3))
            ];
          case 3:
            return [
              new Vector(Math.round(backgroundPositioningArea.left + x3), Math.round(backgroundPositioningArea.top)),
              new Vector(Math.round(backgroundPositioningArea.left + x3 + width), Math.round(backgroundPositioningArea.top)),
              new Vector(Math.round(backgroundPositioningArea.left + x3 + width), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top)),
              new Vector(Math.round(backgroundPositioningArea.left + x3), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top))
            ];
          case 1:
            return [
              new Vector(Math.round(backgroundPositioningArea.left + x3), Math.round(backgroundPositioningArea.top + y3)),
              new Vector(Math.round(backgroundPositioningArea.left + x3 + width), Math.round(backgroundPositioningArea.top + y3)),
              new Vector(Math.round(backgroundPositioningArea.left + x3 + width), Math.round(backgroundPositioningArea.top + y3 + height)),
              new Vector(Math.round(backgroundPositioningArea.left + x3), Math.round(backgroundPositioningArea.top + y3 + height))
            ];
          default:
            return [
              new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.top)),
              new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.top)),
              new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top)),
              new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top))
            ];
        }
      };
      var SMALL_IMAGE = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
      var SAMPLE_TEXT = "Hidden Text";
      var FontMetrics = (
        /** @class */
        function() {
          function FontMetrics2(document2) {
            this._data = {};
            this._document = document2;
          }
          FontMetrics2.prototype.parseMetrics = function(fontFamily2, fontSize2) {
            var container = this._document.createElement("div");
            var img = this._document.createElement("img");
            var span = this._document.createElement("span");
            var body3 = this._document.body;
            container.style.visibility = "hidden";
            container.style.fontFamily = fontFamily2;
            container.style.fontSize = fontSize2;
            container.style.margin = "0";
            container.style.padding = "0";
            container.style.whiteSpace = "nowrap";
            body3.appendChild(container);
            img.src = SMALL_IMAGE;
            img.width = 1;
            img.height = 1;
            img.style.margin = "0";
            img.style.padding = "0";
            img.style.verticalAlign = "baseline";
            span.style.fontFamily = fontFamily2;
            span.style.fontSize = fontSize2;
            span.style.margin = "0";
            span.style.padding = "0";
            span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
            container.appendChild(span);
            container.appendChild(img);
            var baseline = img.offsetTop - span.offsetTop + 2;
            container.removeChild(span);
            container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
            container.style.lineHeight = "normal";
            img.style.verticalAlign = "super";
            var middle = img.offsetTop - container.offsetTop + 2;
            body3.removeChild(container);
            return { baseline, middle };
          };
          FontMetrics2.prototype.getMetrics = function(fontFamily2, fontSize2) {
            var key2 = fontFamily2 + " " + fontSize2;
            if (typeof this._data[key2] === "undefined") {
              this._data[key2] = this.parseMetrics(fontFamily2, fontSize2);
            }
            return this._data[key2];
          };
          return FontMetrics2;
        }()
      );
      var Renderer3 = (
        /** @class */
        /* @__PURE__ */ function() {
          function Renderer4(context, options2) {
            this.context = context;
            this.options = options2;
          }
          return Renderer4;
        }()
      );
      var MASK_OFFSET = 1e4;
      var CanvasRenderer = (
        /** @class */
        function(_super) {
          __extends(CanvasRenderer2, _super);
          function CanvasRenderer2(context, options2) {
            var _this = _super.call(this, context, options2) || this;
            _this._activeEffects = [];
            _this.canvas = options2.canvas ? options2.canvas : document.createElement("canvas");
            _this.ctx = _this.canvas.getContext("2d");
            if (!options2.canvas) {
              _this.canvas.width = Math.floor(options2.width * options2.scale);
              _this.canvas.height = Math.floor(options2.height * options2.scale);
              _this.canvas.style.width = options2.width + "px";
              _this.canvas.style.height = options2.height + "px";
            }
            _this.fontMetrics = new FontMetrics(document);
            _this.ctx.scale(_this.options.scale, _this.options.scale);
            _this.ctx.translate(-options2.x, -options2.y);
            _this.ctx.textBaseline = "bottom";
            _this._activeEffects = [];
            _this.context.logger.debug("Canvas renderer initialized (" + options2.width + "x" + options2.height + ") with scale " + options2.scale);
            return _this;
          }
          CanvasRenderer2.prototype.applyEffects = function(effects) {
            var _this = this;
            while (this._activeEffects.length) {
              this.popEffect();
            }
            effects.forEach(function(effect2) {
              return _this.applyEffect(effect2);
            });
          };
          CanvasRenderer2.prototype.applyEffect = function(effect2) {
            this.ctx.save();
            if (isOpacityEffect(effect2)) {
              this.ctx.globalAlpha = effect2.opacity;
            }
            if (isTransformEffect(effect2)) {
              this.ctx.translate(effect2.offsetX, effect2.offsetY);
              this.ctx.transform(effect2.matrix[0], effect2.matrix[1], effect2.matrix[2], effect2.matrix[3], effect2.matrix[4], effect2.matrix[5]);
              this.ctx.translate(-effect2.offsetX, -effect2.offsetY);
            }
            if (isClipEffect(effect2)) {
              this.path(effect2.path);
              this.ctx.clip();
            }
            this._activeEffects.push(effect2);
          };
          CanvasRenderer2.prototype.popEffect = function() {
            this._activeEffects.pop();
            this.ctx.restore();
          };
          CanvasRenderer2.prototype.renderStack = function(stack) {
            return __awaiter(this, void 0, void 0, function() {
              var styles;
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    styles = stack.element.container.styles;
                    if (!styles.isVisible()) return [3, 2];
                    return [4, this.renderStackContent(stack)];
                  case 1:
                    _a4.sent();
                    _a4.label = 2;
                  case 2:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.renderNode = function(paint) {
            return __awaiter(this, void 0, void 0, function() {
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    if (contains4(
                      paint.container.flags,
                      16
                      /* DEBUG_RENDER */
                    )) {
                      debugger;
                    }
                    if (!paint.container.styles.isVisible()) return [3, 3];
                    return [4, this.renderNodeBackgroundAndBorders(paint)];
                  case 1:
                    _a4.sent();
                    return [4, this.renderNodeContent(paint)];
                  case 2:
                    _a4.sent();
                    _a4.label = 3;
                  case 3:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.renderTextWithLetterSpacing = function(text3, letterSpacing2, baseline) {
            var _this = this;
            if (letterSpacing2 === 0) {
              this.ctx.fillText(text3.text, text3.bounds.left, text3.bounds.top + baseline);
            } else {
              var letters = segmentGraphemes(text3.text);
              letters.reduce(function(left, letter) {
                _this.ctx.fillText(letter, left, text3.bounds.top + baseline);
                return left + _this.ctx.measureText(letter).width;
              }, text3.bounds.left);
            }
          };
          CanvasRenderer2.prototype.createFontStyle = function(styles) {
            var fontVariant2 = styles.fontVariant.filter(function(variant) {
              return variant === "normal" || variant === "small-caps";
            }).join("");
            var fontFamily2 = fixIOSSystemFonts(styles.fontFamily).join(", ");
            var fontSize2 = isDimensionToken(styles.fontSize) ? "" + styles.fontSize.number + styles.fontSize.unit : styles.fontSize.number + "px";
            return [
              [styles.fontStyle, fontVariant2, styles.fontWeight, fontSize2, fontFamily2].join(" "),
              fontFamily2,
              fontSize2
            ];
          };
          CanvasRenderer2.prototype.renderTextNode = function(text3, styles) {
            return __awaiter(this, void 0, void 0, function() {
              var _a4, font, fontFamily2, fontSize2, _b, baseline, middle, paintOrder2;
              var _this = this;
              return __generator(this, function(_c) {
                _a4 = this.createFontStyle(styles), font = _a4[0], fontFamily2 = _a4[1], fontSize2 = _a4[2];
                this.ctx.font = font;
                this.ctx.direction = styles.direction === 1 ? "rtl" : "ltr";
                this.ctx.textAlign = "left";
                this.ctx.textBaseline = "alphabetic";
                _b = this.fontMetrics.getMetrics(fontFamily2, fontSize2), baseline = _b.baseline, middle = _b.middle;
                paintOrder2 = styles.paintOrder;
                text3.textBounds.forEach(function(text4) {
                  paintOrder2.forEach(function(paintOrderLayer) {
                    switch (paintOrderLayer) {
                      case 0:
                        _this.ctx.fillStyle = asString(styles.color);
                        _this.renderTextWithLetterSpacing(text4, styles.letterSpacing, baseline);
                        var textShadows = styles.textShadow;
                        if (textShadows.length && text4.text.trim().length) {
                          textShadows.slice(0).reverse().forEach(function(textShadow2) {
                            _this.ctx.shadowColor = asString(textShadow2.color);
                            _this.ctx.shadowOffsetX = textShadow2.offsetX.number * _this.options.scale;
                            _this.ctx.shadowOffsetY = textShadow2.offsetY.number * _this.options.scale;
                            _this.ctx.shadowBlur = textShadow2.blur.number;
                            _this.renderTextWithLetterSpacing(text4, styles.letterSpacing, baseline);
                          });
                          _this.ctx.shadowColor = "";
                          _this.ctx.shadowOffsetX = 0;
                          _this.ctx.shadowOffsetY = 0;
                          _this.ctx.shadowBlur = 0;
                        }
                        if (styles.textDecorationLine.length) {
                          _this.ctx.fillStyle = asString(styles.textDecorationColor || styles.color);
                          styles.textDecorationLine.forEach(function(textDecorationLine2) {
                            switch (textDecorationLine2) {
                              case 1:
                                _this.ctx.fillRect(text4.bounds.left, Math.round(text4.bounds.top + baseline), text4.bounds.width, 1);
                                break;
                              case 2:
                                _this.ctx.fillRect(text4.bounds.left, Math.round(text4.bounds.top), text4.bounds.width, 1);
                                break;
                              case 3:
                                _this.ctx.fillRect(text4.bounds.left, Math.ceil(text4.bounds.top + middle), text4.bounds.width, 1);
                                break;
                            }
                          });
                        }
                        break;
                      case 1:
                        if (styles.webkitTextStrokeWidth && text4.text.trim().length) {
                          _this.ctx.strokeStyle = asString(styles.webkitTextStrokeColor);
                          _this.ctx.lineWidth = styles.webkitTextStrokeWidth;
                          _this.ctx.lineJoin = !!window.chrome ? "miter" : "round";
                          _this.ctx.strokeText(text4.text, text4.bounds.left, text4.bounds.top + baseline);
                        }
                        _this.ctx.strokeStyle = "";
                        _this.ctx.lineWidth = 0;
                        _this.ctx.lineJoin = "miter";
                        break;
                    }
                  });
                });
                return [
                  2
                  /*return*/
                ];
              });
            });
          };
          CanvasRenderer2.prototype.renderReplacedElement = function(container, curves, image3) {
            if (image3 && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
              var box = contentBox(container);
              var path = calculatePaddingBoxPath(curves);
              this.path(path);
              this.ctx.save();
              this.ctx.clip();
              this.ctx.drawImage(image3, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
              this.ctx.restore();
            }
          };
          CanvasRenderer2.prototype.renderNodeContent = function(paint) {
            return __awaiter(this, void 0, void 0, function() {
              var container, curves, styles, _i, _a4, child, image3, image3, iframeRenderer, canvas, size4, _b, fontFamily2, fontSize2, baseline, bounds, x3, textBounds, img, image3, url2, fontFamily2, bounds;
              return __generator(this, function(_c) {
                switch (_c.label) {
                  case 0:
                    this.applyEffects(paint.getEffects(
                      4
                      /* CONTENT */
                    ));
                    container = paint.container;
                    curves = paint.curves;
                    styles = container.styles;
                    _i = 0, _a4 = container.textNodes;
                    _c.label = 1;
                  case 1:
                    if (!(_i < _a4.length)) return [3, 4];
                    child = _a4[_i];
                    return [4, this.renderTextNode(child, styles)];
                  case 2:
                    _c.sent();
                    _c.label = 3;
                  case 3:
                    _i++;
                    return [3, 1];
                  case 4:
                    if (!(container instanceof ImageElementContainer)) return [3, 8];
                    _c.label = 5;
                  case 5:
                    _c.trys.push([5, 7, , 8]);
                    return [4, this.context.cache.match(container.src)];
                  case 6:
                    image3 = _c.sent();
                    this.renderReplacedElement(container, curves, image3);
                    return [3, 8];
                  case 7:
                    _c.sent();
                    this.context.logger.error("Error loading image " + container.src);
                    return [3, 8];
                  case 8:
                    if (container instanceof CanvasElementContainer) {
                      this.renderReplacedElement(container, curves, container.canvas);
                    }
                    if (!(container instanceof SVGElementContainer)) return [3, 12];
                    _c.label = 9;
                  case 9:
                    _c.trys.push([9, 11, , 12]);
                    return [4, this.context.cache.match(container.svg)];
                  case 10:
                    image3 = _c.sent();
                    this.renderReplacedElement(container, curves, image3);
                    return [3, 12];
                  case 11:
                    _c.sent();
                    this.context.logger.error("Error loading svg " + container.svg.substring(0, 255));
                    return [3, 12];
                  case 12:
                    if (!(container instanceof IFrameElementContainer && container.tree)) return [3, 14];
                    iframeRenderer = new CanvasRenderer2(this.context, {
                      scale: this.options.scale,
                      backgroundColor: container.backgroundColor,
                      x: 0,
                      y: 0,
                      width: container.width,
                      height: container.height
                    });
                    return [4, iframeRenderer.render(container.tree)];
                  case 13:
                    canvas = _c.sent();
                    if (container.width && container.height) {
                      this.ctx.drawImage(canvas, 0, 0, container.width, container.height, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height);
                    }
                    _c.label = 14;
                  case 14:
                    if (container instanceof InputElementContainer) {
                      size4 = Math.min(container.bounds.width, container.bounds.height);
                      if (container.type === CHECKBOX) {
                        if (container.checked) {
                          this.ctx.save();
                          this.path([
                            new Vector(container.bounds.left + size4 * 0.39363, container.bounds.top + size4 * 0.79),
                            new Vector(container.bounds.left + size4 * 0.16, container.bounds.top + size4 * 0.5549),
                            new Vector(container.bounds.left + size4 * 0.27347, container.bounds.top + size4 * 0.44071),
                            new Vector(container.bounds.left + size4 * 0.39694, container.bounds.top + size4 * 0.5649),
                            new Vector(container.bounds.left + size4 * 0.72983, container.bounds.top + size4 * 0.23),
                            new Vector(container.bounds.left + size4 * 0.84, container.bounds.top + size4 * 0.34085),
                            new Vector(container.bounds.left + size4 * 0.39363, container.bounds.top + size4 * 0.79)
                          ]);
                          this.ctx.fillStyle = asString(INPUT_COLOR);
                          this.ctx.fill();
                          this.ctx.restore();
                        }
                      } else if (container.type === RADIO) {
                        if (container.checked) {
                          this.ctx.save();
                          this.ctx.beginPath();
                          this.ctx.arc(container.bounds.left + size4 / 2, container.bounds.top + size4 / 2, size4 / 4, 0, Math.PI * 2, true);
                          this.ctx.fillStyle = asString(INPUT_COLOR);
                          this.ctx.fill();
                          this.ctx.restore();
                        }
                      }
                    }
                    if (isTextInputElement(container) && container.value.length) {
                      _b = this.createFontStyle(styles), fontFamily2 = _b[0], fontSize2 = _b[1];
                      baseline = this.fontMetrics.getMetrics(fontFamily2, fontSize2).baseline;
                      this.ctx.font = fontFamily2;
                      this.ctx.fillStyle = asString(styles.color);
                      this.ctx.textBaseline = "alphabetic";
                      this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
                      bounds = contentBox(container);
                      x3 = 0;
                      switch (container.styles.textAlign) {
                        case 1:
                          x3 += bounds.width / 2;
                          break;
                        case 2:
                          x3 += bounds.width;
                          break;
                      }
                      textBounds = bounds.add(x3, 0, 0, -bounds.height / 2 + 1);
                      this.ctx.save();
                      this.path([
                        new Vector(bounds.left, bounds.top),
                        new Vector(bounds.left + bounds.width, bounds.top),
                        new Vector(bounds.left + bounds.width, bounds.top + bounds.height),
                        new Vector(bounds.left, bounds.top + bounds.height)
                      ]);
                      this.ctx.clip();
                      this.renderTextWithLetterSpacing(new TextBounds(container.value, textBounds), styles.letterSpacing, baseline);
                      this.ctx.restore();
                      this.ctx.textBaseline = "alphabetic";
                      this.ctx.textAlign = "left";
                    }
                    if (!contains4(
                      container.styles.display,
                      2048
                      /* LIST_ITEM */
                    )) return [3, 20];
                    if (!(container.styles.listStyleImage !== null)) return [3, 19];
                    img = container.styles.listStyleImage;
                    if (!(img.type === 0)) return [3, 18];
                    image3 = void 0;
                    url2 = img.url;
                    _c.label = 15;
                  case 15:
                    _c.trys.push([15, 17, , 18]);
                    return [4, this.context.cache.match(url2)];
                  case 16:
                    image3 = _c.sent();
                    this.ctx.drawImage(image3, container.bounds.left - (image3.width + 10), container.bounds.top);
                    return [3, 18];
                  case 17:
                    _c.sent();
                    this.context.logger.error("Error loading list-style-image " + url2);
                    return [3, 18];
                  case 18:
                    return [3, 20];
                  case 19:
                    if (paint.listValue && container.styles.listStyleType !== -1) {
                      fontFamily2 = this.createFontStyle(styles)[0];
                      this.ctx.font = fontFamily2;
                      this.ctx.fillStyle = asString(styles.color);
                      this.ctx.textBaseline = "middle";
                      this.ctx.textAlign = "right";
                      bounds = new Bounds2(container.bounds.left, container.bounds.top + getAbsoluteValue(container.styles.paddingTop, container.bounds.width), container.bounds.width, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1);
                      this.renderTextWithLetterSpacing(new TextBounds(paint.listValue, bounds), styles.letterSpacing, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 2);
                      this.ctx.textBaseline = "bottom";
                      this.ctx.textAlign = "left";
                    }
                    _c.label = 20;
                  case 20:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.renderStackContent = function(stack) {
            return __awaiter(this, void 0, void 0, function() {
              var _i, _a4, child, _b, _c, child, _d, _e, child, _f, _g, child, _h, _j, child, _k, _l, child, _m, _o, child;
              return __generator(this, function(_p2) {
                switch (_p2.label) {
                  case 0:
                    if (contains4(
                      stack.element.container.flags,
                      16
                      /* DEBUG_RENDER */
                    )) {
                      debugger;
                    }
                    return [4, this.renderNodeBackgroundAndBorders(stack.element)];
                  case 1:
                    _p2.sent();
                    _i = 0, _a4 = stack.negativeZIndex;
                    _p2.label = 2;
                  case 2:
                    if (!(_i < _a4.length)) return [3, 5];
                    child = _a4[_i];
                    return [4, this.renderStack(child)];
                  case 3:
                    _p2.sent();
                    _p2.label = 4;
                  case 4:
                    _i++;
                    return [3, 2];
                  case 5:
                    return [4, this.renderNodeContent(stack.element)];
                  case 6:
                    _p2.sent();
                    _b = 0, _c = stack.nonInlineLevel;
                    _p2.label = 7;
                  case 7:
                    if (!(_b < _c.length)) return [3, 10];
                    child = _c[_b];
                    return [4, this.renderNode(child)];
                  case 8:
                    _p2.sent();
                    _p2.label = 9;
                  case 9:
                    _b++;
                    return [3, 7];
                  case 10:
                    _d = 0, _e = stack.nonPositionedFloats;
                    _p2.label = 11;
                  case 11:
                    if (!(_d < _e.length)) return [3, 14];
                    child = _e[_d];
                    return [4, this.renderStack(child)];
                  case 12:
                    _p2.sent();
                    _p2.label = 13;
                  case 13:
                    _d++;
                    return [3, 11];
                  case 14:
                    _f = 0, _g = stack.nonPositionedInlineLevel;
                    _p2.label = 15;
                  case 15:
                    if (!(_f < _g.length)) return [3, 18];
                    child = _g[_f];
                    return [4, this.renderStack(child)];
                  case 16:
                    _p2.sent();
                    _p2.label = 17;
                  case 17:
                    _f++;
                    return [3, 15];
                  case 18:
                    _h = 0, _j = stack.inlineLevel;
                    _p2.label = 19;
                  case 19:
                    if (!(_h < _j.length)) return [3, 22];
                    child = _j[_h];
                    return [4, this.renderNode(child)];
                  case 20:
                    _p2.sent();
                    _p2.label = 21;
                  case 21:
                    _h++;
                    return [3, 19];
                  case 22:
                    _k = 0, _l = stack.zeroOrAutoZIndexOrTransformedOrOpacity;
                    _p2.label = 23;
                  case 23:
                    if (!(_k < _l.length)) return [3, 26];
                    child = _l[_k];
                    return [4, this.renderStack(child)];
                  case 24:
                    _p2.sent();
                    _p2.label = 25;
                  case 25:
                    _k++;
                    return [3, 23];
                  case 26:
                    _m = 0, _o = stack.positiveZIndex;
                    _p2.label = 27;
                  case 27:
                    if (!(_m < _o.length)) return [3, 30];
                    child = _o[_m];
                    return [4, this.renderStack(child)];
                  case 28:
                    _p2.sent();
                    _p2.label = 29;
                  case 29:
                    _m++;
                    return [3, 27];
                  case 30:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.mask = function(paths) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, 0);
            this.ctx.lineTo(this.canvas.width, 0);
            this.ctx.lineTo(this.canvas.width, this.canvas.height);
            this.ctx.lineTo(0, this.canvas.height);
            this.ctx.lineTo(0, 0);
            this.formatPath(paths.slice(0).reverse());
            this.ctx.closePath();
          };
          CanvasRenderer2.prototype.path = function(paths) {
            this.ctx.beginPath();
            this.formatPath(paths);
            this.ctx.closePath();
          };
          CanvasRenderer2.prototype.formatPath = function(paths) {
            var _this = this;
            paths.forEach(function(point, index2) {
              var start = isBezierCurve(point) ? point.start : point;
              if (index2 === 0) {
                _this.ctx.moveTo(start.x, start.y);
              } else {
                _this.ctx.lineTo(start.x, start.y);
              }
              if (isBezierCurve(point)) {
                _this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
              }
            });
          };
          CanvasRenderer2.prototype.renderRepeat = function(path, pattern2, offsetX, offsetY) {
            this.path(path);
            this.ctx.fillStyle = pattern2;
            this.ctx.translate(offsetX, offsetY);
            this.ctx.fill();
            this.ctx.translate(-offsetX, -offsetY);
          };
          CanvasRenderer2.prototype.resizeImage = function(image3, width, height) {
            var _a4;
            if (image3.width === width && image3.height === height) {
              return image3;
            }
            var ownerDocument2 = (_a4 = this.canvas.ownerDocument) !== null && _a4 !== void 0 ? _a4 : document;
            var canvas = ownerDocument2.createElement("canvas");
            canvas.width = Math.max(1, width);
            canvas.height = Math.max(1, height);
            var ctx = canvas.getContext("2d");
            ctx.drawImage(image3, 0, 0, image3.width, image3.height, 0, 0, width, height);
            return canvas;
          };
          CanvasRenderer2.prototype.renderBackgroundImage = function(container) {
            return __awaiter(this, void 0, void 0, function() {
              var index2, _loop_1, this_1, _i, _a4, backgroundImage2;
              return __generator(this, function(_b) {
                switch (_b.label) {
                  case 0:
                    index2 = container.styles.backgroundImage.length - 1;
                    _loop_1 = function(backgroundImage3) {
                      var image3, url2, _c, path, x3, y3, width, height, pattern2, _d, path, x3, y3, width, height, _e, lineLength, x0, x1, y0, y1, canvas, ctx, gradient_1, pattern2, _f, path, left, top_1, width, height, position2, x3, y3, _g, rx, ry, radialGradient_1, midX, midY, f4, invF;
                      return __generator(this, function(_h) {
                        switch (_h.label) {
                          case 0:
                            if (!(backgroundImage3.type === 0)) return [3, 5];
                            image3 = void 0;
                            url2 = backgroundImage3.url;
                            _h.label = 1;
                          case 1:
                            _h.trys.push([1, 3, , 4]);
                            return [4, this_1.context.cache.match(url2)];
                          case 2:
                            image3 = _h.sent();
                            return [3, 4];
                          case 3:
                            _h.sent();
                            this_1.context.logger.error("Error loading background-image " + url2);
                            return [3, 4];
                          case 4:
                            if (image3) {
                              _c = calculateBackgroundRendering(container, index2, [
                                image3.width,
                                image3.height,
                                image3.width / image3.height
                              ]), path = _c[0], x3 = _c[1], y3 = _c[2], width = _c[3], height = _c[4];
                              pattern2 = this_1.ctx.createPattern(this_1.resizeImage(image3, width, height), "repeat");
                              this_1.renderRepeat(path, pattern2, x3, y3);
                            }
                            return [3, 6];
                          case 5:
                            if (isLinearGradient(backgroundImage3)) {
                              _d = calculateBackgroundRendering(container, index2, [null, null, null]), path = _d[0], x3 = _d[1], y3 = _d[2], width = _d[3], height = _d[4];
                              _e = calculateGradientDirection(backgroundImage3.angle, width, height), lineLength = _e[0], x0 = _e[1], x1 = _e[2], y0 = _e[3], y1 = _e[4];
                              canvas = document.createElement("canvas");
                              canvas.width = width;
                              canvas.height = height;
                              ctx = canvas.getContext("2d");
                              gradient_1 = ctx.createLinearGradient(x0, y0, x1, y1);
                              processColorStops(backgroundImage3.stops, lineLength).forEach(function(colorStop) {
                                return gradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
                              });
                              ctx.fillStyle = gradient_1;
                              ctx.fillRect(0, 0, width, height);
                              if (width > 0 && height > 0) {
                                pattern2 = this_1.ctx.createPattern(canvas, "repeat");
                                this_1.renderRepeat(path, pattern2, x3, y3);
                              }
                            } else if (isRadialGradient(backgroundImage3)) {
                              _f = calculateBackgroundRendering(container, index2, [
                                null,
                                null,
                                null
                              ]), path = _f[0], left = _f[1], top_1 = _f[2], width = _f[3], height = _f[4];
                              position2 = backgroundImage3.position.length === 0 ? [FIFTY_PERCENT] : backgroundImage3.position;
                              x3 = getAbsoluteValue(position2[0], width);
                              y3 = getAbsoluteValue(position2[position2.length - 1], height);
                              _g = calculateRadius(backgroundImage3, x3, y3, width, height), rx = _g[0], ry = _g[1];
                              if (rx > 0 && ry > 0) {
                                radialGradient_1 = this_1.ctx.createRadialGradient(left + x3, top_1 + y3, 0, left + x3, top_1 + y3, rx);
                                processColorStops(backgroundImage3.stops, rx * 2).forEach(function(colorStop) {
                                  return radialGradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
                                });
                                this_1.path(path);
                                this_1.ctx.fillStyle = radialGradient_1;
                                if (rx !== ry) {
                                  midX = container.bounds.left + 0.5 * container.bounds.width;
                                  midY = container.bounds.top + 0.5 * container.bounds.height;
                                  f4 = ry / rx;
                                  invF = 1 / f4;
                                  this_1.ctx.save();
                                  this_1.ctx.translate(midX, midY);
                                  this_1.ctx.transform(1, 0, 0, f4, 0, 0);
                                  this_1.ctx.translate(-midX, -midY);
                                  this_1.ctx.fillRect(left, invF * (top_1 - midY) + midY, width, height * invF);
                                  this_1.ctx.restore();
                                } else {
                                  this_1.ctx.fill();
                                }
                              }
                            }
                            _h.label = 6;
                          case 6:
                            index2--;
                            return [
                              2
                              /*return*/
                            ];
                        }
                      });
                    };
                    this_1 = this;
                    _i = 0, _a4 = container.styles.backgroundImage.slice(0).reverse();
                    _b.label = 1;
                  case 1:
                    if (!(_i < _a4.length)) return [3, 4];
                    backgroundImage2 = _a4[_i];
                    return [5, _loop_1(backgroundImage2)];
                  case 2:
                    _b.sent();
                    _b.label = 3;
                  case 3:
                    _i++;
                    return [3, 1];
                  case 4:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.renderSolidBorder = function(color2, side, curvePoints) {
            return __awaiter(this, void 0, void 0, function() {
              return __generator(this, function(_a4) {
                this.path(parsePathForBorder(curvePoints, side));
                this.ctx.fillStyle = asString(color2);
                this.ctx.fill();
                return [
                  2
                  /*return*/
                ];
              });
            });
          };
          CanvasRenderer2.prototype.renderDoubleBorder = function(color2, width, side, curvePoints) {
            return __awaiter(this, void 0, void 0, function() {
              var outerPaths, innerPaths;
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    if (!(width < 3)) return [3, 2];
                    return [4, this.renderSolidBorder(color2, side, curvePoints)];
                  case 1:
                    _a4.sent();
                    return [
                      2
                      /*return*/
                    ];
                  case 2:
                    outerPaths = parsePathForBorderDoubleOuter(curvePoints, side);
                    this.path(outerPaths);
                    this.ctx.fillStyle = asString(color2);
                    this.ctx.fill();
                    innerPaths = parsePathForBorderDoubleInner(curvePoints, side);
                    this.path(innerPaths);
                    this.ctx.fill();
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.renderNodeBackgroundAndBorders = function(paint) {
            return __awaiter(this, void 0, void 0, function() {
              var styles, hasBackground, borders, backgroundPaintingArea, side, _i, borders_1, border;
              var _this = this;
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    this.applyEffects(paint.getEffects(
                      2
                      /* BACKGROUND_BORDERS */
                    ));
                    styles = paint.container.styles;
                    hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
                    borders = [
                      { style: styles.borderTopStyle, color: styles.borderTopColor, width: styles.borderTopWidth },
                      { style: styles.borderRightStyle, color: styles.borderRightColor, width: styles.borderRightWidth },
                      { style: styles.borderBottomStyle, color: styles.borderBottomColor, width: styles.borderBottomWidth },
                      { style: styles.borderLeftStyle, color: styles.borderLeftColor, width: styles.borderLeftWidth }
                    ];
                    backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(getBackgroundValueForIndex(styles.backgroundClip, 0), paint.curves);
                    if (!(hasBackground || styles.boxShadow.length)) return [3, 2];
                    this.ctx.save();
                    this.path(backgroundPaintingArea);
                    this.ctx.clip();
                    if (!isTransparent(styles.backgroundColor)) {
                      this.ctx.fillStyle = asString(styles.backgroundColor);
                      this.ctx.fill();
                    }
                    return [4, this.renderBackgroundImage(paint.container)];
                  case 1:
                    _a4.sent();
                    this.ctx.restore();
                    styles.boxShadow.slice(0).reverse().forEach(function(shadow) {
                      _this.ctx.save();
                      var borderBoxArea = calculateBorderBoxPath(paint.curves);
                      var maskOffset = shadow.inset ? 0 : MASK_OFFSET;
                      var shadowPaintingArea = transformPath(borderBoxArea, -maskOffset + (shadow.inset ? 1 : -1) * shadow.spread.number, (shadow.inset ? 1 : -1) * shadow.spread.number, shadow.spread.number * (shadow.inset ? -2 : 2), shadow.spread.number * (shadow.inset ? -2 : 2));
                      if (shadow.inset) {
                        _this.path(borderBoxArea);
                        _this.ctx.clip();
                        _this.mask(shadowPaintingArea);
                      } else {
                        _this.mask(borderBoxArea);
                        _this.ctx.clip();
                        _this.path(shadowPaintingArea);
                      }
                      _this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset;
                      _this.ctx.shadowOffsetY = shadow.offsetY.number;
                      _this.ctx.shadowColor = asString(shadow.color);
                      _this.ctx.shadowBlur = shadow.blur.number;
                      _this.ctx.fillStyle = shadow.inset ? asString(shadow.color) : "rgba(0,0,0,1)";
                      _this.ctx.fill();
                      _this.ctx.restore();
                    });
                    _a4.label = 2;
                  case 2:
                    side = 0;
                    _i = 0, borders_1 = borders;
                    _a4.label = 3;
                  case 3:
                    if (!(_i < borders_1.length)) return [3, 13];
                    border = borders_1[_i];
                    if (!(border.style !== 0 && !isTransparent(border.color) && border.width > 0)) return [3, 11];
                    if (!(border.style === 2)) return [3, 5];
                    return [4, this.renderDashedDottedBorder(
                      border.color,
                      border.width,
                      side,
                      paint.curves,
                      2
                      /* DASHED */
                    )];
                  case 4:
                    _a4.sent();
                    return [3, 11];
                  case 5:
                    if (!(border.style === 3)) return [3, 7];
                    return [4, this.renderDashedDottedBorder(
                      border.color,
                      border.width,
                      side,
                      paint.curves,
                      3
                      /* DOTTED */
                    )];
                  case 6:
                    _a4.sent();
                    return [3, 11];
                  case 7:
                    if (!(border.style === 4)) return [3, 9];
                    return [4, this.renderDoubleBorder(border.color, border.width, side, paint.curves)];
                  case 8:
                    _a4.sent();
                    return [3, 11];
                  case 9:
                    return [4, this.renderSolidBorder(border.color, side, paint.curves)];
                  case 10:
                    _a4.sent();
                    _a4.label = 11;
                  case 11:
                    side++;
                    _a4.label = 12;
                  case 12:
                    _i++;
                    return [3, 3];
                  case 13:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          CanvasRenderer2.prototype.renderDashedDottedBorder = function(color2, width, side, curvePoints, style3) {
            return __awaiter(this, void 0, void 0, function() {
              var strokePaths, boxPaths, startX, startY, endX, endY, length, dashLength, spaceLength, useLineDash, multiplier, numberOfDashes, minSpace, maxSpace, path1, path2, path1, path2;
              return __generator(this, function(_a4) {
                this.ctx.save();
                strokePaths = parsePathForBorderStroke(curvePoints, side);
                boxPaths = parsePathForBorder(curvePoints, side);
                if (style3 === 2) {
                  this.path(boxPaths);
                  this.ctx.clip();
                }
                if (isBezierCurve(boxPaths[0])) {
                  startX = boxPaths[0].start.x;
                  startY = boxPaths[0].start.y;
                } else {
                  startX = boxPaths[0].x;
                  startY = boxPaths[0].y;
                }
                if (isBezierCurve(boxPaths[1])) {
                  endX = boxPaths[1].end.x;
                  endY = boxPaths[1].end.y;
                } else {
                  endX = boxPaths[1].x;
                  endY = boxPaths[1].y;
                }
                if (side === 0 || side === 2) {
                  length = Math.abs(startX - endX);
                } else {
                  length = Math.abs(startY - endY);
                }
                this.ctx.beginPath();
                if (style3 === 3) {
                  this.formatPath(strokePaths);
                } else {
                  this.formatPath(boxPaths.slice(0, 2));
                }
                dashLength = width < 3 ? width * 3 : width * 2;
                spaceLength = width < 3 ? width * 2 : width;
                if (style3 === 3) {
                  dashLength = width;
                  spaceLength = width;
                }
                useLineDash = true;
                if (length <= dashLength * 2) {
                  useLineDash = false;
                } else if (length <= dashLength * 2 + spaceLength) {
                  multiplier = length / (2 * dashLength + spaceLength);
                  dashLength *= multiplier;
                  spaceLength *= multiplier;
                } else {
                  numberOfDashes = Math.floor((length + spaceLength) / (dashLength + spaceLength));
                  minSpace = (length - numberOfDashes * dashLength) / (numberOfDashes - 1);
                  maxSpace = (length - (numberOfDashes + 1) * dashLength) / numberOfDashes;
                  spaceLength = maxSpace <= 0 || Math.abs(spaceLength - minSpace) < Math.abs(spaceLength - maxSpace) ? minSpace : maxSpace;
                }
                if (useLineDash) {
                  if (style3 === 3) {
                    this.ctx.setLineDash([0, dashLength + spaceLength]);
                  } else {
                    this.ctx.setLineDash([dashLength, spaceLength]);
                  }
                }
                if (style3 === 3) {
                  this.ctx.lineCap = "round";
                  this.ctx.lineWidth = width;
                } else {
                  this.ctx.lineWidth = width * 2 + 1.1;
                }
                this.ctx.strokeStyle = asString(color2);
                this.ctx.stroke();
                this.ctx.setLineDash([]);
                if (style3 === 2) {
                  if (isBezierCurve(boxPaths[0])) {
                    path1 = boxPaths[3];
                    path2 = boxPaths[0];
                    this.ctx.beginPath();
                    this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
                    this.ctx.stroke();
                  }
                  if (isBezierCurve(boxPaths[1])) {
                    path1 = boxPaths[1];
                    path2 = boxPaths[2];
                    this.ctx.beginPath();
                    this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
                    this.ctx.stroke();
                  }
                }
                this.ctx.restore();
                return [
                  2
                  /*return*/
                ];
              });
            });
          };
          CanvasRenderer2.prototype.render = function(element2) {
            return __awaiter(this, void 0, void 0, function() {
              var stack;
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    if (this.options.backgroundColor) {
                      this.ctx.fillStyle = asString(this.options.backgroundColor);
                      this.ctx.fillRect(this.options.x, this.options.y, this.options.width, this.options.height);
                    }
                    stack = parseStackingContexts(element2);
                    return [4, this.renderStack(stack)];
                  case 1:
                    _a4.sent();
                    this.applyEffects([]);
                    return [2, this.canvas];
                }
              });
            });
          };
          return CanvasRenderer2;
        }(Renderer3)
      );
      var isTextInputElement = function(container) {
        if (container instanceof TextareaElementContainer) {
          return true;
        } else if (container instanceof SelectElementContainer) {
          return true;
        } else if (container instanceof InputElementContainer && container.type !== RADIO && container.type !== CHECKBOX) {
          return true;
        }
        return false;
      };
      var calculateBackgroundCurvedPaintingArea = function(clip2, curves) {
        switch (clip2) {
          case 0:
            return calculateBorderBoxPath(curves);
          case 2:
            return calculateContentBoxPath(curves);
          case 1:
          default:
            return calculatePaddingBoxPath(curves);
        }
      };
      var canvasTextAlign = function(textAlign2) {
        switch (textAlign2) {
          case 1:
            return "center";
          case 2:
            return "right";
          case 0:
          default:
            return "left";
        }
      };
      var iOSBrokenFonts = ["-apple-system", "system-ui"];
      var fixIOSSystemFonts = function(fontFamilies) {
        return /iPhone OS 15_(0|1)/.test(window.navigator.userAgent) ? fontFamilies.filter(function(fontFamily2) {
          return iOSBrokenFonts.indexOf(fontFamily2) === -1;
        }) : fontFamilies;
      };
      var ForeignObjectRenderer = (
        /** @class */
        function(_super) {
          __extends(ForeignObjectRenderer2, _super);
          function ForeignObjectRenderer2(context, options2) {
            var _this = _super.call(this, context, options2) || this;
            _this.canvas = options2.canvas ? options2.canvas : document.createElement("canvas");
            _this.ctx = _this.canvas.getContext("2d");
            _this.options = options2;
            _this.canvas.width = Math.floor(options2.width * options2.scale);
            _this.canvas.height = Math.floor(options2.height * options2.scale);
            _this.canvas.style.width = options2.width + "px";
            _this.canvas.style.height = options2.height + "px";
            _this.ctx.scale(_this.options.scale, _this.options.scale);
            _this.ctx.translate(-options2.x, -options2.y);
            _this.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized (" + options2.width + "x" + options2.height + " at " + options2.x + "," + options2.y + ") with scale " + options2.scale);
            return _this;
          }
          ForeignObjectRenderer2.prototype.render = function(element2) {
            return __awaiter(this, void 0, void 0, function() {
              var svg4, img;
              return __generator(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    svg4 = createForeignObjectSVG(this.options.width * this.options.scale, this.options.height * this.options.scale, this.options.scale, this.options.scale, element2);
                    return [4, loadSerializedSVG(svg4)];
                  case 1:
                    img = _a4.sent();
                    if (this.options.backgroundColor) {
                      this.ctx.fillStyle = asString(this.options.backgroundColor);
                      this.ctx.fillRect(0, 0, this.options.width * this.options.scale, this.options.height * this.options.scale);
                    }
                    this.ctx.drawImage(img, -this.options.x * this.options.scale, -this.options.y * this.options.scale);
                    return [2, this.canvas];
                }
              });
            });
          };
          return ForeignObjectRenderer2;
        }(Renderer3)
      );
      var loadSerializedSVG = function(svg4) {
        return new Promise(function(resolve2, reject2) {
          var img = new Image();
          img.onload = function() {
            resolve2(img);
          };
          img.onerror = reject2;
          img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg4));
        });
      };
      var Logger = (
        /** @class */
        function() {
          function Logger2(_a4) {
            var id = _a4.id, enabled = _a4.enabled;
            this.id = id;
            this.enabled = enabled;
            this.start = Date.now();
          }
          Logger2.prototype.debug = function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            if (this.enabled) {
              if (typeof window !== "undefined" && window.console && typeof console.debug === "function") {
                console.debug.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
              } else {
                this.info.apply(this, args);
              }
            }
          };
          Logger2.prototype.getTime = function() {
            return Date.now() - this.start;
          };
          Logger2.prototype.info = function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            if (this.enabled) {
              if (typeof window !== "undefined" && window.console && typeof console.info === "function") {
                console.info.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
              }
            }
          };
          Logger2.prototype.warn = function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            if (this.enabled) {
              if (typeof window !== "undefined" && window.console && typeof console.warn === "function") {
                console.warn.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
              } else {
                this.info.apply(this, args);
              }
            }
          };
          Logger2.prototype.error = function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            if (this.enabled) {
              if (typeof window !== "undefined" && window.console && typeof console.error === "function") {
                console.error.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
              } else {
                this.info.apply(this, args);
              }
            }
          };
          Logger2.instances = {};
          return Logger2;
        }()
      );
      var Context = (
        /** @class */
        function() {
          function Context2(options2, windowBounds) {
            var _a4;
            this.windowBounds = windowBounds;
            this.instanceName = "#" + Context2.instanceCount++;
            this.logger = new Logger({ id: this.instanceName, enabled: options2.logging });
            this.cache = (_a4 = options2.cache) !== null && _a4 !== void 0 ? _a4 : new Cache(this, options2);
          }
          Context2.instanceCount = 1;
          return Context2;
        }()
      );
      var html2canvas2 = function(element2, options2) {
        if (options2 === void 0) {
          options2 = {};
        }
        return renderElement(element2, options2);
      };
      if (typeof window !== "undefined") {
        CacheStorage.setContext(window);
      }
      var renderElement = function(element2, opts) {
        return __awaiter(void 0, void 0, void 0, function() {
          var ownerDocument2, defaultView, resourceOptions, contextOptions, windowOptions, windowBounds, context, foreignObjectRendering, cloneOptions, documentCloner, clonedElement, container, _a4, width, height, left, top2, backgroundColor2, renderOptions, canvas, renderer2, root3, renderer2;
          var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p2, _q, _r, _s, _t;
          return __generator(this, function(_u) {
            switch (_u.label) {
              case 0:
                if (!element2 || typeof element2 !== "object") {
                  return [2, Promise.reject("Invalid element provided as first argument")];
                }
                ownerDocument2 = element2.ownerDocument;
                if (!ownerDocument2) {
                  throw new Error("Element is not attached to a Document");
                }
                defaultView = ownerDocument2.defaultView;
                if (!defaultView) {
                  throw new Error("Document is not attached to a Window");
                }
                resourceOptions = {
                  allowTaint: (_b = opts.allowTaint) !== null && _b !== void 0 ? _b : false,
                  imageTimeout: (_c = opts.imageTimeout) !== null && _c !== void 0 ? _c : 15e3,
                  proxy: opts.proxy,
                  useCORS: (_d = opts.useCORS) !== null && _d !== void 0 ? _d : false
                };
                contextOptions = __assign({ logging: (_e = opts.logging) !== null && _e !== void 0 ? _e : true, cache: opts.cache }, resourceOptions);
                windowOptions = {
                  windowWidth: (_f = opts.windowWidth) !== null && _f !== void 0 ? _f : defaultView.innerWidth,
                  windowHeight: (_g = opts.windowHeight) !== null && _g !== void 0 ? _g : defaultView.innerHeight,
                  scrollX: (_h = opts.scrollX) !== null && _h !== void 0 ? _h : defaultView.pageXOffset,
                  scrollY: (_j = opts.scrollY) !== null && _j !== void 0 ? _j : defaultView.pageYOffset
                };
                windowBounds = new Bounds2(windowOptions.scrollX, windowOptions.scrollY, windowOptions.windowWidth, windowOptions.windowHeight);
                context = new Context(contextOptions, windowBounds);
                foreignObjectRendering = (_k = opts.foreignObjectRendering) !== null && _k !== void 0 ? _k : false;
                cloneOptions = {
                  allowTaint: (_l = opts.allowTaint) !== null && _l !== void 0 ? _l : false,
                  onclone: opts.onclone,
                  ignoreElements: opts.ignoreElements,
                  inlineImages: foreignObjectRendering,
                  copyStyles: foreignObjectRendering
                };
                context.logger.debug("Starting document clone with size " + windowBounds.width + "x" + windowBounds.height + " scrolled to " + -windowBounds.left + "," + -windowBounds.top);
                documentCloner = new DocumentCloner(context, element2, cloneOptions);
                clonedElement = documentCloner.clonedReferenceElement;
                if (!clonedElement) {
                  return [2, Promise.reject("Unable to find element in cloned iframe")];
                }
                return [4, documentCloner.toIFrame(ownerDocument2, windowBounds)];
              case 1:
                container = _u.sent();
                _a4 = isBodyElement(clonedElement) || isHTMLElement(clonedElement) ? parseDocumentSize(clonedElement.ownerDocument) : parseBounds(context, clonedElement), width = _a4.width, height = _a4.height, left = _a4.left, top2 = _a4.top;
                backgroundColor2 = parseBackgroundColor(context, clonedElement, opts.backgroundColor);
                renderOptions = {
                  canvas: opts.canvas,
                  backgroundColor: backgroundColor2,
                  scale: (_o = (_m = opts.scale) !== null && _m !== void 0 ? _m : defaultView.devicePixelRatio) !== null && _o !== void 0 ? _o : 1,
                  x: ((_p2 = opts.x) !== null && _p2 !== void 0 ? _p2 : 0) + left,
                  y: ((_q = opts.y) !== null && _q !== void 0 ? _q : 0) + top2,
                  width: (_r = opts.width) !== null && _r !== void 0 ? _r : Math.ceil(width),
                  height: (_s = opts.height) !== null && _s !== void 0 ? _s : Math.ceil(height)
                };
                if (!foreignObjectRendering) return [3, 3];
                context.logger.debug("Document cloned, using foreign object rendering");
                renderer2 = new ForeignObjectRenderer(context, renderOptions);
                return [4, renderer2.render(clonedElement)];
              case 2:
                canvas = _u.sent();
                return [3, 5];
              case 3:
                context.logger.debug("Document cloned, element located at " + left + "," + top2 + " with size " + width + "x" + height + " using computed rendering");
                context.logger.debug("Starting DOM parsing");
                root3 = parseTree(context, clonedElement);
                if (backgroundColor2 === root3.styles.backgroundColor) {
                  root3.styles.backgroundColor = COLORS.TRANSPARENT;
                }
                context.logger.debug("Starting renderer for element at " + renderOptions.x + "," + renderOptions.y + " with size " + renderOptions.width + "x" + renderOptions.height);
                renderer2 = new CanvasRenderer(context, renderOptions);
                return [4, renderer2.render(root3)];
              case 4:
                canvas = _u.sent();
                _u.label = 5;
              case 5:
                if ((_t = opts.removeContainer) !== null && _t !== void 0 ? _t : true) {
                  if (!DocumentCloner.destroy(container)) {
                    context.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore");
                  }
                }
                context.logger.debug("Finished rendering");
                return [2, canvas];
            }
          });
        });
      };
      var parseBackgroundColor = function(context, element2, backgroundColorOverride) {
        var ownerDocument2 = element2.ownerDocument;
        var documentBackgroundColor = ownerDocument2.documentElement ? parseColor2(context, getComputedStyle(ownerDocument2.documentElement).backgroundColor) : COLORS.TRANSPARENT;
        var bodyBackgroundColor = ownerDocument2.body ? parseColor2(context, getComputedStyle(ownerDocument2.body).backgroundColor) : COLORS.TRANSPARENT;
        var defaultBackgroundColor = typeof backgroundColorOverride === "string" ? parseColor2(context, backgroundColorOverride) : backgroundColorOverride === null ? COLORS.TRANSPARENT : 4294967295;
        return element2 === ownerDocument2.documentElement ? isTransparent(documentBackgroundColor) ? isTransparent(bodyBackgroundColor) ? defaultBackgroundColor : bodyBackgroundColor : documentBackgroundColor : defaultBackgroundColor;
      };
      return html2canvas2;
    });
  }
});

// node_modules/qrious/dist/qrious.js
var require_qrious = __commonJS({
  "node_modules/qrious/dist/qrious.js"(exports, module) {
    (function(global5, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global5.QRious = factory();
    })(exports, function() {
      "use strict";
      var Constructor = (
        /* istanbul ignore next */
        function() {
        }
      );
      var hasOwnProperty5 = Object.prototype.hasOwnProperty;
      var slice3 = Array.prototype.slice;
      function createObject(prototype, properties) {
        var result2;
        if (typeof Object.create === "function") {
          result2 = Object.create(prototype);
        } else {
          Constructor.prototype = prototype;
          result2 = new Constructor();
          Constructor.prototype = null;
        }
        if (properties) {
          extendObject(true, result2, properties);
        }
        return result2;
      }
      function extend(name2, constructor, prototype, statics) {
        var superConstructor = this;
        if (typeof name2 !== "string") {
          statics = prototype;
          prototype = constructor;
          constructor = name2;
          name2 = null;
        }
        if (typeof constructor !== "function") {
          statics = prototype;
          prototype = constructor;
          constructor = function() {
            return superConstructor.apply(this, arguments);
          };
        }
        extendObject(false, constructor, superConstructor, statics);
        constructor.prototype = createObject(superConstructor.prototype, prototype);
        constructor.prototype.constructor = constructor;
        constructor.class_ = name2 || superConstructor.class_;
        constructor.super_ = superConstructor;
        return constructor;
      }
      function extendObject(own4, target, sources) {
        sources = slice3.call(arguments, 2);
        var property2;
        var source;
        for (var i3 = 0, length = sources.length; i3 < length; i3++) {
          source = sources[i3];
          for (property2 in source) {
            if (!own4 || hasOwnProperty5.call(source, property2)) {
              target[property2] = source[property2];
            }
          }
        }
      }
      var extend_1 = extend;
      function Nevis() {
      }
      Nevis.class_ = "Nevis";
      Nevis.super_ = Object;
      Nevis.extend = extend_1;
      var nevis = Nevis;
      var lite = nevis;
      var Renderer3 = lite.extend(function(qrious, element2, enabled) {
        this.qrious = qrious;
        this.element = element2;
        this.element.qrious = qrious;
        this.enabled = Boolean(enabled);
      }, {
        /**
         * Draws the specified QR code <code>frame</code> on the underlying element.
         *
         * Implementations of {@link Renderer} <b>must</b> override this method with their own specific logic.
         *
         * @param {Frame} frame - the {@link Frame} to be drawn
         * @return {void}
         * @protected
         * @abstract
         * @memberof Renderer#
         */
        draw: function(frame) {
        },
        /**
         * Returns the element onto which this {@link Renderer} is rendering the QR code.
         *
         * If this method is called while this {@link Renderer} is disabled, it will be immediately enabled and rendered
         * before the element is returned.
         *
         * @return {*} The element.
         * @public
         * @memberof Renderer#
         */
        getElement: function() {
          if (!this.enabled) {
            this.enabled = true;
            this.render();
          }
          return this.element;
        },
        /**
         * Calculates the size (in pixel units) to represent an individual module within the QR code based on the
         * <code>frame</code> provided.
         *
         * Any configured padding will be excluded from the returned size.
         *
         * The returned value will be at least one, even in cases where the size of the QR code does not fit its contents.
         * This is done so that the inevitable clipping is handled more gracefully since this way at least something is
         * displayed instead of just a blank space filled by the background color.
         *
         * @param {Frame} frame - the {@link Frame} from which the module size is to be derived
         * @return {number} The pixel size for each module in the QR code which will be no less than one.
         * @protected
         * @memberof Renderer#
         */
        getModuleSize: function(frame) {
          var qrious = this.qrious;
          var padding = qrious.padding || 0;
          var pixels = Math.floor((qrious.size - padding * 2) / frame.width);
          return Math.max(1, pixels);
        },
        /**
         * Calculates the offset/padding (in pixel units) to be inserted before the QR code based on the <code>frame</code>
         * provided.
         *
         * The returned value will be zero if there is no available offset or if the size of the QR code does not fit its
         * contents. It will never be a negative value. This is done so that the inevitable clipping appears more naturally
         * and it is not clipped from all directions.
         *
         * @param {Frame} frame - the {@link Frame} from which the offset is to be derived
         * @return {number} The pixel offset for the QR code which will be no less than zero.
         * @protected
         * @memberof Renderer#
         */
        getOffset: function(frame) {
          var qrious = this.qrious;
          var padding = qrious.padding;
          if (padding != null) {
            return padding;
          }
          var moduleSize = this.getModuleSize(frame);
          var offset = Math.floor((qrious.size - moduleSize * frame.width) / 2);
          return Math.max(0, offset);
        },
        /**
         * Renders a QR code on the underlying element based on the <code>frame</code> provided.
         *
         * @param {Frame} frame - the {@link Frame} to be rendered
         * @return {void}
         * @public
         * @memberof Renderer#
         */
        render: function(frame) {
          if (this.enabled) {
            this.resize();
            this.reset();
            this.draw(frame);
          }
        },
        /**
         * Resets the underlying element, effectively clearing any previously rendered QR code.
         *
         * Implementations of {@link Renderer} <b>must</b> override this method with their own specific logic.
         *
         * @return {void}
         * @protected
         * @abstract
         * @memberof Renderer#
         */
        reset: function() {
        },
        /**
         * Ensures that the size of the underlying element matches that defined on the associated {@link QRious} instance.
         *
         * Implementations of {@link Renderer} <b>must</b> override this method with their own specific logic.
         *
         * @return {void}
         * @protected
         * @abstract
         * @memberof Renderer#
         */
        resize: function() {
        }
      });
      var Renderer_1 = Renderer3;
      var CanvasRenderer = Renderer_1.extend({
        /**
         * @override
         */
        draw: function(frame) {
          var i3, j;
          var qrious = this.qrious;
          var moduleSize = this.getModuleSize(frame);
          var offset = this.getOffset(frame);
          var context = this.element.getContext("2d");
          context.fillStyle = qrious.foreground;
          context.globalAlpha = qrious.foregroundAlpha;
          for (i3 = 0; i3 < frame.width; i3++) {
            for (j = 0; j < frame.width; j++) {
              if (frame.buffer[j * frame.width + i3]) {
                context.fillRect(moduleSize * i3 + offset, moduleSize * j + offset, moduleSize, moduleSize);
              }
            }
          }
        },
        /**
         * @override
         */
        reset: function() {
          var qrious = this.qrious;
          var context = this.element.getContext("2d");
          var size4 = qrious.size;
          context.lineWidth = 1;
          context.clearRect(0, 0, size4, size4);
          context.fillStyle = qrious.background;
          context.globalAlpha = qrious.backgroundAlpha;
          context.fillRect(0, 0, size4, size4);
        },
        /**
         * @override
         */
        resize: function() {
          var element2 = this.element;
          element2.width = element2.height = this.qrious.size;
        }
      });
      var CanvasRenderer_1 = CanvasRenderer;
      var Alignment = lite.extend(null, {
        /**
         * The alignment pattern block.
         *
         * @public
         * @static
         * @type {number[]}
         * @memberof Alignment
         */
        BLOCK: [
          0,
          11,
          15,
          19,
          23,
          27,
          31,
          16,
          18,
          20,
          22,
          24,
          26,
          28,
          20,
          22,
          24,
          24,
          26,
          28,
          28,
          22,
          24,
          24,
          26,
          26,
          28,
          28,
          24,
          24,
          26,
          26,
          26,
          28,
          28,
          24,
          26,
          26,
          26,
          28,
          28
        ]
      });
      var Alignment_1 = Alignment;
      var ErrorCorrection = lite.extend(null, {
        /**
         * The error correction blocks.
         *
         * There are four elements per version. The first two indicate the number of blocks, then the data width, and finally
         * the ECC width.
         *
         * @public
         * @static
         * @type {number[]}
         * @memberof ErrorCorrection
         */
        BLOCKS: [
          1,
          0,
          19,
          7,
          1,
          0,
          16,
          10,
          1,
          0,
          13,
          13,
          1,
          0,
          9,
          17,
          1,
          0,
          34,
          10,
          1,
          0,
          28,
          16,
          1,
          0,
          22,
          22,
          1,
          0,
          16,
          28,
          1,
          0,
          55,
          15,
          1,
          0,
          44,
          26,
          2,
          0,
          17,
          18,
          2,
          0,
          13,
          22,
          1,
          0,
          80,
          20,
          2,
          0,
          32,
          18,
          2,
          0,
          24,
          26,
          4,
          0,
          9,
          16,
          1,
          0,
          108,
          26,
          2,
          0,
          43,
          24,
          2,
          2,
          15,
          18,
          2,
          2,
          11,
          22,
          2,
          0,
          68,
          18,
          4,
          0,
          27,
          16,
          4,
          0,
          19,
          24,
          4,
          0,
          15,
          28,
          2,
          0,
          78,
          20,
          4,
          0,
          31,
          18,
          2,
          4,
          14,
          18,
          4,
          1,
          13,
          26,
          2,
          0,
          97,
          24,
          2,
          2,
          38,
          22,
          4,
          2,
          18,
          22,
          4,
          2,
          14,
          26,
          2,
          0,
          116,
          30,
          3,
          2,
          36,
          22,
          4,
          4,
          16,
          20,
          4,
          4,
          12,
          24,
          2,
          2,
          68,
          18,
          4,
          1,
          43,
          26,
          6,
          2,
          19,
          24,
          6,
          2,
          15,
          28,
          4,
          0,
          81,
          20,
          1,
          4,
          50,
          30,
          4,
          4,
          22,
          28,
          3,
          8,
          12,
          24,
          2,
          2,
          92,
          24,
          6,
          2,
          36,
          22,
          4,
          6,
          20,
          26,
          7,
          4,
          14,
          28,
          4,
          0,
          107,
          26,
          8,
          1,
          37,
          22,
          8,
          4,
          20,
          24,
          12,
          4,
          11,
          22,
          3,
          1,
          115,
          30,
          4,
          5,
          40,
          24,
          11,
          5,
          16,
          20,
          11,
          5,
          12,
          24,
          5,
          1,
          87,
          22,
          5,
          5,
          41,
          24,
          5,
          7,
          24,
          30,
          11,
          7,
          12,
          24,
          5,
          1,
          98,
          24,
          7,
          3,
          45,
          28,
          15,
          2,
          19,
          24,
          3,
          13,
          15,
          30,
          1,
          5,
          107,
          28,
          10,
          1,
          46,
          28,
          1,
          15,
          22,
          28,
          2,
          17,
          14,
          28,
          5,
          1,
          120,
          30,
          9,
          4,
          43,
          26,
          17,
          1,
          22,
          28,
          2,
          19,
          14,
          28,
          3,
          4,
          113,
          28,
          3,
          11,
          44,
          26,
          17,
          4,
          21,
          26,
          9,
          16,
          13,
          26,
          3,
          5,
          107,
          28,
          3,
          13,
          41,
          26,
          15,
          5,
          24,
          30,
          15,
          10,
          15,
          28,
          4,
          4,
          116,
          28,
          17,
          0,
          42,
          26,
          17,
          6,
          22,
          28,
          19,
          6,
          16,
          30,
          2,
          7,
          111,
          28,
          17,
          0,
          46,
          28,
          7,
          16,
          24,
          30,
          34,
          0,
          13,
          24,
          4,
          5,
          121,
          30,
          4,
          14,
          47,
          28,
          11,
          14,
          24,
          30,
          16,
          14,
          15,
          30,
          6,
          4,
          117,
          30,
          6,
          14,
          45,
          28,
          11,
          16,
          24,
          30,
          30,
          2,
          16,
          30,
          8,
          4,
          106,
          26,
          8,
          13,
          47,
          28,
          7,
          22,
          24,
          30,
          22,
          13,
          15,
          30,
          10,
          2,
          114,
          28,
          19,
          4,
          46,
          28,
          28,
          6,
          22,
          28,
          33,
          4,
          16,
          30,
          8,
          4,
          122,
          30,
          22,
          3,
          45,
          28,
          8,
          26,
          23,
          30,
          12,
          28,
          15,
          30,
          3,
          10,
          117,
          30,
          3,
          23,
          45,
          28,
          4,
          31,
          24,
          30,
          11,
          31,
          15,
          30,
          7,
          7,
          116,
          30,
          21,
          7,
          45,
          28,
          1,
          37,
          23,
          30,
          19,
          26,
          15,
          30,
          5,
          10,
          115,
          30,
          19,
          10,
          47,
          28,
          15,
          25,
          24,
          30,
          23,
          25,
          15,
          30,
          13,
          3,
          115,
          30,
          2,
          29,
          46,
          28,
          42,
          1,
          24,
          30,
          23,
          28,
          15,
          30,
          17,
          0,
          115,
          30,
          10,
          23,
          46,
          28,
          10,
          35,
          24,
          30,
          19,
          35,
          15,
          30,
          17,
          1,
          115,
          30,
          14,
          21,
          46,
          28,
          29,
          19,
          24,
          30,
          11,
          46,
          15,
          30,
          13,
          6,
          115,
          30,
          14,
          23,
          46,
          28,
          44,
          7,
          24,
          30,
          59,
          1,
          16,
          30,
          12,
          7,
          121,
          30,
          12,
          26,
          47,
          28,
          39,
          14,
          24,
          30,
          22,
          41,
          15,
          30,
          6,
          14,
          121,
          30,
          6,
          34,
          47,
          28,
          46,
          10,
          24,
          30,
          2,
          64,
          15,
          30,
          17,
          4,
          122,
          30,
          29,
          14,
          46,
          28,
          49,
          10,
          24,
          30,
          24,
          46,
          15,
          30,
          4,
          18,
          122,
          30,
          13,
          32,
          46,
          28,
          48,
          14,
          24,
          30,
          42,
          32,
          15,
          30,
          20,
          4,
          117,
          30,
          40,
          7,
          47,
          28,
          43,
          22,
          24,
          30,
          10,
          67,
          15,
          30,
          19,
          6,
          118,
          30,
          18,
          31,
          47,
          28,
          34,
          34,
          24,
          30,
          20,
          61,
          15,
          30
        ],
        /**
         * The final format bits with mask (level << 3 | mask).
         *
         * @public
         * @static
         * @type {number[]}
         * @memberof ErrorCorrection
         */
        FINAL_FORMAT: [
          // L
          30660,
          29427,
          32170,
          30877,
          26159,
          25368,
          27713,
          26998,
          // M
          21522,
          20773,
          24188,
          23371,
          17913,
          16590,
          20375,
          19104,
          // Q
          13663,
          12392,
          16177,
          14854,
          9396,
          8579,
          11994,
          11245,
          // H
          5769,
          5054,
          7399,
          6608,
          1890,
          597,
          3340,
          2107
        ],
        /**
         * A map of human-readable ECC levels.
         *
         * @public
         * @static
         * @type {Object.<string, number>}
         * @memberof ErrorCorrection
         */
        LEVELS: {
          L: 1,
          M: 2,
          Q: 3,
          H: 4
        }
      });
      var ErrorCorrection_1 = ErrorCorrection;
      var Galois = lite.extend(null, {
        /**
         * The Galois field exponent table.
         *
         * @public
         * @static
         * @type {number[]}
         * @memberof Galois
         */
        EXPONENT: [
          1,
          2,
          4,
          8,
          16,
          32,
          64,
          128,
          29,
          58,
          116,
          232,
          205,
          135,
          19,
          38,
          76,
          152,
          45,
          90,
          180,
          117,
          234,
          201,
          143,
          3,
          6,
          12,
          24,
          48,
          96,
          192,
          157,
          39,
          78,
          156,
          37,
          74,
          148,
          53,
          106,
          212,
          181,
          119,
          238,
          193,
          159,
          35,
          70,
          140,
          5,
          10,
          20,
          40,
          80,
          160,
          93,
          186,
          105,
          210,
          185,
          111,
          222,
          161,
          95,
          190,
          97,
          194,
          153,
          47,
          94,
          188,
          101,
          202,
          137,
          15,
          30,
          60,
          120,
          240,
          253,
          231,
          211,
          187,
          107,
          214,
          177,
          127,
          254,
          225,
          223,
          163,
          91,
          182,
          113,
          226,
          217,
          175,
          67,
          134,
          17,
          34,
          68,
          136,
          13,
          26,
          52,
          104,
          208,
          189,
          103,
          206,
          129,
          31,
          62,
          124,
          248,
          237,
          199,
          147,
          59,
          118,
          236,
          197,
          151,
          51,
          102,
          204,
          133,
          23,
          46,
          92,
          184,
          109,
          218,
          169,
          79,
          158,
          33,
          66,
          132,
          21,
          42,
          84,
          168,
          77,
          154,
          41,
          82,
          164,
          85,
          170,
          73,
          146,
          57,
          114,
          228,
          213,
          183,
          115,
          230,
          209,
          191,
          99,
          198,
          145,
          63,
          126,
          252,
          229,
          215,
          179,
          123,
          246,
          241,
          255,
          227,
          219,
          171,
          75,
          150,
          49,
          98,
          196,
          149,
          55,
          110,
          220,
          165,
          87,
          174,
          65,
          130,
          25,
          50,
          100,
          200,
          141,
          7,
          14,
          28,
          56,
          112,
          224,
          221,
          167,
          83,
          166,
          81,
          162,
          89,
          178,
          121,
          242,
          249,
          239,
          195,
          155,
          43,
          86,
          172,
          69,
          138,
          9,
          18,
          36,
          72,
          144,
          61,
          122,
          244,
          245,
          247,
          243,
          251,
          235,
          203,
          139,
          11,
          22,
          44,
          88,
          176,
          125,
          250,
          233,
          207,
          131,
          27,
          54,
          108,
          216,
          173,
          71,
          142,
          0
        ],
        /**
         * The Galois field log table.
         *
         * @public
         * @static
         * @type {number[]}
         * @memberof Galois
         */
        LOG: [
          255,
          0,
          1,
          25,
          2,
          50,
          26,
          198,
          3,
          223,
          51,
          238,
          27,
          104,
          199,
          75,
          4,
          100,
          224,
          14,
          52,
          141,
          239,
          129,
          28,
          193,
          105,
          248,
          200,
          8,
          76,
          113,
          5,
          138,
          101,
          47,
          225,
          36,
          15,
          33,
          53,
          147,
          142,
          218,
          240,
          18,
          130,
          69,
          29,
          181,
          194,
          125,
          106,
          39,
          249,
          185,
          201,
          154,
          9,
          120,
          77,
          228,
          114,
          166,
          6,
          191,
          139,
          98,
          102,
          221,
          48,
          253,
          226,
          152,
          37,
          179,
          16,
          145,
          34,
          136,
          54,
          208,
          148,
          206,
          143,
          150,
          219,
          189,
          241,
          210,
          19,
          92,
          131,
          56,
          70,
          64,
          30,
          66,
          182,
          163,
          195,
          72,
          126,
          110,
          107,
          58,
          40,
          84,
          250,
          133,
          186,
          61,
          202,
          94,
          155,
          159,
          10,
          21,
          121,
          43,
          78,
          212,
          229,
          172,
          115,
          243,
          167,
          87,
          7,
          112,
          192,
          247,
          140,
          128,
          99,
          13,
          103,
          74,
          222,
          237,
          49,
          197,
          254,
          24,
          227,
          165,
          153,
          119,
          38,
          184,
          180,
          124,
          17,
          68,
          146,
          217,
          35,
          32,
          137,
          46,
          55,
          63,
          209,
          91,
          149,
          188,
          207,
          205,
          144,
          135,
          151,
          178,
          220,
          252,
          190,
          97,
          242,
          86,
          211,
          171,
          20,
          42,
          93,
          158,
          132,
          60,
          57,
          83,
          71,
          109,
          65,
          162,
          31,
          45,
          67,
          216,
          183,
          123,
          164,
          118,
          196,
          23,
          73,
          236,
          127,
          12,
          111,
          246,
          108,
          161,
          59,
          82,
          41,
          157,
          85,
          170,
          251,
          96,
          134,
          177,
          187,
          204,
          62,
          90,
          203,
          89,
          95,
          176,
          156,
          169,
          160,
          81,
          11,
          245,
          22,
          235,
          122,
          117,
          44,
          215,
          79,
          174,
          213,
          233,
          230,
          231,
          173,
          232,
          116,
          214,
          244,
          234,
          168,
          80,
          88,
          175
        ]
      });
      var Galois_1 = Galois;
      var Version = lite.extend(null, {
        /**
         * The version pattern block.
         *
         * @public
         * @static
         * @type {number[]}
         * @memberof Version
         */
        BLOCK: [
          3220,
          1468,
          2713,
          1235,
          3062,
          1890,
          2119,
          1549,
          2344,
          2936,
          1117,
          2583,
          1330,
          2470,
          1667,
          2249,
          2028,
          3780,
          481,
          4011,
          142,
          3098,
          831,
          3445,
          592,
          2517,
          1776,
          2234,
          1951,
          2827,
          1070,
          2660,
          1345,
          3177
        ]
      });
      var Version_1 = Version;
      var Frame = lite.extend(function(options2) {
        var dataBlock, eccBlock, index3, neccBlock1, neccBlock2;
        var valueLength = options2.value.length;
        this._badness = [];
        this._level = ErrorCorrection_1.LEVELS[options2.level];
        this._polynomial = [];
        this._value = options2.value;
        this._version = 0;
        this._stringBuffer = [];
        while (this._version < 40) {
          this._version++;
          index3 = (this._level - 1) * 4 + (this._version - 1) * 16;
          neccBlock1 = ErrorCorrection_1.BLOCKS[index3++];
          neccBlock2 = ErrorCorrection_1.BLOCKS[index3++];
          dataBlock = ErrorCorrection_1.BLOCKS[index3++];
          eccBlock = ErrorCorrection_1.BLOCKS[index3];
          index3 = dataBlock * (neccBlock1 + neccBlock2) + neccBlock2 - 3 + (this._version <= 9);
          if (valueLength <= index3) {
            break;
          }
        }
        this._dataBlock = dataBlock;
        this._eccBlock = eccBlock;
        this._neccBlock1 = neccBlock1;
        this._neccBlock2 = neccBlock2;
        var width = this.width = 17 + 4 * this._version;
        this.buffer = Frame._createArray(width * width);
        this._ecc = Frame._createArray(dataBlock + (dataBlock + eccBlock) * (neccBlock1 + neccBlock2) + neccBlock2);
        this._mask = Frame._createArray((width * (width + 1) + 1) / 2);
        this._insertFinders();
        this._insertAlignments();
        this.buffer[8 + width * (width - 8)] = 1;
        this._insertTimingGap();
        this._reverseMask();
        this._insertTimingRowAndColumn();
        this._insertVersion();
        this._syncMask();
        this._convertBitStream(valueLength);
        this._calculatePolynomial();
        this._appendEccToData();
        this._interleaveBlocks();
        this._pack();
        this._finish();
      }, {
        _addAlignment: function(x3, y3) {
          var i3;
          var buffer = this.buffer;
          var width = this.width;
          buffer[x3 + width * y3] = 1;
          for (i3 = -2; i3 < 2; i3++) {
            buffer[x3 + i3 + width * (y3 - 2)] = 1;
            buffer[x3 - 2 + width * (y3 + i3 + 1)] = 1;
            buffer[x3 + 2 + width * (y3 + i3)] = 1;
            buffer[x3 + i3 + 1 + width * (y3 + 2)] = 1;
          }
          for (i3 = 0; i3 < 2; i3++) {
            this._setMask(x3 - 1, y3 + i3);
            this._setMask(x3 + 1, y3 - i3);
            this._setMask(x3 - i3, y3 - 1);
            this._setMask(x3 + i3, y3 + 1);
          }
        },
        _appendData: function(data2, dataLength, ecc, eccLength) {
          var bit, i3, j;
          var polynomial = this._polynomial;
          var stringBuffer = this._stringBuffer;
          for (i3 = 0; i3 < eccLength; i3++) {
            stringBuffer[ecc + i3] = 0;
          }
          for (i3 = 0; i3 < dataLength; i3++) {
            bit = Galois_1.LOG[stringBuffer[data2 + i3] ^ stringBuffer[ecc]];
            if (bit !== 255) {
              for (j = 1; j < eccLength; j++) {
                stringBuffer[ecc + j - 1] = stringBuffer[ecc + j] ^ Galois_1.EXPONENT[Frame._modN(bit + polynomial[eccLength - j])];
              }
            } else {
              for (j = ecc; j < ecc + eccLength; j++) {
                stringBuffer[j] = stringBuffer[j + 1];
              }
            }
            stringBuffer[ecc + eccLength - 1] = bit === 255 ? 0 : Galois_1.EXPONENT[Frame._modN(bit + polynomial[0])];
          }
        },
        _appendEccToData: function() {
          var i3;
          var data2 = 0;
          var dataBlock = this._dataBlock;
          var ecc = this._calculateMaxLength();
          var eccBlock = this._eccBlock;
          for (i3 = 0; i3 < this._neccBlock1; i3++) {
            this._appendData(data2, dataBlock, ecc, eccBlock);
            data2 += dataBlock;
            ecc += eccBlock;
          }
          for (i3 = 0; i3 < this._neccBlock2; i3++) {
            this._appendData(data2, dataBlock + 1, ecc, eccBlock);
            data2 += dataBlock + 1;
            ecc += eccBlock;
          }
        },
        _applyMask: function(mask) {
          var r3x, r3y, x3, y3;
          var buffer = this.buffer;
          var width = this.width;
          switch (mask) {
            case 0:
              for (y3 = 0; y3 < width; y3++) {
                for (x3 = 0; x3 < width; x3++) {
                  if (!(x3 + y3 & 1) && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 1:
              for (y3 = 0; y3 < width; y3++) {
                for (x3 = 0; x3 < width; x3++) {
                  if (!(y3 & 1) && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 2:
              for (y3 = 0; y3 < width; y3++) {
                for (r3x = 0, x3 = 0; x3 < width; x3++, r3x++) {
                  if (r3x === 3) {
                    r3x = 0;
                  }
                  if (!r3x && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 3:
              for (r3y = 0, y3 = 0; y3 < width; y3++, r3y++) {
                if (r3y === 3) {
                  r3y = 0;
                }
                for (r3x = r3y, x3 = 0; x3 < width; x3++, r3x++) {
                  if (r3x === 3) {
                    r3x = 0;
                  }
                  if (!r3x && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 4:
              for (y3 = 0; y3 < width; y3++) {
                for (r3x = 0, r3y = y3 >> 1 & 1, x3 = 0; x3 < width; x3++, r3x++) {
                  if (r3x === 3) {
                    r3x = 0;
                    r3y = !r3y;
                  }
                  if (!r3y && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 5:
              for (r3y = 0, y3 = 0; y3 < width; y3++, r3y++) {
                if (r3y === 3) {
                  r3y = 0;
                }
                for (r3x = 0, x3 = 0; x3 < width; x3++, r3x++) {
                  if (r3x === 3) {
                    r3x = 0;
                  }
                  if (!((x3 & y3 & 1) + !(!r3x | !r3y)) && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 6:
              for (r3y = 0, y3 = 0; y3 < width; y3++, r3y++) {
                if (r3y === 3) {
                  r3y = 0;
                }
                for (r3x = 0, x3 = 0; x3 < width; x3++, r3x++) {
                  if (r3x === 3) {
                    r3x = 0;
                  }
                  if (!((x3 & y3 & 1) + (r3x && r3x === r3y) & 1) && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
            case 7:
              for (r3y = 0, y3 = 0; y3 < width; y3++, r3y++) {
                if (r3y === 3) {
                  r3y = 0;
                }
                for (r3x = 0, x3 = 0; x3 < width; x3++, r3x++) {
                  if (r3x === 3) {
                    r3x = 0;
                  }
                  if (!((r3x && r3x === r3y) + (x3 + y3 & 1) & 1) && !this._isMasked(x3, y3)) {
                    buffer[x3 + y3 * width] ^= 1;
                  }
                }
              }
              break;
          }
        },
        _calculateMaxLength: function() {
          return this._dataBlock * (this._neccBlock1 + this._neccBlock2) + this._neccBlock2;
        },
        _calculatePolynomial: function() {
          var i3, j;
          var eccBlock = this._eccBlock;
          var polynomial = this._polynomial;
          polynomial[0] = 1;
          for (i3 = 0; i3 < eccBlock; i3++) {
            polynomial[i3 + 1] = 1;
            for (j = i3; j > 0; j--) {
              polynomial[j] = polynomial[j] ? polynomial[j - 1] ^ Galois_1.EXPONENT[Frame._modN(Galois_1.LOG[polynomial[j]] + i3)] : polynomial[j - 1];
            }
            polynomial[0] = Galois_1.EXPONENT[Frame._modN(Galois_1.LOG[polynomial[0]] + i3)];
          }
          for (i3 = 0; i3 <= eccBlock; i3++) {
            polynomial[i3] = Galois_1.LOG[polynomial[i3]];
          }
        },
        _checkBadness: function() {
          var b3, b1, h3, x3, y3;
          var bad = 0;
          var badness = this._badness;
          var buffer = this.buffer;
          var width = this.width;
          for (y3 = 0; y3 < width - 1; y3++) {
            for (x3 = 0; x3 < width - 1; x3++) {
              if (buffer[x3 + width * y3] && buffer[x3 + 1 + width * y3] && buffer[x3 + width * (y3 + 1)] && buffer[x3 + 1 + width * (y3 + 1)] || // All background colour.
              !(buffer[x3 + width * y3] || buffer[x3 + 1 + width * y3] || buffer[x3 + width * (y3 + 1)] || buffer[x3 + 1 + width * (y3 + 1)])) {
                bad += Frame.N2;
              }
            }
          }
          var bw = 0;
          for (y3 = 0; y3 < width; y3++) {
            h3 = 0;
            badness[0] = 0;
            for (b3 = 0, x3 = 0; x3 < width; x3++) {
              b1 = buffer[x3 + width * y3];
              if (b3 === b1) {
                badness[h3]++;
              } else {
                badness[++h3] = 1;
              }
              b3 = b1;
              bw += b3 ? 1 : -1;
            }
            bad += this._getBadness(h3);
          }
          if (bw < 0) {
            bw = -bw;
          }
          var count = 0;
          var big = bw;
          big += big << 2;
          big <<= 1;
          while (big > width * width) {
            big -= width * width;
            count++;
          }
          bad += count * Frame.N4;
          for (x3 = 0; x3 < width; x3++) {
            h3 = 0;
            badness[0] = 0;
            for (b3 = 0, y3 = 0; y3 < width; y3++) {
              b1 = buffer[x3 + width * y3];
              if (b3 === b1) {
                badness[h3]++;
              } else {
                badness[++h3] = 1;
              }
              b3 = b1;
            }
            bad += this._getBadness(h3);
          }
          return bad;
        },
        _convertBitStream: function(length) {
          var bit, i3;
          var ecc = this._ecc;
          var version = this._version;
          for (i3 = 0; i3 < length; i3++) {
            ecc[i3] = this._value.charCodeAt(i3);
          }
          var stringBuffer = this._stringBuffer = ecc.slice();
          var maxLength = this._calculateMaxLength();
          if (length >= maxLength - 2) {
            length = maxLength - 2;
            if (version > 9) {
              length--;
            }
          }
          var index3 = length;
          if (version > 9) {
            stringBuffer[index3 + 2] = 0;
            stringBuffer[index3 + 3] = 0;
            while (index3--) {
              bit = stringBuffer[index3];
              stringBuffer[index3 + 3] |= 255 & bit << 4;
              stringBuffer[index3 + 2] = bit >> 4;
            }
            stringBuffer[2] |= 255 & length << 4;
            stringBuffer[1] = length >> 4;
            stringBuffer[0] = 64 | length >> 12;
          } else {
            stringBuffer[index3 + 1] = 0;
            stringBuffer[index3 + 2] = 0;
            while (index3--) {
              bit = stringBuffer[index3];
              stringBuffer[index3 + 2] |= 255 & bit << 4;
              stringBuffer[index3 + 1] = bit >> 4;
            }
            stringBuffer[1] |= 255 & length << 4;
            stringBuffer[0] = 64 | length >> 4;
          }
          index3 = length + 3 - (version < 10);
          while (index3 < maxLength) {
            stringBuffer[index3++] = 236;
            stringBuffer[index3++] = 17;
          }
        },
        _getBadness: function(length) {
          var i3;
          var badRuns = 0;
          var badness = this._badness;
          for (i3 = 0; i3 <= length; i3++) {
            if (badness[i3] >= 5) {
              badRuns += Frame.N1 + badness[i3] - 5;
            }
          }
          for (i3 = 3; i3 < length - 1; i3 += 2) {
            if (badness[i3 - 2] === badness[i3 + 2] && badness[i3 + 2] === badness[i3 - 1] && badness[i3 - 1] === badness[i3 + 1] && badness[i3 - 1] * 3 === badness[i3] && // Background around the foreground pattern? Not part of the specs.
            (badness[i3 - 3] === 0 || i3 + 3 > length || badness[i3 - 3] * 3 >= badness[i3] * 4 || badness[i3 + 3] * 3 >= badness[i3] * 4)) {
              badRuns += Frame.N3;
            }
          }
          return badRuns;
        },
        _finish: function() {
          this._stringBuffer = this.buffer.slice();
          var currentMask, i3;
          var bit = 0;
          var mask = 3e4;
          for (i3 = 0; i3 < 8; i3++) {
            this._applyMask(i3);
            currentMask = this._checkBadness();
            if (currentMask < mask) {
              mask = currentMask;
              bit = i3;
            }
            if (bit === 7) {
              break;
            }
            this.buffer = this._stringBuffer.slice();
          }
          if (bit !== i3) {
            this._applyMask(bit);
          }
          mask = ErrorCorrection_1.FINAL_FORMAT[bit + (this._level - 1 << 3)];
          var buffer = this.buffer;
          var width = this.width;
          for (i3 = 0; i3 < 8; i3++, mask >>= 1) {
            if (mask & 1) {
              buffer[width - 1 - i3 + width * 8] = 1;
              if (i3 < 6) {
                buffer[8 + width * i3] = 1;
              } else {
                buffer[8 + width * (i3 + 1)] = 1;
              }
            }
          }
          for (i3 = 0; i3 < 7; i3++, mask >>= 1) {
            if (mask & 1) {
              buffer[8 + width * (width - 7 + i3)] = 1;
              if (i3) {
                buffer[6 - i3 + width * 8] = 1;
              } else {
                buffer[7 + width * 8] = 1;
              }
            }
          }
        },
        _interleaveBlocks: function() {
          var i3, j;
          var dataBlock = this._dataBlock;
          var ecc = this._ecc;
          var eccBlock = this._eccBlock;
          var k2 = 0;
          var maxLength = this._calculateMaxLength();
          var neccBlock1 = this._neccBlock1;
          var neccBlock2 = this._neccBlock2;
          var stringBuffer = this._stringBuffer;
          for (i3 = 0; i3 < dataBlock; i3++) {
            for (j = 0; j < neccBlock1; j++) {
              ecc[k2++] = stringBuffer[i3 + j * dataBlock];
            }
            for (j = 0; j < neccBlock2; j++) {
              ecc[k2++] = stringBuffer[neccBlock1 * dataBlock + i3 + j * (dataBlock + 1)];
            }
          }
          for (j = 0; j < neccBlock2; j++) {
            ecc[k2++] = stringBuffer[neccBlock1 * dataBlock + i3 + j * (dataBlock + 1)];
          }
          for (i3 = 0; i3 < eccBlock; i3++) {
            for (j = 0; j < neccBlock1 + neccBlock2; j++) {
              ecc[k2++] = stringBuffer[maxLength + i3 + j * eccBlock];
            }
          }
          this._stringBuffer = ecc;
        },
        _insertAlignments: function() {
          var i3, x3, y3;
          var version = this._version;
          var width = this.width;
          if (version > 1) {
            i3 = Alignment_1.BLOCK[version];
            y3 = width - 7;
            for (; ; ) {
              x3 = width - 7;
              while (x3 > i3 - 3) {
                this._addAlignment(x3, y3);
                if (x3 < i3) {
                  break;
                }
                x3 -= i3;
              }
              if (y3 <= i3 + 9) {
                break;
              }
              y3 -= i3;
              this._addAlignment(6, y3);
              this._addAlignment(y3, 6);
            }
          }
        },
        _insertFinders: function() {
          var i3, j, x3, y3;
          var buffer = this.buffer;
          var width = this.width;
          for (i3 = 0; i3 < 3; i3++) {
            j = 0;
            y3 = 0;
            if (i3 === 1) {
              j = width - 7;
            }
            if (i3 === 2) {
              y3 = width - 7;
            }
            buffer[y3 + 3 + width * (j + 3)] = 1;
            for (x3 = 0; x3 < 6; x3++) {
              buffer[y3 + x3 + width * j] = 1;
              buffer[y3 + width * (j + x3 + 1)] = 1;
              buffer[y3 + 6 + width * (j + x3)] = 1;
              buffer[y3 + x3 + 1 + width * (j + 6)] = 1;
            }
            for (x3 = 1; x3 < 5; x3++) {
              this._setMask(y3 + x3, j + 1);
              this._setMask(y3 + 1, j + x3 + 1);
              this._setMask(y3 + 5, j + x3);
              this._setMask(y3 + x3 + 1, j + 5);
            }
            for (x3 = 2; x3 < 4; x3++) {
              buffer[y3 + x3 + width * (j + 2)] = 1;
              buffer[y3 + 2 + width * (j + x3 + 1)] = 1;
              buffer[y3 + 4 + width * (j + x3)] = 1;
              buffer[y3 + x3 + 1 + width * (j + 4)] = 1;
            }
          }
        },
        _insertTimingGap: function() {
          var x3, y3;
          var width = this.width;
          for (y3 = 0; y3 < 7; y3++) {
            this._setMask(7, y3);
            this._setMask(width - 8, y3);
            this._setMask(7, y3 + width - 7);
          }
          for (x3 = 0; x3 < 8; x3++) {
            this._setMask(x3, 7);
            this._setMask(x3 + width - 8, 7);
            this._setMask(x3, width - 8);
          }
        },
        _insertTimingRowAndColumn: function() {
          var x3;
          var buffer = this.buffer;
          var width = this.width;
          for (x3 = 0; x3 < width - 14; x3++) {
            if (x3 & 1) {
              this._setMask(8 + x3, 6);
              this._setMask(6, 8 + x3);
            } else {
              buffer[8 + x3 + width * 6] = 1;
              buffer[6 + width * (8 + x3)] = 1;
            }
          }
        },
        _insertVersion: function() {
          var i3, j, x3, y3;
          var buffer = this.buffer;
          var version = this._version;
          var width = this.width;
          if (version > 6) {
            i3 = Version_1.BLOCK[version - 7];
            j = 17;
            for (x3 = 0; x3 < 6; x3++) {
              for (y3 = 0; y3 < 3; y3++, j--) {
                if (1 & (j > 11 ? version >> j - 12 : i3 >> j)) {
                  buffer[5 - x3 + width * (2 - y3 + width - 11)] = 1;
                  buffer[2 - y3 + width - 11 + width * (5 - x3)] = 1;
                } else {
                  this._setMask(5 - x3, 2 - y3 + width - 11);
                  this._setMask(2 - y3 + width - 11, 5 - x3);
                }
              }
            }
          }
        },
        _isMasked: function(x3, y3) {
          var bit = Frame._getMaskBit(x3, y3);
          return this._mask[bit] === 1;
        },
        _pack: function() {
          var bit, i3, j;
          var k2 = 1;
          var v3 = 1;
          var width = this.width;
          var x3 = width - 1;
          var y3 = width - 1;
          var length = (this._dataBlock + this._eccBlock) * (this._neccBlock1 + this._neccBlock2) + this._neccBlock2;
          for (i3 = 0; i3 < length; i3++) {
            bit = this._stringBuffer[i3];
            for (j = 0; j < 8; j++, bit <<= 1) {
              if (128 & bit) {
                this.buffer[x3 + width * y3] = 1;
              }
              do {
                if (v3) {
                  x3--;
                } else {
                  x3++;
                  if (k2) {
                    if (y3 !== 0) {
                      y3--;
                    } else {
                      x3 -= 2;
                      k2 = !k2;
                      if (x3 === 6) {
                        x3--;
                        y3 = 9;
                      }
                    }
                  } else if (y3 !== width - 1) {
                    y3++;
                  } else {
                    x3 -= 2;
                    k2 = !k2;
                    if (x3 === 6) {
                      x3--;
                      y3 -= 8;
                    }
                  }
                }
                v3 = !v3;
              } while (this._isMasked(x3, y3));
            }
          }
        },
        _reverseMask: function() {
          var x3, y3;
          var width = this.width;
          for (x3 = 0; x3 < 9; x3++) {
            this._setMask(x3, 8);
          }
          for (x3 = 0; x3 < 8; x3++) {
            this._setMask(x3 + width - 8, 8);
            this._setMask(8, x3);
          }
          for (y3 = 0; y3 < 7; y3++) {
            this._setMask(8, y3 + width - 7);
          }
        },
        _setMask: function(x3, y3) {
          var bit = Frame._getMaskBit(x3, y3);
          this._mask[bit] = 1;
        },
        _syncMask: function() {
          var x3, y3;
          var width = this.width;
          for (y3 = 0; y3 < width; y3++) {
            for (x3 = 0; x3 <= y3; x3++) {
              if (this.buffer[x3 + width * y3]) {
                this._setMask(x3, y3);
              }
            }
          }
        }
      }, {
        _createArray: function(length) {
          var i3;
          var array = [];
          for (i3 = 0; i3 < length; i3++) {
            array[i3] = 0;
          }
          return array;
        },
        _getMaskBit: function(x3, y3) {
          var bit;
          if (x3 > y3) {
            bit = x3;
            x3 = y3;
            y3 = bit;
          }
          bit = y3;
          bit += y3 * y3;
          bit >>= 1;
          bit += x3;
          return bit;
        },
        _modN: function(x3) {
          while (x3 >= 255) {
            x3 -= 255;
            x3 = (x3 >> 8) + (x3 & 255);
          }
          return x3;
        },
        // *Badness* coefficients.
        N1: 3,
        N2: 3,
        N3: 40,
        N4: 10
      });
      var Frame_1 = Frame;
      var ImageRenderer = Renderer_1.extend({
        /**
         * @override
         */
        draw: function() {
          this.element.src = this.qrious.toDataURL();
        },
        /**
         * @override
         */
        reset: function() {
          this.element.src = "";
        },
        /**
         * @override
         */
        resize: function() {
          var element2 = this.element;
          element2.width = element2.height = this.qrious.size;
        }
      });
      var ImageRenderer_1 = ImageRenderer;
      var Option2 = lite.extend(function(name2, modifiable, defaultValue, valueTransformer) {
        this.name = name2;
        this.modifiable = Boolean(modifiable);
        this.defaultValue = defaultValue;
        this._valueTransformer = valueTransformer;
      }, {
        /**
         * Transforms the specified <code>value</code> so that it can be applied for this {@link Option}.
         *
         * If a value transformer has been specified for this {@link Option}, it will be called upon to transform
         * <code>value</code>. Otherwise, <code>value</code> will be returned directly.
         *
         * @param {*} value - the value to be transformed
         * @return {*} The transformed value or <code>value</code> if no value transformer is specified.
         * @public
         * @memberof Option#
         */
        transform: function(value2) {
          var transformer = this._valueTransformer;
          if (typeof transformer === "function") {
            return transformer(value2, this);
          }
          return value2;
        }
      });
      var Option_1 = Option2;
      var Utilities = lite.extend(null, {
        /**
         * Returns the absolute value of a given number.
         *
         * This method is simply a convenient shorthand for <code>Math.abs</code> while ensuring that nulls are returned as
         * <code>null</code> instead of zero.
         *
         * @param {number} value - the number whose absolute value is to be returned
         * @return {number} The absolute value of <code>value</code> or <code>null</code> if <code>value</code> is
         * <code>null</code>.
         * @public
         * @static
         * @memberof Utilities
         */
        abs: function(value2) {
          return value2 != null ? Math.abs(value2) : null;
        },
        /**
         * Returns whether the specified <code>object</code> has a property with the specified <code>name</code> as an own
         * (not inherited) property.
         *
         * @param {Object} object - the object on which the property is to be checked
         * @param {string} name - the name of the property to be checked
         * @return {boolean} <code>true</code> if <code>object</code> has an own property with <code>name</code>.
         * @public
         * @static
         * @memberof Utilities
         */
        hasOwn: function(object2, name2) {
          return Object.prototype.hasOwnProperty.call(object2, name2);
        },
        /**
         * A non-operation method that does absolutely nothing.
         *
         * @return {void}
         * @public
         * @static
         * @memberof Utilities
         */
        noop: function() {
        },
        /**
         * Transforms the specified <code>string</code> to upper case while remaining null-safe.
         *
         * @param {string} string - the string to be transformed to upper case
         * @return {string} <code>string</code> transformed to upper case if <code>string</code> is not <code>null</code>.
         * @public
         * @static
         * @memberof Utilities
         */
        toUpperCase: function(string3) {
          return string3 != null ? string3.toUpperCase() : null;
        }
      });
      var Utilities_1 = Utilities;
      var OptionManager = lite.extend(function(options2) {
        this.options = {};
        options2.forEach(function(option2) {
          this.options[option2.name] = option2;
        }, this);
      }, {
        /**
         * Returns whether an option with the specified <code>name</code> is available.
         *
         * @param {string} name - the name of the {@link Option} whose existence is to be checked
         * @return {boolean} <code>true</code> if an {@link Option} exists with <code>name</code>; otherwise
         * <code>false</code>.
         * @public
         * @memberof OptionManager#
         */
        exists: function(name2) {
          return this.options[name2] != null;
        },
        /**
         * Returns the value of the option with the specified <code>name</code> on the <code>target</code> object provided.
         *
         * @param {string} name - the name of the {@link Option} whose value on <code>target</code> is to be returned
         * @param {Object} target - the object from which the value of the named {@link Option} is to be returned
         * @return {*} The value of the {@link Option} with <code>name</code> on <code>target</code>.
         * @public
         * @memberof OptionManager#
         */
        get: function(name2, target) {
          return OptionManager._get(this.options[name2], target);
        },
        /**
         * Returns a copy of all of the available options on the <code>target</code> object provided.
         *
         * @param {Object} target - the object from which the option name/value pairs are to be returned
         * @return {Object.<string, *>} A hash containing the name/value pairs of all options on <code>target</code>.
         * @public
         * @memberof OptionManager#
         */
        getAll: function(target) {
          var name2;
          var options2 = this.options;
          var result2 = {};
          for (name2 in options2) {
            if (Utilities_1.hasOwn(options2, name2)) {
              result2[name2] = OptionManager._get(options2[name2], target);
            }
          }
          return result2;
        },
        /**
         * Initializes the available options for the <code>target</code> object provided and then applies the initial values
         * within the speciifed <code>options</code>.
         *
         * This method will throw an error if any of the names within <code>options</code> does not match an available option.
         *
         * This involves setting the default values and defining properties for all of the available options on
         * <code>target</code> before finally calling {@link OptionMananger#setAll} with <code>options</code> and
         * <code>target</code>. Any options that are configured to be modifiable will have a setter included in their defined
         * property that will allow its corresponding value to be modified.
         *
         * If a change handler is specified, it will be called whenever the value changes on <code>target</code> for a
         * modifiable option, but only when done so via the defined property's setter.
         *
         * @param {Object.<string, *>} options - the name/value pairs of the initial options to be set
         * @param {Object} target - the object on which the options are to be initialized
         * @param {Function} [changeHandler] - the function to be called whenever the value of an modifiable option changes on
         * <code>target</code>
         * @return {void}
         * @throws {Error} If <code>options</code> contains an invalid option name.
         * @public
         * @memberof OptionManager#
         */
        init: function(options2, target, changeHandler) {
          if (typeof changeHandler !== "function") {
            changeHandler = Utilities_1.noop;
          }
          var name2, option2;
          for (name2 in this.options) {
            if (Utilities_1.hasOwn(this.options, name2)) {
              option2 = this.options[name2];
              OptionManager._set(option2, option2.defaultValue, target);
              OptionManager._createAccessor(option2, target, changeHandler);
            }
          }
          this._setAll(options2, target, true);
        },
        /**
         * Sets the value of the option with the specified <code>name</code> on the <code>target</code> object provided to
         * <code>value</code>.
         *
         * This method will throw an error if <code>name</code> does not match an available option or matches an option that
         * cannot be modified.
         *
         * If <code>value</code> is <code>null</code> and the {@link Option} has a default value configured, then that default
         * value will be used instead. If the {@link Option} also has a value transformer configured, it will be used to
         * transform whichever value was determined to be used.
         *
         * This method returns whether the value of the underlying field on <code>target</code> was changed as a result.
         *
         * @param {string} name - the name of the {@link Option} whose value is to be set
         * @param {*} value - the value to be set for the named {@link Option} on <code>target</code>
         * @param {Object} target - the object on which <code>value</code> is to be set for the named {@link Option}
         * @return {boolean} <code>true</code> if the underlying field on <code>target</code> was changed; otherwise
         * <code>false</code>.
         * @throws {Error} If <code>name</code> is invalid or is for an option that cannot be modified.
         * @public
         * @memberof OptionManager#
         */
        set: function(name2, value2, target) {
          return this._set(name2, value2, target);
        },
        /**
         * Sets all of the specified <code>options</code> on the <code>target</code> object provided to their corresponding
         * values.
         *
         * This method will throw an error if any of the names within <code>options</code> does not match an available option
         * or matches an option that cannot be modified.
         *
         * If any value within <code>options</code> is <code>null</code> and the corresponding {@link Option} has a default
         * value configured, then that default value will be used instead. If an {@link Option} also has a value transformer
         * configured, it will be used to transform whichever value was determined to be used.
         *
         * This method returns whether the value for any of the underlying fields on <code>target</code> were changed as a
         * result.
         *
         * @param {Object.<string, *>} options - the name/value pairs of options to be set
         * @param {Object} target - the object on which the options are to be set
         * @return {boolean} <code>true</code> if any of the underlying fields on <code>target</code> were changed; otherwise
         * <code>false</code>.
         * @throws {Error} If <code>options</code> contains an invalid option name or an option that cannot be modiifed.
         * @public
         * @memberof OptionManager#
         */
        setAll: function(options2, target) {
          return this._setAll(options2, target);
        },
        _set: function(name2, value2, target, allowUnmodifiable) {
          var option2 = this.options[name2];
          if (!option2) {
            throw new Error("Invalid option: " + name2);
          }
          if (!option2.modifiable && !allowUnmodifiable) {
            throw new Error("Option cannot be modified: " + name2);
          }
          return OptionManager._set(option2, value2, target);
        },
        _setAll: function(options2, target, allowUnmodifiable) {
          if (!options2) {
            return false;
          }
          var name2;
          var changed = false;
          for (name2 in options2) {
            if (Utilities_1.hasOwn(options2, name2) && this._set(name2, options2[name2], target, allowUnmodifiable)) {
              changed = true;
            }
          }
          return changed;
        }
      }, {
        _createAccessor: function(option2, target, changeHandler) {
          var descriptor = {
            get: function() {
              return OptionManager._get(option2, target);
            }
          };
          if (option2.modifiable) {
            descriptor.set = function(value2) {
              if (OptionManager._set(option2, value2, target)) {
                changeHandler(value2, option2);
              }
            };
          }
          Object.defineProperty(target, option2.name, descriptor);
        },
        _get: function(option2, target) {
          return target["_" + option2.name];
        },
        _set: function(option2, value2, target) {
          var fieldName = "_" + option2.name;
          var oldValue = target[fieldName];
          var newValue = option2.transform(value2 != null ? value2 : option2.defaultValue);
          target[fieldName] = newValue;
          return newValue !== oldValue;
        }
      });
      var OptionManager_1 = OptionManager;
      var ServiceManager = lite.extend(function() {
        this._services = {};
      }, {
        /**
         * Returns the {@link Service} being managed with the specified <code>name</code>.
         *
         * @param {string} name - the name of the {@link Service} to be returned
         * @return {Service} The {@link Service} is being managed with <code>name</code>.
         * @throws {Error} If no {@link Service} is being managed with <code>name</code>.
         * @public
         * @memberof ServiceManager#
         */
        getService: function(name2) {
          var service = this._services[name2];
          if (!service) {
            throw new Error("Service is not being managed with name: " + name2);
          }
          return service;
        },
        /**
         * Sets the {@link Service} implementation to be managed for the specified <code>name</code> to the
         * <code>service</code> provided.
         *
         * @param {string} name - the name of the {@link Service} to be managed with <code>name</code>
         * @param {Service} service - the {@link Service} implementation to be managed
         * @return {void}
         * @throws {Error} If a {@link Service} is already being managed with the same <code>name</code>.
         * @public
         * @memberof ServiceManager#
         */
        setService: function(name2, service) {
          if (this._services[name2]) {
            throw new Error("Service is already managed with name: " + name2);
          }
          if (service) {
            this._services[name2] = service;
          }
        }
      });
      var ServiceManager_1 = ServiceManager;
      var optionManager = new OptionManager_1([
        new Option_1("background", true, "white"),
        new Option_1("backgroundAlpha", true, 1, Utilities_1.abs),
        new Option_1("element"),
        new Option_1("foreground", true, "black"),
        new Option_1("foregroundAlpha", true, 1, Utilities_1.abs),
        new Option_1("level", true, "L", Utilities_1.toUpperCase),
        new Option_1("mime", true, "image/png"),
        new Option_1("padding", true, null, Utilities_1.abs),
        new Option_1("size", true, 100, Utilities_1.abs),
        new Option_1("value", true, "")
      ]);
      var serviceManager = new ServiceManager_1();
      var QRious3 = lite.extend(function(options2) {
        optionManager.init(options2, this, this.update.bind(this));
        var element2 = optionManager.get("element", this);
        var elementService = serviceManager.getService("element");
        var canvas = element2 && elementService.isCanvas(element2) ? element2 : elementService.createCanvas();
        var image2 = element2 && elementService.isImage(element2) ? element2 : elementService.createImage();
        this._canvasRenderer = new CanvasRenderer_1(this, canvas, true);
        this._imageRenderer = new ImageRenderer_1(this, image2, image2 === element2);
        this.update();
      }, {
        /**
         * Returns all of the options configured for this {@link QRious}.
         *
         * Any changes made to the returned object will not be reflected in the options themselves or their corresponding
         * underlying fields.
         *
         * @return {Object.<string, *>} A copy of the applied options.
         * @public
         * @memberof QRious#
         */
        get: function() {
          return optionManager.getAll(this);
        },
        /**
         * Sets all of the specified <code>options</code> and automatically updates this {@link QRious} if any of the
         * underlying fields are changed as a result.
         *
         * This is the preferred method for updating multiple options at one time to avoid unnecessary updates between
         * changes.
         *
         * @param {QRious~Options} options - the options to be set
         * @return {void}
         * @throws {Error} If any <code>options</code> are invalid or cannot be modified.
         * @public
         * @memberof QRious#
         */
        set: function(options2) {
          if (optionManager.setAll(options2, this)) {
            this.update();
          }
        },
        /**
         * Returns the image data URI for the generated QR code using the <code>mime</code> provided.
         *
         * @param {string} [mime] - the MIME type for the image
         * @return {string} The image data URI for the QR code.
         * @public
         * @memberof QRious#
         */
        toDataURL: function(mime) {
          return this.canvas.toDataURL(mime || this.mime);
        },
        /**
         * Updates this {@link QRious} by generating a new {@link Frame} and re-rendering the QR code.
         *
         * @return {void}
         * @protected
         * @memberof QRious#
         */
        update: function() {
          var frame = new Frame_1({
            level: this.level,
            value: this.value
          });
          this._canvasRenderer.render(frame);
          this._imageRenderer.render(frame);
        }
      }, {
        /**
         * Configures the <code>service</code> provided to be used by all {@link QRious} instances.
         *
         * @param {Service} service - the {@link Service} to be configured
         * @return {void}
         * @throws {Error} If a {@link Service} has already been configured with the same name.
         * @public
         * @static
         * @memberof QRious
         */
        use: function(service) {
          serviceManager.setService(service.getName(), service);
        }
      });
      Object.defineProperties(QRious3.prototype, {
        canvas: {
          /**
           * Returns the <code>canvas</code> element being used to render the QR code for this {@link QRious}.
           *
           * @return {*} The <code>canvas</code> element.
           * @public
           * @memberof QRious#
           * @alias canvas
           */
          get: function() {
            return this._canvasRenderer.getElement();
          }
        },
        image: {
          /**
           * Returns the <code>img</code> element being used to render the QR code for this {@link QRious}.
           *
           * @return {*} The <code>img</code> element.
           * @public
           * @memberof QRious#
           * @alias image
           */
          get: function() {
            return this._imageRenderer.getElement();
          }
        }
      });
      var QRious_1$2 = QRious3;
      var index2 = QRious_1$2;
      var Service = lite.extend({
        /**
         * Returns the name of this {@link Service}.
         *
         * @return {string} The service name.
         * @public
         * @abstract
         * @memberof Service#
         */
        getName: function() {
        }
      });
      var Service_1 = Service;
      var ElementService = Service_1.extend({
        /**
         * Creates an instance of a canvas element.
         *
         * Implementations of {@link ElementService} <b>must</b> override this method with their own specific logic.
         *
         * @return {*} The newly created canvas element.
         * @public
         * @abstract
         * @memberof ElementService#
         */
        createCanvas: function() {
        },
        /**
         * Creates an instance of a image element.
         *
         * Implementations of {@link ElementService} <b>must</b> override this method with their own specific logic.
         *
         * @return {*} The newly created image element.
         * @public
         * @abstract
         * @memberof ElementService#
         */
        createImage: function() {
        },
        /**
         * @override
         */
        getName: function() {
          return "element";
        },
        /**
         * Returns whether the specified <code>element</code> is a canvas.
         *
         * Implementations of {@link ElementService} <b>must</b> override this method with their own specific logic.
         *
         * @param {*} element - the element to be checked
         * @return {boolean} <code>true</code> if <code>element</code> is a canvas; otherwise <code>false</code>.
         * @public
         * @abstract
         * @memberof ElementService#
         */
        isCanvas: function(element2) {
        },
        /**
         * Returns whether the specified <code>element</code> is an image.
         *
         * Implementations of {@link ElementService} <b>must</b> override this method with their own specific logic.
         *
         * @param {*} element - the element to be checked
         * @return {boolean} <code>true</code> if <code>element</code> is an image; otherwise <code>false</code>.
         * @public
         * @abstract
         * @memberof ElementService#
         */
        isImage: function(element2) {
        }
      });
      var ElementService_1 = ElementService;
      var BrowserElementService = ElementService_1.extend({
        /**
         * @override
         */
        createCanvas: function() {
          return document.createElement("canvas");
        },
        /**
         * @override
         */
        createImage: function() {
          return document.createElement("img");
        },
        /**
         * @override
         */
        isCanvas: function(element2) {
          return element2 instanceof HTMLCanvasElement;
        },
        /**
         * @override
         */
        isImage: function(element2) {
          return element2 instanceof HTMLImageElement;
        }
      });
      var BrowserElementService_1 = BrowserElementService;
      index2.use(new BrowserElementService_1());
      var QRious_1 = index2;
      return QRious_1;
    });
  }
});

// node_modules/leaflet/dist/leaflet-src.js
var require_leaflet_src = __commonJS({
  "node_modules/leaflet/dist/leaflet-src.js"(exports, module) {
    (function(global5, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global5 = typeof globalThis !== "undefined" ? globalThis : global5 || self, factory(global5.leaflet = {}));
    })(exports, function(exports2) {
      "use strict";
      var version = "1.9.4";
      function extend(dest) {
        var i3, j, len, src;
        for (j = 1, len = arguments.length; j < len; j++) {
          src = arguments[j];
          for (i3 in src) {
            dest[i3] = src[i3];
          }
        }
        return dest;
      }
      var create$2 = Object.create || /* @__PURE__ */ function() {
        function F2() {
        }
        return function(proto) {
          F2.prototype = proto;
          return new F2();
        };
      }();
      function bind2(fn, obj) {
        var slice3 = Array.prototype.slice;
        if (fn.bind) {
          return fn.bind.apply(fn, slice3.call(arguments, 1));
        }
        var args = slice3.call(arguments, 2);
        return function() {
          return fn.apply(obj, args.length ? args.concat(slice3.call(arguments)) : arguments);
        };
      }
      var lastId = 0;
      function stamp(obj) {
        if (!("_leaflet_id" in obj)) {
          obj["_leaflet_id"] = ++lastId;
        }
        return obj._leaflet_id;
      }
      function throttle3(fn, time3, context) {
        var lock, args, wrapperFn, later;
        later = function() {
          lock = false;
          if (args) {
            wrapperFn.apply(context, args);
            args = false;
          }
        };
        wrapperFn = function() {
          if (lock) {
            args = arguments;
          } else {
            fn.apply(context, arguments);
            setTimeout(later, time3);
            lock = true;
          }
        };
        return wrapperFn;
      }
      function wrapNum(x3, range2, includeMax) {
        var max3 = range2[1], min3 = range2[0], d3 = max3 - min3;
        return x3 === max3 && includeMax ? x3 : ((x3 - min3) % d3 + d3) % d3 + min3;
      }
      function falseFn2() {
        return false;
      }
      function formatNum(num, precision) {
        if (precision === false) {
          return num;
        }
        var pow = Math.pow(10, precision === void 0 ? 6 : precision);
        return Math.round(num * pow) / pow;
      }
      function trim(str) {
        return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, "");
      }
      function splitWords(str) {
        return trim(str).split(/\s+/);
      }
      function setOptions2(obj, options2) {
        if (!Object.prototype.hasOwnProperty.call(obj, "options")) {
          obj.options = obj.options ? create$2(obj.options) : {};
        }
        for (var i3 in options2) {
          obj.options[i3] = options2[i3];
        }
        return obj.options;
      }
      function getParamString(obj, existingUrl, uppercase) {
        var params = [];
        for (var i3 in obj) {
          params.push(encodeURIComponent(uppercase ? i3.toUpperCase() : i3) + "=" + encodeURIComponent(obj[i3]));
        }
        return (!existingUrl || existingUrl.indexOf("?") === -1 ? "?" : "&") + params.join("&");
      }
      var templateRe = /\{ *([\w_ -]+) *\}/g;
      function template3(str, data2) {
        return str.replace(templateRe, function(str2, key2) {
          var value2 = data2[key2];
          if (value2 === void 0) {
            throw new Error("No value provided for variable " + str2);
          } else if (typeof value2 === "function") {
            value2 = value2(data2);
          }
          return value2;
        });
      }
      var isArray3 = Array.isArray || function(obj) {
        return Object.prototype.toString.call(obj) === "[object Array]";
      };
      function indexOf(array, el2) {
        for (var i3 = 0; i3 < array.length; i3++) {
          if (array[i3] === el2) {
            return i3;
          }
        }
        return -1;
      }
      var emptyImageUrl = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";
      function getPrefixed(name2) {
        return window["webkit" + name2] || window["moz" + name2] || window["ms" + name2];
      }
      var lastTime = 0;
      function timeoutDefer(fn) {
        var time3 = +/* @__PURE__ */ new Date(), timeToCall = Math.max(0, 16 - (time3 - lastTime));
        lastTime = time3 + timeToCall;
        return window.setTimeout(fn, timeToCall);
      }
      var requestFn = window.requestAnimationFrame || getPrefixed("RequestAnimationFrame") || timeoutDefer;
      var cancelFn = window.cancelAnimationFrame || getPrefixed("CancelAnimationFrame") || getPrefixed("CancelRequestAnimationFrame") || function(id) {
        window.clearTimeout(id);
      };
      function requestAnimFrame(fn, context, immediate) {
        if (immediate && requestFn === timeoutDefer) {
          fn.call(context);
        } else {
          return requestFn.call(window, bind2(fn, context));
        }
      }
      function cancelAnimFrame(id) {
        if (id) {
          cancelFn.call(window, id);
        }
      }
      var Util = {
        __proto__: null,
        extend,
        create: create$2,
        bind: bind2,
        get lastId() {
          return lastId;
        },
        stamp,
        throttle: throttle3,
        wrapNum,
        falseFn: falseFn2,
        formatNum,
        trim,
        splitWords,
        setOptions: setOptions2,
        getParamString,
        template: template3,
        isArray: isArray3,
        indexOf,
        emptyImageUrl,
        requestFn,
        cancelFn,
        requestAnimFrame,
        cancelAnimFrame
      };
      function Class() {
      }
      Class.extend = function(props2) {
        var NewClass = function() {
          setOptions2(this);
          if (this.initialize) {
            this.initialize.apply(this, arguments);
          }
          this.callInitHooks();
        };
        var parentProto = NewClass.__super__ = this.prototype;
        var proto = create$2(parentProto);
        proto.constructor = NewClass;
        NewClass.prototype = proto;
        for (var i3 in this) {
          if (Object.prototype.hasOwnProperty.call(this, i3) && i3 !== "prototype" && i3 !== "__super__") {
            NewClass[i3] = this[i3];
          }
        }
        if (props2.statics) {
          extend(NewClass, props2.statics);
        }
        if (props2.includes) {
          checkDeprecatedMixinEvents(props2.includes);
          extend.apply(null, [proto].concat(props2.includes));
        }
        extend(proto, props2);
        delete proto.statics;
        delete proto.includes;
        if (proto.options) {
          proto.options = parentProto.options ? create$2(parentProto.options) : {};
          extend(proto.options, props2.options);
        }
        proto._initHooks = [];
        proto.callInitHooks = function() {
          if (this._initHooksCalled) {
            return;
          }
          if (parentProto.callInitHooks) {
            parentProto.callInitHooks.call(this);
          }
          this._initHooksCalled = true;
          for (var i4 = 0, len = proto._initHooks.length; i4 < len; i4++) {
            proto._initHooks[i4].call(this);
          }
        };
        return NewClass;
      };
      Class.include = function(props2) {
        var parentOptions = this.prototype.options;
        extend(this.prototype, props2);
        if (props2.options) {
          this.prototype.options = parentOptions;
          this.mergeOptions(props2.options);
        }
        return this;
      };
      Class.mergeOptions = function(options2) {
        extend(this.prototype.options, options2);
        return this;
      };
      Class.addInitHook = function(fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        var init = typeof fn === "function" ? fn : function() {
          this[fn].apply(this, args);
        };
        this.prototype._initHooks = this.prototype._initHooks || [];
        this.prototype._initHooks.push(init);
        return this;
      };
      function checkDeprecatedMixinEvents(includes) {
        if (typeof L === "undefined" || !L || !L.Mixin) {
          return;
        }
        includes = isArray3(includes) ? includes : [includes];
        for (var i3 = 0; i3 < includes.length; i3++) {
          if (includes[i3] === L.Mixin.Events) {
            console.warn("Deprecated include of L.Mixin.Events: this property will be removed in future releases, please inherit from L.Evented instead.", new Error().stack);
          }
        }
      }
      var Events = {
        /* @method on(type: String, fn: Function, context?: Object): this
         * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
         *
         * @alternative
         * @method on(eventMap: Object): this
         * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
         */
        on: function(types2, fn, context) {
          if (typeof types2 === "object") {
            for (var type in types2) {
              this._on(type, types2[type], fn);
            }
          } else {
            types2 = splitWords(types2);
            for (var i3 = 0, len = types2.length; i3 < len; i3++) {
              this._on(types2[i3], fn, context);
            }
          }
          return this;
        },
        /* @method off(type: String, fn?: Function, context?: Object): this
         * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
         *
         * @alternative
         * @method off(eventMap: Object): this
         * Removes a set of type/listener pairs.
         *
         * @alternative
         * @method off: this
         * Removes all listeners to all events on the object. This includes implicitly attached events.
         */
        off: function(types2, fn, context) {
          if (!arguments.length) {
            delete this._events;
          } else if (typeof types2 === "object") {
            for (var type in types2) {
              this._off(type, types2[type], fn);
            }
          } else {
            types2 = splitWords(types2);
            var removeAll = arguments.length === 1;
            for (var i3 = 0, len = types2.length; i3 < len; i3++) {
              if (removeAll) {
                this._off(types2[i3]);
              } else {
                this._off(types2[i3], fn, context);
              }
            }
          }
          return this;
        },
        // attach listener (without syntactic sugar now)
        _on: function(type, fn, context, _once) {
          if (typeof fn !== "function") {
            console.warn("wrong listener type: " + typeof fn);
            return;
          }
          if (this._listens(type, fn, context) !== false) {
            return;
          }
          if (context === this) {
            context = void 0;
          }
          var newListener = { fn, ctx: context };
          if (_once) {
            newListener.once = true;
          }
          this._events = this._events || {};
          this._events[type] = this._events[type] || [];
          this._events[type].push(newListener);
        },
        _off: function(type, fn, context) {
          var listeners, i3, len;
          if (!this._events) {
            return;
          }
          listeners = this._events[type];
          if (!listeners) {
            return;
          }
          if (arguments.length === 1) {
            if (this._firingCount) {
              for (i3 = 0, len = listeners.length; i3 < len; i3++) {
                listeners[i3].fn = falseFn2;
              }
            }
            delete this._events[type];
            return;
          }
          if (typeof fn !== "function") {
            console.warn("wrong listener type: " + typeof fn);
            return;
          }
          var index3 = this._listens(type, fn, context);
          if (index3 !== false) {
            var listener = listeners[index3];
            if (this._firingCount) {
              listener.fn = falseFn2;
              this._events[type] = listeners = listeners.slice();
            }
            listeners.splice(index3, 1);
          }
        },
        // @method fire(type: String, data?: Object, propagate?: Boolean): this
        // Fires an event of the specified type. You can optionally provide a data
        // object — the first argument of the listener function will contain its
        // properties. The event can optionally be propagated to event parents.
        fire: function(type, data2, propagate) {
          if (!this.listens(type, propagate)) {
            return this;
          }
          var event2 = extend({}, data2, {
            type,
            target: this,
            sourceTarget: data2 && data2.sourceTarget || this
          });
          if (this._events) {
            var listeners = this._events[type];
            if (listeners) {
              this._firingCount = this._firingCount + 1 || 1;
              for (var i3 = 0, len = listeners.length; i3 < len; i3++) {
                var l3 = listeners[i3];
                var fn = l3.fn;
                if (l3.once) {
                  this.off(type, fn, l3.ctx);
                }
                fn.call(l3.ctx || this, event2);
              }
              this._firingCount--;
            }
          }
          if (propagate) {
            this._propagateEvent(event2);
          }
          return this;
        },
        // @method listens(type: String, propagate?: Boolean): Boolean
        // @method listens(type: String, fn: Function, context?: Object, propagate?: Boolean): Boolean
        // Returns `true` if a particular event type has any listeners attached to it.
        // The verification can optionally be propagated, it will return `true` if parents have the listener attached to it.
        listens: function(type, fn, context, propagate) {
          if (typeof type !== "string") {
            console.warn('"string" type argument expected');
          }
          var _fn = fn;
          if (typeof fn !== "function") {
            propagate = !!fn;
            _fn = void 0;
            context = void 0;
          }
          var listeners = this._events && this._events[type];
          if (listeners && listeners.length) {
            if (this._listens(type, _fn, context) !== false) {
              return true;
            }
          }
          if (propagate) {
            for (var id in this._eventParents) {
              if (this._eventParents[id].listens(type, fn, context, propagate)) {
                return true;
              }
            }
          }
          return false;
        },
        // returns the index (number) or false
        _listens: function(type, fn, context) {
          if (!this._events) {
            return false;
          }
          var listeners = this._events[type] || [];
          if (!fn) {
            return !!listeners.length;
          }
          if (context === this) {
            context = void 0;
          }
          for (var i3 = 0, len = listeners.length; i3 < len; i3++) {
            if (listeners[i3].fn === fn && listeners[i3].ctx === context) {
              return i3;
            }
          }
          return false;
        },
        // @method once(…): this
        // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
        once: function(types2, fn, context) {
          if (typeof types2 === "object") {
            for (var type in types2) {
              this._on(type, types2[type], fn, true);
            }
          } else {
            types2 = splitWords(types2);
            for (var i3 = 0, len = types2.length; i3 < len; i3++) {
              this._on(types2[i3], fn, context, true);
            }
          }
          return this;
        },
        // @method addEventParent(obj: Evented): this
        // Adds an event parent - an `Evented` that will receive propagated events
        addEventParent: function(obj) {
          this._eventParents = this._eventParents || {};
          this._eventParents[stamp(obj)] = obj;
          return this;
        },
        // @method removeEventParent(obj: Evented): this
        // Removes an event parent, so it will stop receiving propagated events
        removeEventParent: function(obj) {
          if (this._eventParents) {
            delete this._eventParents[stamp(obj)];
          }
          return this;
        },
        _propagateEvent: function(e3) {
          for (var id in this._eventParents) {
            this._eventParents[id].fire(e3.type, extend({
              layer: e3.target,
              propagatedFrom: e3.target
            }, e3), true);
          }
        }
      };
      Events.addEventListener = Events.on;
      Events.removeEventListener = Events.clearAllEventListeners = Events.off;
      Events.addOneTimeEventListener = Events.once;
      Events.fireEvent = Events.fire;
      Events.hasEventListeners = Events.listens;
      var Evented = Class.extend(Events);
      function Point2(x3, y3, round) {
        this.x = round ? Math.round(x3) : x3;
        this.y = round ? Math.round(y3) : y3;
      }
      var trunc = Math.trunc || function(v3) {
        return v3 > 0 ? Math.floor(v3) : Math.ceil(v3);
      };
      Point2.prototype = {
        // @method clone(): Point
        // Returns a copy of the current point.
        clone: function() {
          return new Point2(this.x, this.y);
        },
        // @method add(otherPoint: Point): Point
        // Returns the result of addition of the current and the given points.
        add: function(point) {
          return this.clone()._add(toPoint(point));
        },
        _add: function(point) {
          this.x += point.x;
          this.y += point.y;
          return this;
        },
        // @method subtract(otherPoint: Point): Point
        // Returns the result of subtraction of the given point from the current.
        subtract: function(point) {
          return this.clone()._subtract(toPoint(point));
        },
        _subtract: function(point) {
          this.x -= point.x;
          this.y -= point.y;
          return this;
        },
        // @method divideBy(num: Number): Point
        // Returns the result of division of the current point by the given number.
        divideBy: function(num) {
          return this.clone()._divideBy(num);
        },
        _divideBy: function(num) {
          this.x /= num;
          this.y /= num;
          return this;
        },
        // @method multiplyBy(num: Number): Point
        // Returns the result of multiplication of the current point by the given number.
        multiplyBy: function(num) {
          return this.clone()._multiplyBy(num);
        },
        _multiplyBy: function(num) {
          this.x *= num;
          this.y *= num;
          return this;
        },
        // @method scaleBy(scale: Point): Point
        // Multiply each coordinate of the current point by each coordinate of
        // `scale`. In linear algebra terms, multiply the point by the
        // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
        // defined by `scale`.
        scaleBy: function(point) {
          return new Point2(this.x * point.x, this.y * point.y);
        },
        // @method unscaleBy(scale: Point): Point
        // Inverse of `scaleBy`. Divide each coordinate of the current point by
        // each coordinate of `scale`.
        unscaleBy: function(point) {
          return new Point2(this.x / point.x, this.y / point.y);
        },
        // @method round(): Point
        // Returns a copy of the current point with rounded coordinates.
        round: function() {
          return this.clone()._round();
        },
        _round: function() {
          this.x = Math.round(this.x);
          this.y = Math.round(this.y);
          return this;
        },
        // @method floor(): Point
        // Returns a copy of the current point with floored coordinates (rounded down).
        floor: function() {
          return this.clone()._floor();
        },
        _floor: function() {
          this.x = Math.floor(this.x);
          this.y = Math.floor(this.y);
          return this;
        },
        // @method ceil(): Point
        // Returns a copy of the current point with ceiled coordinates (rounded up).
        ceil: function() {
          return this.clone()._ceil();
        },
        _ceil: function() {
          this.x = Math.ceil(this.x);
          this.y = Math.ceil(this.y);
          return this;
        },
        // @method trunc(): Point
        // Returns a copy of the current point with truncated coordinates (rounded towards zero).
        trunc: function() {
          return this.clone()._trunc();
        },
        _trunc: function() {
          this.x = trunc(this.x);
          this.y = trunc(this.y);
          return this;
        },
        // @method distanceTo(otherPoint: Point): Number
        // Returns the cartesian distance between the current and the given points.
        distanceTo: function(point) {
          point = toPoint(point);
          var x3 = point.x - this.x, y3 = point.y - this.y;
          return Math.sqrt(x3 * x3 + y3 * y3);
        },
        // @method equals(otherPoint: Point): Boolean
        // Returns `true` if the given point has the same coordinates.
        equals: function(point) {
          point = toPoint(point);
          return point.x === this.x && point.y === this.y;
        },
        // @method contains(otherPoint: Point): Boolean
        // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
        contains: function(point) {
          point = toPoint(point);
          return Math.abs(point.x) <= Math.abs(this.x) && Math.abs(point.y) <= Math.abs(this.y);
        },
        // @method toString(): String
        // Returns a string representation of the point for debugging purposes.
        toString: function() {
          return "Point(" + formatNum(this.x) + ", " + formatNum(this.y) + ")";
        }
      };
      function toPoint(x3, y3, round) {
        if (x3 instanceof Point2) {
          return x3;
        }
        if (isArray3(x3)) {
          return new Point2(x3[0], x3[1]);
        }
        if (x3 === void 0 || x3 === null) {
          return x3;
        }
        if (typeof x3 === "object" && "x" in x3 && "y" in x3) {
          return new Point2(x3.x, x3.y);
        }
        return new Point2(x3, y3, round);
      }
      function Bounds2(a3, b3) {
        if (!a3) {
          return;
        }
        var points = b3 ? [a3, b3] : a3;
        for (var i3 = 0, len = points.length; i3 < len; i3++) {
          this.extend(points[i3]);
        }
      }
      Bounds2.prototype = {
        // @method extend(point: Point): this
        // Extends the bounds to contain the given point.
        // @alternative
        // @method extend(otherBounds: Bounds): this
        // Extend the bounds to contain the given bounds
        extend: function(obj) {
          var min22, max22;
          if (!obj) {
            return this;
          }
          if (obj instanceof Point2 || typeof obj[0] === "number" || "x" in obj) {
            min22 = max22 = toPoint(obj);
          } else {
            obj = toBounds(obj);
            min22 = obj.min;
            max22 = obj.max;
            if (!min22 || !max22) {
              return this;
            }
          }
          if (!this.min && !this.max) {
            this.min = min22.clone();
            this.max = max22.clone();
          } else {
            this.min.x = Math.min(min22.x, this.min.x);
            this.max.x = Math.max(max22.x, this.max.x);
            this.min.y = Math.min(min22.y, this.min.y);
            this.max.y = Math.max(max22.y, this.max.y);
          }
          return this;
        },
        // @method getCenter(round?: Boolean): Point
        // Returns the center point of the bounds.
        getCenter: function(round) {
          return toPoint(
            (this.min.x + this.max.x) / 2,
            (this.min.y + this.max.y) / 2,
            round
          );
        },
        // @method getBottomLeft(): Point
        // Returns the bottom-left point of the bounds.
        getBottomLeft: function() {
          return toPoint(this.min.x, this.max.y);
        },
        // @method getTopRight(): Point
        // Returns the top-right point of the bounds.
        getTopRight: function() {
          return toPoint(this.max.x, this.min.y);
        },
        // @method getTopLeft(): Point
        // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
        getTopLeft: function() {
          return this.min;
        },
        // @method getBottomRight(): Point
        // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
        getBottomRight: function() {
          return this.max;
        },
        // @method getSize(): Point
        // Returns the size of the given bounds
        getSize: function() {
          return this.max.subtract(this.min);
        },
        // @method contains(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle contains the given one.
        // @alternative
        // @method contains(point: Point): Boolean
        // Returns `true` if the rectangle contains the given point.
        contains: function(obj) {
          var min3, max3;
          if (typeof obj[0] === "number" || obj instanceof Point2) {
            obj = toPoint(obj);
          } else {
            obj = toBounds(obj);
          }
          if (obj instanceof Bounds2) {
            min3 = obj.min;
            max3 = obj.max;
          } else {
            min3 = max3 = obj;
          }
          return min3.x >= this.min.x && max3.x <= this.max.x && min3.y >= this.min.y && max3.y <= this.max.y;
        },
        // @method intersects(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle intersects the given bounds. Two bounds
        // intersect if they have at least one point in common.
        intersects: function(bounds) {
          bounds = toBounds(bounds);
          var min3 = this.min, max3 = this.max, min22 = bounds.min, max22 = bounds.max, xIntersects = max22.x >= min3.x && min22.x <= max3.x, yIntersects = max22.y >= min3.y && min22.y <= max3.y;
          return xIntersects && yIntersects;
        },
        // @method overlaps(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle overlaps the given bounds. Two bounds
        // overlap if their intersection is an area.
        overlaps: function(bounds) {
          bounds = toBounds(bounds);
          var min3 = this.min, max3 = this.max, min22 = bounds.min, max22 = bounds.max, xOverlaps = max22.x > min3.x && min22.x < max3.x, yOverlaps = max22.y > min3.y && min22.y < max3.y;
          return xOverlaps && yOverlaps;
        },
        // @method isValid(): Boolean
        // Returns `true` if the bounds are properly initialized.
        isValid: function() {
          return !!(this.min && this.max);
        },
        // @method pad(bufferRatio: Number): Bounds
        // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
        // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
        // Negative values will retract the bounds.
        pad: function(bufferRatio) {
          var min3 = this.min, max3 = this.max, heightBuffer = Math.abs(min3.x - max3.x) * bufferRatio, widthBuffer = Math.abs(min3.y - max3.y) * bufferRatio;
          return toBounds(
            toPoint(min3.x - heightBuffer, min3.y - widthBuffer),
            toPoint(max3.x + heightBuffer, max3.y + widthBuffer)
          );
        },
        // @method equals(otherBounds: Bounds): Boolean
        // Returns `true` if the rectangle is equivalent to the given bounds.
        equals: function(bounds) {
          if (!bounds) {
            return false;
          }
          bounds = toBounds(bounds);
          return this.min.equals(bounds.getTopLeft()) && this.max.equals(bounds.getBottomRight());
        }
      };
      function toBounds(a3, b3) {
        if (!a3 || a3 instanceof Bounds2) {
          return a3;
        }
        return new Bounds2(a3, b3);
      }
      function LatLngBounds(corner1, corner2) {
        if (!corner1) {
          return;
        }
        var latlngs = corner2 ? [corner1, corner2] : corner1;
        for (var i3 = 0, len = latlngs.length; i3 < len; i3++) {
          this.extend(latlngs[i3]);
        }
      }
      LatLngBounds.prototype = {
        // @method extend(latlng: LatLng): this
        // Extend the bounds to contain the given point
        // @alternative
        // @method extend(otherBounds: LatLngBounds): this
        // Extend the bounds to contain the given bounds
        extend: function(obj) {
          var sw = this._southWest, ne = this._northEast, sw2, ne2;
          if (obj instanceof LatLng) {
            sw2 = obj;
            ne2 = obj;
          } else if (obj instanceof LatLngBounds) {
            sw2 = obj._southWest;
            ne2 = obj._northEast;
            if (!sw2 || !ne2) {
              return this;
            }
          } else {
            return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
          }
          if (!sw && !ne) {
            this._southWest = new LatLng(sw2.lat, sw2.lng);
            this._northEast = new LatLng(ne2.lat, ne2.lng);
          } else {
            sw.lat = Math.min(sw2.lat, sw.lat);
            sw.lng = Math.min(sw2.lng, sw.lng);
            ne.lat = Math.max(ne2.lat, ne.lat);
            ne.lng = Math.max(ne2.lng, ne.lng);
          }
          return this;
        },
        // @method pad(bufferRatio: Number): LatLngBounds
        // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
        // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
        // Negative values will retract the bounds.
        pad: function(bufferRatio) {
          var sw = this._southWest, ne = this._northEast, heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio, widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
          return new LatLngBounds(
            new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
            new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer)
          );
        },
        // @method getCenter(): LatLng
        // Returns the center point of the bounds.
        getCenter: function() {
          return new LatLng(
            (this._southWest.lat + this._northEast.lat) / 2,
            (this._southWest.lng + this._northEast.lng) / 2
          );
        },
        // @method getSouthWest(): LatLng
        // Returns the south-west point of the bounds.
        getSouthWest: function() {
          return this._southWest;
        },
        // @method getNorthEast(): LatLng
        // Returns the north-east point of the bounds.
        getNorthEast: function() {
          return this._northEast;
        },
        // @method getNorthWest(): LatLng
        // Returns the north-west point of the bounds.
        getNorthWest: function() {
          return new LatLng(this.getNorth(), this.getWest());
        },
        // @method getSouthEast(): LatLng
        // Returns the south-east point of the bounds.
        getSouthEast: function() {
          return new LatLng(this.getSouth(), this.getEast());
        },
        // @method getWest(): Number
        // Returns the west longitude of the bounds
        getWest: function() {
          return this._southWest.lng;
        },
        // @method getSouth(): Number
        // Returns the south latitude of the bounds
        getSouth: function() {
          return this._southWest.lat;
        },
        // @method getEast(): Number
        // Returns the east longitude of the bounds
        getEast: function() {
          return this._northEast.lng;
        },
        // @method getNorth(): Number
        // Returns the north latitude of the bounds
        getNorth: function() {
          return this._northEast.lat;
        },
        // @method contains(otherBounds: LatLngBounds): Boolean
        // Returns `true` if the rectangle contains the given one.
        // @alternative
        // @method contains (latlng: LatLng): Boolean
        // Returns `true` if the rectangle contains the given point.
        contains: function(obj) {
          if (typeof obj[0] === "number" || obj instanceof LatLng || "lat" in obj) {
            obj = toLatLng(obj);
          } else {
            obj = toLatLngBounds(obj);
          }
          var sw = this._southWest, ne = this._northEast, sw2, ne2;
          if (obj instanceof LatLngBounds) {
            sw2 = obj.getSouthWest();
            ne2 = obj.getNorthEast();
          } else {
            sw2 = ne2 = obj;
          }
          return sw2.lat >= sw.lat && ne2.lat <= ne.lat && sw2.lng >= sw.lng && ne2.lng <= ne.lng;
        },
        // @method intersects(otherBounds: LatLngBounds): Boolean
        // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
        intersects: function(bounds) {
          bounds = toLatLngBounds(bounds);
          var sw = this._southWest, ne = this._northEast, sw2 = bounds.getSouthWest(), ne2 = bounds.getNorthEast(), latIntersects = ne2.lat >= sw.lat && sw2.lat <= ne.lat, lngIntersects = ne2.lng >= sw.lng && sw2.lng <= ne.lng;
          return latIntersects && lngIntersects;
        },
        // @method overlaps(otherBounds: LatLngBounds): Boolean
        // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
        overlaps: function(bounds) {
          bounds = toLatLngBounds(bounds);
          var sw = this._southWest, ne = this._northEast, sw2 = bounds.getSouthWest(), ne2 = bounds.getNorthEast(), latOverlaps = ne2.lat > sw.lat && sw2.lat < ne.lat, lngOverlaps = ne2.lng > sw.lng && sw2.lng < ne.lng;
          return latOverlaps && lngOverlaps;
        },
        // @method toBBoxString(): String
        // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
        toBBoxString: function() {
          return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(",");
        },
        // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
        // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
        equals: function(bounds, maxMargin) {
          if (!bounds) {
            return false;
          }
          bounds = toLatLngBounds(bounds);
          return this._southWest.equals(bounds.getSouthWest(), maxMargin) && this._northEast.equals(bounds.getNorthEast(), maxMargin);
        },
        // @method isValid(): Boolean
        // Returns `true` if the bounds are properly initialized.
        isValid: function() {
          return !!(this._southWest && this._northEast);
        }
      };
      function toLatLngBounds(a3, b3) {
        if (a3 instanceof LatLngBounds) {
          return a3;
        }
        return new LatLngBounds(a3, b3);
      }
      function LatLng(lat, lng, alt) {
        if (isNaN(lat) || isNaN(lng)) {
          throw new Error("Invalid LatLng object: (" + lat + ", " + lng + ")");
        }
        this.lat = +lat;
        this.lng = +lng;
        if (alt !== void 0) {
          this.alt = +alt;
        }
      }
      LatLng.prototype = {
        // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
        // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
        equals: function(obj, maxMargin) {
          if (!obj) {
            return false;
          }
          obj = toLatLng(obj);
          var margin = Math.max(
            Math.abs(this.lat - obj.lat),
            Math.abs(this.lng - obj.lng)
          );
          return margin <= (maxMargin === void 0 ? 1e-9 : maxMargin);
        },
        // @method toString(): String
        // Returns a string representation of the point (for debugging purposes).
        toString: function(precision) {
          return "LatLng(" + formatNum(this.lat, precision) + ", " + formatNum(this.lng, precision) + ")";
        },
        // @method distanceTo(otherLatLng: LatLng): Number
        // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
        distanceTo: function(other) {
          return Earth.distance(this, toLatLng(other));
        },
        // @method wrap(): LatLng
        // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
        wrap: function() {
          return Earth.wrapLatLng(this);
        },
        // @method toBounds(sizeInMeters: Number): LatLngBounds
        // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
        toBounds: function(sizeInMeters) {
          var latAccuracy = 180 * sizeInMeters / 40075017, lngAccuracy = latAccuracy / Math.cos(Math.PI / 180 * this.lat);
          return toLatLngBounds(
            [this.lat - latAccuracy, this.lng - lngAccuracy],
            [this.lat + latAccuracy, this.lng + lngAccuracy]
          );
        },
        clone: function() {
          return new LatLng(this.lat, this.lng, this.alt);
        }
      };
      function toLatLng(a3, b3, c3) {
        if (a3 instanceof LatLng) {
          return a3;
        }
        if (isArray3(a3) && typeof a3[0] !== "object") {
          if (a3.length === 3) {
            return new LatLng(a3[0], a3[1], a3[2]);
          }
          if (a3.length === 2) {
            return new LatLng(a3[0], a3[1]);
          }
          return null;
        }
        if (a3 === void 0 || a3 === null) {
          return a3;
        }
        if (typeof a3 === "object" && "lat" in a3) {
          return new LatLng(a3.lat, "lng" in a3 ? a3.lng : a3.lon, a3.alt);
        }
        if (b3 === void 0) {
          return null;
        }
        return new LatLng(a3, b3, c3);
      }
      var CRS = {
        // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
        // Projects geographical coordinates into pixel coordinates for a given zoom.
        latLngToPoint: function(latlng, zoom2) {
          var projectedPoint = this.projection.project(latlng), scale2 = this.scale(zoom2);
          return this.transformation._transform(projectedPoint, scale2);
        },
        // @method pointToLatLng(point: Point, zoom: Number): LatLng
        // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
        // zoom into geographical coordinates.
        pointToLatLng: function(point, zoom2) {
          var scale2 = this.scale(zoom2), untransformedPoint = this.transformation.untransform(point, scale2);
          return this.projection.unproject(untransformedPoint);
        },
        // @method project(latlng: LatLng): Point
        // Projects geographical coordinates into coordinates in units accepted for
        // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
        project: function(latlng) {
          return this.projection.project(latlng);
        },
        // @method unproject(point: Point): LatLng
        // Given a projected coordinate returns the corresponding LatLng.
        // The inverse of `project`.
        unproject: function(point) {
          return this.projection.unproject(point);
        },
        // @method scale(zoom: Number): Number
        // Returns the scale used when transforming projected coordinates into
        // pixel coordinates for a particular zoom. For example, it returns
        // `256 * 2^zoom` for Mercator-based CRS.
        scale: function(zoom2) {
          return 256 * Math.pow(2, zoom2);
        },
        // @method zoom(scale: Number): Number
        // Inverse of `scale()`, returns the zoom level corresponding to a scale
        // factor of `scale`.
        zoom: function(scale2) {
          return Math.log(scale2 / 256) / Math.LN2;
        },
        // @method getProjectedBounds(zoom: Number): Bounds
        // Returns the projection's bounds scaled and transformed for the provided `zoom`.
        getProjectedBounds: function(zoom2) {
          if (this.infinite) {
            return null;
          }
          var b3 = this.projection.bounds, s3 = this.scale(zoom2), min3 = this.transformation.transform(b3.min, s3), max3 = this.transformation.transform(b3.max, s3);
          return new Bounds2(min3, max3);
        },
        // @method distance(latlng1: LatLng, latlng2: LatLng): Number
        // Returns the distance between two geographical coordinates.
        // @property code: String
        // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
        //
        // @property wrapLng: Number[]
        // An array of two numbers defining whether the longitude (horizontal) coordinate
        // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
        // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
        //
        // @property wrapLat: Number[]
        // Like `wrapLng`, but for the latitude (vertical) axis.
        // wrapLng: [min, max],
        // wrapLat: [min, max],
        // @property infinite: Boolean
        // If true, the coordinate space will be unbounded (infinite in both axes)
        infinite: false,
        // @method wrapLatLng(latlng: LatLng): LatLng
        // Returns a `LatLng` where lat and lng has been wrapped according to the
        // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
        wrapLatLng: function(latlng) {
          var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng, lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat, alt = latlng.alt;
          return new LatLng(lat, lng, alt);
        },
        // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
        // Returns a `LatLngBounds` with the same size as the given one, ensuring
        // that its center is within the CRS's bounds.
        // Only accepts actual `L.LatLngBounds` instances, not arrays.
        wrapLatLngBounds: function(bounds) {
          var center = bounds.getCenter(), newCenter = this.wrapLatLng(center), latShift = center.lat - newCenter.lat, lngShift = center.lng - newCenter.lng;
          if (latShift === 0 && lngShift === 0) {
            return bounds;
          }
          var sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift), newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
          return new LatLngBounds(newSw, newNe);
        }
      };
      var Earth = extend({}, CRS, {
        wrapLng: [-180, 180],
        // Mean Earth Radius, as recommended for use by
        // the International Union of Geodesy and Geophysics,
        // see https://rosettacode.org/wiki/Haversine_formula
        R: 6371e3,
        // distance between two geographical points using spherical law of cosines approximation
        distance: function(latlng1, latlng2) {
          var rad = Math.PI / 180, lat1 = latlng1.lat * rad, lat2 = latlng2.lat * rad, sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2), sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2), a3 = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon, c3 = 2 * Math.atan2(Math.sqrt(a3), Math.sqrt(1 - a3));
          return this.R * c3;
        }
      });
      var earthRadius = 6378137;
      var SphericalMercator = {
        R: earthRadius,
        MAX_LATITUDE: 85.0511287798,
        project: function(latlng) {
          var d3 = Math.PI / 180, max3 = this.MAX_LATITUDE, lat = Math.max(Math.min(max3, latlng.lat), -max3), sin = Math.sin(lat * d3);
          return new Point2(
            this.R * latlng.lng * d3,
            this.R * Math.log((1 + sin) / (1 - sin)) / 2
          );
        },
        unproject: function(point) {
          var d3 = 180 / Math.PI;
          return new LatLng(
            (2 * Math.atan(Math.exp(point.y / this.R)) - Math.PI / 2) * d3,
            point.x * d3 / this.R
          );
        },
        bounds: function() {
          var d3 = earthRadius * Math.PI;
          return new Bounds2([-d3, -d3], [d3, d3]);
        }()
      };
      function Transformation(a3, b3, c3, d3) {
        if (isArray3(a3)) {
          this._a = a3[0];
          this._b = a3[1];
          this._c = a3[2];
          this._d = a3[3];
          return;
        }
        this._a = a3;
        this._b = b3;
        this._c = c3;
        this._d = d3;
      }
      Transformation.prototype = {
        // @method transform(point: Point, scale?: Number): Point
        // Returns a transformed point, optionally multiplied by the given scale.
        // Only accepts actual `L.Point` instances, not arrays.
        transform: function(point, scale2) {
          return this._transform(point.clone(), scale2);
        },
        // destructive transform (faster)
        _transform: function(point, scale2) {
          scale2 = scale2 || 1;
          point.x = scale2 * (this._a * point.x + this._b);
          point.y = scale2 * (this._c * point.y + this._d);
          return point;
        },
        // @method untransform(point: Point, scale?: Number): Point
        // Returns the reverse transformation of the given point, optionally divided
        // by the given scale. Only accepts actual `L.Point` instances, not arrays.
        untransform: function(point, scale2) {
          scale2 = scale2 || 1;
          return new Point2(
            (point.x / scale2 - this._b) / this._a,
            (point.y / scale2 - this._d) / this._c
          );
        }
      };
      function toTransformation(a3, b3, c3, d3) {
        return new Transformation(a3, b3, c3, d3);
      }
      var EPSG3857 = extend({}, Earth, {
        code: "EPSG:3857",
        projection: SphericalMercator,
        transformation: function() {
          var scale2 = 0.5 / (Math.PI * SphericalMercator.R);
          return toTransformation(scale2, 0.5, -scale2, 0.5);
        }()
      });
      var EPSG900913 = extend({}, EPSG3857, {
        code: "EPSG:900913"
      });
      function svgCreate(name2) {
        return document.createElementNS("http://www.w3.org/2000/svg", name2);
      }
      function pointsToPath(rings, closed) {
        var str = "", i3, j, len, len2, points, p4;
        for (i3 = 0, len = rings.length; i3 < len; i3++) {
          points = rings[i3];
          for (j = 0, len2 = points.length; j < len2; j++) {
            p4 = points[j];
            str += (j ? "L" : "M") + p4.x + " " + p4.y;
          }
          str += closed ? Browser.svg ? "z" : "x" : "";
        }
        return str || "M0 0";
      }
      var style3 = document.documentElement.style;
      var ie4 = "ActiveXObject" in window;
      var ielt9 = ie4 && !document.addEventListener;
      var edge = "msLaunchUri" in navigator && !("documentMode" in document);
      var webkit3 = userAgentContains("webkit");
      var android3 = userAgentContains("android");
      var android23 = userAgentContains("android 2") || userAgentContains("android 3");
      var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10);
      var androidStock = android3 && userAgentContains("Google") && webkitVer < 537 && !("AudioNode" in window);
      var opera = !!window.opera;
      var chrome4 = !edge && userAgentContains("chrome");
      var gecko4 = userAgentContains("gecko") && !webkit3 && !opera && !ie4;
      var safari3 = !chrome4 && userAgentContains("safari");
      var phantom = userAgentContains("phantom");
      var opera12 = "OTransition" in style3;
      var win = navigator.platform.indexOf("Win") === 0;
      var ie3d = ie4 && "transition" in style3;
      var webkit3d = "WebKitCSSMatrix" in window && "m11" in new window.WebKitCSSMatrix() && !android23;
      var gecko3d = "MozPerspective" in style3;
      var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
      var mobile = typeof orientation !== "undefined" || userAgentContains("mobile");
      var mobileWebkit = mobile && webkit3;
      var mobileWebkit3d = mobile && webkit3d;
      var msPointer = !window.PointerEvent && window.MSPointerEvent;
      var pointer = !!(window.PointerEvent || msPointer);
      var touchNative = "ontouchstart" in window || !!window.TouchEvent;
      var touch = !window.L_NO_TOUCH && (touchNative || pointer);
      var mobileOpera = mobile && opera;
      var mobileGecko = mobile && gecko4;
      var retina = (window.devicePixelRatio || window.screen.deviceXDPI / window.screen.logicalXDPI) > 1;
      var passiveEvents = function() {
        var supportsPassiveOption = false;
        try {
          var opts = Object.defineProperty({}, "passive", {
            get: function() {
              supportsPassiveOption = true;
            }
          });
          window.addEventListener("testPassiveEventSupport", falseFn2, opts);
          window.removeEventListener("testPassiveEventSupport", falseFn2, opts);
        } catch (e3) {
        }
        return supportsPassiveOption;
      }();
      var canvas$1 = function() {
        return !!document.createElement("canvas").getContext;
      }();
      var svg$1 = !!(document.createElementNS && svgCreate("svg").createSVGRect);
      var inlineSvg = !!svg$1 && function() {
        var div = document.createElement("div");
        div.innerHTML = "<svg/>";
        return (div.firstChild && div.firstChild.namespaceURI) === "http://www.w3.org/2000/svg";
      }();
      var vml = !svg$1 && function() {
        try {
          var div = document.createElement("div");
          div.innerHTML = '<v:shape adj="1"/>';
          var shape = div.firstChild;
          shape.style.behavior = "url(#default#VML)";
          return shape && typeof shape.adj === "object";
        } catch (e3) {
          return false;
        }
      }();
      var mac6 = navigator.platform.indexOf("Mac") === 0;
      var linux = navigator.platform.indexOf("Linux") === 0;
      function userAgentContains(str) {
        return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
      }
      var Browser = {
        ie: ie4,
        ielt9,
        edge,
        webkit: webkit3,
        android: android3,
        android23,
        androidStock,
        opera,
        chrome: chrome4,
        gecko: gecko4,
        safari: safari3,
        phantom,
        opera12,
        win,
        ie3d,
        webkit3d,
        gecko3d,
        any3d,
        mobile,
        mobileWebkit,
        mobileWebkit3d,
        msPointer,
        pointer,
        touch,
        touchNative,
        mobileOpera,
        mobileGecko,
        retina,
        passiveEvents,
        canvas: canvas$1,
        svg: svg$1,
        vml,
        inlineSvg,
        mac: mac6,
        linux
      };
      var POINTER_DOWN = Browser.msPointer ? "MSPointerDown" : "pointerdown";
      var POINTER_MOVE = Browser.msPointer ? "MSPointerMove" : "pointermove";
      var POINTER_UP = Browser.msPointer ? "MSPointerUp" : "pointerup";
      var POINTER_CANCEL = Browser.msPointer ? "MSPointerCancel" : "pointercancel";
      var pEvent = {
        touchstart: POINTER_DOWN,
        touchmove: POINTER_MOVE,
        touchend: POINTER_UP,
        touchcancel: POINTER_CANCEL
      };
      var handle2 = {
        touchstart: _onPointerStart,
        touchmove: _handlePointer,
        touchend: _handlePointer,
        touchcancel: _handlePointer
      };
      var _pointers = {};
      var _pointerDocListener = false;
      function addPointerListener(obj, type, handler) {
        if (type === "touchstart") {
          _addPointerDocListener();
        }
        if (!handle2[type]) {
          console.warn("wrong event specified:", type);
          return falseFn2;
        }
        handler = handle2[type].bind(this, handler);
        obj.addEventListener(pEvent[type], handler, false);
        return handler;
      }
      function removePointerListener(obj, type, handler) {
        if (!pEvent[type]) {
          console.warn("wrong event specified:", type);
          return;
        }
        obj.removeEventListener(pEvent[type], handler, false);
      }
      function _globalPointerDown(e3) {
        _pointers[e3.pointerId] = e3;
      }
      function _globalPointerMove(e3) {
        if (_pointers[e3.pointerId]) {
          _pointers[e3.pointerId] = e3;
        }
      }
      function _globalPointerUp(e3) {
        delete _pointers[e3.pointerId];
      }
      function _addPointerDocListener() {
        if (!_pointerDocListener) {
          document.addEventListener(POINTER_DOWN, _globalPointerDown, true);
          document.addEventListener(POINTER_MOVE, _globalPointerMove, true);
          document.addEventListener(POINTER_UP, _globalPointerUp, true);
          document.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
          _pointerDocListener = true;
        }
      }
      function _handlePointer(handler, e3) {
        if (e3.pointerType === (e3.MSPOINTER_TYPE_MOUSE || "mouse")) {
          return;
        }
        e3.touches = [];
        for (var i3 in _pointers) {
          e3.touches.push(_pointers[i3]);
        }
        e3.changedTouches = [e3];
        handler(e3);
      }
      function _onPointerStart(handler, e3) {
        if (e3.MSPOINTER_TYPE_TOUCH && e3.pointerType === e3.MSPOINTER_TYPE_TOUCH) {
          preventDefault(e3);
        }
        _handlePointer(handler, e3);
      }
      function makeDblclick(event2) {
        var newEvent = {}, prop2, i3;
        for (i3 in event2) {
          prop2 = event2[i3];
          newEvent[i3] = prop2 && prop2.bind ? prop2.bind(event2) : prop2;
        }
        event2 = newEvent;
        newEvent.type = "dblclick";
        newEvent.detail = 2;
        newEvent.isTrusted = false;
        newEvent._simulated = true;
        return newEvent;
      }
      var delay = 200;
      function addDoubleTapListener(obj, handler) {
        obj.addEventListener("dblclick", handler);
        var last3 = 0, detail;
        function simDblclick(e3) {
          if (e3.detail !== 1) {
            detail = e3.detail;
            return;
          }
          if (e3.pointerType === "mouse" || e3.sourceCapabilities && !e3.sourceCapabilities.firesTouchEvents) {
            return;
          }
          var path = getPropagationPath(e3);
          if (path.some(function(el2) {
            return el2 instanceof HTMLLabelElement && el2.attributes.for;
          }) && !path.some(function(el2) {
            return el2 instanceof HTMLInputElement || el2 instanceof HTMLSelectElement;
          })) {
            return;
          }
          var now = Date.now();
          if (now - last3 <= delay) {
            detail++;
            if (detail === 2) {
              handler(makeDblclick(e3));
            }
          } else {
            detail = 1;
          }
          last3 = now;
        }
        obj.addEventListener("click", simDblclick);
        return {
          dblclick: handler,
          simDblclick
        };
      }
      function removeDoubleTapListener(obj, handlers3) {
        obj.removeEventListener("dblclick", handlers3.dblclick);
        obj.removeEventListener("click", handlers3.simDblclick);
      }
      var TRANSFORM = testProp(
        ["transform", "webkitTransform", "OTransform", "MozTransform", "msTransform"]
      );
      var TRANSITION = testProp(
        ["webkitTransition", "transition", "OTransition", "MozTransition", "msTransition"]
      );
      var TRANSITION_END = TRANSITION === "webkitTransition" || TRANSITION === "OTransition" ? TRANSITION + "End" : "transitionend";
      function get7(id) {
        return typeof id === "string" ? document.getElementById(id) : id;
      }
      function getStyle(el2, style4) {
        var value2 = el2.style[style4] || el2.currentStyle && el2.currentStyle[style4];
        if ((!value2 || value2 === "auto") && document.defaultView) {
          var css = document.defaultView.getComputedStyle(el2, null);
          value2 = css ? css[style4] : null;
        }
        return value2 === "auto" ? null : value2;
      }
      function create$1(tagName, className2, container) {
        var el2 = document.createElement(tagName);
        el2.className = className2 || "";
        if (container) {
          container.appendChild(el2);
        }
        return el2;
      }
      function remove3(el2) {
        var parent = el2.parentNode;
        if (parent) {
          parent.removeChild(el2);
        }
      }
      function empty4(el2) {
        while (el2.firstChild) {
          el2.removeChild(el2.firstChild);
        }
      }
      function toFront(el2) {
        var parent = el2.parentNode;
        if (parent && parent.lastChild !== el2) {
          parent.appendChild(el2);
        }
      }
      function toBack(el2) {
        var parent = el2.parentNode;
        if (parent && parent.firstChild !== el2) {
          parent.insertBefore(el2, parent.firstChild);
        }
      }
      function hasClass(el2, name2) {
        if (el2.classList !== void 0) {
          return el2.classList.contains(name2);
        }
        var className2 = getClass(el2);
        return className2.length > 0 && new RegExp("(^|\\s)" + name2 + "(\\s|$)").test(className2);
      }
      function addClass(el2, name2) {
        if (el2.classList !== void 0) {
          var classes = splitWords(name2);
          for (var i3 = 0, len = classes.length; i3 < len; i3++) {
            el2.classList.add(classes[i3]);
          }
        } else if (!hasClass(el2, name2)) {
          var className2 = getClass(el2);
          setClass3(el2, (className2 ? className2 + " " : "") + name2);
        }
      }
      function removeClass(el2, name2) {
        if (el2.classList !== void 0) {
          el2.classList.remove(name2);
        } else {
          setClass3(el2, trim((" " + getClass(el2) + " ").replace(" " + name2 + " ", " ")));
        }
      }
      function setClass3(el2, name2) {
        if (el2.className.baseVal === void 0) {
          el2.className = name2;
        } else {
          el2.className.baseVal = name2;
        }
      }
      function getClass(el2) {
        if (el2.correspondingElement) {
          el2 = el2.correspondingElement;
        }
        return el2.className.baseVal === void 0 ? el2.className : el2.className.baseVal;
      }
      function setOpacity(el2, value2) {
        if ("opacity" in el2.style) {
          el2.style.opacity = value2;
        } else if ("filter" in el2.style) {
          _setOpacityIE(el2, value2);
        }
      }
      function _setOpacityIE(el2, value2) {
        var filter4 = false, filterName = "DXImageTransform.Microsoft.Alpha";
        try {
          filter4 = el2.filters.item(filterName);
        } catch (e3) {
          if (value2 === 1) {
            return;
          }
        }
        value2 = Math.round(value2 * 100);
        if (filter4) {
          filter4.Enabled = value2 !== 100;
          filter4.Opacity = value2;
        } else {
          el2.style.filter += " progid:" + filterName + "(opacity=" + value2 + ")";
        }
      }
      function testProp(props2) {
        var style4 = document.documentElement.style;
        for (var i3 = 0; i3 < props2.length; i3++) {
          if (props2[i3] in style4) {
            return props2[i3];
          }
        }
        return false;
      }
      function setTransform(el2, offset, scale2) {
        var pos = offset || new Point2(0, 0);
        el2.style[TRANSFORM] = (Browser.ie3d ? "translate(" + pos.x + "px," + pos.y + "px)" : "translate3d(" + pos.x + "px," + pos.y + "px,0)") + (scale2 ? " scale(" + scale2 + ")" : "");
      }
      function setPosition(el2, point) {
        el2._leaflet_pos = point;
        if (Browser.any3d) {
          setTransform(el2, point);
        } else {
          el2.style.left = point.x + "px";
          el2.style.top = point.y + "px";
        }
      }
      function getPosition(el2) {
        return el2._leaflet_pos || new Point2(0, 0);
      }
      var disableTextSelection;
      var enableTextSelection;
      var _userSelect;
      if ("onselectstart" in document) {
        disableTextSelection = function() {
          on2(window, "selectstart", preventDefault);
        };
        enableTextSelection = function() {
          off(window, "selectstart", preventDefault);
        };
      } else {
        var userSelectProperty = testProp(
          ["userSelect", "WebkitUserSelect", "OUserSelect", "MozUserSelect", "msUserSelect"]
        );
        disableTextSelection = function() {
          if (userSelectProperty) {
            var style4 = document.documentElement.style;
            _userSelect = style4[userSelectProperty];
            style4[userSelectProperty] = "none";
          }
        };
        enableTextSelection = function() {
          if (userSelectProperty) {
            document.documentElement.style[userSelectProperty] = _userSelect;
            _userSelect = void 0;
          }
        };
      }
      function disableImageDrag() {
        on2(window, "dragstart", preventDefault);
      }
      function enableImageDrag() {
        off(window, "dragstart", preventDefault);
      }
      var _outlineElement, _outlineStyle;
      function preventOutline(element2) {
        while (element2.tabIndex === -1) {
          element2 = element2.parentNode;
        }
        if (!element2.style) {
          return;
        }
        restoreOutline();
        _outlineElement = element2;
        _outlineStyle = element2.style.outlineStyle;
        element2.style.outlineStyle = "none";
        on2(window, "keydown", restoreOutline);
      }
      function restoreOutline() {
        if (!_outlineElement) {
          return;
        }
        _outlineElement.style.outlineStyle = _outlineStyle;
        _outlineElement = void 0;
        _outlineStyle = void 0;
        off(window, "keydown", restoreOutline);
      }
      function getSizedParentNode(element2) {
        do {
          element2 = element2.parentNode;
        } while ((!element2.offsetWidth || !element2.offsetHeight) && element2 !== document.body);
        return element2;
      }
      function getScale2(element2) {
        var rect = element2.getBoundingClientRect();
        return {
          x: rect.width / element2.offsetWidth || 1,
          y: rect.height / element2.offsetHeight || 1,
          boundingClientRect: rect
        };
      }
      var DomUtil = {
        __proto__: null,
        TRANSFORM,
        TRANSITION,
        TRANSITION_END,
        get: get7,
        getStyle,
        create: create$1,
        remove: remove3,
        empty: empty4,
        toFront,
        toBack,
        hasClass,
        addClass,
        removeClass,
        setClass: setClass3,
        getClass,
        setOpacity,
        testProp,
        setTransform,
        setPosition,
        getPosition,
        get disableTextSelection() {
          return disableTextSelection;
        },
        get enableTextSelection() {
          return enableTextSelection;
        },
        disableImageDrag,
        enableImageDrag,
        preventOutline,
        restoreOutline,
        getSizedParentNode,
        getScale: getScale2
      };
      function on2(obj, types2, fn, context) {
        if (types2 && typeof types2 === "object") {
          for (var type in types2) {
            addOne(obj, type, types2[type], fn);
          }
        } else {
          types2 = splitWords(types2);
          for (var i3 = 0, len = types2.length; i3 < len; i3++) {
            addOne(obj, types2[i3], fn, context);
          }
        }
        return this;
      }
      var eventsKey = "_leaflet_events";
      function off(obj, types2, fn, context) {
        if (arguments.length === 1) {
          batchRemove(obj);
          delete obj[eventsKey];
        } else if (types2 && typeof types2 === "object") {
          for (var type in types2) {
            removeOne(obj, type, types2[type], fn);
          }
        } else {
          types2 = splitWords(types2);
          if (arguments.length === 2) {
            batchRemove(obj, function(type2) {
              return indexOf(types2, type2) !== -1;
            });
          } else {
            for (var i3 = 0, len = types2.length; i3 < len; i3++) {
              removeOne(obj, types2[i3], fn, context);
            }
          }
        }
        return this;
      }
      function batchRemove(obj, filterFn) {
        for (var id in obj[eventsKey]) {
          var type = id.split(/\d/)[0];
          if (!filterFn || filterFn(type)) {
            removeOne(obj, type, null, null, id);
          }
        }
      }
      var mouseSubst = {
        mouseenter: "mouseover",
        mouseleave: "mouseout",
        wheel: !("onwheel" in window) && "mousewheel"
      };
      function addOne(obj, type, fn, context) {
        var id = type + stamp(fn) + (context ? "_" + stamp(context) : "");
        if (obj[eventsKey] && obj[eventsKey][id]) {
          return this;
        }
        var handler = function(e3) {
          return fn.call(context || obj, e3 || window.event);
        };
        var originalHandler = handler;
        if (!Browser.touchNative && Browser.pointer && type.indexOf("touch") === 0) {
          handler = addPointerListener(obj, type, handler);
        } else if (Browser.touch && type === "dblclick") {
          handler = addDoubleTapListener(obj, handler);
        } else if ("addEventListener" in obj) {
          if (type === "touchstart" || type === "touchmove" || type === "wheel" || type === "mousewheel") {
            obj.addEventListener(mouseSubst[type] || type, handler, Browser.passiveEvents ? { passive: false } : false);
          } else if (type === "mouseenter" || type === "mouseleave") {
            handler = function(e3) {
              e3 = e3 || window.event;
              if (isExternalTarget(obj, e3)) {
                originalHandler(e3);
              }
            };
            obj.addEventListener(mouseSubst[type], handler, false);
          } else {
            obj.addEventListener(type, originalHandler, false);
          }
        } else {
          obj.attachEvent("on" + type, handler);
        }
        obj[eventsKey] = obj[eventsKey] || {};
        obj[eventsKey][id] = handler;
      }
      function removeOne(obj, type, fn, context, id) {
        id = id || type + stamp(fn) + (context ? "_" + stamp(context) : "");
        var handler = obj[eventsKey] && obj[eventsKey][id];
        if (!handler) {
          return this;
        }
        if (!Browser.touchNative && Browser.pointer && type.indexOf("touch") === 0) {
          removePointerListener(obj, type, handler);
        } else if (Browser.touch && type === "dblclick") {
          removeDoubleTapListener(obj, handler);
        } else if ("removeEventListener" in obj) {
          obj.removeEventListener(mouseSubst[type] || type, handler, false);
        } else {
          obj.detachEvent("on" + type, handler);
        }
        obj[eventsKey][id] = null;
      }
      function stopPropagation(e3) {
        if (e3.stopPropagation) {
          e3.stopPropagation();
        } else if (e3.originalEvent) {
          e3.originalEvent._stopped = true;
        } else {
          e3.cancelBubble = true;
        }
        return this;
      }
      function disableScrollPropagation(el2) {
        addOne(el2, "wheel", stopPropagation);
        return this;
      }
      function disableClickPropagation(el2) {
        on2(el2, "mousedown touchstart dblclick contextmenu", stopPropagation);
        el2["_leaflet_disable_click"] = true;
        return this;
      }
      function preventDefault(e3) {
        if (e3.preventDefault) {
          e3.preventDefault();
        } else {
          e3.returnValue = false;
        }
        return this;
      }
      function stop(e3) {
        preventDefault(e3);
        stopPropagation(e3);
        return this;
      }
      function getPropagationPath(ev) {
        if (ev.composedPath) {
          return ev.composedPath();
        }
        var path = [];
        var el2 = ev.target;
        while (el2) {
          path.push(el2);
          el2 = el2.parentNode;
        }
        return path;
      }
      function getMousePosition(e3, container) {
        if (!container) {
          return new Point2(e3.clientX, e3.clientY);
        }
        var scale2 = getScale2(container), offset = scale2.boundingClientRect;
        return new Point2(
          // offset.left/top values are in page scale (like clientX/Y),
          // whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).
          (e3.clientX - offset.left) / scale2.x - container.clientLeft,
          (e3.clientY - offset.top) / scale2.y - container.clientTop
        );
      }
      var wheelPxFactor = Browser.linux && Browser.chrome ? window.devicePixelRatio : Browser.mac ? window.devicePixelRatio * 3 : window.devicePixelRatio > 0 ? 2 * window.devicePixelRatio : 1;
      function getWheelDelta(e3) {
        return Browser.edge ? e3.wheelDeltaY / 2 : (
          // Don't trust window-geometry-based delta
          e3.deltaY && e3.deltaMode === 0 ? -e3.deltaY / wheelPxFactor : (
            // Pixels
            e3.deltaY && e3.deltaMode === 1 ? -e3.deltaY * 20 : (
              // Lines
              e3.deltaY && e3.deltaMode === 2 ? -e3.deltaY * 60 : (
                // Pages
                e3.deltaX || e3.deltaZ ? 0 : (
                  // Skip horizontal/depth wheel events
                  e3.wheelDelta ? (e3.wheelDeltaY || e3.wheelDelta) / 2 : (
                    // Legacy IE pixels
                    e3.detail && Math.abs(e3.detail) < 32765 ? -e3.detail * 20 : (
                      // Legacy Moz lines
                      e3.detail ? e3.detail / -32765 * 60 : (
                        // Legacy Moz pages
                        0
                      )
                    )
                  )
                )
              )
            )
          )
        );
      }
      function isExternalTarget(el2, e3) {
        var related = e3.relatedTarget;
        if (!related) {
          return true;
        }
        try {
          while (related && related !== el2) {
            related = related.parentNode;
          }
        } catch (err) {
          return false;
        }
        return related !== el2;
      }
      var DomEvent = {
        __proto__: null,
        on: on2,
        off,
        stopPropagation,
        disableScrollPropagation,
        disableClickPropagation,
        preventDefault,
        stop,
        getPropagationPath,
        getMousePosition,
        getWheelDelta,
        isExternalTarget,
        addListener: on2,
        removeListener: off
      };
      var PosAnimation = Evented.extend({
        // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
        // Run an animation of a given element to a new position, optionally setting
        // duration in seconds (`0.25` by default) and easing linearity factor (3rd
        // argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
        // `0.5` by default).
        run: function(el2, newPos, duration, easeLinearity) {
          this.stop();
          this._el = el2;
          this._inProgress = true;
          this._duration = duration || 0.25;
          this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
          this._startPos = getPosition(el2);
          this._offset = newPos.subtract(this._startPos);
          this._startTime = +/* @__PURE__ */ new Date();
          this.fire("start");
          this._animate();
        },
        // @method stop()
        // Stops the animation (if currently running).
        stop: function() {
          if (!this._inProgress) {
            return;
          }
          this._step(true);
          this._complete();
        },
        _animate: function() {
          this._animId = requestAnimFrame(this._animate, this);
          this._step();
        },
        _step: function(round) {
          var elapsed = +/* @__PURE__ */ new Date() - this._startTime, duration = this._duration * 1e3;
          if (elapsed < duration) {
            this._runFrame(this._easeOut(elapsed / duration), round);
          } else {
            this._runFrame(1);
            this._complete();
          }
        },
        _runFrame: function(progress2, round) {
          var pos = this._startPos.add(this._offset.multiplyBy(progress2));
          if (round) {
            pos._round();
          }
          setPosition(this._el, pos);
          this.fire("step");
        },
        _complete: function() {
          cancelAnimFrame(this._animId);
          this._inProgress = false;
          this.fire("end");
        },
        _easeOut: function(t3) {
          return 1 - Math.pow(1 - t3, this._easeOutPower);
        }
      });
      var Map2 = Evented.extend({
        options: {
          // @section Map State Options
          // @option crs: CRS = L.CRS.EPSG3857
          // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
          // sure what it means.
          crs: EPSG3857,
          // @option center: LatLng = undefined
          // Initial geographic center of the map
          center: void 0,
          // @option zoom: Number = undefined
          // Initial map zoom level
          zoom: void 0,
          // @option minZoom: Number = *
          // Minimum zoom level of the map.
          // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
          // the lowest of their `minZoom` options will be used instead.
          minZoom: void 0,
          // @option maxZoom: Number = *
          // Maximum zoom level of the map.
          // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
          // the highest of their `maxZoom` options will be used instead.
          maxZoom: void 0,
          // @option layers: Layer[] = []
          // Array of layers that will be added to the map initially
          layers: [],
          // @option maxBounds: LatLngBounds = null
          // When this option is set, the map restricts the view to the given
          // geographical bounds, bouncing the user back if the user tries to pan
          // outside the view. To set the restriction dynamically, use
          // [`setMaxBounds`](#map-setmaxbounds) method.
          maxBounds: void 0,
          // @option renderer: Renderer = *
          // The default method for drawing vector layers on the map. `L.SVG`
          // or `L.Canvas` by default depending on browser support.
          renderer: void 0,
          // @section Animation Options
          // @option zoomAnimation: Boolean = true
          // Whether the map zoom animation is enabled. By default it's enabled
          // in all browsers that support CSS3 Transitions except Android.
          zoomAnimation: true,
          // @option zoomAnimationThreshold: Number = 4
          // Won't animate zoom if the zoom difference exceeds this value.
          zoomAnimationThreshold: 4,
          // @option fadeAnimation: Boolean = true
          // Whether the tile fade animation is enabled. By default it's enabled
          // in all browsers that support CSS3 Transitions except Android.
          fadeAnimation: true,
          // @option markerZoomAnimation: Boolean = true
          // Whether markers animate their zoom with the zoom animation, if disabled
          // they will disappear for the length of the animation. By default it's
          // enabled in all browsers that support CSS3 Transitions except Android.
          markerZoomAnimation: true,
          // @option transform3DLimit: Number = 2^23
          // Defines the maximum size of a CSS translation transform. The default
          // value should not be changed unless a web browser positions layers in
          // the wrong place after doing a large `panBy`.
          transform3DLimit: 8388608,
          // Precision limit of a 32-bit float
          // @section Interaction Options
          // @option zoomSnap: Number = 1
          // Forces the map's zoom level to always be a multiple of this, particularly
          // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
          // By default, the zoom level snaps to the nearest integer; lower values
          // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
          // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
          zoomSnap: 1,
          // @option zoomDelta: Number = 1
          // Controls how much the map's zoom level will change after a
          // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
          // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
          // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
          zoomDelta: 1,
          // @option trackResize: Boolean = true
          // Whether the map automatically handles browser window resize to update itself.
          trackResize: true
        },
        initialize: function(id, options2) {
          options2 = setOptions2(this, options2);
          this._handlers = [];
          this._layers = {};
          this._zoomBoundLayers = {};
          this._sizeChanged = true;
          this._initContainer(id);
          this._initLayout();
          this._onResize = bind2(this._onResize, this);
          this._initEvents();
          if (options2.maxBounds) {
            this.setMaxBounds(options2.maxBounds);
          }
          if (options2.zoom !== void 0) {
            this._zoom = this._limitZoom(options2.zoom);
          }
          if (options2.center && options2.zoom !== void 0) {
            this.setView(toLatLng(options2.center), options2.zoom, { reset: true });
          }
          this.callInitHooks();
          this._zoomAnimated = TRANSITION && Browser.any3d && !Browser.mobileOpera && this.options.zoomAnimation;
          if (this._zoomAnimated) {
            this._createAnimProxy();
            on2(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
          }
          this._addLayers(this.options.layers);
        },
        // @section Methods for modifying map state
        // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
        // Sets the view of the map (geographical center and zoom) with the given
        // animation options.
        setView: function(center, zoom2, options2) {
          zoom2 = zoom2 === void 0 ? this._zoom : this._limitZoom(zoom2);
          center = this._limitCenter(toLatLng(center), zoom2, this.options.maxBounds);
          options2 = options2 || {};
          this._stop();
          if (this._loaded && !options2.reset && options2 !== true) {
            if (options2.animate !== void 0) {
              options2.zoom = extend({ animate: options2.animate }, options2.zoom);
              options2.pan = extend({ animate: options2.animate, duration: options2.duration }, options2.pan);
            }
            var moved = this._zoom !== zoom2 ? this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom2, options2.zoom) : this._tryAnimatedPan(center, options2.pan);
            if (moved) {
              clearTimeout(this._sizeTimer);
              return this;
            }
          }
          this._resetView(center, zoom2, options2.pan && options2.pan.noMoveStart);
          return this;
        },
        // @method setZoom(zoom: Number, options?: Zoom/pan options): this
        // Sets the zoom of the map.
        setZoom: function(zoom2, options2) {
          if (!this._loaded) {
            this._zoom = zoom2;
            return this;
          }
          return this.setView(this.getCenter(), zoom2, { zoom: options2 });
        },
        // @method zoomIn(delta?: Number, options?: Zoom options): this
        // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
        zoomIn: function(delta, options2) {
          delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
          return this.setZoom(this._zoom + delta, options2);
        },
        // @method zoomOut(delta?: Number, options?: Zoom options): this
        // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
        zoomOut: function(delta, options2) {
          delta = delta || (Browser.any3d ? this.options.zoomDelta : 1);
          return this.setZoom(this._zoom - delta, options2);
        },
        // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
        // Zooms the map while keeping a specified geographical point on the map
        // stationary (e.g. used internally for scroll zoom and double-click zoom).
        // @alternative
        // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
        // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
        setZoomAround: function(latlng, zoom2, options2) {
          var scale2 = this.getZoomScale(zoom2), viewHalf = this.getSize().divideBy(2), containerPoint = latlng instanceof Point2 ? latlng : this.latLngToContainerPoint(latlng), centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale2), newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
          return this.setView(newCenter, zoom2, { zoom: options2 });
        },
        _getBoundsCenterZoom: function(bounds, options2) {
          options2 = options2 || {};
          bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
          var paddingTL = toPoint(options2.paddingTopLeft || options2.padding || [0, 0]), paddingBR = toPoint(options2.paddingBottomRight || options2.padding || [0, 0]), zoom2 = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
          zoom2 = typeof options2.maxZoom === "number" ? Math.min(options2.maxZoom, zoom2) : zoom2;
          if (zoom2 === Infinity) {
            return {
              center: bounds.getCenter(),
              zoom: zoom2
            };
          }
          var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2), swPoint = this.project(bounds.getSouthWest(), zoom2), nePoint = this.project(bounds.getNorthEast(), zoom2), center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom2);
          return {
            center,
            zoom: zoom2
          };
        },
        // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
        // Sets a map view that contains the given geographical bounds with the
        // maximum zoom level possible.
        fitBounds: function(bounds, options2) {
          bounds = toLatLngBounds(bounds);
          if (!bounds.isValid()) {
            throw new Error("Bounds are not valid.");
          }
          var target = this._getBoundsCenterZoom(bounds, options2);
          return this.setView(target.center, target.zoom, options2);
        },
        // @method fitWorld(options?: fitBounds options): this
        // Sets a map view that mostly contains the whole world with the maximum
        // zoom level possible.
        fitWorld: function(options2) {
          return this.fitBounds([[-90, -180], [90, 180]], options2);
        },
        // @method panTo(latlng: LatLng, options?: Pan options): this
        // Pans the map to a given center.
        panTo: function(center, options2) {
          return this.setView(center, this._zoom, { pan: options2 });
        },
        // @method panBy(offset: Point, options?: Pan options): this
        // Pans the map by a given number of pixels (animated).
        panBy: function(offset, options2) {
          offset = toPoint(offset).round();
          options2 = options2 || {};
          if (!offset.x && !offset.y) {
            return this.fire("moveend");
          }
          if (options2.animate !== true && !this.getSize().contains(offset)) {
            this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
            return this;
          }
          if (!this._panAnim) {
            this._panAnim = new PosAnimation();
            this._panAnim.on({
              "step": this._onPanTransitionStep,
              "end": this._onPanTransitionEnd
            }, this);
          }
          if (!options2.noMoveStart) {
            this.fire("movestart");
          }
          if (options2.animate !== false) {
            addClass(this._mapPane, "leaflet-pan-anim");
            var newPos = this._getMapPanePos().subtract(offset).round();
            this._panAnim.run(this._mapPane, newPos, options2.duration || 0.25, options2.easeLinearity);
          } else {
            this._rawPanBy(offset);
            this.fire("move").fire("moveend");
          }
          return this;
        },
        // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
        // Sets the view of the map (geographical center and zoom) performing a smooth
        // pan-zoom animation.
        flyTo: function(targetCenter, targetZoom, options2) {
          options2 = options2 || {};
          if (options2.animate === false || !Browser.any3d) {
            return this.setView(targetCenter, targetZoom, options2);
          }
          this._stop();
          var from2 = this.project(this.getCenter()), to = this.project(targetCenter), size4 = this.getSize(), startZoom = this._zoom;
          targetCenter = toLatLng(targetCenter);
          targetZoom = targetZoom === void 0 ? startZoom : targetZoom;
          var w0 = Math.max(size4.x, size4.y), w1 = w0 * this.getZoomScale(startZoom, targetZoom), u1 = to.distanceTo(from2) || 1, rho = 1.42, rho2 = rho * rho;
          function r3(i3) {
            var s1 = i3 ? -1 : 1, s22 = i3 ? w1 : w0, t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1, b1 = 2 * s22 * rho2 * u1, b3 = t1 / b1, sq = Math.sqrt(b3 * b3 + 1) - b3;
            var log2 = sq < 1e-9 ? -18 : Math.log(sq);
            return log2;
          }
          function sinh(n4) {
            return (Math.exp(n4) - Math.exp(-n4)) / 2;
          }
          function cosh(n4) {
            return (Math.exp(n4) + Math.exp(-n4)) / 2;
          }
          function tanh(n4) {
            return sinh(n4) / cosh(n4);
          }
          var r0 = r3(0);
          function w3(s3) {
            return w0 * (cosh(r0) / cosh(r0 + rho * s3));
          }
          function u3(s3) {
            return w0 * (cosh(r0) * tanh(r0 + rho * s3) - sinh(r0)) / rho2;
          }
          function easeOut(t3) {
            return 1 - Math.pow(1 - t3, 1.5);
          }
          var start = Date.now(), S2 = (r3(1) - r0) / rho, duration = options2.duration ? 1e3 * options2.duration : 1e3 * S2 * 0.8;
          function frame() {
            var t3 = (Date.now() - start) / duration, s3 = easeOut(t3) * S2;
            if (t3 <= 1) {
              this._flyToFrame = requestAnimFrame(frame, this);
              this._move(
                this.unproject(from2.add(to.subtract(from2).multiplyBy(u3(s3) / u1)), startZoom),
                this.getScaleZoom(w0 / w3(s3), startZoom),
                { flyTo: true }
              );
            } else {
              this._move(targetCenter, targetZoom)._moveEnd(true);
            }
          }
          this._moveStart(true, options2.noMoveStart);
          frame.call(this);
          return this;
        },
        // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
        // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
        // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
        flyToBounds: function(bounds, options2) {
          var target = this._getBoundsCenterZoom(bounds, options2);
          return this.flyTo(target.center, target.zoom, options2);
        },
        // @method setMaxBounds(bounds: LatLngBounds): this
        // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
        setMaxBounds: function(bounds) {
          bounds = toLatLngBounds(bounds);
          if (this.listens("moveend", this._panInsideMaxBounds)) {
            this.off("moveend", this._panInsideMaxBounds);
          }
          if (!bounds.isValid()) {
            this.options.maxBounds = null;
            return this;
          }
          this.options.maxBounds = bounds;
          if (this._loaded) {
            this._panInsideMaxBounds();
          }
          return this.on("moveend", this._panInsideMaxBounds);
        },
        // @method setMinZoom(zoom: Number): this
        // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
        setMinZoom: function(zoom2) {
          var oldZoom = this.options.minZoom;
          this.options.minZoom = zoom2;
          if (this._loaded && oldZoom !== zoom2) {
            this.fire("zoomlevelschange");
            if (this.getZoom() < this.options.minZoom) {
              return this.setZoom(zoom2);
            }
          }
          return this;
        },
        // @method setMaxZoom(zoom: Number): this
        // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
        setMaxZoom: function(zoom2) {
          var oldZoom = this.options.maxZoom;
          this.options.maxZoom = zoom2;
          if (this._loaded && oldZoom !== zoom2) {
            this.fire("zoomlevelschange");
            if (this.getZoom() > this.options.maxZoom) {
              return this.setZoom(zoom2);
            }
          }
          return this;
        },
        // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
        // Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
        panInsideBounds: function(bounds, options2) {
          this._enforcingBounds = true;
          var center = this.getCenter(), newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
          if (!center.equals(newCenter)) {
            this.panTo(newCenter, options2);
          }
          this._enforcingBounds = false;
          return this;
        },
        // @method panInside(latlng: LatLng, options?: padding options): this
        // Pans the map the minimum amount to make the `latlng` visible. Use
        // padding options to fit the display to more restricted bounds.
        // If `latlng` is already within the (optionally padded) display bounds,
        // the map will not be panned.
        panInside: function(latlng, options2) {
          options2 = options2 || {};
          var paddingTL = toPoint(options2.paddingTopLeft || options2.padding || [0, 0]), paddingBR = toPoint(options2.paddingBottomRight || options2.padding || [0, 0]), pixelCenter = this.project(this.getCenter()), pixelPoint = this.project(latlng), pixelBounds = this.getPixelBounds(), paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]), paddedSize = paddedBounds.getSize();
          if (!paddedBounds.contains(pixelPoint)) {
            this._enforcingBounds = true;
            var centerOffset = pixelPoint.subtract(paddedBounds.getCenter());
            var offset = paddedBounds.extend(pixelPoint).getSize().subtract(paddedSize);
            pixelCenter.x += centerOffset.x < 0 ? -offset.x : offset.x;
            pixelCenter.y += centerOffset.y < 0 ? -offset.y : offset.y;
            this.panTo(this.unproject(pixelCenter), options2);
            this._enforcingBounds = false;
          }
          return this;
        },
        // @method invalidateSize(options: Zoom/pan options): this
        // Checks if the map container size changed and updates the map if so —
        // call it after you've changed the map size dynamically, also animating
        // pan by default. If `options.pan` is `false`, panning will not occur.
        // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
        // that it doesn't happen often even if the method is called many
        // times in a row.
        // @alternative
        // @method invalidateSize(animate: Boolean): this
        // Checks if the map container size changed and updates the map if so —
        // call it after you've changed the map size dynamically, also animating
        // pan by default.
        invalidateSize: function(options2) {
          if (!this._loaded) {
            return this;
          }
          options2 = extend({
            animate: false,
            pan: true
          }, options2 === true ? { animate: true } : options2);
          var oldSize = this.getSize();
          this._sizeChanged = true;
          this._lastCenter = null;
          var newSize = this.getSize(), oldCenter = oldSize.divideBy(2).round(), newCenter = newSize.divideBy(2).round(), offset = oldCenter.subtract(newCenter);
          if (!offset.x && !offset.y) {
            return this;
          }
          if (options2.animate && options2.pan) {
            this.panBy(offset);
          } else {
            if (options2.pan) {
              this._rawPanBy(offset);
            }
            this.fire("move");
            if (options2.debounceMoveend) {
              clearTimeout(this._sizeTimer);
              this._sizeTimer = setTimeout(bind2(this.fire, this, "moveend"), 200);
            } else {
              this.fire("moveend");
            }
          }
          return this.fire("resize", {
            oldSize,
            newSize
          });
        },
        // @section Methods for modifying map state
        // @method stop(): this
        // Stops the currently running `panTo` or `flyTo` animation, if any.
        stop: function() {
          this.setZoom(this._limitZoom(this._zoom));
          if (!this.options.zoomSnap) {
            this.fire("viewreset");
          }
          return this._stop();
        },
        // @section Geolocation methods
        // @method locate(options?: Locate options): this
        // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
        // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
        // and optionally sets the map view to the user's location with respect to
        // detection accuracy (or to the world view if geolocation failed).
        // Note that, if your page doesn't use HTTPS, this method will fail in
        // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
        // See `Locate options` for more details.
        locate: function(options2) {
          options2 = this._locateOptions = extend({
            timeout: 1e4,
            watch: false
            // setView: false
            // maxZoom: <Number>
            // maximumAge: 0
            // enableHighAccuracy: false
          }, options2);
          if (!("geolocation" in navigator)) {
            this._handleGeolocationError({
              code: 0,
              message: "Geolocation not supported."
            });
            return this;
          }
          var onResponse = bind2(this._handleGeolocationResponse, this), onError = bind2(this._handleGeolocationError, this);
          if (options2.watch) {
            this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options2);
          } else {
            navigator.geolocation.getCurrentPosition(onResponse, onError, options2);
          }
          return this;
        },
        // @method stopLocate(): this
        // Stops watching location previously initiated by `map.locate({watch: true})`
        // and aborts resetting the map view if map.locate was called with
        // `{setView: true}`.
        stopLocate: function() {
          if (navigator.geolocation && navigator.geolocation.clearWatch) {
            navigator.geolocation.clearWatch(this._locationWatchId);
          }
          if (this._locateOptions) {
            this._locateOptions.setView = false;
          }
          return this;
        },
        _handleGeolocationError: function(error2) {
          if (!this._container._leaflet_id) {
            return;
          }
          var c3 = error2.code, message = error2.message || (c3 === 1 ? "permission denied" : c3 === 2 ? "position unavailable" : "timeout");
          if (this._locateOptions.setView && !this._loaded) {
            this.fitWorld();
          }
          this.fire("locationerror", {
            code: c3,
            message: "Geolocation error: " + message + "."
          });
        },
        _handleGeolocationResponse: function(pos) {
          if (!this._container._leaflet_id) {
            return;
          }
          var lat = pos.coords.latitude, lng = pos.coords.longitude, latlng = new LatLng(lat, lng), bounds = latlng.toBounds(pos.coords.accuracy * 2), options2 = this._locateOptions;
          if (options2.setView) {
            var zoom2 = this.getBoundsZoom(bounds);
            this.setView(latlng, options2.maxZoom ? Math.min(zoom2, options2.maxZoom) : zoom2);
          }
          var data2 = {
            latlng,
            bounds,
            timestamp: pos.timestamp
          };
          for (var i3 in pos.coords) {
            if (typeof pos.coords[i3] === "number") {
              data2[i3] = pos.coords[i3];
            }
          }
          this.fire("locationfound", data2);
        },
        // TODO Appropriate docs section?
        // @section Other Methods
        // @method addHandler(name: String, HandlerClass: Function): this
        // Adds a new `Handler` to the map, given its name and constructor function.
        addHandler: function(name2, HandlerClass) {
          if (!HandlerClass) {
            return this;
          }
          var handler = this[name2] = new HandlerClass(this);
          this._handlers.push(handler);
          if (this.options[name2]) {
            handler.enable();
          }
          return this;
        },
        // @method remove(): this
        // Destroys the map and clears all related event listeners.
        remove: function() {
          this._initEvents(true);
          if (this.options.maxBounds) {
            this.off("moveend", this._panInsideMaxBounds);
          }
          if (this._containerId !== this._container._leaflet_id) {
            throw new Error("Map container is being reused by another instance");
          }
          try {
            delete this._container._leaflet_id;
            delete this._containerId;
          } catch (e3) {
            this._container._leaflet_id = void 0;
            this._containerId = void 0;
          }
          if (this._locationWatchId !== void 0) {
            this.stopLocate();
          }
          this._stop();
          remove3(this._mapPane);
          if (this._clearControlPos) {
            this._clearControlPos();
          }
          if (this._resizeRequest) {
            cancelAnimFrame(this._resizeRequest);
            this._resizeRequest = null;
          }
          this._clearHandlers();
          if (this._loaded) {
            this.fire("unload");
          }
          var i3;
          for (i3 in this._layers) {
            this._layers[i3].remove();
          }
          for (i3 in this._panes) {
            remove3(this._panes[i3]);
          }
          this._layers = [];
          this._panes = [];
          delete this._mapPane;
          delete this._renderer;
          return this;
        },
        // @section Other Methods
        // @method createPane(name: String, container?: HTMLElement): HTMLElement
        // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
        // then returns it. The pane is created as a child of `container`, or
        // as a child of the main map pane if not set.
        createPane: function(name2, container) {
          var className2 = "leaflet-pane" + (name2 ? " leaflet-" + name2.replace("Pane", "") + "-pane" : ""), pane = create$1("div", className2, container || this._mapPane);
          if (name2) {
            this._panes[name2] = pane;
          }
          return pane;
        },
        // @section Methods for Getting Map State
        // @method getCenter(): LatLng
        // Returns the geographical center of the map view
        getCenter: function() {
          this._checkIfLoaded();
          if (this._lastCenter && !this._moved()) {
            return this._lastCenter.clone();
          }
          return this.layerPointToLatLng(this._getCenterLayerPoint());
        },
        // @method getZoom(): Number
        // Returns the current zoom level of the map view
        getZoom: function() {
          return this._zoom;
        },
        // @method getBounds(): LatLngBounds
        // Returns the geographical bounds visible in the current map view
        getBounds: function() {
          var bounds = this.getPixelBounds(), sw = this.unproject(bounds.getBottomLeft()), ne = this.unproject(bounds.getTopRight());
          return new LatLngBounds(sw, ne);
        },
        // @method getMinZoom(): Number
        // Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.
        getMinZoom: function() {
          return this.options.minZoom === void 0 ? this._layersMinZoom || 0 : this.options.minZoom;
        },
        // @method getMaxZoom(): Number
        // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
        getMaxZoom: function() {
          return this.options.maxZoom === void 0 ? this._layersMaxZoom === void 0 ? Infinity : this._layersMaxZoom : this.options.maxZoom;
        },
        // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number
        // Returns the maximum zoom level on which the given bounds fit to the map
        // view in its entirety. If `inside` (optional) is set to `true`, the method
        // instead returns the minimum zoom level on which the map view fits into
        // the given bounds in its entirety.
        getBoundsZoom: function(bounds, inside, padding) {
          bounds = toLatLngBounds(bounds);
          padding = toPoint(padding || [0, 0]);
          var zoom2 = this.getZoom() || 0, min3 = this.getMinZoom(), max3 = this.getMaxZoom(), nw = bounds.getNorthWest(), se = bounds.getSouthEast(), size4 = this.getSize().subtract(padding), boundsSize = toBounds(this.project(se, zoom2), this.project(nw, zoom2)).getSize(), snap = Browser.any3d ? this.options.zoomSnap : 1, scalex = size4.x / boundsSize.x, scaley = size4.y / boundsSize.y, scale2 = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
          zoom2 = this.getScaleZoom(scale2, zoom2);
          if (snap) {
            zoom2 = Math.round(zoom2 / (snap / 100)) * (snap / 100);
            zoom2 = inside ? Math.ceil(zoom2 / snap) * snap : Math.floor(zoom2 / snap) * snap;
          }
          return Math.max(min3, Math.min(max3, zoom2));
        },
        // @method getSize(): Point
        // Returns the current size of the map container (in pixels).
        getSize: function() {
          if (!this._size || this._sizeChanged) {
            this._size = new Point2(
              this._container.clientWidth || 0,
              this._container.clientHeight || 0
            );
            this._sizeChanged = false;
          }
          return this._size.clone();
        },
        // @method getPixelBounds(): Bounds
        // Returns the bounds of the current map view in projected pixel
        // coordinates (sometimes useful in layer and overlay implementations).
        getPixelBounds: function(center, zoom2) {
          var topLeftPoint = this._getTopLeftPoint(center, zoom2);
          return new Bounds2(topLeftPoint, topLeftPoint.add(this.getSize()));
        },
        // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
        // the map pane? "left point of the map layer" can be confusing, specially
        // since there can be negative offsets.
        // @method getPixelOrigin(): Point
        // Returns the projected pixel coordinates of the top left point of
        // the map layer (useful in custom layer and overlay implementations).
        getPixelOrigin: function() {
          this._checkIfLoaded();
          return this._pixelOrigin;
        },
        // @method getPixelWorldBounds(zoom?: Number): Bounds
        // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
        // If `zoom` is omitted, the map's current zoom level is used.
        getPixelWorldBounds: function(zoom2) {
          return this.options.crs.getProjectedBounds(zoom2 === void 0 ? this.getZoom() : zoom2);
        },
        // @section Other Methods
        // @method getPane(pane: String|HTMLElement): HTMLElement
        // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
        getPane: function(pane) {
          return typeof pane === "string" ? this._panes[pane] : pane;
        },
        // @method getPanes(): Object
        // Returns a plain object containing the names of all [panes](#map-pane) as keys and
        // the panes as values.
        getPanes: function() {
          return this._panes;
        },
        // @method getContainer: HTMLElement
        // Returns the HTML element that contains the map.
        getContainer: function() {
          return this._container;
        },
        // @section Conversion Methods
        // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
        // Returns the scale factor to be applied to a map transition from zoom level
        // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
        getZoomScale: function(toZoom, fromZoom) {
          var crs = this.options.crs;
          fromZoom = fromZoom === void 0 ? this._zoom : fromZoom;
          return crs.scale(toZoom) / crs.scale(fromZoom);
        },
        // @method getScaleZoom(scale: Number, fromZoom: Number): Number
        // Returns the zoom level that the map would end up at, if it is at `fromZoom`
        // level and everything is scaled by a factor of `scale`. Inverse of
        // [`getZoomScale`](#map-getZoomScale).
        getScaleZoom: function(scale2, fromZoom) {
          var crs = this.options.crs;
          fromZoom = fromZoom === void 0 ? this._zoom : fromZoom;
          var zoom2 = crs.zoom(scale2 * crs.scale(fromZoom));
          return isNaN(zoom2) ? Infinity : zoom2;
        },
        // @method project(latlng: LatLng, zoom: Number): Point
        // Projects a geographical coordinate `LatLng` according to the projection
        // of the map's CRS, then scales it according to `zoom` and the CRS's
        // `Transformation`. The result is pixel coordinate relative to
        // the CRS origin.
        project: function(latlng, zoom2) {
          zoom2 = zoom2 === void 0 ? this._zoom : zoom2;
          return this.options.crs.latLngToPoint(toLatLng(latlng), zoom2);
        },
        // @method unproject(point: Point, zoom: Number): LatLng
        // Inverse of [`project`](#map-project).
        unproject: function(point, zoom2) {
          zoom2 = zoom2 === void 0 ? this._zoom : zoom2;
          return this.options.crs.pointToLatLng(toPoint(point), zoom2);
        },
        // @method layerPointToLatLng(point: Point): LatLng
        // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
        // returns the corresponding geographical coordinate (for the current zoom level).
        layerPointToLatLng: function(point) {
          var projectedPoint = toPoint(point).add(this.getPixelOrigin());
          return this.unproject(projectedPoint);
        },
        // @method latLngToLayerPoint(latlng: LatLng): Point
        // Given a geographical coordinate, returns the corresponding pixel coordinate
        // relative to the [origin pixel](#map-getpixelorigin).
        latLngToLayerPoint: function(latlng) {
          var projectedPoint = this.project(toLatLng(latlng))._round();
          return projectedPoint._subtract(this.getPixelOrigin());
        },
        // @method wrapLatLng(latlng: LatLng): LatLng
        // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
        // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
        // CRS's bounds.
        // By default this means longitude is wrapped around the dateline so its
        // value is between -180 and +180 degrees.
        wrapLatLng: function(latlng) {
          return this.options.crs.wrapLatLng(toLatLng(latlng));
        },
        // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
        // Returns a `LatLngBounds` with the same size as the given one, ensuring that
        // its center is within the CRS's bounds.
        // By default this means the center longitude is wrapped around the dateline so its
        // value is between -180 and +180 degrees, and the majority of the bounds
        // overlaps the CRS's bounds.
        wrapLatLngBounds: function(latlng) {
          return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
        },
        // @method distance(latlng1: LatLng, latlng2: LatLng): Number
        // Returns the distance between two geographical coordinates according to
        // the map's CRS. By default this measures distance in meters.
        distance: function(latlng1, latlng2) {
          return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
        },
        // @method containerPointToLayerPoint(point: Point): Point
        // Given a pixel coordinate relative to the map container, returns the corresponding
        // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
        containerPointToLayerPoint: function(point) {
          return toPoint(point).subtract(this._getMapPanePos());
        },
        // @method layerPointToContainerPoint(point: Point): Point
        // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
        // returns the corresponding pixel coordinate relative to the map container.
        layerPointToContainerPoint: function(point) {
          return toPoint(point).add(this._getMapPanePos());
        },
        // @method containerPointToLatLng(point: Point): LatLng
        // Given a pixel coordinate relative to the map container, returns
        // the corresponding geographical coordinate (for the current zoom level).
        containerPointToLatLng: function(point) {
          var layerPoint = this.containerPointToLayerPoint(toPoint(point));
          return this.layerPointToLatLng(layerPoint);
        },
        // @method latLngToContainerPoint(latlng: LatLng): Point
        // Given a geographical coordinate, returns the corresponding pixel coordinate
        // relative to the map container.
        latLngToContainerPoint: function(latlng) {
          return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
        },
        // @method mouseEventToContainerPoint(ev: MouseEvent): Point
        // Given a MouseEvent object, returns the pixel coordinate relative to the
        // map container where the event took place.
        mouseEventToContainerPoint: function(e3) {
          return getMousePosition(e3, this._container);
        },
        // @method mouseEventToLayerPoint(ev: MouseEvent): Point
        // Given a MouseEvent object, returns the pixel coordinate relative to
        // the [origin pixel](#map-getpixelorigin) where the event took place.
        mouseEventToLayerPoint: function(e3) {
          return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e3));
        },
        // @method mouseEventToLatLng(ev: MouseEvent): LatLng
        // Given a MouseEvent object, returns geographical coordinate where the
        // event took place.
        mouseEventToLatLng: function(e3) {
          return this.layerPointToLatLng(this.mouseEventToLayerPoint(e3));
        },
        // map initialization methods
        _initContainer: function(id) {
          var container = this._container = get7(id);
          if (!container) {
            throw new Error("Map container not found.");
          } else if (container._leaflet_id) {
            throw new Error("Map container is already initialized.");
          }
          on2(container, "scroll", this._onScroll, this);
          this._containerId = stamp(container);
        },
        _initLayout: function() {
          var container = this._container;
          this._fadeAnimated = this.options.fadeAnimation && Browser.any3d;
          addClass(container, "leaflet-container" + (Browser.touch ? " leaflet-touch" : "") + (Browser.retina ? " leaflet-retina" : "") + (Browser.ielt9 ? " leaflet-oldie" : "") + (Browser.safari ? " leaflet-safari" : "") + (this._fadeAnimated ? " leaflet-fade-anim" : ""));
          var position = getStyle(container, "position");
          if (position !== "absolute" && position !== "relative" && position !== "fixed" && position !== "sticky") {
            container.style.position = "relative";
          }
          this._initPanes();
          if (this._initControlPos) {
            this._initControlPos();
          }
        },
        _initPanes: function() {
          var panes = this._panes = {};
          this._paneRenderers = {};
          this._mapPane = this.createPane("mapPane", this._container);
          setPosition(this._mapPane, new Point2(0, 0));
          this.createPane("tilePane");
          this.createPane("overlayPane");
          this.createPane("shadowPane");
          this.createPane("markerPane");
          this.createPane("tooltipPane");
          this.createPane("popupPane");
          if (!this.options.markerZoomAnimation) {
            addClass(panes.markerPane, "leaflet-zoom-hide");
            addClass(panes.shadowPane, "leaflet-zoom-hide");
          }
        },
        // private methods that modify map state
        // @section Map state change events
        _resetView: function(center, zoom2, noMoveStart) {
          setPosition(this._mapPane, new Point2(0, 0));
          var loading = !this._loaded;
          this._loaded = true;
          zoom2 = this._limitZoom(zoom2);
          this.fire("viewprereset");
          var zoomChanged = this._zoom !== zoom2;
          this._moveStart(zoomChanged, noMoveStart)._move(center, zoom2)._moveEnd(zoomChanged);
          this.fire("viewreset");
          if (loading) {
            this.fire("load");
          }
        },
        _moveStart: function(zoomChanged, noMoveStart) {
          if (zoomChanged) {
            this.fire("zoomstart");
          }
          if (!noMoveStart) {
            this.fire("movestart");
          }
          return this;
        },
        _move: function(center, zoom2, data2, supressEvent) {
          if (zoom2 === void 0) {
            zoom2 = this._zoom;
          }
          var zoomChanged = this._zoom !== zoom2;
          this._zoom = zoom2;
          this._lastCenter = center;
          this._pixelOrigin = this._getNewPixelOrigin(center);
          if (!supressEvent) {
            if (zoomChanged || data2 && data2.pinch) {
              this.fire("zoom", data2);
            }
            this.fire("move", data2);
          } else if (data2 && data2.pinch) {
            this.fire("zoom", data2);
          }
          return this;
        },
        _moveEnd: function(zoomChanged) {
          if (zoomChanged) {
            this.fire("zoomend");
          }
          return this.fire("moveend");
        },
        _stop: function() {
          cancelAnimFrame(this._flyToFrame);
          if (this._panAnim) {
            this._panAnim.stop();
          }
          return this;
        },
        _rawPanBy: function(offset) {
          setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
        },
        _getZoomSpan: function() {
          return this.getMaxZoom() - this.getMinZoom();
        },
        _panInsideMaxBounds: function() {
          if (!this._enforcingBounds) {
            this.panInsideBounds(this.options.maxBounds);
          }
        },
        _checkIfLoaded: function() {
          if (!this._loaded) {
            throw new Error("Set map center and zoom first.");
          }
        },
        // DOM event handling
        // @section Interaction events
        _initEvents: function(remove4) {
          this._targets = {};
          this._targets[stamp(this._container)] = this;
          var onOff = remove4 ? off : on2;
          onOff(this._container, "click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup", this._handleDOMEvent, this);
          if (this.options.trackResize) {
            onOff(window, "resize", this._onResize, this);
          }
          if (Browser.any3d && this.options.transform3DLimit) {
            (remove4 ? this.off : this.on).call(this, "moveend", this._onMoveEnd);
          }
        },
        _onResize: function() {
          cancelAnimFrame(this._resizeRequest);
          this._resizeRequest = requestAnimFrame(
            function() {
              this.invalidateSize({ debounceMoveend: true });
            },
            this
          );
        },
        _onScroll: function() {
          this._container.scrollTop = 0;
          this._container.scrollLeft = 0;
        },
        _onMoveEnd: function() {
          var pos = this._getMapPanePos();
          if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
            this._resetView(this.getCenter(), this.getZoom());
          }
        },
        _findEventTargets: function(e3, type) {
          var targets = [], target, isHover = type === "mouseout" || type === "mouseover", src = e3.target || e3.srcElement, dragging = false;
          while (src) {
            target = this._targets[stamp(src)];
            if (target && (type === "click" || type === "preclick") && this._draggableMoved(target)) {
              dragging = true;
              break;
            }
            if (target && target.listens(type, true)) {
              if (isHover && !isExternalTarget(src, e3)) {
                break;
              }
              targets.push(target);
              if (isHover) {
                break;
              }
            }
            if (src === this._container) {
              break;
            }
            src = src.parentNode;
          }
          if (!targets.length && !dragging && !isHover && this.listens(type, true)) {
            targets = [this];
          }
          return targets;
        },
        _isClickDisabled: function(el2) {
          while (el2 && el2 !== this._container) {
            if (el2["_leaflet_disable_click"]) {
              return true;
            }
            el2 = el2.parentNode;
          }
        },
        _handleDOMEvent: function(e3) {
          var el2 = e3.target || e3.srcElement;
          if (!this._loaded || el2["_leaflet_disable_events"] || e3.type === "click" && this._isClickDisabled(el2)) {
            return;
          }
          var type = e3.type;
          if (type === "mousedown") {
            preventOutline(el2);
          }
          this._fireDOMEvent(e3, type);
        },
        _mouseEvents: ["click", "dblclick", "mouseover", "mouseout", "contextmenu"],
        _fireDOMEvent: function(e3, type, canvasTargets) {
          if (e3.type === "click") {
            var synth = extend({}, e3);
            synth.type = "preclick";
            this._fireDOMEvent(synth, synth.type, canvasTargets);
          }
          var targets = this._findEventTargets(e3, type);
          if (canvasTargets) {
            var filtered = [];
            for (var i3 = 0; i3 < canvasTargets.length; i3++) {
              if (canvasTargets[i3].listens(type, true)) {
                filtered.push(canvasTargets[i3]);
              }
            }
            targets = filtered.concat(targets);
          }
          if (!targets.length) {
            return;
          }
          if (type === "contextmenu") {
            preventDefault(e3);
          }
          var target = targets[0];
          var data2 = {
            originalEvent: e3
          };
          if (e3.type !== "keypress" && e3.type !== "keydown" && e3.type !== "keyup") {
            var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
            data2.containerPoint = isMarker ? this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e3);
            data2.layerPoint = this.containerPointToLayerPoint(data2.containerPoint);
            data2.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data2.layerPoint);
          }
          for (i3 = 0; i3 < targets.length; i3++) {
            targets[i3].fire(type, data2, true);
            if (data2.originalEvent._stopped || targets[i3].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1) {
              return;
            }
          }
        },
        _draggableMoved: function(obj) {
          obj = obj.dragging && obj.dragging.enabled() ? obj : this;
          return obj.dragging && obj.dragging.moved() || this.boxZoom && this.boxZoom.moved();
        },
        _clearHandlers: function() {
          for (var i3 = 0, len = this._handlers.length; i3 < len; i3++) {
            this._handlers[i3].disable();
          }
        },
        // @section Other Methods
        // @method whenReady(fn: Function, context?: Object): this
        // Runs the given function `fn` when the map gets initialized with
        // a view (center and zoom) and at least one layer, or immediately
        // if it's already initialized, optionally passing a function context.
        whenReady: function(callback, context) {
          if (this._loaded) {
            callback.call(context || this, { target: this });
          } else {
            this.on("load", callback, context);
          }
          return this;
        },
        // private methods for getting map state
        _getMapPanePos: function() {
          return getPosition(this._mapPane) || new Point2(0, 0);
        },
        _moved: function() {
          var pos = this._getMapPanePos();
          return pos && !pos.equals([0, 0]);
        },
        _getTopLeftPoint: function(center, zoom2) {
          var pixelOrigin = center && zoom2 !== void 0 ? this._getNewPixelOrigin(center, zoom2) : this.getPixelOrigin();
          return pixelOrigin.subtract(this._getMapPanePos());
        },
        _getNewPixelOrigin: function(center, zoom2) {
          var viewHalf = this.getSize()._divideBy(2);
          return this.project(center, zoom2)._subtract(viewHalf)._add(this._getMapPanePos())._round();
        },
        _latLngToNewLayerPoint: function(latlng, zoom2, center) {
          var topLeft = this._getNewPixelOrigin(center, zoom2);
          return this.project(latlng, zoom2)._subtract(topLeft);
        },
        _latLngBoundsToNewLayerBounds: function(latLngBounds, zoom2, center) {
          var topLeft = this._getNewPixelOrigin(center, zoom2);
          return toBounds([
            this.project(latLngBounds.getSouthWest(), zoom2)._subtract(topLeft),
            this.project(latLngBounds.getNorthWest(), zoom2)._subtract(topLeft),
            this.project(latLngBounds.getSouthEast(), zoom2)._subtract(topLeft),
            this.project(latLngBounds.getNorthEast(), zoom2)._subtract(topLeft)
          ]);
        },
        // layer point of the current center
        _getCenterLayerPoint: function() {
          return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
        },
        // offset of the specified place to the current center in pixels
        _getCenterOffset: function(latlng) {
          return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
        },
        // adjust center for view to get inside bounds
        _limitCenter: function(center, zoom2, bounds) {
          if (!bounds) {
            return center;
          }
          var centerPoint = this.project(center, zoom2), viewHalf = this.getSize().divideBy(2), viewBounds = new Bounds2(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), offset = this._getBoundsOffset(viewBounds, bounds, zoom2);
          if (Math.abs(offset.x) <= 1 && Math.abs(offset.y) <= 1) {
            return center;
          }
          return this.unproject(centerPoint.add(offset), zoom2);
        },
        // adjust offset for view to get inside bounds
        _limitOffset: function(offset, bounds) {
          if (!bounds) {
            return offset;
          }
          var viewBounds = this.getPixelBounds(), newBounds = new Bounds2(viewBounds.min.add(offset), viewBounds.max.add(offset));
          return offset.add(this._getBoundsOffset(newBounds, bounds));
        },
        // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
        _getBoundsOffset: function(pxBounds, maxBounds, zoom2) {
          var projectedMaxBounds = toBounds(
            this.project(maxBounds.getNorthEast(), zoom2),
            this.project(maxBounds.getSouthWest(), zoom2)
          ), minOffset = projectedMaxBounds.min.subtract(pxBounds.min), maxOffset2 = projectedMaxBounds.max.subtract(pxBounds.max), dx = this._rebound(minOffset.x, -maxOffset2.x), dy = this._rebound(minOffset.y, -maxOffset2.y);
          return new Point2(dx, dy);
        },
        _rebound: function(left, right) {
          return left + right > 0 ? Math.round(left - right) / 2 : Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
        },
        _limitZoom: function(zoom2) {
          var min3 = this.getMinZoom(), max3 = this.getMaxZoom(), snap = Browser.any3d ? this.options.zoomSnap : 1;
          if (snap) {
            zoom2 = Math.round(zoom2 / snap) * snap;
          }
          return Math.max(min3, Math.min(max3, zoom2));
        },
        _onPanTransitionStep: function() {
          this.fire("move");
        },
        _onPanTransitionEnd: function() {
          removeClass(this._mapPane, "leaflet-pan-anim");
          this.fire("moveend");
        },
        _tryAnimatedPan: function(center, options2) {
          var offset = this._getCenterOffset(center)._trunc();
          if ((options2 && options2.animate) !== true && !this.getSize().contains(offset)) {
            return false;
          }
          this.panBy(offset, options2);
          return true;
        },
        _createAnimProxy: function() {
          var proxy = this._proxy = create$1("div", "leaflet-proxy leaflet-zoom-animated");
          this._panes.mapPane.appendChild(proxy);
          this.on("zoomanim", function(e3) {
            var prop2 = TRANSFORM, transform = this._proxy.style[prop2];
            setTransform(this._proxy, this.project(e3.center, e3.zoom), this.getZoomScale(e3.zoom, 1));
            if (transform === this._proxy.style[prop2] && this._animatingZoom) {
              this._onZoomTransitionEnd();
            }
          }, this);
          this.on("load moveend", this._animMoveEnd, this);
          this._on("unload", this._destroyAnimProxy, this);
        },
        _destroyAnimProxy: function() {
          remove3(this._proxy);
          this.off("load moveend", this._animMoveEnd, this);
          delete this._proxy;
        },
        _animMoveEnd: function() {
          var c3 = this.getCenter(), z2 = this.getZoom();
          setTransform(this._proxy, this.project(c3, z2), this.getZoomScale(z2, 1));
        },
        _catchTransitionEnd: function(e3) {
          if (this._animatingZoom && e3.propertyName.indexOf("transform") >= 0) {
            this._onZoomTransitionEnd();
          }
        },
        _nothingToAnimate: function() {
          return !this._container.getElementsByClassName("leaflet-zoom-animated").length;
        },
        _tryAnimatedZoom: function(center, zoom2, options2) {
          if (this._animatingZoom) {
            return true;
          }
          options2 = options2 || {};
          if (!this._zoomAnimated || options2.animate === false || this._nothingToAnimate() || Math.abs(zoom2 - this._zoom) > this.options.zoomAnimationThreshold) {
            return false;
          }
          var scale2 = this.getZoomScale(zoom2), offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale2);
          if (options2.animate !== true && !this.getSize().contains(offset)) {
            return false;
          }
          requestAnimFrame(function() {
            this._moveStart(true, options2.noMoveStart || false)._animateZoom(center, zoom2, true);
          }, this);
          return true;
        },
        _animateZoom: function(center, zoom2, startAnim, noUpdate) {
          if (!this._mapPane) {
            return;
          }
          if (startAnim) {
            this._animatingZoom = true;
            this._animateToCenter = center;
            this._animateToZoom = zoom2;
            addClass(this._mapPane, "leaflet-zoom-anim");
          }
          this.fire("zoomanim", {
            center,
            zoom: zoom2,
            noUpdate
          });
          if (!this._tempFireZoomEvent) {
            this._tempFireZoomEvent = this._zoom !== this._animateToZoom;
          }
          this._move(this._animateToCenter, this._animateToZoom, void 0, true);
          setTimeout(bind2(this._onZoomTransitionEnd, this), 250);
        },
        _onZoomTransitionEnd: function() {
          if (!this._animatingZoom) {
            return;
          }
          if (this._mapPane) {
            removeClass(this._mapPane, "leaflet-zoom-anim");
          }
          this._animatingZoom = false;
          this._move(this._animateToCenter, this._animateToZoom, void 0, true);
          if (this._tempFireZoomEvent) {
            this.fire("zoom");
          }
          delete this._tempFireZoomEvent;
          this.fire("move");
          this._moveEnd(true);
        }
      });
      function createMap(id, options2) {
        return new Map2(id, options2);
      }
      var Control = Class.extend({
        // @section
        // @aka Control Options
        options: {
          // @option position: String = 'topright'
          // The position of the control (one of the map corners). Possible values are `'topleft'`,
          // `'topright'`, `'bottomleft'` or `'bottomright'`
          position: "topright"
        },
        initialize: function(options2) {
          setOptions2(this, options2);
        },
        /* @section
         * Classes extending L.Control will inherit the following methods:
         *
         * @method getPosition: string
         * Returns the position of the control.
         */
        getPosition: function() {
          return this.options.position;
        },
        // @method setPosition(position: string): this
        // Sets the position of the control.
        setPosition: function(position) {
          var map5 = this._map;
          if (map5) {
            map5.removeControl(this);
          }
          this.options.position = position;
          if (map5) {
            map5.addControl(this);
          }
          return this;
        },
        // @method getContainer: HTMLElement
        // Returns the HTMLElement that contains the control.
        getContainer: function() {
          return this._container;
        },
        // @method addTo(map: Map): this
        // Adds the control to the given map.
        addTo: function(map5) {
          this.remove();
          this._map = map5;
          var container = this._container = this.onAdd(map5), pos = this.getPosition(), corner = map5._controlCorners[pos];
          addClass(container, "leaflet-control");
          if (pos.indexOf("bottom") !== -1) {
            corner.insertBefore(container, corner.firstChild);
          } else {
            corner.appendChild(container);
          }
          this._map.on("unload", this.remove, this);
          return this;
        },
        // @method remove: this
        // Removes the control from the map it is currently active on.
        remove: function() {
          if (!this._map) {
            return this;
          }
          remove3(this._container);
          if (this.onRemove) {
            this.onRemove(this._map);
          }
          this._map.off("unload", this.remove, this);
          this._map = null;
          return this;
        },
        _refocusOnMap: function(e3) {
          if (this._map && e3 && e3.screenX > 0 && e3.screenY > 0) {
            this._map.getContainer().focus();
          }
        }
      });
      var control = function(options2) {
        return new Control(options2);
      };
      Map2.include({
        // @method addControl(control: Control): this
        // Adds the given control to the map
        addControl: function(control2) {
          control2.addTo(this);
          return this;
        },
        // @method removeControl(control: Control): this
        // Removes the given control from the map
        removeControl: function(control2) {
          control2.remove();
          return this;
        },
        _initControlPos: function() {
          var corners = this._controlCorners = {}, l3 = "leaflet-", container = this._controlContainer = create$1("div", l3 + "control-container", this._container);
          function createCorner(vSide, hSide) {
            var className2 = l3 + vSide + " " + l3 + hSide;
            corners[vSide + hSide] = create$1("div", className2, container);
          }
          createCorner("top", "left");
          createCorner("top", "right");
          createCorner("bottom", "left");
          createCorner("bottom", "right");
        },
        _clearControlPos: function() {
          for (var i3 in this._controlCorners) {
            remove3(this._controlCorners[i3]);
          }
          remove3(this._controlContainer);
          delete this._controlCorners;
          delete this._controlContainer;
        }
      });
      var Layers = Control.extend({
        // @section
        // @aka Control.Layers options
        options: {
          // @option collapsed: Boolean = true
          // If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation.
          collapsed: true,
          position: "topright",
          // @option autoZIndex: Boolean = true
          // If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.
          autoZIndex: true,
          // @option hideSingleBase: Boolean = false
          // If `true`, the base layers in the control will be hidden when there is only one.
          hideSingleBase: false,
          // @option sortLayers: Boolean = false
          // Whether to sort the layers. When `false`, layers will keep the order
          // in which they were added to the control.
          sortLayers: false,
          // @option sortFunction: Function = *
          // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
          // that will be used for sorting the layers, when `sortLayers` is `true`.
          // The function receives both the `L.Layer` instances and their names, as in
          // `sortFunction(layerA, layerB, nameA, nameB)`.
          // By default, it sorts layers alphabetically by their name.
          sortFunction: function(layerA, layerB, nameA, nameB) {
            return nameA < nameB ? -1 : nameB < nameA ? 1 : 0;
          }
        },
        initialize: function(baseLayers, overlays, options2) {
          setOptions2(this, options2);
          this._layerControlInputs = [];
          this._layers = [];
          this._lastZIndex = 0;
          this._handlingClick = false;
          this._preventClick = false;
          for (var i3 in baseLayers) {
            this._addLayer(baseLayers[i3], i3);
          }
          for (i3 in overlays) {
            this._addLayer(overlays[i3], i3, true);
          }
        },
        onAdd: function(map5) {
          this._initLayout();
          this._update();
          this._map = map5;
          map5.on("zoomend", this._checkDisabledLayers, this);
          for (var i3 = 0; i3 < this._layers.length; i3++) {
            this._layers[i3].layer.on("add remove", this._onLayerChange, this);
          }
          return this._container;
        },
        addTo: function(map5) {
          Control.prototype.addTo.call(this, map5);
          return this._expandIfNotCollapsed();
        },
        onRemove: function() {
          this._map.off("zoomend", this._checkDisabledLayers, this);
          for (var i3 = 0; i3 < this._layers.length; i3++) {
            this._layers[i3].layer.off("add remove", this._onLayerChange, this);
          }
        },
        // @method addBaseLayer(layer: Layer, name: String): this
        // Adds a base layer (radio button entry) with the given name to the control.
        addBaseLayer: function(layer2, name2) {
          this._addLayer(layer2, name2);
          return this._map ? this._update() : this;
        },
        // @method addOverlay(layer: Layer, name: String): this
        // Adds an overlay (checkbox entry) with the given name to the control.
        addOverlay: function(layer2, name2) {
          this._addLayer(layer2, name2, true);
          return this._map ? this._update() : this;
        },
        // @method removeLayer(layer: Layer): this
        // Remove the given layer from the control.
        removeLayer: function(layer2) {
          layer2.off("add remove", this._onLayerChange, this);
          var obj = this._getLayer(stamp(layer2));
          if (obj) {
            this._layers.splice(this._layers.indexOf(obj), 1);
          }
          return this._map ? this._update() : this;
        },
        // @method expand(): this
        // Expand the control container if collapsed.
        expand: function() {
          addClass(this._container, "leaflet-control-layers-expanded");
          this._section.style.height = null;
          var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
          if (acceptableHeight < this._section.clientHeight) {
            addClass(this._section, "leaflet-control-layers-scrollbar");
            this._section.style.height = acceptableHeight + "px";
          } else {
            removeClass(this._section, "leaflet-control-layers-scrollbar");
          }
          this._checkDisabledLayers();
          return this;
        },
        // @method collapse(): this
        // Collapse the control container if expanded.
        collapse: function() {
          removeClass(this._container, "leaflet-control-layers-expanded");
          return this;
        },
        _initLayout: function() {
          var className2 = "leaflet-control-layers", container = this._container = create$1("div", className2), collapsed = this.options.collapsed;
          container.setAttribute("aria-haspopup", true);
          disableClickPropagation(container);
          disableScrollPropagation(container);
          var section = this._section = create$1("section", className2 + "-list");
          if (collapsed) {
            this._map.on("click", this.collapse, this);
            on2(container, {
              mouseenter: this._expandSafely,
              mouseleave: this.collapse
            }, this);
          }
          var link2 = this._layersLink = create$1("a", className2 + "-toggle", container);
          link2.href = "#";
          link2.title = "Layers";
          link2.setAttribute("role", "button");
          on2(link2, {
            keydown: function(e3) {
              if (e3.keyCode === 13) {
                this._expandSafely();
              }
            },
            // Certain screen readers intercept the key event and instead send a click event
            click: function(e3) {
              preventDefault(e3);
              this._expandSafely();
            }
          }, this);
          if (!collapsed) {
            this.expand();
          }
          this._baseLayersList = create$1("div", className2 + "-base", section);
          this._separator = create$1("div", className2 + "-separator", section);
          this._overlaysList = create$1("div", className2 + "-overlays", section);
          container.appendChild(section);
        },
        _getLayer: function(id) {
          for (var i3 = 0; i3 < this._layers.length; i3++) {
            if (this._layers[i3] && stamp(this._layers[i3].layer) === id) {
              return this._layers[i3];
            }
          }
        },
        _addLayer: function(layer2, name2, overlay) {
          if (this._map) {
            layer2.on("add remove", this._onLayerChange, this);
          }
          this._layers.push({
            layer: layer2,
            name: name2,
            overlay
          });
          if (this.options.sortLayers) {
            this._layers.sort(bind2(function(a3, b3) {
              return this.options.sortFunction(a3.layer, b3.layer, a3.name, b3.name);
            }, this));
          }
          if (this.options.autoZIndex && layer2.setZIndex) {
            this._lastZIndex++;
            layer2.setZIndex(this._lastZIndex);
          }
          this._expandIfNotCollapsed();
        },
        _update: function() {
          if (!this._container) {
            return this;
          }
          empty4(this._baseLayersList);
          empty4(this._overlaysList);
          this._layerControlInputs = [];
          var baseLayersPresent, overlaysPresent, i3, obj, baseLayersCount = 0;
          for (i3 = 0; i3 < this._layers.length; i3++) {
            obj = this._layers[i3];
            this._addItem(obj);
            overlaysPresent = overlaysPresent || obj.overlay;
            baseLayersPresent = baseLayersPresent || !obj.overlay;
            baseLayersCount += !obj.overlay ? 1 : 0;
          }
          if (this.options.hideSingleBase) {
            baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
            this._baseLayersList.style.display = baseLayersPresent ? "" : "none";
          }
          this._separator.style.display = overlaysPresent && baseLayersPresent ? "" : "none";
          return this;
        },
        _onLayerChange: function(e3) {
          if (!this._handlingClick) {
            this._update();
          }
          var obj = this._getLayer(stamp(e3.target));
          var type = obj.overlay ? e3.type === "add" ? "overlayadd" : "overlayremove" : e3.type === "add" ? "baselayerchange" : null;
          if (type) {
            this._map.fire(type, obj);
          }
        },
        // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see https://stackoverflow.com/a/119079)
        _createRadioElement: function(name2, checked) {
          var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name2 + '"' + (checked ? ' checked="checked"' : "") + "/>";
          var radioFragment = document.createElement("div");
          radioFragment.innerHTML = radioHtml;
          return radioFragment.firstChild;
        },
        _addItem: function(obj) {
          var label = document.createElement("label"), checked = this._map.hasLayer(obj.layer), input;
          if (obj.overlay) {
            input = document.createElement("input");
            input.type = "checkbox";
            input.className = "leaflet-control-layers-selector";
            input.defaultChecked = checked;
          } else {
            input = this._createRadioElement("leaflet-base-layers_" + stamp(this), checked);
          }
          this._layerControlInputs.push(input);
          input.layerId = stamp(obj.layer);
          on2(input, "click", this._onInputClick, this);
          var name2 = document.createElement("span");
          name2.innerHTML = " " + obj.name;
          var holder = document.createElement("span");
          label.appendChild(holder);
          holder.appendChild(input);
          holder.appendChild(name2);
          var container = obj.overlay ? this._overlaysList : this._baseLayersList;
          container.appendChild(label);
          this._checkDisabledLayers();
          return label;
        },
        _onInputClick: function() {
          if (this._preventClick) {
            return;
          }
          var inputs = this._layerControlInputs, input, layer2;
          var addedLayers = [], removedLayers = [];
          this._handlingClick = true;
          for (var i3 = inputs.length - 1; i3 >= 0; i3--) {
            input = inputs[i3];
            layer2 = this._getLayer(input.layerId).layer;
            if (input.checked) {
              addedLayers.push(layer2);
            } else if (!input.checked) {
              removedLayers.push(layer2);
            }
          }
          for (i3 = 0; i3 < removedLayers.length; i3++) {
            if (this._map.hasLayer(removedLayers[i3])) {
              this._map.removeLayer(removedLayers[i3]);
            }
          }
          for (i3 = 0; i3 < addedLayers.length; i3++) {
            if (!this._map.hasLayer(addedLayers[i3])) {
              this._map.addLayer(addedLayers[i3]);
            }
          }
          this._handlingClick = false;
          this._refocusOnMap();
        },
        _checkDisabledLayers: function() {
          var inputs = this._layerControlInputs, input, layer2, zoom2 = this._map.getZoom();
          for (var i3 = inputs.length - 1; i3 >= 0; i3--) {
            input = inputs[i3];
            layer2 = this._getLayer(input.layerId).layer;
            input.disabled = layer2.options.minZoom !== void 0 && zoom2 < layer2.options.minZoom || layer2.options.maxZoom !== void 0 && zoom2 > layer2.options.maxZoom;
          }
        },
        _expandIfNotCollapsed: function() {
          if (this._map && !this.options.collapsed) {
            this.expand();
          }
          return this;
        },
        _expandSafely: function() {
          var section = this._section;
          this._preventClick = true;
          on2(section, "click", preventDefault);
          this.expand();
          var that = this;
          setTimeout(function() {
            off(section, "click", preventDefault);
            that._preventClick = false;
          });
        }
      });
      var layers = function(baseLayers, overlays, options2) {
        return new Layers(baseLayers, overlays, options2);
      };
      var Zoom = Control.extend({
        // @section
        // @aka Control.Zoom options
        options: {
          position: "topleft",
          // @option zoomInText: String = '<span aria-hidden="true">+</span>'
          // The text set on the 'zoom in' button.
          zoomInText: '<span aria-hidden="true">+</span>',
          // @option zoomInTitle: String = 'Zoom in'
          // The title set on the 'zoom in' button.
          zoomInTitle: "Zoom in",
          // @option zoomOutText: String = '<span aria-hidden="true">&#x2212;</span>'
          // The text set on the 'zoom out' button.
          zoomOutText: '<span aria-hidden="true">&#x2212;</span>',
          // @option zoomOutTitle: String = 'Zoom out'
          // The title set on the 'zoom out' button.
          zoomOutTitle: "Zoom out"
        },
        onAdd: function(map5) {
          var zoomName = "leaflet-control-zoom", container = create$1("div", zoomName + " leaflet-bar"), options2 = this.options;
          this._zoomInButton = this._createButton(
            options2.zoomInText,
            options2.zoomInTitle,
            zoomName + "-in",
            container,
            this._zoomIn
          );
          this._zoomOutButton = this._createButton(
            options2.zoomOutText,
            options2.zoomOutTitle,
            zoomName + "-out",
            container,
            this._zoomOut
          );
          this._updateDisabled();
          map5.on("zoomend zoomlevelschange", this._updateDisabled, this);
          return container;
        },
        onRemove: function(map5) {
          map5.off("zoomend zoomlevelschange", this._updateDisabled, this);
        },
        disable: function() {
          this._disabled = true;
          this._updateDisabled();
          return this;
        },
        enable: function() {
          this._disabled = false;
          this._updateDisabled();
          return this;
        },
        _zoomIn: function(e3) {
          if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
            this._map.zoomIn(this._map.options.zoomDelta * (e3.shiftKey ? 3 : 1));
          }
        },
        _zoomOut: function(e3) {
          if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
            this._map.zoomOut(this._map.options.zoomDelta * (e3.shiftKey ? 3 : 1));
          }
        },
        _createButton: function(html5, title, className2, container, fn) {
          var link2 = create$1("a", className2, container);
          link2.innerHTML = html5;
          link2.href = "#";
          link2.title = title;
          link2.setAttribute("role", "button");
          link2.setAttribute("aria-label", title);
          disableClickPropagation(link2);
          on2(link2, "click", stop);
          on2(link2, "click", fn, this);
          on2(link2, "click", this._refocusOnMap, this);
          return link2;
        },
        _updateDisabled: function() {
          var map5 = this._map, className2 = "leaflet-disabled";
          removeClass(this._zoomInButton, className2);
          removeClass(this._zoomOutButton, className2);
          this._zoomInButton.setAttribute("aria-disabled", "false");
          this._zoomOutButton.setAttribute("aria-disabled", "false");
          if (this._disabled || map5._zoom === map5.getMinZoom()) {
            addClass(this._zoomOutButton, className2);
            this._zoomOutButton.setAttribute("aria-disabled", "true");
          }
          if (this._disabled || map5._zoom === map5.getMaxZoom()) {
            addClass(this._zoomInButton, className2);
            this._zoomInButton.setAttribute("aria-disabled", "true");
          }
        }
      });
      Map2.mergeOptions({
        zoomControl: true
      });
      Map2.addInitHook(function() {
        if (this.options.zoomControl) {
          this.zoomControl = new Zoom();
          this.addControl(this.zoomControl);
        }
      });
      var zoom = function(options2) {
        return new Zoom(options2);
      };
      var Scale = Control.extend({
        // @section
        // @aka Control.Scale options
        options: {
          position: "bottomleft",
          // @option maxWidth: Number = 100
          // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
          maxWidth: 100,
          // @option metric: Boolean = True
          // Whether to show the metric scale line (m/km).
          metric: true,
          // @option imperial: Boolean = True
          // Whether to show the imperial scale line (mi/ft).
          imperial: true
          // @option updateWhenIdle: Boolean = false
          // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
        },
        onAdd: function(map5) {
          var className2 = "leaflet-control-scale", container = create$1("div", className2), options2 = this.options;
          this._addScales(options2, className2 + "-line", container);
          map5.on(options2.updateWhenIdle ? "moveend" : "move", this._update, this);
          map5.whenReady(this._update, this);
          return container;
        },
        onRemove: function(map5) {
          map5.off(this.options.updateWhenIdle ? "moveend" : "move", this._update, this);
        },
        _addScales: function(options2, className2, container) {
          if (options2.metric) {
            this._mScale = create$1("div", className2, container);
          }
          if (options2.imperial) {
            this._iScale = create$1("div", className2, container);
          }
        },
        _update: function() {
          var map5 = this._map, y3 = map5.getSize().y / 2;
          var maxMeters = map5.distance(
            map5.containerPointToLatLng([0, y3]),
            map5.containerPointToLatLng([this.options.maxWidth, y3])
          );
          this._updateScales(maxMeters);
        },
        _updateScales: function(maxMeters) {
          if (this.options.metric && maxMeters) {
            this._updateMetric(maxMeters);
          }
          if (this.options.imperial && maxMeters) {
            this._updateImperial(maxMeters);
          }
        },
        _updateMetric: function(maxMeters) {
          var meters = this._getRoundNum(maxMeters), label = meters < 1e3 ? meters + " m" : meters / 1e3 + " km";
          this._updateScale(this._mScale, label, meters / maxMeters);
        },
        _updateImperial: function(maxMeters) {
          var maxFeet = maxMeters * 3.2808399, maxMiles, miles, feet;
          if (maxFeet > 5280) {
            maxMiles = maxFeet / 5280;
            miles = this._getRoundNum(maxMiles);
            this._updateScale(this._iScale, miles + " mi", miles / maxMiles);
          } else {
            feet = this._getRoundNum(maxFeet);
            this._updateScale(this._iScale, feet + " ft", feet / maxFeet);
          }
        },
        _updateScale: function(scale2, text3, ratio) {
          scale2.style.width = Math.round(this.options.maxWidth * ratio) + "px";
          scale2.innerHTML = text3;
        },
        _getRoundNum: function(num) {
          var pow10 = Math.pow(10, (Math.floor(num) + "").length - 1), d3 = num / pow10;
          d3 = d3 >= 10 ? 10 : d3 >= 5 ? 5 : d3 >= 3 ? 3 : d3 >= 2 ? 2 : 1;
          return pow10 * d3;
        }
      });
      var scale = function(options2) {
        return new Scale(options2);
      };
      var ukrainianFlag = '<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" class="leaflet-attribution-flag"><path fill="#4C7BE1" d="M0 0h12v4H0z"/><path fill="#FFD500" d="M0 4h12v3H0z"/><path fill="#E0BC00" d="M0 7h12v1H0z"/></svg>';
      var Attribution = Control.extend({
        // @section
        // @aka Control.Attribution options
        options: {
          position: "bottomright",
          // @option prefix: String|false = 'Leaflet'
          // The HTML text shown before the attributions. Pass `false` to disable.
          prefix: '<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">' + (Browser.inlineSvg ? ukrainianFlag + " " : "") + "Leaflet</a>"
        },
        initialize: function(options2) {
          setOptions2(this, options2);
          this._attributions = {};
        },
        onAdd: function(map5) {
          map5.attributionControl = this;
          this._container = create$1("div", "leaflet-control-attribution");
          disableClickPropagation(this._container);
          for (var i3 in map5._layers) {
            if (map5._layers[i3].getAttribution) {
              this.addAttribution(map5._layers[i3].getAttribution());
            }
          }
          this._update();
          map5.on("layeradd", this._addAttribution, this);
          return this._container;
        },
        onRemove: function(map5) {
          map5.off("layeradd", this._addAttribution, this);
        },
        _addAttribution: function(ev) {
          if (ev.layer.getAttribution) {
            this.addAttribution(ev.layer.getAttribution());
            ev.layer.once("remove", function() {
              this.removeAttribution(ev.layer.getAttribution());
            }, this);
          }
        },
        // @method setPrefix(prefix: String|false): this
        // The HTML text shown before the attributions. Pass `false` to disable.
        setPrefix: function(prefix5) {
          this.options.prefix = prefix5;
          this._update();
          return this;
        },
        // @method addAttribution(text: String): this
        // Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`).
        addAttribution: function(text3) {
          if (!text3) {
            return this;
          }
          if (!this._attributions[text3]) {
            this._attributions[text3] = 0;
          }
          this._attributions[text3]++;
          this._update();
          return this;
        },
        // @method removeAttribution(text: String): this
        // Removes an attribution text.
        removeAttribution: function(text3) {
          if (!text3) {
            return this;
          }
          if (this._attributions[text3]) {
            this._attributions[text3]--;
            this._update();
          }
          return this;
        },
        _update: function() {
          if (!this._map) {
            return;
          }
          var attribs = [];
          for (var i3 in this._attributions) {
            if (this._attributions[i3]) {
              attribs.push(i3);
            }
          }
          var prefixAndAttribs = [];
          if (this.options.prefix) {
            prefixAndAttribs.push(this.options.prefix);
          }
          if (attribs.length) {
            prefixAndAttribs.push(attribs.join(", "));
          }
          this._container.innerHTML = prefixAndAttribs.join(' <span aria-hidden="true">|</span> ');
        }
      });
      Map2.mergeOptions({
        attributionControl: true
      });
      Map2.addInitHook(function() {
        if (this.options.attributionControl) {
          new Attribution().addTo(this);
        }
      });
      var attribution = function(options2) {
        return new Attribution(options2);
      };
      Control.Layers = Layers;
      Control.Zoom = Zoom;
      Control.Scale = Scale;
      Control.Attribution = Attribution;
      control.layers = layers;
      control.zoom = zoom;
      control.scale = scale;
      control.attribution = attribution;
      var Handler = Class.extend({
        initialize: function(map5) {
          this._map = map5;
        },
        // @method enable(): this
        // Enables the handler
        enable: function() {
          if (this._enabled) {
            return this;
          }
          this._enabled = true;
          this.addHooks();
          return this;
        },
        // @method disable(): this
        // Disables the handler
        disable: function() {
          if (!this._enabled) {
            return this;
          }
          this._enabled = false;
          this.removeHooks();
          return this;
        },
        // @method enabled(): Boolean
        // Returns `true` if the handler is enabled
        enabled: function() {
          return !!this._enabled;
        }
        // @section Extension methods
        // Classes inheriting from `Handler` must implement the two following methods:
        // @method addHooks()
        // Called when the handler is enabled, should add event hooks.
        // @method removeHooks()
        // Called when the handler is disabled, should remove the event hooks added previously.
      });
      Handler.addTo = function(map5, name2) {
        map5.addHandler(name2, this);
        return this;
      };
      var Mixin = { Events };
      var START = Browser.touch ? "touchstart mousedown" : "mousedown";
      var Draggable = Evented.extend({
        options: {
          // @section
          // @aka Draggable options
          // @option clickTolerance: Number = 3
          // The max number of pixels a user can shift the mouse pointer during a click
          // for it to be considered a valid click (as opposed to a mouse drag).
          clickTolerance: 3
        },
        // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
        // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
        initialize: function(element2, dragStartTarget, preventOutline2, options2) {
          setOptions2(this, options2);
          this._element = element2;
          this._dragStartTarget = dragStartTarget || element2;
          this._preventOutline = preventOutline2;
        },
        // @method enable()
        // Enables the dragging ability
        enable: function() {
          if (this._enabled) {
            return;
          }
          on2(this._dragStartTarget, START, this._onDown, this);
          this._enabled = true;
        },
        // @method disable()
        // Disables the dragging ability
        disable: function() {
          if (!this._enabled) {
            return;
          }
          if (Draggable._dragging === this) {
            this.finishDrag(true);
          }
          off(this._dragStartTarget, START, this._onDown, this);
          this._enabled = false;
          this._moved = false;
        },
        _onDown: function(e3) {
          if (!this._enabled) {
            return;
          }
          this._moved = false;
          if (hasClass(this._element, "leaflet-zoom-anim")) {
            return;
          }
          if (e3.touches && e3.touches.length !== 1) {
            if (Draggable._dragging === this) {
              this.finishDrag();
            }
            return;
          }
          if (Draggable._dragging || e3.shiftKey || e3.which !== 1 && e3.button !== 1 && !e3.touches) {
            return;
          }
          Draggable._dragging = this;
          if (this._preventOutline) {
            preventOutline(this._element);
          }
          disableImageDrag();
          disableTextSelection();
          if (this._moving) {
            return;
          }
          this.fire("down");
          var first2 = e3.touches ? e3.touches[0] : e3, sizedParent = getSizedParentNode(this._element);
          this._startPoint = new Point2(first2.clientX, first2.clientY);
          this._startPos = getPosition(this._element);
          this._parentScale = getScale2(sizedParent);
          var mouseevent = e3.type === "mousedown";
          on2(document, mouseevent ? "mousemove" : "touchmove", this._onMove, this);
          on2(document, mouseevent ? "mouseup" : "touchend touchcancel", this._onUp, this);
        },
        _onMove: function(e3) {
          if (!this._enabled) {
            return;
          }
          if (e3.touches && e3.touches.length > 1) {
            this._moved = true;
            return;
          }
          var first2 = e3.touches && e3.touches.length === 1 ? e3.touches[0] : e3, offset = new Point2(first2.clientX, first2.clientY)._subtract(this._startPoint);
          if (!offset.x && !offset.y) {
            return;
          }
          if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) {
            return;
          }
          offset.x /= this._parentScale.x;
          offset.y /= this._parentScale.y;
          preventDefault(e3);
          if (!this._moved) {
            this.fire("dragstart");
            this._moved = true;
            addClass(document.body, "leaflet-dragging");
            this._lastTarget = e3.target || e3.srcElement;
            if (window.SVGElementInstance && this._lastTarget instanceof window.SVGElementInstance) {
              this._lastTarget = this._lastTarget.correspondingUseElement;
            }
            addClass(this._lastTarget, "leaflet-drag-target");
          }
          this._newPos = this._startPos.add(offset);
          this._moving = true;
          this._lastEvent = e3;
          this._updatePosition();
        },
        _updatePosition: function() {
          var e3 = { originalEvent: this._lastEvent };
          this.fire("predrag", e3);
          setPosition(this._element, this._newPos);
          this.fire("drag", e3);
        },
        _onUp: function() {
          if (!this._enabled) {
            return;
          }
          this.finishDrag();
        },
        finishDrag: function(noInertia) {
          removeClass(document.body, "leaflet-dragging");
          if (this._lastTarget) {
            removeClass(this._lastTarget, "leaflet-drag-target");
            this._lastTarget = null;
          }
          off(document, "mousemove touchmove", this._onMove, this);
          off(document, "mouseup touchend touchcancel", this._onUp, this);
          enableImageDrag();
          enableTextSelection();
          var fireDragend = this._moved && this._moving;
          this._moving = false;
          Draggable._dragging = false;
          if (fireDragend) {
            this.fire("dragend", {
              noInertia,
              distance: this._newPos.distanceTo(this._startPos)
            });
          }
        }
      });
      function clipPolygon(points, bounds, round) {
        var clippedPoints, edges = [1, 4, 2, 8], i3, j, k2, a3, b3, len, edge2, p4;
        for (i3 = 0, len = points.length; i3 < len; i3++) {
          points[i3]._code = _getBitCode(points[i3], bounds);
        }
        for (k2 = 0; k2 < 4; k2++) {
          edge2 = edges[k2];
          clippedPoints = [];
          for (i3 = 0, len = points.length, j = len - 1; i3 < len; j = i3++) {
            a3 = points[i3];
            b3 = points[j];
            if (!(a3._code & edge2)) {
              if (b3._code & edge2) {
                p4 = _getEdgeIntersection(b3, a3, edge2, bounds, round);
                p4._code = _getBitCode(p4, bounds);
                clippedPoints.push(p4);
              }
              clippedPoints.push(a3);
            } else if (!(b3._code & edge2)) {
              p4 = _getEdgeIntersection(b3, a3, edge2, bounds, round);
              p4._code = _getBitCode(p4, bounds);
              clippedPoints.push(p4);
            }
          }
          points = clippedPoints;
        }
        return points;
      }
      function polygonCenter(latlngs, crs) {
        var i3, j, p1, p22, f3, area, x3, y3, center;
        if (!latlngs || latlngs.length === 0) {
          throw new Error("latlngs not passed");
        }
        if (!isFlat(latlngs)) {
          console.warn("latlngs are not flat! Only the first ring will be used");
          latlngs = latlngs[0];
        }
        var centroidLatLng = toLatLng([0, 0]);
        var bounds = toLatLngBounds(latlngs);
        var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
        if (areaBounds < 1700) {
          centroidLatLng = centroid(latlngs);
        }
        var len = latlngs.length;
        var points = [];
        for (i3 = 0; i3 < len; i3++) {
          var latlng = toLatLng(latlngs[i3]);
          points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
        }
        area = x3 = y3 = 0;
        for (i3 = 0, j = len - 1; i3 < len; j = i3++) {
          p1 = points[i3];
          p22 = points[j];
          f3 = p1.y * p22.x - p22.y * p1.x;
          x3 += (p1.x + p22.x) * f3;
          y3 += (p1.y + p22.y) * f3;
          area += f3 * 3;
        }
        if (area === 0) {
          center = points[0];
        } else {
          center = [x3 / area, y3 / area];
        }
        var latlngCenter = crs.unproject(toPoint(center));
        return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
      }
      function centroid(coords) {
        var latSum = 0;
        var lngSum = 0;
        var len = 0;
        for (var i3 = 0; i3 < coords.length; i3++) {
          var latlng = toLatLng(coords[i3]);
          latSum += latlng.lat;
          lngSum += latlng.lng;
          len++;
        }
        return toLatLng([latSum / len, lngSum / len]);
      }
      var PolyUtil = {
        __proto__: null,
        clipPolygon,
        polygonCenter,
        centroid
      };
      function simplify(points, tolerance) {
        if (!tolerance || !points.length) {
          return points.slice();
        }
        var sqTolerance = tolerance * tolerance;
        points = _reducePoints(points, sqTolerance);
        points = _simplifyDP(points, sqTolerance);
        return points;
      }
      function pointToSegmentDistance(p4, p1, p22) {
        return Math.sqrt(_sqClosestPointOnSegment(p4, p1, p22, true));
      }
      function closestPointOnSegment(p4, p1, p22) {
        return _sqClosestPointOnSegment(p4, p1, p22);
      }
      function _simplifyDP(points, sqTolerance) {
        var len = points.length, ArrayConstructor = typeof Uint8Array !== "undefined" ? Uint8Array : Array, markers = new ArrayConstructor(len);
        markers[0] = markers[len - 1] = 1;
        _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
        var i3, newPoints = [];
        for (i3 = 0; i3 < len; i3++) {
          if (markers[i3]) {
            newPoints.push(points[i3]);
          }
        }
        return newPoints;
      }
      function _simplifyDPStep(points, markers, sqTolerance, first2, last3) {
        var maxSqDist = 0, index3, i3, sqDist;
        for (i3 = first2 + 1; i3 <= last3 - 1; i3++) {
          sqDist = _sqClosestPointOnSegment(points[i3], points[first2], points[last3], true);
          if (sqDist > maxSqDist) {
            index3 = i3;
            maxSqDist = sqDist;
          }
        }
        if (maxSqDist > sqTolerance) {
          markers[index3] = 1;
          _simplifyDPStep(points, markers, sqTolerance, first2, index3);
          _simplifyDPStep(points, markers, sqTolerance, index3, last3);
        }
      }
      function _reducePoints(points, sqTolerance) {
        var reducedPoints = [points[0]];
        for (var i3 = 1, prev = 0, len = points.length; i3 < len; i3++) {
          if (_sqDist(points[i3], points[prev]) > sqTolerance) {
            reducedPoints.push(points[i3]);
            prev = i3;
          }
        }
        if (prev < len - 1) {
          reducedPoints.push(points[len - 1]);
        }
        return reducedPoints;
      }
      var _lastCode;
      function clipSegment(a3, b3, bounds, useLastCode, round) {
        var codeA = useLastCode ? _lastCode : _getBitCode(a3, bounds), codeB = _getBitCode(b3, bounds), codeOut, p4, newCode;
        _lastCode = codeB;
        while (true) {
          if (!(codeA | codeB)) {
            return [a3, b3];
          }
          if (codeA & codeB) {
            return false;
          }
          codeOut = codeA || codeB;
          p4 = _getEdgeIntersection(a3, b3, codeOut, bounds, round);
          newCode = _getBitCode(p4, bounds);
          if (codeOut === codeA) {
            a3 = p4;
            codeA = newCode;
          } else {
            b3 = p4;
            codeB = newCode;
          }
        }
      }
      function _getEdgeIntersection(a3, b3, code2, bounds, round) {
        var dx = b3.x - a3.x, dy = b3.y - a3.y, min3 = bounds.min, max3 = bounds.max, x3, y3;
        if (code2 & 8) {
          x3 = a3.x + dx * (max3.y - a3.y) / dy;
          y3 = max3.y;
        } else if (code2 & 4) {
          x3 = a3.x + dx * (min3.y - a3.y) / dy;
          y3 = min3.y;
        } else if (code2 & 2) {
          x3 = max3.x;
          y3 = a3.y + dy * (max3.x - a3.x) / dx;
        } else if (code2 & 1) {
          x3 = min3.x;
          y3 = a3.y + dy * (min3.x - a3.x) / dx;
        }
        return new Point2(x3, y3, round);
      }
      function _getBitCode(p4, bounds) {
        var code2 = 0;
        if (p4.x < bounds.min.x) {
          code2 |= 1;
        } else if (p4.x > bounds.max.x) {
          code2 |= 2;
        }
        if (p4.y < bounds.min.y) {
          code2 |= 4;
        } else if (p4.y > bounds.max.y) {
          code2 |= 8;
        }
        return code2;
      }
      function _sqDist(p1, p22) {
        var dx = p22.x - p1.x, dy = p22.y - p1.y;
        return dx * dx + dy * dy;
      }
      function _sqClosestPointOnSegment(p4, p1, p22, sqDist) {
        var x3 = p1.x, y3 = p1.y, dx = p22.x - x3, dy = p22.y - y3, dot = dx * dx + dy * dy, t3;
        if (dot > 0) {
          t3 = ((p4.x - x3) * dx + (p4.y - y3) * dy) / dot;
          if (t3 > 1) {
            x3 = p22.x;
            y3 = p22.y;
          } else if (t3 > 0) {
            x3 += dx * t3;
            y3 += dy * t3;
          }
        }
        dx = p4.x - x3;
        dy = p4.y - y3;
        return sqDist ? dx * dx + dy * dy : new Point2(x3, y3);
      }
      function isFlat(latlngs) {
        return !isArray3(latlngs[0]) || typeof latlngs[0][0] !== "object" && typeof latlngs[0][0] !== "undefined";
      }
      function _flat(latlngs) {
        console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead.");
        return isFlat(latlngs);
      }
      function polylineCenter(latlngs, crs) {
        var i3, halfDist, segDist, dist2, p1, p22, ratio, center;
        if (!latlngs || latlngs.length === 0) {
          throw new Error("latlngs not passed");
        }
        if (!isFlat(latlngs)) {
          console.warn("latlngs are not flat! Only the first ring will be used");
          latlngs = latlngs[0];
        }
        var centroidLatLng = toLatLng([0, 0]);
        var bounds = toLatLngBounds(latlngs);
        var areaBounds = bounds.getNorthWest().distanceTo(bounds.getSouthWest()) * bounds.getNorthEast().distanceTo(bounds.getNorthWest());
        if (areaBounds < 1700) {
          centroidLatLng = centroid(latlngs);
        }
        var len = latlngs.length;
        var points = [];
        for (i3 = 0; i3 < len; i3++) {
          var latlng = toLatLng(latlngs[i3]);
          points.push(crs.project(toLatLng([latlng.lat - centroidLatLng.lat, latlng.lng - centroidLatLng.lng])));
        }
        for (i3 = 0, halfDist = 0; i3 < len - 1; i3++) {
          halfDist += points[i3].distanceTo(points[i3 + 1]) / 2;
        }
        if (halfDist === 0) {
          center = points[0];
        } else {
          for (i3 = 0, dist2 = 0; i3 < len - 1; i3++) {
            p1 = points[i3];
            p22 = points[i3 + 1];
            segDist = p1.distanceTo(p22);
            dist2 += segDist;
            if (dist2 > halfDist) {
              ratio = (dist2 - halfDist) / segDist;
              center = [
                p22.x - ratio * (p22.x - p1.x),
                p22.y - ratio * (p22.y - p1.y)
              ];
              break;
            }
          }
        }
        var latlngCenter = crs.unproject(toPoint(center));
        return toLatLng([latlngCenter.lat + centroidLatLng.lat, latlngCenter.lng + centroidLatLng.lng]);
      }
      var LineUtil = {
        __proto__: null,
        simplify,
        pointToSegmentDistance,
        closestPointOnSegment,
        clipSegment,
        _getEdgeIntersection,
        _getBitCode,
        _sqClosestPointOnSegment,
        isFlat,
        _flat,
        polylineCenter
      };
      var LonLat = {
        project: function(latlng) {
          return new Point2(latlng.lng, latlng.lat);
        },
        unproject: function(point) {
          return new LatLng(point.y, point.x);
        },
        bounds: new Bounds2([-180, -90], [180, 90])
      };
      var Mercator = {
        R: 6378137,
        R_MINOR: 6356752314245179e-9,
        bounds: new Bounds2([-2003750834279e-5, -1549657073972e-5], [2003750834279e-5, 1876465623138e-5]),
        project: function(latlng) {
          var d3 = Math.PI / 180, r3 = this.R, y3 = latlng.lat * d3, tmp = this.R_MINOR / r3, e3 = Math.sqrt(1 - tmp * tmp), con = e3 * Math.sin(y3);
          var ts = Math.tan(Math.PI / 4 - y3 / 2) / Math.pow((1 - con) / (1 + con), e3 / 2);
          y3 = -r3 * Math.log(Math.max(ts, 1e-10));
          return new Point2(latlng.lng * d3 * r3, y3);
        },
        unproject: function(point) {
          var d3 = 180 / Math.PI, r3 = this.R, tmp = this.R_MINOR / r3, e3 = Math.sqrt(1 - tmp * tmp), ts = Math.exp(-point.y / r3), phi = Math.PI / 2 - 2 * Math.atan(ts);
          for (var i3 = 0, dphi = 0.1, con; i3 < 15 && Math.abs(dphi) > 1e-7; i3++) {
            con = e3 * Math.sin(phi);
            con = Math.pow((1 - con) / (1 + con), e3 / 2);
            dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
            phi += dphi;
          }
          return new LatLng(phi * d3, point.x * d3 / r3);
        }
      };
      var index2 = {
        __proto__: null,
        LonLat,
        Mercator,
        SphericalMercator
      };
      var EPSG3395 = extend({}, Earth, {
        code: "EPSG:3395",
        projection: Mercator,
        transformation: function() {
          var scale2 = 0.5 / (Math.PI * Mercator.R);
          return toTransformation(scale2, 0.5, -scale2, 0.5);
        }()
      });
      var EPSG4326 = extend({}, Earth, {
        code: "EPSG:4326",
        projection: LonLat,
        transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
      });
      var Simple = extend({}, CRS, {
        projection: LonLat,
        transformation: toTransformation(1, 0, -1, 0),
        scale: function(zoom2) {
          return Math.pow(2, zoom2);
        },
        zoom: function(scale2) {
          return Math.log(scale2) / Math.LN2;
        },
        distance: function(latlng1, latlng2) {
          var dx = latlng2.lng - latlng1.lng, dy = latlng2.lat - latlng1.lat;
          return Math.sqrt(dx * dx + dy * dy);
        },
        infinite: true
      });
      CRS.Earth = Earth;
      CRS.EPSG3395 = EPSG3395;
      CRS.EPSG3857 = EPSG3857;
      CRS.EPSG900913 = EPSG900913;
      CRS.EPSG4326 = EPSG4326;
      CRS.Simple = Simple;
      var Layer2 = Evented.extend({
        // Classes extending `L.Layer` will inherit the following options:
        options: {
          // @option pane: String = 'overlayPane'
          // By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.
          pane: "overlayPane",
          // @option attribution: String = null
          // String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.
          attribution: null,
          bubblingMouseEvents: true
        },
        /* @section
         * Classes extending `L.Layer` will inherit the following methods:
         *
         * @method addTo(map: Map|LayerGroup): this
         * Adds the layer to the given map or layer group.
         */
        addTo: function(map5) {
          map5.addLayer(this);
          return this;
        },
        // @method remove: this
        // Removes the layer from the map it is currently active on.
        remove: function() {
          return this.removeFrom(this._map || this._mapToAdd);
        },
        // @method removeFrom(map: Map): this
        // Removes the layer from the given map
        //
        // @alternative
        // @method removeFrom(group: LayerGroup): this
        // Removes the layer from the given `LayerGroup`
        removeFrom: function(obj) {
          if (obj) {
            obj.removeLayer(this);
          }
          return this;
        },
        // @method getPane(name? : String): HTMLElement
        // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
        getPane: function(name2) {
          return this._map.getPane(name2 ? this.options[name2] || name2 : this.options.pane);
        },
        addInteractiveTarget: function(targetEl) {
          this._map._targets[stamp(targetEl)] = this;
          return this;
        },
        removeInteractiveTarget: function(targetEl) {
          delete this._map._targets[stamp(targetEl)];
          return this;
        },
        // @method getAttribution: String
        // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
        getAttribution: function() {
          return this.options.attribution;
        },
        _layerAdd: function(e3) {
          var map5 = e3.target;
          if (!map5.hasLayer(this)) {
            return;
          }
          this._map = map5;
          this._zoomAnimated = map5._zoomAnimated;
          if (this.getEvents) {
            var events2 = this.getEvents();
            map5.on(events2, this);
            this.once("remove", function() {
              map5.off(events2, this);
            }, this);
          }
          this.onAdd(map5);
          this.fire("add");
          map5.fire("layeradd", { layer: this });
        }
      });
      Map2.include({
        // @method addLayer(layer: Layer): this
        // Adds the given layer to the map
        addLayer: function(layer2) {
          if (!layer2._layerAdd) {
            throw new Error("The provided object is not a Layer.");
          }
          var id = stamp(layer2);
          if (this._layers[id]) {
            return this;
          }
          this._layers[id] = layer2;
          layer2._mapToAdd = this;
          if (layer2.beforeAdd) {
            layer2.beforeAdd(this);
          }
          this.whenReady(layer2._layerAdd, layer2);
          return this;
        },
        // @method removeLayer(layer: Layer): this
        // Removes the given layer from the map.
        removeLayer: function(layer2) {
          var id = stamp(layer2);
          if (!this._layers[id]) {
            return this;
          }
          if (this._loaded) {
            layer2.onRemove(this);
          }
          delete this._layers[id];
          if (this._loaded) {
            this.fire("layerremove", { layer: layer2 });
            layer2.fire("remove");
          }
          layer2._map = layer2._mapToAdd = null;
          return this;
        },
        // @method hasLayer(layer: Layer): Boolean
        // Returns `true` if the given layer is currently added to the map
        hasLayer: function(layer2) {
          return stamp(layer2) in this._layers;
        },
        /* @method eachLayer(fn: Function, context?: Object): this
         * Iterates over the layers of the map, optionally specifying context of the iterator function.
         * ```
         * map.eachLayer(function(layer){
         *     layer.bindPopup('Hello');
         * });
         * ```
         */
        eachLayer: function(method, context) {
          for (var i3 in this._layers) {
            method.call(context, this._layers[i3]);
          }
          return this;
        },
        _addLayers: function(layers2) {
          layers2 = layers2 ? isArray3(layers2) ? layers2 : [layers2] : [];
          for (var i3 = 0, len = layers2.length; i3 < len; i3++) {
            this.addLayer(layers2[i3]);
          }
        },
        _addZoomLimit: function(layer2) {
          if (!isNaN(layer2.options.maxZoom) || !isNaN(layer2.options.minZoom)) {
            this._zoomBoundLayers[stamp(layer2)] = layer2;
            this._updateZoomLevels();
          }
        },
        _removeZoomLimit: function(layer2) {
          var id = stamp(layer2);
          if (this._zoomBoundLayers[id]) {
            delete this._zoomBoundLayers[id];
            this._updateZoomLevels();
          }
        },
        _updateZoomLevels: function() {
          var minZoom = Infinity, maxZoom = -Infinity, oldZoomSpan = this._getZoomSpan();
          for (var i3 in this._zoomBoundLayers) {
            var options2 = this._zoomBoundLayers[i3].options;
            minZoom = options2.minZoom === void 0 ? minZoom : Math.min(minZoom, options2.minZoom);
            maxZoom = options2.maxZoom === void 0 ? maxZoom : Math.max(maxZoom, options2.maxZoom);
          }
          this._layersMaxZoom = maxZoom === -Infinity ? void 0 : maxZoom;
          this._layersMinZoom = minZoom === Infinity ? void 0 : minZoom;
          if (oldZoomSpan !== this._getZoomSpan()) {
            this.fire("zoomlevelschange");
          }
          if (this.options.maxZoom === void 0 && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
            this.setZoom(this._layersMaxZoom);
          }
          if (this.options.minZoom === void 0 && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
            this.setZoom(this._layersMinZoom);
          }
        }
      });
      var LayerGroup = Layer2.extend({
        initialize: function(layers2, options2) {
          setOptions2(this, options2);
          this._layers = {};
          var i3, len;
          if (layers2) {
            for (i3 = 0, len = layers2.length; i3 < len; i3++) {
              this.addLayer(layers2[i3]);
            }
          }
        },
        // @method addLayer(layer: Layer): this
        // Adds the given layer to the group.
        addLayer: function(layer2) {
          var id = this.getLayerId(layer2);
          this._layers[id] = layer2;
          if (this._map) {
            this._map.addLayer(layer2);
          }
          return this;
        },
        // @method removeLayer(layer: Layer): this
        // Removes the given layer from the group.
        // @alternative
        // @method removeLayer(id: Number): this
        // Removes the layer with the given internal ID from the group.
        removeLayer: function(layer2) {
          var id = layer2 in this._layers ? layer2 : this.getLayerId(layer2);
          if (this._map && this._layers[id]) {
            this._map.removeLayer(this._layers[id]);
          }
          delete this._layers[id];
          return this;
        },
        // @method hasLayer(layer: Layer): Boolean
        // Returns `true` if the given layer is currently added to the group.
        // @alternative
        // @method hasLayer(id: Number): Boolean
        // Returns `true` if the given internal ID is currently added to the group.
        hasLayer: function(layer2) {
          var layerId = typeof layer2 === "number" ? layer2 : this.getLayerId(layer2);
          return layerId in this._layers;
        },
        // @method clearLayers(): this
        // Removes all the layers from the group.
        clearLayers: function() {
          return this.eachLayer(this.removeLayer, this);
        },
        // @method invoke(methodName: String, …): this
        // Calls `methodName` on every layer contained in this group, passing any
        // additional parameters. Has no effect if the layers contained do not
        // implement `methodName`.
        invoke: function(methodName) {
          var args = Array.prototype.slice.call(arguments, 1), i3, layer2;
          for (i3 in this._layers) {
            layer2 = this._layers[i3];
            if (layer2[methodName]) {
              layer2[methodName].apply(layer2, args);
            }
          }
          return this;
        },
        onAdd: function(map5) {
          this.eachLayer(map5.addLayer, map5);
        },
        onRemove: function(map5) {
          this.eachLayer(map5.removeLayer, map5);
        },
        // @method eachLayer(fn: Function, context?: Object): this
        // Iterates over the layers of the group, optionally specifying context of the iterator function.
        // ```js
        // group.eachLayer(function (layer) {
        // 	layer.bindPopup('Hello');
        // });
        // ```
        eachLayer: function(method, context) {
          for (var i3 in this._layers) {
            method.call(context, this._layers[i3]);
          }
          return this;
        },
        // @method getLayer(id: Number): Layer
        // Returns the layer with the given internal ID.
        getLayer: function(id) {
          return this._layers[id];
        },
        // @method getLayers(): Layer[]
        // Returns an array of all the layers added to the group.
        getLayers: function() {
          var layers2 = [];
          this.eachLayer(layers2.push, layers2);
          return layers2;
        },
        // @method setZIndex(zIndex: Number): this
        // Calls `setZIndex` on every layer contained in this group, passing the z-index.
        setZIndex: function(zIndex) {
          return this.invoke("setZIndex", zIndex);
        },
        // @method getLayerId(layer: Layer): Number
        // Returns the internal ID for a layer
        getLayerId: function(layer2) {
          return stamp(layer2);
        }
      });
      var layerGroup = function(layers2, options2) {
        return new LayerGroup(layers2, options2);
      };
      var FeatureGroup = LayerGroup.extend({
        addLayer: function(layer2) {
          if (this.hasLayer(layer2)) {
            return this;
          }
          layer2.addEventParent(this);
          LayerGroup.prototype.addLayer.call(this, layer2);
          return this.fire("layeradd", { layer: layer2 });
        },
        removeLayer: function(layer2) {
          if (!this.hasLayer(layer2)) {
            return this;
          }
          if (layer2 in this._layers) {
            layer2 = this._layers[layer2];
          }
          layer2.removeEventParent(this);
          LayerGroup.prototype.removeLayer.call(this, layer2);
          return this.fire("layerremove", { layer: layer2 });
        },
        // @method setStyle(style: Path options): this
        // Sets the given path options to each layer of the group that has a `setStyle` method.
        setStyle: function(style4) {
          return this.invoke("setStyle", style4);
        },
        // @method bringToFront(): this
        // Brings the layer group to the top of all other layers
        bringToFront: function() {
          return this.invoke("bringToFront");
        },
        // @method bringToBack(): this
        // Brings the layer group to the back of all other layers
        bringToBack: function() {
          return this.invoke("bringToBack");
        },
        // @method getBounds(): LatLngBounds
        // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
        getBounds: function() {
          var bounds = new LatLngBounds();
          for (var id in this._layers) {
            var layer2 = this._layers[id];
            bounds.extend(layer2.getBounds ? layer2.getBounds() : layer2.getLatLng());
          }
          return bounds;
        }
      });
      var featureGroup = function(layers2, options2) {
        return new FeatureGroup(layers2, options2);
      };
      var Icon2 = Class.extend({
        /* @section
         * @aka Icon options
         *
         * @option iconUrl: String = null
         * **(required)** The URL to the icon image (absolute or relative to your script path).
         *
         * @option iconRetinaUrl: String = null
         * The URL to a retina sized version of the icon image (absolute or relative to your
         * script path). Used for Retina screen devices.
         *
         * @option iconSize: Point = null
         * Size of the icon image in pixels.
         *
         * @option iconAnchor: Point = null
         * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
         * will be aligned so that this point is at the marker's geographical location. Centered
         * by default if size is specified, also can be set in CSS with negative margins.
         *
         * @option popupAnchor: Point = [0, 0]
         * The coordinates of the point from which popups will "open", relative to the icon anchor.
         *
         * @option tooltipAnchor: Point = [0, 0]
         * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
         *
         * @option shadowUrl: String = null
         * The URL to the icon shadow image. If not specified, no shadow image will be created.
         *
         * @option shadowRetinaUrl: String = null
         *
         * @option shadowSize: Point = null
         * Size of the shadow image in pixels.
         *
         * @option shadowAnchor: Point = null
         * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
         * as iconAnchor if not specified).
         *
         * @option className: String = ''
         * A custom class name to assign to both icon and shadow images. Empty by default.
         */
        options: {
          popupAnchor: [0, 0],
          tooltipAnchor: [0, 0],
          // @option crossOrigin: Boolean|String = false
          // Whether the crossOrigin attribute will be added to the tiles.
          // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
          // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
          crossOrigin: false
        },
        initialize: function(options2) {
          setOptions2(this, options2);
        },
        // @method createIcon(oldIcon?: HTMLElement): HTMLElement
        // Called internally when the icon has to be shown, returns a `<img>` HTML element
        // styled according to the options.
        createIcon: function(oldIcon) {
          return this._createIcon("icon", oldIcon);
        },
        // @method createShadow(oldIcon?: HTMLElement): HTMLElement
        // As `createIcon`, but for the shadow beneath it.
        createShadow: function(oldIcon) {
          return this._createIcon("shadow", oldIcon);
        },
        _createIcon: function(name2, oldIcon) {
          var src = this._getIconUrl(name2);
          if (!src) {
            if (name2 === "icon") {
              throw new Error("iconUrl not set in Icon options (see the docs).");
            }
            return null;
          }
          var img = this._createImg(src, oldIcon && oldIcon.tagName === "IMG" ? oldIcon : null);
          this._setIconStyles(img, name2);
          if (this.options.crossOrigin || this.options.crossOrigin === "") {
            img.crossOrigin = this.options.crossOrigin === true ? "" : this.options.crossOrigin;
          }
          return img;
        },
        _setIconStyles: function(img, name2) {
          var options2 = this.options;
          var sizeOption = options2[name2 + "Size"];
          if (typeof sizeOption === "number") {
            sizeOption = [sizeOption, sizeOption];
          }
          var size4 = toPoint(sizeOption), anchor = toPoint(name2 === "shadow" && options2.shadowAnchor || options2.iconAnchor || size4 && size4.divideBy(2, true));
          img.className = "leaflet-marker-" + name2 + " " + (options2.className || "");
          if (anchor) {
            img.style.marginLeft = -anchor.x + "px";
            img.style.marginTop = -anchor.y + "px";
          }
          if (size4) {
            img.style.width = size4.x + "px";
            img.style.height = size4.y + "px";
          }
        },
        _createImg: function(src, el2) {
          el2 = el2 || document.createElement("img");
          el2.src = src;
          return el2;
        },
        _getIconUrl: function(name2) {
          return Browser.retina && this.options[name2 + "RetinaUrl"] || this.options[name2 + "Url"];
        }
      });
      function icon(options2) {
        return new Icon2(options2);
      }
      var IconDefault = Icon2.extend({
        options: {
          iconUrl: "marker-icon.png",
          iconRetinaUrl: "marker-icon-2x.png",
          shadowUrl: "marker-shadow.png",
          iconSize: [25, 41],
          iconAnchor: [12, 41],
          popupAnchor: [1, -34],
          tooltipAnchor: [16, -28],
          shadowSize: [41, 41]
        },
        _getIconUrl: function(name2) {
          if (typeof IconDefault.imagePath !== "string") {
            IconDefault.imagePath = this._detectIconPath();
          }
          return (this.options.imagePath || IconDefault.imagePath) + Icon2.prototype._getIconUrl.call(this, name2);
        },
        _stripUrl: function(path) {
          var strip = function(str, re2, idx) {
            var match2 = re2.exec(str);
            return match2 && match2[idx];
          };
          path = strip(path, /^url\((['"])?(.+)\1\)$/, 2);
          return path && strip(path, /^(.*)marker-icon\.png$/, 1);
        },
        _detectIconPath: function() {
          var el2 = create$1("div", "leaflet-default-icon-path", document.body);
          var path = getStyle(el2, "background-image") || getStyle(el2, "backgroundImage");
          document.body.removeChild(el2);
          path = this._stripUrl(path);
          if (path) {
            return path;
          }
          var link2 = document.querySelector('link[href$="leaflet.css"]');
          if (!link2) {
            return "";
          }
          return link2.href.substring(0, link2.href.length - "leaflet.css".length - 1);
        }
      });
      var MarkerDrag = Handler.extend({
        initialize: function(marker2) {
          this._marker = marker2;
        },
        addHooks: function() {
          var icon2 = this._marker._icon;
          if (!this._draggable) {
            this._draggable = new Draggable(icon2, icon2, true);
          }
          this._draggable.on({
            dragstart: this._onDragStart,
            predrag: this._onPreDrag,
            drag: this._onDrag,
            dragend: this._onDragEnd
          }, this).enable();
          addClass(icon2, "leaflet-marker-draggable");
        },
        removeHooks: function() {
          this._draggable.off({
            dragstart: this._onDragStart,
            predrag: this._onPreDrag,
            drag: this._onDrag,
            dragend: this._onDragEnd
          }, this).disable();
          if (this._marker._icon) {
            removeClass(this._marker._icon, "leaflet-marker-draggable");
          }
        },
        moved: function() {
          return this._draggable && this._draggable._moved;
        },
        _adjustPan: function(e3) {
          var marker2 = this._marker, map5 = marker2._map, speed = this._marker.options.autoPanSpeed, padding = this._marker.options.autoPanPadding, iconPos = getPosition(marker2._icon), bounds = map5.getPixelBounds(), origin = map5.getPixelOrigin();
          var panBounds = toBounds(
            bounds.min._subtract(origin).add(padding),
            bounds.max._subtract(origin).subtract(padding)
          );
          if (!panBounds.contains(iconPos)) {
            var movement = toPoint(
              (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) - (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
              (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) - (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
            ).multiplyBy(speed);
            map5.panBy(movement, { animate: false });
            this._draggable._newPos._add(movement);
            this._draggable._startPos._add(movement);
            setPosition(marker2._icon, this._draggable._newPos);
            this._onDrag(e3);
            this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e3));
          }
        },
        _onDragStart: function() {
          this._oldLatLng = this._marker.getLatLng();
          this._marker.closePopup && this._marker.closePopup();
          this._marker.fire("movestart").fire("dragstart");
        },
        _onPreDrag: function(e3) {
          if (this._marker.options.autoPan) {
            cancelAnimFrame(this._panRequest);
            this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e3));
          }
        },
        _onDrag: function(e3) {
          var marker2 = this._marker, shadow = marker2._shadow, iconPos = getPosition(marker2._icon), latlng = marker2._map.layerPointToLatLng(iconPos);
          if (shadow) {
            setPosition(shadow, iconPos);
          }
          marker2._latlng = latlng;
          e3.latlng = latlng;
          e3.oldLatLng = this._oldLatLng;
          marker2.fire("move", e3).fire("drag", e3);
        },
        _onDragEnd: function(e3) {
          cancelAnimFrame(this._panRequest);
          delete this._oldLatLng;
          this._marker.fire("moveend").fire("dragend", e3);
        }
      });
      var Marker2 = Layer2.extend({
        // @section
        // @aka Marker options
        options: {
          // @option icon: Icon = *
          // Icon instance to use for rendering the marker.
          // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
          // If not specified, a common instance of `L.Icon.Default` is used.
          icon: new IconDefault(),
          // Option inherited from "Interactive layer" abstract class
          interactive: true,
          // @option keyboard: Boolean = true
          // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
          keyboard: true,
          // @option title: String = ''
          // Text for the browser tooltip that appear on marker hover (no tooltip by default).
          // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
          title: "",
          // @option alt: String = 'Marker'
          // Text for the `alt` attribute of the icon image.
          // [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled).
          alt: "Marker",
          // @option zIndexOffset: Number = 0
          // By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).
          zIndexOffset: 0,
          // @option opacity: Number = 1.0
          // The opacity of the marker.
          opacity: 1,
          // @option riseOnHover: Boolean = false
          // If `true`, the marker will get on top of others when you hover the mouse over it.
          riseOnHover: false,
          // @option riseOffset: Number = 250
          // The z-index offset used for the `riseOnHover` feature.
          riseOffset: 250,
          // @option pane: String = 'markerPane'
          // `Map pane` where the markers icon will be added.
          pane: "markerPane",
          // @option shadowPane: String = 'shadowPane'
          // `Map pane` where the markers shadow will be added.
          shadowPane: "shadowPane",
          // @option bubblingMouseEvents: Boolean = false
          // When `true`, a mouse event on this marker will trigger the same event on the map
          // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
          bubblingMouseEvents: false,
          // @option autoPanOnFocus: Boolean = true
          // When `true`, the map will pan whenever the marker is focused (via
          // e.g. pressing `tab` on the keyboard) to ensure the marker is
          // visible within the map's bounds
          autoPanOnFocus: true,
          // @section Draggable marker options
          // @option draggable: Boolean = false
          // Whether the marker is draggable with mouse/touch or not.
          draggable: false,
          // @option autoPan: Boolean = false
          // Whether to pan the map when dragging this marker near its edge or not.
          autoPan: false,
          // @option autoPanPadding: Point = Point(50, 50)
          // Distance (in pixels to the left/right and to the top/bottom) of the
          // map edge to start panning the map.
          autoPanPadding: [50, 50],
          // @option autoPanSpeed: Number = 10
          // Number of pixels the map should pan by.
          autoPanSpeed: 10
        },
        /* @section
         *
         * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
         */
        initialize: function(latlng, options2) {
          setOptions2(this, options2);
          this._latlng = toLatLng(latlng);
        },
        onAdd: function(map5) {
          this._zoomAnimated = this._zoomAnimated && map5.options.markerZoomAnimation;
          if (this._zoomAnimated) {
            map5.on("zoomanim", this._animateZoom, this);
          }
          this._initIcon();
          this.update();
        },
        onRemove: function(map5) {
          if (this.dragging && this.dragging.enabled()) {
            this.options.draggable = true;
            this.dragging.removeHooks();
          }
          delete this.dragging;
          if (this._zoomAnimated) {
            map5.off("zoomanim", this._animateZoom, this);
          }
          this._removeIcon();
          this._removeShadow();
        },
        getEvents: function() {
          return {
            zoom: this.update,
            viewreset: this.update
          };
        },
        // @method getLatLng: LatLng
        // Returns the current geographical position of the marker.
        getLatLng: function() {
          return this._latlng;
        },
        // @method setLatLng(latlng: LatLng): this
        // Changes the marker position to the given point.
        setLatLng: function(latlng) {
          var oldLatLng = this._latlng;
          this._latlng = toLatLng(latlng);
          this.update();
          return this.fire("move", { oldLatLng, latlng: this._latlng });
        },
        // @method setZIndexOffset(offset: Number): this
        // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
        setZIndexOffset: function(offset) {
          this.options.zIndexOffset = offset;
          return this.update();
        },
        // @method getIcon: Icon
        // Returns the current icon used by the marker
        getIcon: function() {
          return this.options.icon;
        },
        // @method setIcon(icon: Icon): this
        // Changes the marker icon.
        setIcon: function(icon2) {
          this.options.icon = icon2;
          if (this._map) {
            this._initIcon();
            this.update();
          }
          if (this._popup) {
            this.bindPopup(this._popup, this._popup.options);
          }
          return this;
        },
        getElement: function() {
          return this._icon;
        },
        update: function() {
          if (this._icon && this._map) {
            var pos = this._map.latLngToLayerPoint(this._latlng).round();
            this._setPos(pos);
          }
          return this;
        },
        _initIcon: function() {
          var options2 = this.options, classToAdd = "leaflet-zoom-" + (this._zoomAnimated ? "animated" : "hide");
          var icon2 = options2.icon.createIcon(this._icon), addIcon = false;
          if (icon2 !== this._icon) {
            if (this._icon) {
              this._removeIcon();
            }
            addIcon = true;
            if (options2.title) {
              icon2.title = options2.title;
            }
            if (icon2.tagName === "IMG") {
              icon2.alt = options2.alt || "";
            }
          }
          addClass(icon2, classToAdd);
          if (options2.keyboard) {
            icon2.tabIndex = "0";
            icon2.setAttribute("role", "button");
          }
          this._icon = icon2;
          if (options2.riseOnHover) {
            this.on({
              mouseover: this._bringToFront,
              mouseout: this._resetZIndex
            });
          }
          if (this.options.autoPanOnFocus) {
            on2(icon2, "focus", this._panOnFocus, this);
          }
          var newShadow = options2.icon.createShadow(this._shadow), addShadow = false;
          if (newShadow !== this._shadow) {
            this._removeShadow();
            addShadow = true;
          }
          if (newShadow) {
            addClass(newShadow, classToAdd);
            newShadow.alt = "";
          }
          this._shadow = newShadow;
          if (options2.opacity < 1) {
            this._updateOpacity();
          }
          if (addIcon) {
            this.getPane().appendChild(this._icon);
          }
          this._initInteraction();
          if (newShadow && addShadow) {
            this.getPane(options2.shadowPane).appendChild(this._shadow);
          }
        },
        _removeIcon: function() {
          if (this.options.riseOnHover) {
            this.off({
              mouseover: this._bringToFront,
              mouseout: this._resetZIndex
            });
          }
          if (this.options.autoPanOnFocus) {
            off(this._icon, "focus", this._panOnFocus, this);
          }
          remove3(this._icon);
          this.removeInteractiveTarget(this._icon);
          this._icon = null;
        },
        _removeShadow: function() {
          if (this._shadow) {
            remove3(this._shadow);
          }
          this._shadow = null;
        },
        _setPos: function(pos) {
          if (this._icon) {
            setPosition(this._icon, pos);
          }
          if (this._shadow) {
            setPosition(this._shadow, pos);
          }
          this._zIndex = pos.y + this.options.zIndexOffset;
          this._resetZIndex();
        },
        _updateZIndex: function(offset) {
          if (this._icon) {
            this._icon.style.zIndex = this._zIndex + offset;
          }
        },
        _animateZoom: function(opt) {
          var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
          this._setPos(pos);
        },
        _initInteraction: function() {
          if (!this.options.interactive) {
            return;
          }
          addClass(this._icon, "leaflet-interactive");
          this.addInteractiveTarget(this._icon);
          if (MarkerDrag) {
            var draggable2 = this.options.draggable;
            if (this.dragging) {
              draggable2 = this.dragging.enabled();
              this.dragging.disable();
            }
            this.dragging = new MarkerDrag(this);
            if (draggable2) {
              this.dragging.enable();
            }
          }
        },
        // @method setOpacity(opacity: Number): this
        // Changes the opacity of the marker.
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          if (this._map) {
            this._updateOpacity();
          }
          return this;
        },
        _updateOpacity: function() {
          var opacity = this.options.opacity;
          if (this._icon) {
            setOpacity(this._icon, opacity);
          }
          if (this._shadow) {
            setOpacity(this._shadow, opacity);
          }
        },
        _bringToFront: function() {
          this._updateZIndex(this.options.riseOffset);
        },
        _resetZIndex: function() {
          this._updateZIndex(0);
        },
        _panOnFocus: function() {
          var map5 = this._map;
          if (!map5) {
            return;
          }
          var iconOpts = this.options.icon.options;
          var size4 = iconOpts.iconSize ? toPoint(iconOpts.iconSize) : toPoint(0, 0);
          var anchor = iconOpts.iconAnchor ? toPoint(iconOpts.iconAnchor) : toPoint(0, 0);
          map5.panInside(this._latlng, {
            paddingTopLeft: anchor,
            paddingBottomRight: size4.subtract(anchor)
          });
        },
        _getPopupAnchor: function() {
          return this.options.icon.options.popupAnchor;
        },
        _getTooltipAnchor: function() {
          return this.options.icon.options.tooltipAnchor;
        }
      });
      function marker(latlng, options2) {
        return new Marker2(latlng, options2);
      }
      var Path = Layer2.extend({
        // @section
        // @aka Path options
        options: {
          // @option stroke: Boolean = true
          // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
          stroke: true,
          // @option color: String = '#3388ff'
          // Stroke color
          color: "#3388ff",
          // @option weight: Number = 3
          // Stroke width in pixels
          weight: 3,
          // @option opacity: Number = 1.0
          // Stroke opacity
          opacity: 1,
          // @option lineCap: String= 'round'
          // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
          lineCap: "round",
          // @option lineJoin: String = 'round'
          // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
          lineJoin: "round",
          // @option dashArray: String = null
          // A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
          dashArray: null,
          // @option dashOffset: String = null
          // A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).
          dashOffset: null,
          // @option fill: Boolean = depends
          // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
          fill: false,
          // @option fillColor: String = *
          // Fill color. Defaults to the value of the [`color`](#path-color) option
          fillColor: null,
          // @option fillOpacity: Number = 0.2
          // Fill opacity.
          fillOpacity: 0.2,
          // @option fillRule: String = 'evenodd'
          // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
          fillRule: "evenodd",
          // className: '',
          // Option inherited from "Interactive layer" abstract class
          interactive: true,
          // @option bubblingMouseEvents: Boolean = true
          // When `true`, a mouse event on this path will trigger the same event on the map
          // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
          bubblingMouseEvents: true
        },
        beforeAdd: function(map5) {
          this._renderer = map5.getRenderer(this);
        },
        onAdd: function() {
          this._renderer._initPath(this);
          this._reset();
          this._renderer._addPath(this);
        },
        onRemove: function() {
          this._renderer._removePath(this);
        },
        // @method redraw(): this
        // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
        redraw: function() {
          if (this._map) {
            this._renderer._updatePath(this);
          }
          return this;
        },
        // @method setStyle(style: Path options): this
        // Changes the appearance of a Path based on the options in the `Path options` object.
        setStyle: function(style4) {
          setOptions2(this, style4);
          if (this._renderer) {
            this._renderer._updateStyle(this);
            if (this.options.stroke && style4 && Object.prototype.hasOwnProperty.call(style4, "weight")) {
              this._updateBounds();
            }
          }
          return this;
        },
        // @method bringToFront(): this
        // Brings the layer to the top of all path layers.
        bringToFront: function() {
          if (this._renderer) {
            this._renderer._bringToFront(this);
          }
          return this;
        },
        // @method bringToBack(): this
        // Brings the layer to the bottom of all path layers.
        bringToBack: function() {
          if (this._renderer) {
            this._renderer._bringToBack(this);
          }
          return this;
        },
        getElement: function() {
          return this._path;
        },
        _reset: function() {
          this._project();
          this._update();
        },
        _clickTolerance: function() {
          return (this.options.stroke ? this.options.weight / 2 : 0) + (this._renderer.options.tolerance || 0);
        }
      });
      var CircleMarker = Path.extend({
        // @section
        // @aka CircleMarker options
        options: {
          fill: true,
          // @option radius: Number = 10
          // Radius of the circle marker, in pixels
          radius: 10
        },
        initialize: function(latlng, options2) {
          setOptions2(this, options2);
          this._latlng = toLatLng(latlng);
          this._radius = this.options.radius;
        },
        // @method setLatLng(latLng: LatLng): this
        // Sets the position of a circle marker to a new location.
        setLatLng: function(latlng) {
          var oldLatLng = this._latlng;
          this._latlng = toLatLng(latlng);
          this.redraw();
          return this.fire("move", { oldLatLng, latlng: this._latlng });
        },
        // @method getLatLng(): LatLng
        // Returns the current geographical position of the circle marker
        getLatLng: function() {
          return this._latlng;
        },
        // @method setRadius(radius: Number): this
        // Sets the radius of a circle marker. Units are in pixels.
        setRadius: function(radius) {
          this.options.radius = this._radius = radius;
          return this.redraw();
        },
        // @method getRadius(): Number
        // Returns the current radius of the circle
        getRadius: function() {
          return this._radius;
        },
        setStyle: function(options2) {
          var radius = options2 && options2.radius || this._radius;
          Path.prototype.setStyle.call(this, options2);
          this.setRadius(radius);
          return this;
        },
        _project: function() {
          this._point = this._map.latLngToLayerPoint(this._latlng);
          this._updateBounds();
        },
        _updateBounds: function() {
          var r3 = this._radius, r22 = this._radiusY || r3, w3 = this._clickTolerance(), p4 = [r3 + w3, r22 + w3];
          this._pxBounds = new Bounds2(this._point.subtract(p4), this._point.add(p4));
        },
        _update: function() {
          if (this._map) {
            this._updatePath();
          }
        },
        _updatePath: function() {
          this._renderer._updateCircle(this);
        },
        _empty: function() {
          return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
        },
        // Needed by the `Canvas` renderer for interactivity
        _containsPoint: function(p4) {
          return p4.distanceTo(this._point) <= this._radius + this._clickTolerance();
        }
      });
      function circleMarker(latlng, options2) {
        return new CircleMarker(latlng, options2);
      }
      var Circle = CircleMarker.extend({
        initialize: function(latlng, options2, legacyOptions) {
          if (typeof options2 === "number") {
            options2 = extend({}, legacyOptions, { radius: options2 });
          }
          setOptions2(this, options2);
          this._latlng = toLatLng(latlng);
          if (isNaN(this.options.radius)) {
            throw new Error("Circle radius cannot be NaN");
          }
          this._mRadius = this.options.radius;
        },
        // @method setRadius(radius: Number): this
        // Sets the radius of a circle. Units are in meters.
        setRadius: function(radius) {
          this._mRadius = radius;
          return this.redraw();
        },
        // @method getRadius(): Number
        // Returns the current radius of a circle. Units are in meters.
        getRadius: function() {
          return this._mRadius;
        },
        // @method getBounds(): LatLngBounds
        // Returns the `LatLngBounds` of the path.
        getBounds: function() {
          var half = [this._radius, this._radiusY || this._radius];
          return new LatLngBounds(
            this._map.layerPointToLatLng(this._point.subtract(half)),
            this._map.layerPointToLatLng(this._point.add(half))
          );
        },
        setStyle: Path.prototype.setStyle,
        _project: function() {
          var lng = this._latlng.lng, lat = this._latlng.lat, map5 = this._map, crs = map5.options.crs;
          if (crs.distance === Earth.distance) {
            var d3 = Math.PI / 180, latR = this._mRadius / Earth.R / d3, top2 = map5.project([lat + latR, lng]), bottom = map5.project([lat - latR, lng]), p4 = top2.add(bottom).divideBy(2), lat2 = map5.unproject(p4).lat, lngR = Math.acos((Math.cos(latR * d3) - Math.sin(lat * d3) * Math.sin(lat2 * d3)) / (Math.cos(lat * d3) * Math.cos(lat2 * d3))) / d3;
            if (isNaN(lngR) || lngR === 0) {
              lngR = latR / Math.cos(Math.PI / 180 * lat);
            }
            this._point = p4.subtract(map5.getPixelOrigin());
            this._radius = isNaN(lngR) ? 0 : p4.x - map5.project([lat2, lng - lngR]).x;
            this._radiusY = p4.y - top2.y;
          } else {
            var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
            this._point = map5.latLngToLayerPoint(this._latlng);
            this._radius = this._point.x - map5.latLngToLayerPoint(latlng2).x;
          }
          this._updateBounds();
        }
      });
      function circle(latlng, options2, legacyOptions) {
        return new Circle(latlng, options2, legacyOptions);
      }
      var Polyline = Path.extend({
        // @section
        // @aka Polyline options
        options: {
          // @option smoothFactor: Number = 1.0
          // How much to simplify the polyline on each zoom level. More means
          // better performance and smoother look, and less means more accurate representation.
          smoothFactor: 1,
          // @option noClip: Boolean = false
          // Disable polyline clipping.
          noClip: false
        },
        initialize: function(latlngs, options2) {
          setOptions2(this, options2);
          this._setLatLngs(latlngs);
        },
        // @method getLatLngs(): LatLng[]
        // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
        getLatLngs: function() {
          return this._latlngs;
        },
        // @method setLatLngs(latlngs: LatLng[]): this
        // Replaces all the points in the polyline with the given array of geographical points.
        setLatLngs: function(latlngs) {
          this._setLatLngs(latlngs);
          return this.redraw();
        },
        // @method isEmpty(): Boolean
        // Returns `true` if the Polyline has no LatLngs.
        isEmpty: function() {
          return !this._latlngs.length;
        },
        // @method closestLayerPoint(p: Point): Point
        // Returns the point closest to `p` on the Polyline.
        closestLayerPoint: function(p4) {
          var minDistance = Infinity, minPoint = null, closest = _sqClosestPointOnSegment, p1, p22;
          for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
            var points = this._parts[j];
            for (var i3 = 1, len = points.length; i3 < len; i3++) {
              p1 = points[i3 - 1];
              p22 = points[i3];
              var sqDist = closest(p4, p1, p22, true);
              if (sqDist < minDistance) {
                minDistance = sqDist;
                minPoint = closest(p4, p1, p22);
              }
            }
          }
          if (minPoint) {
            minPoint.distance = Math.sqrt(minDistance);
          }
          return minPoint;
        },
        // @method getCenter(): LatLng
        // Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline.
        getCenter: function() {
          if (!this._map) {
            throw new Error("Must add layer to map before using getCenter()");
          }
          return polylineCenter(this._defaultShape(), this._map.options.crs);
        },
        // @method getBounds(): LatLngBounds
        // Returns the `LatLngBounds` of the path.
        getBounds: function() {
          return this._bounds;
        },
        // @method addLatLng(latlng: LatLng, latlngs?: LatLng[]): this
        // Adds a given point to the polyline. By default, adds to the first ring of
        // the polyline in case of a multi-polyline, but can be overridden by passing
        // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
        addLatLng: function(latlng, latlngs) {
          latlngs = latlngs || this._defaultShape();
          latlng = toLatLng(latlng);
          latlngs.push(latlng);
          this._bounds.extend(latlng);
          return this.redraw();
        },
        _setLatLngs: function(latlngs) {
          this._bounds = new LatLngBounds();
          this._latlngs = this._convertLatLngs(latlngs);
        },
        _defaultShape: function() {
          return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
        },
        // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
        _convertLatLngs: function(latlngs) {
          var result2 = [], flat = isFlat(latlngs);
          for (var i3 = 0, len = latlngs.length; i3 < len; i3++) {
            if (flat) {
              result2[i3] = toLatLng(latlngs[i3]);
              this._bounds.extend(result2[i3]);
            } else {
              result2[i3] = this._convertLatLngs(latlngs[i3]);
            }
          }
          return result2;
        },
        _project: function() {
          var pxBounds = new Bounds2();
          this._rings = [];
          this._projectLatlngs(this._latlngs, this._rings, pxBounds);
          if (this._bounds.isValid() && pxBounds.isValid()) {
            this._rawPxBounds = pxBounds;
            this._updateBounds();
          }
        },
        _updateBounds: function() {
          var w3 = this._clickTolerance(), p4 = new Point2(w3, w3);
          if (!this._rawPxBounds) {
            return;
          }
          this._pxBounds = new Bounds2([
            this._rawPxBounds.min.subtract(p4),
            this._rawPxBounds.max.add(p4)
          ]);
        },
        // recursively turns latlngs into a set of rings with projected coordinates
        _projectLatlngs: function(latlngs, result2, projectedBounds) {
          var flat = latlngs[0] instanceof LatLng, len = latlngs.length, i3, ring;
          if (flat) {
            ring = [];
            for (i3 = 0; i3 < len; i3++) {
              ring[i3] = this._map.latLngToLayerPoint(latlngs[i3]);
              projectedBounds.extend(ring[i3]);
            }
            result2.push(ring);
          } else {
            for (i3 = 0; i3 < len; i3++) {
              this._projectLatlngs(latlngs[i3], result2, projectedBounds);
            }
          }
        },
        // clip polyline by renderer bounds so that we have less to render for performance
        _clipPoints: function() {
          var bounds = this._renderer._bounds;
          this._parts = [];
          if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
            return;
          }
          if (this.options.noClip) {
            this._parts = this._rings;
            return;
          }
          var parts = this._parts, i3, j, k2, len, len2, segment, points;
          for (i3 = 0, k2 = 0, len = this._rings.length; i3 < len; i3++) {
            points = this._rings[i3];
            for (j = 0, len2 = points.length; j < len2 - 1; j++) {
              segment = clipSegment(points[j], points[j + 1], bounds, j, true);
              if (!segment) {
                continue;
              }
              parts[k2] = parts[k2] || [];
              parts[k2].push(segment[0]);
              if (segment[1] !== points[j + 1] || j === len2 - 2) {
                parts[k2].push(segment[1]);
                k2++;
              }
            }
          }
        },
        // simplify each clipped part of the polyline for performance
        _simplifyPoints: function() {
          var parts = this._parts, tolerance = this.options.smoothFactor;
          for (var i3 = 0, len = parts.length; i3 < len; i3++) {
            parts[i3] = simplify(parts[i3], tolerance);
          }
        },
        _update: function() {
          if (!this._map) {
            return;
          }
          this._clipPoints();
          this._simplifyPoints();
          this._updatePath();
        },
        _updatePath: function() {
          this._renderer._updatePoly(this);
        },
        // Needed by the `Canvas` renderer for interactivity
        _containsPoint: function(p4, closed) {
          var i3, j, k2, len, len2, part, w3 = this._clickTolerance();
          if (!this._pxBounds || !this._pxBounds.contains(p4)) {
            return false;
          }
          for (i3 = 0, len = this._parts.length; i3 < len; i3++) {
            part = this._parts[i3];
            for (j = 0, len2 = part.length, k2 = len2 - 1; j < len2; k2 = j++) {
              if (!closed && j === 0) {
                continue;
              }
              if (pointToSegmentDistance(p4, part[k2], part[j]) <= w3) {
                return true;
              }
            }
          }
          return false;
        }
      });
      function polyline(latlngs, options2) {
        return new Polyline(latlngs, options2);
      }
      Polyline._flat = _flat;
      var Polygon = Polyline.extend({
        options: {
          fill: true
        },
        isEmpty: function() {
          return !this._latlngs.length || !this._latlngs[0].length;
        },
        // @method getCenter(): LatLng
        // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon.
        getCenter: function() {
          if (!this._map) {
            throw new Error("Must add layer to map before using getCenter()");
          }
          return polygonCenter(this._defaultShape(), this._map.options.crs);
        },
        _convertLatLngs: function(latlngs) {
          var result2 = Polyline.prototype._convertLatLngs.call(this, latlngs), len = result2.length;
          if (len >= 2 && result2[0] instanceof LatLng && result2[0].equals(result2[len - 1])) {
            result2.pop();
          }
          return result2;
        },
        _setLatLngs: function(latlngs) {
          Polyline.prototype._setLatLngs.call(this, latlngs);
          if (isFlat(this._latlngs)) {
            this._latlngs = [this._latlngs];
          }
        },
        _defaultShape: function() {
          return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
        },
        _clipPoints: function() {
          var bounds = this._renderer._bounds, w3 = this.options.weight, p4 = new Point2(w3, w3);
          bounds = new Bounds2(bounds.min.subtract(p4), bounds.max.add(p4));
          this._parts = [];
          if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
            return;
          }
          if (this.options.noClip) {
            this._parts = this._rings;
            return;
          }
          for (var i3 = 0, len = this._rings.length, clipped; i3 < len; i3++) {
            clipped = clipPolygon(this._rings[i3], bounds, true);
            if (clipped.length) {
              this._parts.push(clipped);
            }
          }
        },
        _updatePath: function() {
          this._renderer._updatePoly(this, true);
        },
        // Needed by the `Canvas` renderer for interactivity
        _containsPoint: function(p4) {
          var inside = false, part, p1, p22, i3, j, k2, len, len2;
          if (!this._pxBounds || !this._pxBounds.contains(p4)) {
            return false;
          }
          for (i3 = 0, len = this._parts.length; i3 < len; i3++) {
            part = this._parts[i3];
            for (j = 0, len2 = part.length, k2 = len2 - 1; j < len2; k2 = j++) {
              p1 = part[j];
              p22 = part[k2];
              if (p1.y > p4.y !== p22.y > p4.y && p4.x < (p22.x - p1.x) * (p4.y - p1.y) / (p22.y - p1.y) + p1.x) {
                inside = !inside;
              }
            }
          }
          return inside || Polyline.prototype._containsPoint.call(this, p4, true);
        }
      });
      function polygon(latlngs, options2) {
        return new Polygon(latlngs, options2);
      }
      var GeoJSON = FeatureGroup.extend({
        /* @section
         * @aka GeoJSON options
         *
         * @option pointToLayer: Function = *
         * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
         * called when data is added, passing the GeoJSON point feature and its `LatLng`.
         * The default is to spawn a default `Marker`:
         * ```js
         * function(geoJsonPoint, latlng) {
         * 	return L.marker(latlng);
         * }
         * ```
         *
         * @option style: Function = *
         * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
         * called internally when data is added.
         * The default value is to not override any defaults:
         * ```js
         * function (geoJsonFeature) {
         * 	return {}
         * }
         * ```
         *
         * @option onEachFeature: Function = *
         * A `Function` that will be called once for each created `Feature`, after it has
         * been created and styled. Useful for attaching events and popups to features.
         * The default is to do nothing with the newly created layers:
         * ```js
         * function (feature, layer) {}
         * ```
         *
         * @option filter: Function = *
         * A `Function` that will be used to decide whether to include a feature or not.
         * The default is to include all features:
         * ```js
         * function (geoJsonFeature) {
         * 	return true;
         * }
         * ```
         * Note: dynamically changing the `filter` option will have effect only on newly
         * added data. It will _not_ re-evaluate already included features.
         *
         * @option coordsToLatLng: Function = *
         * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
         * The default is the `coordsToLatLng` static method.
         *
         * @option markersInheritOptions: Boolean = false
         * Whether default Markers for "Point" type Features inherit from group options.
         */
        initialize: function(geojson, options2) {
          setOptions2(this, options2);
          this._layers = {};
          if (geojson) {
            this.addData(geojson);
          }
        },
        // @method addData( <GeoJSON> data ): this
        // Adds a GeoJSON object to the layer.
        addData: function(geojson) {
          var features = isArray3(geojson) ? geojson : geojson.features, i3, len, feature;
          if (features) {
            for (i3 = 0, len = features.length; i3 < len; i3++) {
              feature = features[i3];
              if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
                this.addData(feature);
              }
            }
            return this;
          }
          var options2 = this.options;
          if (options2.filter && !options2.filter(geojson)) {
            return this;
          }
          var layer2 = geometryToLayer(geojson, options2);
          if (!layer2) {
            return this;
          }
          layer2.feature = asFeature(geojson);
          layer2.defaultOptions = layer2.options;
          this.resetStyle(layer2);
          if (options2.onEachFeature) {
            options2.onEachFeature(geojson, layer2);
          }
          return this.addLayer(layer2);
        },
        // @method resetStyle( <Path> layer? ): this
        // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
        // If `layer` is omitted, the style of all features in the current layer is reset.
        resetStyle: function(layer2) {
          if (layer2 === void 0) {
            return this.eachLayer(this.resetStyle, this);
          }
          layer2.options = extend({}, layer2.defaultOptions);
          this._setLayerStyle(layer2, this.options.style);
          return this;
        },
        // @method setStyle( <Function> style ): this
        // Changes styles of GeoJSON vector layers with the given style function.
        setStyle: function(style4) {
          return this.eachLayer(function(layer2) {
            this._setLayerStyle(layer2, style4);
          }, this);
        },
        _setLayerStyle: function(layer2, style4) {
          if (layer2.setStyle) {
            if (typeof style4 === "function") {
              style4 = style4(layer2.feature);
            }
            layer2.setStyle(style4);
          }
        }
      });
      function geometryToLayer(geojson, options2) {
        var geometry = geojson.type === "Feature" ? geojson.geometry : geojson, coords = geometry ? geometry.coordinates : null, layers2 = [], pointToLayer = options2 && options2.pointToLayer, _coordsToLatLng = options2 && options2.coordsToLatLng || coordsToLatLng, latlng, latlngs, i3, len;
        if (!coords && !geometry) {
          return null;
        }
        switch (geometry.type) {
          case "Point":
            latlng = _coordsToLatLng(coords);
            return _pointToLayer(pointToLayer, geojson, latlng, options2);
          case "MultiPoint":
            for (i3 = 0, len = coords.length; i3 < len; i3++) {
              latlng = _coordsToLatLng(coords[i3]);
              layers2.push(_pointToLayer(pointToLayer, geojson, latlng, options2));
            }
            return new FeatureGroup(layers2);
          case "LineString":
          case "MultiLineString":
            latlngs = coordsToLatLngs(coords, geometry.type === "LineString" ? 0 : 1, _coordsToLatLng);
            return new Polyline(latlngs, options2);
          case "Polygon":
          case "MultiPolygon":
            latlngs = coordsToLatLngs(coords, geometry.type === "Polygon" ? 1 : 2, _coordsToLatLng);
            return new Polygon(latlngs, options2);
          case "GeometryCollection":
            for (i3 = 0, len = geometry.geometries.length; i3 < len; i3++) {
              var geoLayer = geometryToLayer({
                geometry: geometry.geometries[i3],
                type: "Feature",
                properties: geojson.properties
              }, options2);
              if (geoLayer) {
                layers2.push(geoLayer);
              }
            }
            return new FeatureGroup(layers2);
          case "FeatureCollection":
            for (i3 = 0, len = geometry.features.length; i3 < len; i3++) {
              var featureLayer = geometryToLayer(geometry.features[i3], options2);
              if (featureLayer) {
                layers2.push(featureLayer);
              }
            }
            return new FeatureGroup(layers2);
          default:
            throw new Error("Invalid GeoJSON object.");
        }
      }
      function _pointToLayer(pointToLayerFn, geojson, latlng, options2) {
        return pointToLayerFn ? pointToLayerFn(geojson, latlng) : new Marker2(latlng, options2 && options2.markersInheritOptions && options2);
      }
      function coordsToLatLng(coords) {
        return new LatLng(coords[1], coords[0], coords[2]);
      }
      function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
        var latlngs = [];
        for (var i3 = 0, len = coords.length, latlng; i3 < len; i3++) {
          latlng = levelsDeep ? coordsToLatLngs(coords[i3], levelsDeep - 1, _coordsToLatLng) : (_coordsToLatLng || coordsToLatLng)(coords[i3]);
          latlngs.push(latlng);
        }
        return latlngs;
      }
      function latLngToCoords(latlng, precision) {
        latlng = toLatLng(latlng);
        return latlng.alt !== void 0 ? [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] : [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
      }
      function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
        var coords = [];
        for (var i3 = 0, len = latlngs.length; i3 < len; i3++) {
          coords.push(levelsDeep ? latLngsToCoords(latlngs[i3], isFlat(latlngs[i3]) ? 0 : levelsDeep - 1, closed, precision) : latLngToCoords(latlngs[i3], precision));
        }
        if (!levelsDeep && closed && coords.length > 0) {
          coords.push(coords[0].slice());
        }
        return coords;
      }
      function getFeature(layer2, newGeometry) {
        return layer2.feature ? extend({}, layer2.feature, { geometry: newGeometry }) : asFeature(newGeometry);
      }
      function asFeature(geojson) {
        if (geojson.type === "Feature" || geojson.type === "FeatureCollection") {
          return geojson;
        }
        return {
          type: "Feature",
          properties: {},
          geometry: geojson
        };
      }
      var PointToGeoJSON = {
        toGeoJSON: function(precision) {
          return getFeature(this, {
            type: "Point",
            coordinates: latLngToCoords(this.getLatLng(), precision)
          });
        }
      };
      Marker2.include(PointToGeoJSON);
      Circle.include(PointToGeoJSON);
      CircleMarker.include(PointToGeoJSON);
      Polyline.include({
        toGeoJSON: function(precision) {
          var multi = !isFlat(this._latlngs);
          var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
          return getFeature(this, {
            type: (multi ? "Multi" : "") + "LineString",
            coordinates: coords
          });
        }
      });
      Polygon.include({
        toGeoJSON: function(precision) {
          var holes = !isFlat(this._latlngs), multi = holes && !isFlat(this._latlngs[0]);
          var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
          if (!holes) {
            coords = [coords];
          }
          return getFeature(this, {
            type: (multi ? "Multi" : "") + "Polygon",
            coordinates: coords
          });
        }
      });
      LayerGroup.include({
        toMultiPoint: function(precision) {
          var coords = [];
          this.eachLayer(function(layer2) {
            coords.push(layer2.toGeoJSON(precision).geometry.coordinates);
          });
          return getFeature(this, {
            type: "MultiPoint",
            coordinates: coords
          });
        },
        // @method toGeoJSON(precision?: Number|false): Object
        // Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`.
        // Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
        toGeoJSON: function(precision) {
          var type = this.feature && this.feature.geometry && this.feature.geometry.type;
          if (type === "MultiPoint") {
            return this.toMultiPoint(precision);
          }
          var isGeometryCollection = type === "GeometryCollection", jsons = [];
          this.eachLayer(function(layer2) {
            if (layer2.toGeoJSON) {
              var json2 = layer2.toGeoJSON(precision);
              if (isGeometryCollection) {
                jsons.push(json2.geometry);
              } else {
                var feature = asFeature(json2);
                if (feature.type === "FeatureCollection") {
                  jsons.push.apply(jsons, feature.features);
                } else {
                  jsons.push(feature);
                }
              }
            }
          });
          if (isGeometryCollection) {
            return getFeature(this, {
              geometries: jsons,
              type: "GeometryCollection"
            });
          }
          return {
            type: "FeatureCollection",
            features: jsons
          };
        }
      });
      function geoJSON(geojson, options2) {
        return new GeoJSON(geojson, options2);
      }
      var geoJson = geoJSON;
      var ImageOverlay = Layer2.extend({
        // @section
        // @aka ImageOverlay options
        options: {
          // @option opacity: Number = 1.0
          // The opacity of the image overlay.
          opacity: 1,
          // @option alt: String = ''
          // Text for the `alt` attribute of the image (useful for accessibility).
          alt: "",
          // @option interactive: Boolean = false
          // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
          interactive: false,
          // @option crossOrigin: Boolean|String = false
          // Whether the crossOrigin attribute will be added to the image.
          // If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.
          // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
          crossOrigin: false,
          // @option errorOverlayUrl: String = ''
          // URL to the overlay image to show in place of the overlay that failed to load.
          errorOverlayUrl: "",
          // @option zIndex: Number = 1
          // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.
          zIndex: 1,
          // @option className: String = ''
          // A custom class name to assign to the image. Empty by default.
          className: ""
        },
        initialize: function(url2, bounds, options2) {
          this._url = url2;
          this._bounds = toLatLngBounds(bounds);
          setOptions2(this, options2);
        },
        onAdd: function() {
          if (!this._image) {
            this._initImage();
            if (this.options.opacity < 1) {
              this._updateOpacity();
            }
          }
          if (this.options.interactive) {
            addClass(this._image, "leaflet-interactive");
            this.addInteractiveTarget(this._image);
          }
          this.getPane().appendChild(this._image);
          this._reset();
        },
        onRemove: function() {
          remove3(this._image);
          if (this.options.interactive) {
            this.removeInteractiveTarget(this._image);
          }
        },
        // @method setOpacity(opacity: Number): this
        // Sets the opacity of the overlay.
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          if (this._image) {
            this._updateOpacity();
          }
          return this;
        },
        setStyle: function(styleOpts) {
          if (styleOpts.opacity) {
            this.setOpacity(styleOpts.opacity);
          }
          return this;
        },
        // @method bringToFront(): this
        // Brings the layer to the top of all overlays.
        bringToFront: function() {
          if (this._map) {
            toFront(this._image);
          }
          return this;
        },
        // @method bringToBack(): this
        // Brings the layer to the bottom of all overlays.
        bringToBack: function() {
          if (this._map) {
            toBack(this._image);
          }
          return this;
        },
        // @method setUrl(url: String): this
        // Changes the URL of the image.
        setUrl: function(url2) {
          this._url = url2;
          if (this._image) {
            this._image.src = url2;
          }
          return this;
        },
        // @method setBounds(bounds: LatLngBounds): this
        // Update the bounds that this ImageOverlay covers
        setBounds: function(bounds) {
          this._bounds = toLatLngBounds(bounds);
          if (this._map) {
            this._reset();
          }
          return this;
        },
        getEvents: function() {
          var events2 = {
            zoom: this._reset,
            viewreset: this._reset
          };
          if (this._zoomAnimated) {
            events2.zoomanim = this._animateZoom;
          }
          return events2;
        },
        // @method setZIndex(value: Number): this
        // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
        setZIndex: function(value2) {
          this.options.zIndex = value2;
          this._updateZIndex();
          return this;
        },
        // @method getBounds(): LatLngBounds
        // Get the bounds that this ImageOverlay covers
        getBounds: function() {
          return this._bounds;
        },
        // @method getElement(): HTMLElement
        // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
        // used by this overlay.
        getElement: function() {
          return this._image;
        },
        _initImage: function() {
          var wasElementSupplied = this._url.tagName === "IMG";
          var img = this._image = wasElementSupplied ? this._url : create$1("img");
          addClass(img, "leaflet-image-layer");
          if (this._zoomAnimated) {
            addClass(img, "leaflet-zoom-animated");
          }
          if (this.options.className) {
            addClass(img, this.options.className);
          }
          img.onselectstart = falseFn2;
          img.onmousemove = falseFn2;
          img.onload = bind2(this.fire, this, "load");
          img.onerror = bind2(this._overlayOnError, this, "error");
          if (this.options.crossOrigin || this.options.crossOrigin === "") {
            img.crossOrigin = this.options.crossOrigin === true ? "" : this.options.crossOrigin;
          }
          if (this.options.zIndex) {
            this._updateZIndex();
          }
          if (wasElementSupplied) {
            this._url = img.src;
            return;
          }
          img.src = this._url;
          img.alt = this.options.alt;
        },
        _animateZoom: function(e3) {
          var scale2 = this._map.getZoomScale(e3.zoom), offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e3.zoom, e3.center).min;
          setTransform(this._image, offset, scale2);
        },
        _reset: function() {
          var image2 = this._image, bounds = new Bounds2(
            this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
            this._map.latLngToLayerPoint(this._bounds.getSouthEast())
          ), size4 = bounds.getSize();
          setPosition(image2, bounds.min);
          image2.style.width = size4.x + "px";
          image2.style.height = size4.y + "px";
        },
        _updateOpacity: function() {
          setOpacity(this._image, this.options.opacity);
        },
        _updateZIndex: function() {
          if (this._image && this.options.zIndex !== void 0 && this.options.zIndex !== null) {
            this._image.style.zIndex = this.options.zIndex;
          }
        },
        _overlayOnError: function() {
          this.fire("error");
          var errorUrl = this.options.errorOverlayUrl;
          if (errorUrl && this._url !== errorUrl) {
            this._url = errorUrl;
            this._image.src = errorUrl;
          }
        },
        // @method getCenter(): LatLng
        // Returns the center of the ImageOverlay.
        getCenter: function() {
          return this._bounds.getCenter();
        }
      });
      var imageOverlay = function(url2, bounds, options2) {
        return new ImageOverlay(url2, bounds, options2);
      };
      var VideoOverlay = ImageOverlay.extend({
        // @section
        // @aka VideoOverlay options
        options: {
          // @option autoplay: Boolean = true
          // Whether the video starts playing automatically when loaded.
          // On some browsers autoplay will only work with `muted: true`
          autoplay: true,
          // @option loop: Boolean = true
          // Whether the video will loop back to the beginning when played.
          loop: true,
          // @option keepAspectRatio: Boolean = true
          // Whether the video will save aspect ratio after the projection.
          // Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
          keepAspectRatio: true,
          // @option muted: Boolean = false
          // Whether the video starts on mute when loaded.
          muted: false,
          // @option playsInline: Boolean = true
          // Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.
          playsInline: true
        },
        _initImage: function() {
          var wasElementSupplied = this._url.tagName === "VIDEO";
          var vid = this._image = wasElementSupplied ? this._url : create$1("video");
          addClass(vid, "leaflet-image-layer");
          if (this._zoomAnimated) {
            addClass(vid, "leaflet-zoom-animated");
          }
          if (this.options.className) {
            addClass(vid, this.options.className);
          }
          vid.onselectstart = falseFn2;
          vid.onmousemove = falseFn2;
          vid.onloadeddata = bind2(this.fire, this, "load");
          if (wasElementSupplied) {
            var sourceElements = vid.getElementsByTagName("source");
            var sources = [];
            for (var j = 0; j < sourceElements.length; j++) {
              sources.push(sourceElements[j].src);
            }
            this._url = sourceElements.length > 0 ? sources : [vid.src];
            return;
          }
          if (!isArray3(this._url)) {
            this._url = [this._url];
          }
          if (!this.options.keepAspectRatio && Object.prototype.hasOwnProperty.call(vid.style, "objectFit")) {
            vid.style["objectFit"] = "fill";
          }
          vid.autoplay = !!this.options.autoplay;
          vid.loop = !!this.options.loop;
          vid.muted = !!this.options.muted;
          vid.playsInline = !!this.options.playsInline;
          for (var i3 = 0; i3 < this._url.length; i3++) {
            var source = create$1("source");
            source.src = this._url[i3];
            vid.appendChild(source);
          }
        }
        // @method getElement(): HTMLVideoElement
        // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
        // used by this overlay.
      });
      function videoOverlay(video, bounds, options2) {
        return new VideoOverlay(video, bounds, options2);
      }
      var SVGOverlay = ImageOverlay.extend({
        _initImage: function() {
          var el2 = this._image = this._url;
          addClass(el2, "leaflet-image-layer");
          if (this._zoomAnimated) {
            addClass(el2, "leaflet-zoom-animated");
          }
          if (this.options.className) {
            addClass(el2, this.options.className);
          }
          el2.onselectstart = falseFn2;
          el2.onmousemove = falseFn2;
        }
        // @method getElement(): SVGElement
        // Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)
        // used by this overlay.
      });
      function svgOverlay(el2, bounds, options2) {
        return new SVGOverlay(el2, bounds, options2);
      }
      var DivOverlay = Layer2.extend({
        // @section
        // @aka DivOverlay options
        options: {
          // @option interactive: Boolean = false
          // If true, the popup/tooltip will listen to the mouse events.
          interactive: false,
          // @option offset: Point = Point(0, 0)
          // The offset of the overlay position.
          offset: [0, 0],
          // @option className: String = ''
          // A custom CSS class name to assign to the overlay.
          className: "",
          // @option pane: String = undefined
          // `Map pane` where the overlay will be added.
          pane: void 0,
          // @option content: String|HTMLElement|Function = ''
          // Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be
          // passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay.
          content: ""
        },
        initialize: function(options2, source) {
          if (options2 && (options2 instanceof LatLng || isArray3(options2))) {
            this._latlng = toLatLng(options2);
            setOptions2(this, source);
          } else {
            setOptions2(this, options2);
            this._source = source;
          }
          if (this.options.content) {
            this._content = this.options.content;
          }
        },
        // @method openOn(map: Map): this
        // Adds the overlay to the map.
        // Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`.
        openOn: function(map5) {
          map5 = arguments.length ? map5 : this._source._map;
          if (!map5.hasLayer(this)) {
            map5.addLayer(this);
          }
          return this;
        },
        // @method close(): this
        // Closes the overlay.
        // Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)`
        // and `layer.closePopup()`/`.closeTooltip()`.
        close: function() {
          if (this._map) {
            this._map.removeLayer(this);
          }
          return this;
        },
        // @method toggle(layer?: Layer): this
        // Opens or closes the overlay bound to layer depending on its current state.
        // Argument may be omitted only for overlay bound to layer.
        // Alternative to `layer.togglePopup()`/`.toggleTooltip()`.
        toggle: function(layer2) {
          if (this._map) {
            this.close();
          } else {
            if (arguments.length) {
              this._source = layer2;
            } else {
              layer2 = this._source;
            }
            this._prepareOpen();
            this.openOn(layer2._map);
          }
          return this;
        },
        onAdd: function(map5) {
          this._zoomAnimated = map5._zoomAnimated;
          if (!this._container) {
            this._initLayout();
          }
          if (map5._fadeAnimated) {
            setOpacity(this._container, 0);
          }
          clearTimeout(this._removeTimeout);
          this.getPane().appendChild(this._container);
          this.update();
          if (map5._fadeAnimated) {
            setOpacity(this._container, 1);
          }
          this.bringToFront();
          if (this.options.interactive) {
            addClass(this._container, "leaflet-interactive");
            this.addInteractiveTarget(this._container);
          }
        },
        onRemove: function(map5) {
          if (map5._fadeAnimated) {
            setOpacity(this._container, 0);
            this._removeTimeout = setTimeout(bind2(remove3, void 0, this._container), 200);
          } else {
            remove3(this._container);
          }
          if (this.options.interactive) {
            removeClass(this._container, "leaflet-interactive");
            this.removeInteractiveTarget(this._container);
          }
        },
        // @namespace DivOverlay
        // @method getLatLng: LatLng
        // Returns the geographical point of the overlay.
        getLatLng: function() {
          return this._latlng;
        },
        // @method setLatLng(latlng: LatLng): this
        // Sets the geographical point where the overlay will open.
        setLatLng: function(latlng) {
          this._latlng = toLatLng(latlng);
          if (this._map) {
            this._updatePosition();
            this._adjustPan();
          }
          return this;
        },
        // @method getContent: String|HTMLElement
        // Returns the content of the overlay.
        getContent: function() {
          return this._content;
        },
        // @method setContent(htmlContent: String|HTMLElement|Function): this
        // Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function.
        // The function should return a `String` or `HTMLElement` to be used in the overlay.
        setContent: function(content2) {
          this._content = content2;
          this.update();
          return this;
        },
        // @method getElement: String|HTMLElement
        // Returns the HTML container of the overlay.
        getElement: function() {
          return this._container;
        },
        // @method update: null
        // Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.
        update: function() {
          if (!this._map) {
            return;
          }
          this._container.style.visibility = "hidden";
          this._updateContent();
          this._updateLayout();
          this._updatePosition();
          this._container.style.visibility = "";
          this._adjustPan();
        },
        getEvents: function() {
          var events2 = {
            zoom: this._updatePosition,
            viewreset: this._updatePosition
          };
          if (this._zoomAnimated) {
            events2.zoomanim = this._animateZoom;
          }
          return events2;
        },
        // @method isOpen: Boolean
        // Returns `true` when the overlay is visible on the map.
        isOpen: function() {
          return !!this._map && this._map.hasLayer(this);
        },
        // @method bringToFront: this
        // Brings this overlay in front of other overlays (in the same map pane).
        bringToFront: function() {
          if (this._map) {
            toFront(this._container);
          }
          return this;
        },
        // @method bringToBack: this
        // Brings this overlay to the back of other overlays (in the same map pane).
        bringToBack: function() {
          if (this._map) {
            toBack(this._container);
          }
          return this;
        },
        // prepare bound overlay to open: update latlng pos / content source (for FeatureGroup)
        _prepareOpen: function(latlng) {
          var source = this._source;
          if (!source._map) {
            return false;
          }
          if (source instanceof FeatureGroup) {
            source = null;
            var layers2 = this._source._layers;
            for (var id in layers2) {
              if (layers2[id]._map) {
                source = layers2[id];
                break;
              }
            }
            if (!source) {
              return false;
            }
            this._source = source;
          }
          if (!latlng) {
            if (source.getCenter) {
              latlng = source.getCenter();
            } else if (source.getLatLng) {
              latlng = source.getLatLng();
            } else if (source.getBounds) {
              latlng = source.getBounds().getCenter();
            } else {
              throw new Error("Unable to get source layer LatLng.");
            }
          }
          this.setLatLng(latlng);
          if (this._map) {
            this.update();
          }
          return true;
        },
        _updateContent: function() {
          if (!this._content) {
            return;
          }
          var node = this._contentNode;
          var content2 = typeof this._content === "function" ? this._content(this._source || this) : this._content;
          if (typeof content2 === "string") {
            node.innerHTML = content2;
          } else {
            while (node.hasChildNodes()) {
              node.removeChild(node.firstChild);
            }
            node.appendChild(content2);
          }
          this.fire("contentupdate");
        },
        _updatePosition: function() {
          if (!this._map) {
            return;
          }
          var pos = this._map.latLngToLayerPoint(this._latlng), offset = toPoint(this.options.offset), anchor = this._getAnchor();
          if (this._zoomAnimated) {
            setPosition(this._container, pos.add(anchor));
          } else {
            offset = offset.add(pos).add(anchor);
          }
          var bottom = this._containerBottom = -offset.y, left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
          this._container.style.bottom = bottom + "px";
          this._container.style.left = left + "px";
        },
        _getAnchor: function() {
          return [0, 0];
        }
      });
      Map2.include({
        _initOverlay: function(OverlayClass, content2, latlng, options2) {
          var overlay = content2;
          if (!(overlay instanceof OverlayClass)) {
            overlay = new OverlayClass(options2).setContent(content2);
          }
          if (latlng) {
            overlay.setLatLng(latlng);
          }
          return overlay;
        }
      });
      Layer2.include({
        _initOverlay: function(OverlayClass, old, content2, options2) {
          var overlay = content2;
          if (overlay instanceof OverlayClass) {
            setOptions2(overlay, options2);
            overlay._source = this;
          } else {
            overlay = old && !options2 ? old : new OverlayClass(options2, this);
            overlay.setContent(content2);
          }
          return overlay;
        }
      });
      var Popup = DivOverlay.extend({
        // @section
        // @aka Popup options
        options: {
          // @option pane: String = 'popupPane'
          // `Map pane` where the popup will be added.
          pane: "popupPane",
          // @option offset: Point = Point(0, 7)
          // The offset of the popup position.
          offset: [0, 7],
          // @option maxWidth: Number = 300
          // Max width of the popup, in pixels.
          maxWidth: 300,
          // @option minWidth: Number = 50
          // Min width of the popup, in pixels.
          minWidth: 50,
          // @option maxHeight: Number = null
          // If set, creates a scrollable container of the given height
          // inside a popup if its content exceeds it.
          // The scrollable container can be styled using the
          // `leaflet-popup-scrolled` CSS class selector.
          maxHeight: null,
          // @option autoPan: Boolean = true
          // Set it to `false` if you don't want the map to do panning animation
          // to fit the opened popup.
          autoPan: true,
          // @option autoPanPaddingTopLeft: Point = null
          // The margin between the popup and the top left corner of the map
          // view after autopanning was performed.
          autoPanPaddingTopLeft: null,
          // @option autoPanPaddingBottomRight: Point = null
          // The margin between the popup and the bottom right corner of the map
          // view after autopanning was performed.
          autoPanPaddingBottomRight: null,
          // @option autoPanPadding: Point = Point(5, 5)
          // Equivalent of setting both top left and bottom right autopan padding to the same value.
          autoPanPadding: [5, 5],
          // @option keepInView: Boolean = false
          // Set it to `true` if you want to prevent users from panning the popup
          // off of the screen while it is open.
          keepInView: false,
          // @option closeButton: Boolean = true
          // Controls the presence of a close button in the popup.
          closeButton: true,
          // @option autoClose: Boolean = true
          // Set it to `false` if you want to override the default behavior of
          // the popup closing when another popup is opened.
          autoClose: true,
          // @option closeOnEscapeKey: Boolean = true
          // Set it to `false` if you want to override the default behavior of
          // the ESC key for closing of the popup.
          closeOnEscapeKey: true,
          // @option closeOnClick: Boolean = *
          // Set it if you want to override the default behavior of the popup closing when user clicks
          // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
          // @option className: String = ''
          // A custom CSS class name to assign to the popup.
          className: ""
        },
        // @namespace Popup
        // @method openOn(map: Map): this
        // Alternative to `map.openPopup(popup)`.
        // Adds the popup to the map and closes the previous one.
        openOn: function(map5) {
          map5 = arguments.length ? map5 : this._source._map;
          if (!map5.hasLayer(this) && map5._popup && map5._popup.options.autoClose) {
            map5.removeLayer(map5._popup);
          }
          map5._popup = this;
          return DivOverlay.prototype.openOn.call(this, map5);
        },
        onAdd: function(map5) {
          DivOverlay.prototype.onAdd.call(this, map5);
          map5.fire("popupopen", { popup: this });
          if (this._source) {
            this._source.fire("popupopen", { popup: this }, true);
            if (!(this._source instanceof Path)) {
              this._source.on("preclick", stopPropagation);
            }
          }
        },
        onRemove: function(map5) {
          DivOverlay.prototype.onRemove.call(this, map5);
          map5.fire("popupclose", { popup: this });
          if (this._source) {
            this._source.fire("popupclose", { popup: this }, true);
            if (!(this._source instanceof Path)) {
              this._source.off("preclick", stopPropagation);
            }
          }
        },
        getEvents: function() {
          var events2 = DivOverlay.prototype.getEvents.call(this);
          if (this.options.closeOnClick !== void 0 ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
            events2.preclick = this.close;
          }
          if (this.options.keepInView) {
            events2.moveend = this._adjustPan;
          }
          return events2;
        },
        _initLayout: function() {
          var prefix5 = "leaflet-popup", container = this._container = create$1(
            "div",
            prefix5 + " " + (this.options.className || "") + " leaflet-zoom-animated"
          );
          var wrapper = this._wrapper = create$1("div", prefix5 + "-content-wrapper", container);
          this._contentNode = create$1("div", prefix5 + "-content", wrapper);
          disableClickPropagation(container);
          disableScrollPropagation(this._contentNode);
          on2(container, "contextmenu", stopPropagation);
          this._tipContainer = create$1("div", prefix5 + "-tip-container", container);
          this._tip = create$1("div", prefix5 + "-tip", this._tipContainer);
          if (this.options.closeButton) {
            var closeButton = this._closeButton = create$1("a", prefix5 + "-close-button", container);
            closeButton.setAttribute("role", "button");
            closeButton.setAttribute("aria-label", "Close popup");
            closeButton.href = "#close";
            closeButton.innerHTML = '<span aria-hidden="true">&#215;</span>';
            on2(closeButton, "click", function(ev) {
              preventDefault(ev);
              this.close();
            }, this);
          }
        },
        _updateLayout: function() {
          var container = this._contentNode, style4 = container.style;
          style4.width = "";
          style4.whiteSpace = "nowrap";
          var width = container.offsetWidth;
          width = Math.min(width, this.options.maxWidth);
          width = Math.max(width, this.options.minWidth);
          style4.width = width + 1 + "px";
          style4.whiteSpace = "";
          style4.height = "";
          var height = container.offsetHeight, maxHeight = this.options.maxHeight, scrolledClass = "leaflet-popup-scrolled";
          if (maxHeight && height > maxHeight) {
            style4.height = maxHeight + "px";
            addClass(container, scrolledClass);
          } else {
            removeClass(container, scrolledClass);
          }
          this._containerWidth = this._container.offsetWidth;
        },
        _animateZoom: function(e3) {
          var pos = this._map._latLngToNewLayerPoint(this._latlng, e3.zoom, e3.center), anchor = this._getAnchor();
          setPosition(this._container, pos.add(anchor));
        },
        _adjustPan: function() {
          if (!this.options.autoPan) {
            return;
          }
          if (this._map._panAnim) {
            this._map._panAnim.stop();
          }
          if (this._autopanning) {
            this._autopanning = false;
            return;
          }
          var map5 = this._map, marginBottom = parseInt(getStyle(this._container, "marginBottom"), 10) || 0, containerHeight = this._container.offsetHeight + marginBottom, containerWidth = this._containerWidth, layerPos = new Point2(this._containerLeft, -containerHeight - this._containerBottom);
          layerPos._add(getPosition(this._container));
          var containerPos = map5.layerPointToContainerPoint(layerPos), padding = toPoint(this.options.autoPanPadding), paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding), paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding), size4 = map5.getSize(), dx = 0, dy = 0;
          if (containerPos.x + containerWidth + paddingBR.x > size4.x) {
            dx = containerPos.x + containerWidth - size4.x + paddingBR.x;
          }
          if (containerPos.x - dx - paddingTL.x < 0) {
            dx = containerPos.x - paddingTL.x;
          }
          if (containerPos.y + containerHeight + paddingBR.y > size4.y) {
            dy = containerPos.y + containerHeight - size4.y + paddingBR.y;
          }
          if (containerPos.y - dy - paddingTL.y < 0) {
            dy = containerPos.y - paddingTL.y;
          }
          if (dx || dy) {
            if (this.options.keepInView) {
              this._autopanning = true;
            }
            map5.fire("autopanstart").panBy([dx, dy]);
          }
        },
        _getAnchor: function() {
          return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
        }
      });
      var popup = function(options2, source) {
        return new Popup(options2, source);
      };
      Map2.mergeOptions({
        closePopupOnClick: true
      });
      Map2.include({
        // @method openPopup(popup: Popup): this
        // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
        // @alternative
        // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
        // Creates a popup with the specified content and options and opens it in the given point on a map.
        openPopup: function(popup2, latlng, options2) {
          this._initOverlay(Popup, popup2, latlng, options2).openOn(this);
          return this;
        },
        // @method closePopup(popup?: Popup): this
        // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
        closePopup: function(popup2) {
          popup2 = arguments.length ? popup2 : this._popup;
          if (popup2) {
            popup2.close();
          }
          return this;
        }
      });
      Layer2.include({
        // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
        // Binds a popup to the layer with the passed `content` and sets up the
        // necessary event listeners. If a `Function` is passed it will receive
        // the layer as the first argument and should return a `String` or `HTMLElement`.
        bindPopup: function(content2, options2) {
          this._popup = this._initOverlay(Popup, this._popup, content2, options2);
          if (!this._popupHandlersAdded) {
            this.on({
              click: this._openPopup,
              keypress: this._onKeyPress,
              remove: this.closePopup,
              move: this._movePopup
            });
            this._popupHandlersAdded = true;
          }
          return this;
        },
        // @method unbindPopup(): this
        // Removes the popup previously bound with `bindPopup`.
        unbindPopup: function() {
          if (this._popup) {
            this.off({
              click: this._openPopup,
              keypress: this._onKeyPress,
              remove: this.closePopup,
              move: this._movePopup
            });
            this._popupHandlersAdded = false;
            this._popup = null;
          }
          return this;
        },
        // @method openPopup(latlng?: LatLng): this
        // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
        openPopup: function(latlng) {
          if (this._popup) {
            if (!(this instanceof FeatureGroup)) {
              this._popup._source = this;
            }
            if (this._popup._prepareOpen(latlng || this._latlng)) {
              this._popup.openOn(this._map);
            }
          }
          return this;
        },
        // @method closePopup(): this
        // Closes the popup bound to this layer if it is open.
        closePopup: function() {
          if (this._popup) {
            this._popup.close();
          }
          return this;
        },
        // @method togglePopup(): this
        // Opens or closes the popup bound to this layer depending on its current state.
        togglePopup: function() {
          if (this._popup) {
            this._popup.toggle(this);
          }
          return this;
        },
        // @method isPopupOpen(): boolean
        // Returns `true` if the popup bound to this layer is currently open.
        isPopupOpen: function() {
          return this._popup ? this._popup.isOpen() : false;
        },
        // @method setPopupContent(content: String|HTMLElement|Popup): this
        // Sets the content of the popup bound to this layer.
        setPopupContent: function(content2) {
          if (this._popup) {
            this._popup.setContent(content2);
          }
          return this;
        },
        // @method getPopup(): Popup
        // Returns the popup bound to this layer.
        getPopup: function() {
          return this._popup;
        },
        _openPopup: function(e3) {
          if (!this._popup || !this._map) {
            return;
          }
          stop(e3);
          var target = e3.layer || e3.target;
          if (this._popup._source === target && !(target instanceof Path)) {
            if (this._map.hasLayer(this._popup)) {
              this.closePopup();
            } else {
              this.openPopup(e3.latlng);
            }
            return;
          }
          this._popup._source = target;
          this.openPopup(e3.latlng);
        },
        _movePopup: function(e3) {
          this._popup.setLatLng(e3.latlng);
        },
        _onKeyPress: function(e3) {
          if (e3.originalEvent.keyCode === 13) {
            this._openPopup(e3);
          }
        }
      });
      var Tooltip3 = DivOverlay.extend({
        // @section
        // @aka Tooltip options
        options: {
          // @option pane: String = 'tooltipPane'
          // `Map pane` where the tooltip will be added.
          pane: "tooltipPane",
          // @option offset: Point = Point(0, 0)
          // Optional offset of the tooltip position.
          offset: [0, 0],
          // @option direction: String = 'auto'
          // Direction where to open the tooltip. Possible values are: `right`, `left`,
          // `top`, `bottom`, `center`, `auto`.
          // `auto` will dynamically switch between `right` and `left` according to the tooltip
          // position on the map.
          direction: "auto",
          // @option permanent: Boolean = false
          // Whether to open the tooltip permanently or only on mouseover.
          permanent: false,
          // @option sticky: Boolean = false
          // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
          sticky: false,
          // @option opacity: Number = 0.9
          // Tooltip container opacity.
          opacity: 0.9
        },
        onAdd: function(map5) {
          DivOverlay.prototype.onAdd.call(this, map5);
          this.setOpacity(this.options.opacity);
          map5.fire("tooltipopen", { tooltip: this });
          if (this._source) {
            this.addEventParent(this._source);
            this._source.fire("tooltipopen", { tooltip: this }, true);
          }
        },
        onRemove: function(map5) {
          DivOverlay.prototype.onRemove.call(this, map5);
          map5.fire("tooltipclose", { tooltip: this });
          if (this._source) {
            this.removeEventParent(this._source);
            this._source.fire("tooltipclose", { tooltip: this }, true);
          }
        },
        getEvents: function() {
          var events2 = DivOverlay.prototype.getEvents.call(this);
          if (!this.options.permanent) {
            events2.preclick = this.close;
          }
          return events2;
        },
        _initLayout: function() {
          var prefix5 = "leaflet-tooltip", className2 = prefix5 + " " + (this.options.className || "") + " leaflet-zoom-" + (this._zoomAnimated ? "animated" : "hide");
          this._contentNode = this._container = create$1("div", className2);
          this._container.setAttribute("role", "tooltip");
          this._container.setAttribute("id", "leaflet-tooltip-" + stamp(this));
        },
        _updateLayout: function() {
        },
        _adjustPan: function() {
        },
        _setPosition: function(pos) {
          var subX, subY, map5 = this._map, container = this._container, centerPoint = map5.latLngToContainerPoint(map5.getCenter()), tooltipPoint = map5.layerPointToContainerPoint(pos), direction = this.options.direction, tooltipWidth = container.offsetWidth, tooltipHeight = container.offsetHeight, offset = toPoint(this.options.offset), anchor = this._getAnchor();
          if (direction === "top") {
            subX = tooltipWidth / 2;
            subY = tooltipHeight;
          } else if (direction === "bottom") {
            subX = tooltipWidth / 2;
            subY = 0;
          } else if (direction === "center") {
            subX = tooltipWidth / 2;
            subY = tooltipHeight / 2;
          } else if (direction === "right") {
            subX = 0;
            subY = tooltipHeight / 2;
          } else if (direction === "left") {
            subX = tooltipWidth;
            subY = tooltipHeight / 2;
          } else if (tooltipPoint.x < centerPoint.x) {
            direction = "right";
            subX = 0;
            subY = tooltipHeight / 2;
          } else {
            direction = "left";
            subX = tooltipWidth + (offset.x + anchor.x) * 2;
            subY = tooltipHeight / 2;
          }
          pos = pos.subtract(toPoint(subX, subY, true)).add(offset).add(anchor);
          removeClass(container, "leaflet-tooltip-right");
          removeClass(container, "leaflet-tooltip-left");
          removeClass(container, "leaflet-tooltip-top");
          removeClass(container, "leaflet-tooltip-bottom");
          addClass(container, "leaflet-tooltip-" + direction);
          setPosition(container, pos);
        },
        _updatePosition: function() {
          var pos = this._map.latLngToLayerPoint(this._latlng);
          this._setPosition(pos);
        },
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          if (this._container) {
            setOpacity(this._container, opacity);
          }
        },
        _animateZoom: function(e3) {
          var pos = this._map._latLngToNewLayerPoint(this._latlng, e3.zoom, e3.center);
          this._setPosition(pos);
        },
        _getAnchor: function() {
          return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
        }
      });
      var tooltip = function(options2, source) {
        return new Tooltip3(options2, source);
      };
      Map2.include({
        // @method openTooltip(tooltip: Tooltip): this
        // Opens the specified tooltip.
        // @alternative
        // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
        // Creates a tooltip with the specified content and options and open it.
        openTooltip: function(tooltip2, latlng, options2) {
          this._initOverlay(Tooltip3, tooltip2, latlng, options2).openOn(this);
          return this;
        },
        // @method closeTooltip(tooltip: Tooltip): this
        // Closes the tooltip given as parameter.
        closeTooltip: function(tooltip2) {
          tooltip2.close();
          return this;
        }
      });
      Layer2.include({
        // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
        // Binds a tooltip to the layer with the passed `content` and sets up the
        // necessary event listeners. If a `Function` is passed it will receive
        // the layer as the first argument and should return a `String` or `HTMLElement`.
        bindTooltip: function(content2, options2) {
          if (this._tooltip && this.isTooltipOpen()) {
            this.unbindTooltip();
          }
          this._tooltip = this._initOverlay(Tooltip3, this._tooltip, content2, options2);
          this._initTooltipInteractions();
          if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
            this.openTooltip();
          }
          return this;
        },
        // @method unbindTooltip(): this
        // Removes the tooltip previously bound with `bindTooltip`.
        unbindTooltip: function() {
          if (this._tooltip) {
            this._initTooltipInteractions(true);
            this.closeTooltip();
            this._tooltip = null;
          }
          return this;
        },
        _initTooltipInteractions: function(remove4) {
          if (!remove4 && this._tooltipHandlersAdded) {
            return;
          }
          var onOff = remove4 ? "off" : "on", events2 = {
            remove: this.closeTooltip,
            move: this._moveTooltip
          };
          if (!this._tooltip.options.permanent) {
            events2.mouseover = this._openTooltip;
            events2.mouseout = this.closeTooltip;
            events2.click = this._openTooltip;
            if (this._map) {
              this._addFocusListeners();
            } else {
              events2.add = this._addFocusListeners;
            }
          } else {
            events2.add = this._openTooltip;
          }
          if (this._tooltip.options.sticky) {
            events2.mousemove = this._moveTooltip;
          }
          this[onOff](events2);
          this._tooltipHandlersAdded = !remove4;
        },
        // @method openTooltip(latlng?: LatLng): this
        // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
        openTooltip: function(latlng) {
          if (this._tooltip) {
            if (!(this instanceof FeatureGroup)) {
              this._tooltip._source = this;
            }
            if (this._tooltip._prepareOpen(latlng)) {
              this._tooltip.openOn(this._map);
              if (this.getElement) {
                this._setAriaDescribedByOnLayer(this);
              } else if (this.eachLayer) {
                this.eachLayer(this._setAriaDescribedByOnLayer, this);
              }
            }
          }
          return this;
        },
        // @method closeTooltip(): this
        // Closes the tooltip bound to this layer if it is open.
        closeTooltip: function() {
          if (this._tooltip) {
            return this._tooltip.close();
          }
        },
        // @method toggleTooltip(): this
        // Opens or closes the tooltip bound to this layer depending on its current state.
        toggleTooltip: function() {
          if (this._tooltip) {
            this._tooltip.toggle(this);
          }
          return this;
        },
        // @method isTooltipOpen(): boolean
        // Returns `true` if the tooltip bound to this layer is currently open.
        isTooltipOpen: function() {
          return this._tooltip.isOpen();
        },
        // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
        // Sets the content of the tooltip bound to this layer.
        setTooltipContent: function(content2) {
          if (this._tooltip) {
            this._tooltip.setContent(content2);
          }
          return this;
        },
        // @method getTooltip(): Tooltip
        // Returns the tooltip bound to this layer.
        getTooltip: function() {
          return this._tooltip;
        },
        _addFocusListeners: function() {
          if (this.getElement) {
            this._addFocusListenersOnLayer(this);
          } else if (this.eachLayer) {
            this.eachLayer(this._addFocusListenersOnLayer, this);
          }
        },
        _addFocusListenersOnLayer: function(layer2) {
          var el2 = typeof layer2.getElement === "function" && layer2.getElement();
          if (el2) {
            on2(el2, "focus", function() {
              this._tooltip._source = layer2;
              this.openTooltip();
            }, this);
            on2(el2, "blur", this.closeTooltip, this);
          }
        },
        _setAriaDescribedByOnLayer: function(layer2) {
          var el2 = typeof layer2.getElement === "function" && layer2.getElement();
          if (el2) {
            el2.setAttribute("aria-describedby", this._tooltip._container.id);
          }
        },
        _openTooltip: function(e3) {
          if (!this._tooltip || !this._map) {
            return;
          }
          if (this._map.dragging && this._map.dragging.moving() && !this._openOnceFlag) {
            this._openOnceFlag = true;
            var that = this;
            this._map.once("moveend", function() {
              that._openOnceFlag = false;
              that._openTooltip(e3);
            });
            return;
          }
          this._tooltip._source = e3.layer || e3.target;
          this.openTooltip(this._tooltip.options.sticky ? e3.latlng : void 0);
        },
        _moveTooltip: function(e3) {
          var latlng = e3.latlng, containerPoint, layerPoint;
          if (this._tooltip.options.sticky && e3.originalEvent) {
            containerPoint = this._map.mouseEventToContainerPoint(e3.originalEvent);
            layerPoint = this._map.containerPointToLayerPoint(containerPoint);
            latlng = this._map.layerPointToLatLng(layerPoint);
          }
          this._tooltip.setLatLng(latlng);
        }
      });
      var DivIcon = Icon2.extend({
        options: {
          // @section
          // @aka DivIcon options
          iconSize: [12, 12],
          // also can be set through CSS
          // iconAnchor: (Point),
          // popupAnchor: (Point),
          // @option html: String|HTMLElement = ''
          // Custom HTML code to put inside the div element, empty by default. Alternatively,
          // an instance of `HTMLElement`.
          html: false,
          // @option bgPos: Point = [0, 0]
          // Optional relative position of the background, in pixels
          bgPos: null,
          className: "leaflet-div-icon"
        },
        createIcon: function(oldIcon) {
          var div = oldIcon && oldIcon.tagName === "DIV" ? oldIcon : document.createElement("div"), options2 = this.options;
          if (options2.html instanceof Element) {
            empty4(div);
            div.appendChild(options2.html);
          } else {
            div.innerHTML = options2.html !== false ? options2.html : "";
          }
          if (options2.bgPos) {
            var bgPos = toPoint(options2.bgPos);
            div.style.backgroundPosition = -bgPos.x + "px " + -bgPos.y + "px";
          }
          this._setIconStyles(div, "icon");
          return div;
        },
        createShadow: function() {
          return null;
        }
      });
      function divIcon(options2) {
        return new DivIcon(options2);
      }
      Icon2.Default = IconDefault;
      var GridLayer = Layer2.extend({
        // @section
        // @aka GridLayer options
        options: {
          // @option tileSize: Number|Point = 256
          // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
          tileSize: 256,
          // @option opacity: Number = 1.0
          // Opacity of the tiles. Can be used in the `createTile()` function.
          opacity: 1,
          // @option updateWhenIdle: Boolean = (depends)
          // Load new tiles only when panning ends.
          // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
          // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
          // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
          updateWhenIdle: Browser.mobile,
          // @option updateWhenZooming: Boolean = true
          // By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends.
          updateWhenZooming: true,
          // @option updateInterval: Number = 200
          // Tiles will not update more than once every `updateInterval` milliseconds when panning.
          updateInterval: 200,
          // @option zIndex: Number = 1
          // The explicit zIndex of the tile layer.
          zIndex: 1,
          // @option bounds: LatLngBounds = undefined
          // If set, tiles will only be loaded inside the set `LatLngBounds`.
          bounds: null,
          // @option minZoom: Number = 0
          // The minimum zoom level down to which this layer will be displayed (inclusive).
          minZoom: 0,
          // @option maxZoom: Number = undefined
          // The maximum zoom level up to which this layer will be displayed (inclusive).
          maxZoom: void 0,
          // @option maxNativeZoom: Number = undefined
          // Maximum zoom number the tile source has available. If it is specified,
          // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
          // from `maxNativeZoom` level and auto-scaled.
          maxNativeZoom: void 0,
          // @option minNativeZoom: Number = undefined
          // Minimum zoom number the tile source has available. If it is specified,
          // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
          // from `minNativeZoom` level and auto-scaled.
          minNativeZoom: void 0,
          // @option noWrap: Boolean = false
          // Whether the layer is wrapped around the antimeridian. If `true`, the
          // GridLayer will only be displayed once at low zoom levels. Has no
          // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
          // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
          // tiles outside the CRS limits.
          noWrap: false,
          // @option pane: String = 'tilePane'
          // `Map pane` where the grid layer will be added.
          pane: "tilePane",
          // @option className: String = ''
          // A custom class name to assign to the tile layer. Empty by default.
          className: "",
          // @option keepBuffer: Number = 2
          // When panning the map, keep this many rows and columns of tiles before unloading them.
          keepBuffer: 2
        },
        initialize: function(options2) {
          setOptions2(this, options2);
        },
        onAdd: function() {
          this._initContainer();
          this._levels = {};
          this._tiles = {};
          this._resetView();
        },
        beforeAdd: function(map5) {
          map5._addZoomLimit(this);
        },
        onRemove: function(map5) {
          this._removeAllTiles();
          remove3(this._container);
          map5._removeZoomLimit(this);
          this._container = null;
          this._tileZoom = void 0;
        },
        // @method bringToFront: this
        // Brings the tile layer to the top of all tile layers.
        bringToFront: function() {
          if (this._map) {
            toFront(this._container);
            this._setAutoZIndex(Math.max);
          }
          return this;
        },
        // @method bringToBack: this
        // Brings the tile layer to the bottom of all tile layers.
        bringToBack: function() {
          if (this._map) {
            toBack(this._container);
            this._setAutoZIndex(Math.min);
          }
          return this;
        },
        // @method getContainer: HTMLElement
        // Returns the HTML element that contains the tiles for this layer.
        getContainer: function() {
          return this._container;
        },
        // @method setOpacity(opacity: Number): this
        // Changes the [opacity](#gridlayer-opacity) of the grid layer.
        setOpacity: function(opacity) {
          this.options.opacity = opacity;
          this._updateOpacity();
          return this;
        },
        // @method setZIndex(zIndex: Number): this
        // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
        setZIndex: function(zIndex) {
          this.options.zIndex = zIndex;
          this._updateZIndex();
          return this;
        },
        // @method isLoading: Boolean
        // Returns `true` if any tile in the grid layer has not finished loading.
        isLoading: function() {
          return this._loading;
        },
        // @method redraw: this
        // Causes the layer to clear all the tiles and request them again.
        redraw: function() {
          if (this._map) {
            this._removeAllTiles();
            var tileZoom = this._clampZoom(this._map.getZoom());
            if (tileZoom !== this._tileZoom) {
              this._tileZoom = tileZoom;
              this._updateLevels();
            }
            this._update();
          }
          return this;
        },
        getEvents: function() {
          var events2 = {
            viewprereset: this._invalidateAll,
            viewreset: this._resetView,
            zoom: this._resetView,
            moveend: this._onMoveEnd
          };
          if (!this.options.updateWhenIdle) {
            if (!this._onMove) {
              this._onMove = throttle3(this._onMoveEnd, this.options.updateInterval, this);
            }
            events2.move = this._onMove;
          }
          if (this._zoomAnimated) {
            events2.zoomanim = this._animateZoom;
          }
          return events2;
        },
        // @section Extension methods
        // Layers extending `GridLayer` shall reimplement the following method.
        // @method createTile(coords: Object, done?: Function): HTMLElement
        // Called only internally, must be overridden by classes extending `GridLayer`.
        // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
        // is specified, it must be called when the tile has finished loading and drawing.
        createTile: function() {
          return document.createElement("div");
        },
        // @section
        // @method getTileSize: Point
        // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
        getTileSize: function() {
          var s3 = this.options.tileSize;
          return s3 instanceof Point2 ? s3 : new Point2(s3, s3);
        },
        _updateZIndex: function() {
          if (this._container && this.options.zIndex !== void 0 && this.options.zIndex !== null) {
            this._container.style.zIndex = this.options.zIndex;
          }
        },
        _setAutoZIndex: function(compare4) {
          var layers2 = this.getPane().children, edgeZIndex = -compare4(-Infinity, Infinity);
          for (var i3 = 0, len = layers2.length, zIndex; i3 < len; i3++) {
            zIndex = layers2[i3].style.zIndex;
            if (layers2[i3] !== this._container && zIndex) {
              edgeZIndex = compare4(edgeZIndex, +zIndex);
            }
          }
          if (isFinite(edgeZIndex)) {
            this.options.zIndex = edgeZIndex + compare4(-1, 1);
            this._updateZIndex();
          }
        },
        _updateOpacity: function() {
          if (!this._map) {
            return;
          }
          if (Browser.ielt9) {
            return;
          }
          setOpacity(this._container, this.options.opacity);
          var now = +/* @__PURE__ */ new Date(), nextFrame = false, willPrune = false;
          for (var key2 in this._tiles) {
            var tile = this._tiles[key2];
            if (!tile.current || !tile.loaded) {
              continue;
            }
            var fade = Math.min(1, (now - tile.loaded) / 200);
            setOpacity(tile.el, fade);
            if (fade < 1) {
              nextFrame = true;
            } else {
              if (tile.active) {
                willPrune = true;
              } else {
                this._onOpaqueTile(tile);
              }
              tile.active = true;
            }
          }
          if (willPrune && !this._noPrune) {
            this._pruneTiles();
          }
          if (nextFrame) {
            cancelAnimFrame(this._fadeFrame);
            this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
          }
        },
        _onOpaqueTile: falseFn2,
        _initContainer: function() {
          if (this._container) {
            return;
          }
          this._container = create$1("div", "leaflet-layer " + (this.options.className || ""));
          this._updateZIndex();
          if (this.options.opacity < 1) {
            this._updateOpacity();
          }
          this.getPane().appendChild(this._container);
        },
        _updateLevels: function() {
          var zoom2 = this._tileZoom, maxZoom = this.options.maxZoom;
          if (zoom2 === void 0) {
            return void 0;
          }
          for (var z2 in this._levels) {
            z2 = Number(z2);
            if (this._levels[z2].el.children.length || z2 === zoom2) {
              this._levels[z2].el.style.zIndex = maxZoom - Math.abs(zoom2 - z2);
              this._onUpdateLevel(z2);
            } else {
              remove3(this._levels[z2].el);
              this._removeTilesAtZoom(z2);
              this._onRemoveLevel(z2);
              delete this._levels[z2];
            }
          }
          var level = this._levels[zoom2], map5 = this._map;
          if (!level) {
            level = this._levels[zoom2] = {};
            level.el = create$1("div", "leaflet-tile-container leaflet-zoom-animated", this._container);
            level.el.style.zIndex = maxZoom;
            level.origin = map5.project(map5.unproject(map5.getPixelOrigin()), zoom2).round();
            level.zoom = zoom2;
            this._setZoomTransform(level, map5.getCenter(), map5.getZoom());
            falseFn2(level.el.offsetWidth);
            this._onCreateLevel(level);
          }
          this._level = level;
          return level;
        },
        _onUpdateLevel: falseFn2,
        _onRemoveLevel: falseFn2,
        _onCreateLevel: falseFn2,
        _pruneTiles: function() {
          if (!this._map) {
            return;
          }
          var key2, tile;
          var zoom2 = this._map.getZoom();
          if (zoom2 > this.options.maxZoom || zoom2 < this.options.minZoom) {
            this._removeAllTiles();
            return;
          }
          for (key2 in this._tiles) {
            tile = this._tiles[key2];
            tile.retain = tile.current;
          }
          for (key2 in this._tiles) {
            tile = this._tiles[key2];
            if (tile.current && !tile.active) {
              var coords = tile.coords;
              if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
                this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
              }
            }
          }
          for (key2 in this._tiles) {
            if (!this._tiles[key2].retain) {
              this._removeTile(key2);
            }
          }
        },
        _removeTilesAtZoom: function(zoom2) {
          for (var key2 in this._tiles) {
            if (this._tiles[key2].coords.z !== zoom2) {
              continue;
            }
            this._removeTile(key2);
          }
        },
        _removeAllTiles: function() {
          for (var key2 in this._tiles) {
            this._removeTile(key2);
          }
        },
        _invalidateAll: function() {
          for (var z2 in this._levels) {
            remove3(this._levels[z2].el);
            this._onRemoveLevel(Number(z2));
            delete this._levels[z2];
          }
          this._removeAllTiles();
          this._tileZoom = void 0;
        },
        _retainParent: function(x3, y3, z2, minZoom) {
          var x22 = Math.floor(x3 / 2), y22 = Math.floor(y3 / 2), z22 = z2 - 1, coords2 = new Point2(+x22, +y22);
          coords2.z = +z22;
          var key2 = this._tileCoordsToKey(coords2), tile = this._tiles[key2];
          if (tile && tile.active) {
            tile.retain = true;
            return true;
          } else if (tile && tile.loaded) {
            tile.retain = true;
          }
          if (z22 > minZoom) {
            return this._retainParent(x22, y22, z22, minZoom);
          }
          return false;
        },
        _retainChildren: function(x3, y3, z2, maxZoom) {
          for (var i3 = 2 * x3; i3 < 2 * x3 + 2; i3++) {
            for (var j = 2 * y3; j < 2 * y3 + 2; j++) {
              var coords = new Point2(i3, j);
              coords.z = z2 + 1;
              var key2 = this._tileCoordsToKey(coords), tile = this._tiles[key2];
              if (tile && tile.active) {
                tile.retain = true;
                continue;
              } else if (tile && tile.loaded) {
                tile.retain = true;
              }
              if (z2 + 1 < maxZoom) {
                this._retainChildren(i3, j, z2 + 1, maxZoom);
              }
            }
          }
        },
        _resetView: function(e3) {
          var animating = e3 && (e3.pinch || e3.flyTo);
          this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
        },
        _animateZoom: function(e3) {
          this._setView(e3.center, e3.zoom, true, e3.noUpdate);
        },
        _clampZoom: function(zoom2) {
          var options2 = this.options;
          if (void 0 !== options2.minNativeZoom && zoom2 < options2.minNativeZoom) {
            return options2.minNativeZoom;
          }
          if (void 0 !== options2.maxNativeZoom && options2.maxNativeZoom < zoom2) {
            return options2.maxNativeZoom;
          }
          return zoom2;
        },
        _setView: function(center, zoom2, noPrune, noUpdate) {
          var tileZoom = Math.round(zoom2);
          if (this.options.maxZoom !== void 0 && tileZoom > this.options.maxZoom || this.options.minZoom !== void 0 && tileZoom < this.options.minZoom) {
            tileZoom = void 0;
          } else {
            tileZoom = this._clampZoom(tileZoom);
          }
          var tileZoomChanged = this.options.updateWhenZooming && tileZoom !== this._tileZoom;
          if (!noUpdate || tileZoomChanged) {
            this._tileZoom = tileZoom;
            if (this._abortLoading) {
              this._abortLoading();
            }
            this._updateLevels();
            this._resetGrid();
            if (tileZoom !== void 0) {
              this._update(center);
            }
            if (!noPrune) {
              this._pruneTiles();
            }
            this._noPrune = !!noPrune;
          }
          this._setZoomTransforms(center, zoom2);
        },
        _setZoomTransforms: function(center, zoom2) {
          for (var i3 in this._levels) {
            this._setZoomTransform(this._levels[i3], center, zoom2);
          }
        },
        _setZoomTransform: function(level, center, zoom2) {
          var scale2 = this._map.getZoomScale(zoom2, level.zoom), translate3 = level.origin.multiplyBy(scale2).subtract(this._map._getNewPixelOrigin(center, zoom2)).round();
          if (Browser.any3d) {
            setTransform(level.el, translate3, scale2);
          } else {
            setPosition(level.el, translate3);
          }
        },
        _resetGrid: function() {
          var map5 = this._map, crs = map5.options.crs, tileSize = this._tileSize = this.getTileSize(), tileZoom = this._tileZoom;
          var bounds = this._map.getPixelWorldBounds(this._tileZoom);
          if (bounds) {
            this._globalTileRange = this._pxBoundsToTileRange(bounds);
          }
          this._wrapX = crs.wrapLng && !this.options.noWrap && [
            Math.floor(map5.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
            Math.ceil(map5.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
          ];
          this._wrapY = crs.wrapLat && !this.options.noWrap && [
            Math.floor(map5.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
            Math.ceil(map5.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
          ];
        },
        _onMoveEnd: function() {
          if (!this._map || this._map._animatingZoom) {
            return;
          }
          this._update();
        },
        _getTiledPixelBounds: function(center) {
          var map5 = this._map, mapZoom = map5._animatingZoom ? Math.max(map5._animateToZoom, map5.getZoom()) : map5.getZoom(), scale2 = map5.getZoomScale(mapZoom, this._tileZoom), pixelCenter = map5.project(center, this._tileZoom).floor(), halfSize = map5.getSize().divideBy(scale2 * 2);
          return new Bounds2(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
        },
        // Private method to load tiles in the grid's active zoom level according to map bounds
        _update: function(center) {
          var map5 = this._map;
          if (!map5) {
            return;
          }
          var zoom2 = this._clampZoom(map5.getZoom());
          if (center === void 0) {
            center = map5.getCenter();
          }
          if (this._tileZoom === void 0) {
            return;
          }
          var pixelBounds = this._getTiledPixelBounds(center), tileRange = this._pxBoundsToTileRange(pixelBounds), tileCenter = tileRange.getCenter(), queue2 = [], margin = this.options.keepBuffer, noPruneRange = new Bounds2(
            tileRange.getBottomLeft().subtract([margin, -margin]),
            tileRange.getTopRight().add([margin, -margin])
          );
          if (!(isFinite(tileRange.min.x) && isFinite(tileRange.min.y) && isFinite(tileRange.max.x) && isFinite(tileRange.max.y))) {
            throw new Error("Attempted to load an infinite number of tiles");
          }
          for (var key2 in this._tiles) {
            var c3 = this._tiles[key2].coords;
            if (c3.z !== this._tileZoom || !noPruneRange.contains(new Point2(c3.x, c3.y))) {
              this._tiles[key2].current = false;
            }
          }
          if (Math.abs(zoom2 - this._tileZoom) > 1) {
            this._setView(center, zoom2);
            return;
          }
          for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
            for (var i3 = tileRange.min.x; i3 <= tileRange.max.x; i3++) {
              var coords = new Point2(i3, j);
              coords.z = this._tileZoom;
              if (!this._isValidTile(coords)) {
                continue;
              }
              var tile = this._tiles[this._tileCoordsToKey(coords)];
              if (tile) {
                tile.current = true;
              } else {
                queue2.push(coords);
              }
            }
          }
          queue2.sort(function(a3, b3) {
            return a3.distanceTo(tileCenter) - b3.distanceTo(tileCenter);
          });
          if (queue2.length !== 0) {
            if (!this._loading) {
              this._loading = true;
              this.fire("loading");
            }
            var fragment = document.createDocumentFragment();
            for (i3 = 0; i3 < queue2.length; i3++) {
              this._addTile(queue2[i3], fragment);
            }
            this._level.el.appendChild(fragment);
          }
        },
        _isValidTile: function(coords) {
          var crs = this._map.options.crs;
          if (!crs.infinite) {
            var bounds = this._globalTileRange;
            if (!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x) || !crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y)) {
              return false;
            }
          }
          if (!this.options.bounds) {
            return true;
          }
          var tileBounds = this._tileCoordsToBounds(coords);
          return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
        },
        _keyToBounds: function(key2) {
          return this._tileCoordsToBounds(this._keyToTileCoords(key2));
        },
        _tileCoordsToNwSe: function(coords) {
          var map5 = this._map, tileSize = this.getTileSize(), nwPoint = coords.scaleBy(tileSize), sePoint = nwPoint.add(tileSize), nw = map5.unproject(nwPoint, coords.z), se = map5.unproject(sePoint, coords.z);
          return [nw, se];
        },
        // converts tile coordinates to its geographical bounds
        _tileCoordsToBounds: function(coords) {
          var bp = this._tileCoordsToNwSe(coords), bounds = new LatLngBounds(bp[0], bp[1]);
          if (!this.options.noWrap) {
            bounds = this._map.wrapLatLngBounds(bounds);
          }
          return bounds;
        },
        // converts tile coordinates to key for the tile cache
        _tileCoordsToKey: function(coords) {
          return coords.x + ":" + coords.y + ":" + coords.z;
        },
        // converts tile cache key to coordinates
        _keyToTileCoords: function(key2) {
          var k2 = key2.split(":"), coords = new Point2(+k2[0], +k2[1]);
          coords.z = +k2[2];
          return coords;
        },
        _removeTile: function(key2) {
          var tile = this._tiles[key2];
          if (!tile) {
            return;
          }
          remove3(tile.el);
          delete this._tiles[key2];
          this.fire("tileunload", {
            tile: tile.el,
            coords: this._keyToTileCoords(key2)
          });
        },
        _initTile: function(tile) {
          addClass(tile, "leaflet-tile");
          var tileSize = this.getTileSize();
          tile.style.width = tileSize.x + "px";
          tile.style.height = tileSize.y + "px";
          tile.onselectstart = falseFn2;
          tile.onmousemove = falseFn2;
          if (Browser.ielt9 && this.options.opacity < 1) {
            setOpacity(tile, this.options.opacity);
          }
        },
        _addTile: function(coords, container) {
          var tilePos = this._getTilePos(coords), key2 = this._tileCoordsToKey(coords);
          var tile = this.createTile(this._wrapCoords(coords), bind2(this._tileReady, this, coords));
          this._initTile(tile);
          if (this.createTile.length < 2) {
            requestAnimFrame(bind2(this._tileReady, this, coords, null, tile));
          }
          setPosition(tile, tilePos);
          this._tiles[key2] = {
            el: tile,
            coords,
            current: true
          };
          container.appendChild(tile);
          this.fire("tileloadstart", {
            tile,
            coords
          });
        },
        _tileReady: function(coords, err, tile) {
          if (err) {
            this.fire("tileerror", {
              error: err,
              tile,
              coords
            });
          }
          var key2 = this._tileCoordsToKey(coords);
          tile = this._tiles[key2];
          if (!tile) {
            return;
          }
          tile.loaded = +/* @__PURE__ */ new Date();
          if (this._map._fadeAnimated) {
            setOpacity(tile.el, 0);
            cancelAnimFrame(this._fadeFrame);
            this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
          } else {
            tile.active = true;
            this._pruneTiles();
          }
          if (!err) {
            addClass(tile.el, "leaflet-tile-loaded");
            this.fire("tileload", {
              tile: tile.el,
              coords
            });
          }
          if (this._noTilesToLoad()) {
            this._loading = false;
            this.fire("load");
            if (Browser.ielt9 || !this._map._fadeAnimated) {
              requestAnimFrame(this._pruneTiles, this);
            } else {
              setTimeout(bind2(this._pruneTiles, this), 250);
            }
          }
        },
        _getTilePos: function(coords) {
          return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
        },
        _wrapCoords: function(coords) {
          var newCoords = new Point2(
            this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
            this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y
          );
          newCoords.z = coords.z;
          return newCoords;
        },
        _pxBoundsToTileRange: function(bounds) {
          var tileSize = this.getTileSize();
          return new Bounds2(
            bounds.min.unscaleBy(tileSize).floor(),
            bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1])
          );
        },
        _noTilesToLoad: function() {
          for (var key2 in this._tiles) {
            if (!this._tiles[key2].loaded) {
              return false;
            }
          }
          return true;
        }
      });
      function gridLayer(options2) {
        return new GridLayer(options2);
      }
      var TileLayer = GridLayer.extend({
        // @section
        // @aka TileLayer options
        options: {
          // @option minZoom: Number = 0
          // The minimum zoom level down to which this layer will be displayed (inclusive).
          minZoom: 0,
          // @option maxZoom: Number = 18
          // The maximum zoom level up to which this layer will be displayed (inclusive).
          maxZoom: 18,
          // @option subdomains: String|String[] = 'abc'
          // Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.
          subdomains: "abc",
          // @option errorTileUrl: String = ''
          // URL to the tile image to show in place of the tile that failed to load.
          errorTileUrl: "",
          // @option zoomOffset: Number = 0
          // The zoom number used in tile URLs will be offset with this value.
          zoomOffset: 0,
          // @option tms: Boolean = false
          // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
          tms: false,
          // @option zoomReverse: Boolean = false
          // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
          zoomReverse: false,
          // @option detectRetina: Boolean = false
          // If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.
          detectRetina: false,
          // @option crossOrigin: Boolean|String = false
          // Whether the crossOrigin attribute will be added to the tiles.
          // If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data.
          // Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.
          crossOrigin: false,
          // @option referrerPolicy: Boolean|String = false
          // Whether the referrerPolicy attribute will be added to the tiles.
          // If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided.
          // This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer
          // (e.g. to validate an API token).
          // Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values.
          referrerPolicy: false
        },
        initialize: function(url2, options2) {
          this._url = url2;
          options2 = setOptions2(this, options2);
          if (options2.detectRetina && Browser.retina && options2.maxZoom > 0) {
            options2.tileSize = Math.floor(options2.tileSize / 2);
            if (!options2.zoomReverse) {
              options2.zoomOffset++;
              options2.maxZoom = Math.max(options2.minZoom, options2.maxZoom - 1);
            } else {
              options2.zoomOffset--;
              options2.minZoom = Math.min(options2.maxZoom, options2.minZoom + 1);
            }
            options2.minZoom = Math.max(0, options2.minZoom);
          } else if (!options2.zoomReverse) {
            options2.maxZoom = Math.max(options2.minZoom, options2.maxZoom);
          } else {
            options2.minZoom = Math.min(options2.maxZoom, options2.minZoom);
          }
          if (typeof options2.subdomains === "string") {
            options2.subdomains = options2.subdomains.split("");
          }
          this.on("tileunload", this._onTileRemove);
        },
        // @method setUrl(url: String, noRedraw?: Boolean): this
        // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
        // If the URL does not change, the layer will not be redrawn unless
        // the noRedraw parameter is set to false.
        setUrl: function(url2, noRedraw) {
          if (this._url === url2 && noRedraw === void 0) {
            noRedraw = true;
          }
          this._url = url2;
          if (!noRedraw) {
            this.redraw();
          }
          return this;
        },
        // @method createTile(coords: Object, done?: Function): HTMLElement
        // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
        // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
        // callback is called when the tile has been loaded.
        createTile: function(coords, done) {
          var tile = document.createElement("img");
          on2(tile, "load", bind2(this._tileOnLoad, this, done, tile));
          on2(tile, "error", bind2(this._tileOnError, this, done, tile));
          if (this.options.crossOrigin || this.options.crossOrigin === "") {
            tile.crossOrigin = this.options.crossOrigin === true ? "" : this.options.crossOrigin;
          }
          if (typeof this.options.referrerPolicy === "string") {
            tile.referrerPolicy = this.options.referrerPolicy;
          }
          tile.alt = "";
          tile.src = this.getTileUrl(coords);
          return tile;
        },
        // @section Extension methods
        // @uninheritable
        // Layers extending `TileLayer` might reimplement the following method.
        // @method getTileUrl(coords: Object): String
        // Called only internally, returns the URL for a tile given its coordinates.
        // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
        getTileUrl: function(coords) {
          var data2 = {
            r: Browser.retina ? "@2x" : "",
            s: this._getSubdomain(coords),
            x: coords.x,
            y: coords.y,
            z: this._getZoomForUrl()
          };
          if (this._map && !this._map.options.crs.infinite) {
            var invertedY = this._globalTileRange.max.y - coords.y;
            if (this.options.tms) {
              data2["y"] = invertedY;
            }
            data2["-y"] = invertedY;
          }
          return template3(this._url, extend(data2, this.options));
        },
        _tileOnLoad: function(done, tile) {
          if (Browser.ielt9) {
            setTimeout(bind2(done, this, null, tile), 0);
          } else {
            done(null, tile);
          }
        },
        _tileOnError: function(done, tile, e3) {
          var errorUrl = this.options.errorTileUrl;
          if (errorUrl && tile.getAttribute("src") !== errorUrl) {
            tile.src = errorUrl;
          }
          done(e3, tile);
        },
        _onTileRemove: function(e3) {
          e3.tile.onload = null;
        },
        _getZoomForUrl: function() {
          var zoom2 = this._tileZoom, maxZoom = this.options.maxZoom, zoomReverse = this.options.zoomReverse, zoomOffset = this.options.zoomOffset;
          if (zoomReverse) {
            zoom2 = maxZoom - zoom2;
          }
          return zoom2 + zoomOffset;
        },
        _getSubdomain: function(tilePoint) {
          var index3 = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
          return this.options.subdomains[index3];
        },
        // stops loading all tiles in the background layer
        _abortLoading: function() {
          var i3, tile;
          for (i3 in this._tiles) {
            if (this._tiles[i3].coords.z !== this._tileZoom) {
              tile = this._tiles[i3].el;
              tile.onload = falseFn2;
              tile.onerror = falseFn2;
              if (!tile.complete) {
                tile.src = emptyImageUrl;
                var coords = this._tiles[i3].coords;
                remove3(tile);
                delete this._tiles[i3];
                this.fire("tileabort", {
                  tile,
                  coords
                });
              }
            }
          }
        },
        _removeTile: function(key2) {
          var tile = this._tiles[key2];
          if (!tile) {
            return;
          }
          tile.el.setAttribute("src", emptyImageUrl);
          return GridLayer.prototype._removeTile.call(this, key2);
        },
        _tileReady: function(coords, err, tile) {
          if (!this._map || tile && tile.getAttribute("src") === emptyImageUrl) {
            return;
          }
          return GridLayer.prototype._tileReady.call(this, coords, err, tile);
        }
      });
      function tileLayer(url2, options2) {
        return new TileLayer(url2, options2);
      }
      var TileLayerWMS = TileLayer.extend({
        // @section
        // @aka TileLayer.WMS options
        // If any custom options not documented here are used, they will be sent to the
        // WMS server as extra parameters in each request URL. This can be useful for
        // [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
        defaultWmsParams: {
          service: "WMS",
          request: "GetMap",
          // @option layers: String = ''
          // **(required)** Comma-separated list of WMS layers to show.
          layers: "",
          // @option styles: String = ''
          // Comma-separated list of WMS styles.
          styles: "",
          // @option format: String = 'image/jpeg'
          // WMS image format (use `'image/png'` for layers with transparency).
          format: "image/jpeg",
          // @option transparent: Boolean = false
          // If `true`, the WMS service will return images with transparency.
          transparent: false,
          // @option version: String = '1.1.1'
          // Version of the WMS service to use
          version: "1.1.1"
        },
        options: {
          // @option crs: CRS = null
          // Coordinate Reference System to use for the WMS requests, defaults to
          // map CRS. Don't change this if you're not sure what it means.
          crs: null,
          // @option uppercase: Boolean = false
          // If `true`, WMS request parameter keys will be uppercase.
          uppercase: false
        },
        initialize: function(url2, options2) {
          this._url = url2;
          var wmsParams = extend({}, this.defaultWmsParams);
          for (var i3 in options2) {
            if (!(i3 in this.options)) {
              wmsParams[i3] = options2[i3];
            }
          }
          options2 = setOptions2(this, options2);
          var realRetina = options2.detectRetina && Browser.retina ? 2 : 1;
          var tileSize = this.getTileSize();
          wmsParams.width = tileSize.x * realRetina;
          wmsParams.height = tileSize.y * realRetina;
          this.wmsParams = wmsParams;
        },
        onAdd: function(map5) {
          this._crs = this.options.crs || map5.options.crs;
          this._wmsVersion = parseFloat(this.wmsParams.version);
          var projectionKey = this._wmsVersion >= 1.3 ? "crs" : "srs";
          this.wmsParams[projectionKey] = this._crs.code;
          TileLayer.prototype.onAdd.call(this, map5);
        },
        getTileUrl: function(coords) {
          var tileBounds = this._tileCoordsToNwSe(coords), crs = this._crs, bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])), min3 = bounds.min, max3 = bounds.max, bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ? [min3.y, min3.x, max3.y, max3.x] : [min3.x, min3.y, max3.x, max3.y]).join(","), url2 = TileLayer.prototype.getTileUrl.call(this, coords);
          return url2 + getParamString(this.wmsParams, url2, this.options.uppercase) + (this.options.uppercase ? "&BBOX=" : "&bbox=") + bbox;
        },
        // @method setParams(params: Object, noRedraw?: Boolean): this
        // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
        setParams: function(params, noRedraw) {
          extend(this.wmsParams, params);
          if (!noRedraw) {
            this.redraw();
          }
          return this;
        }
      });
      function tileLayerWMS(url2, options2) {
        return new TileLayerWMS(url2, options2);
      }
      TileLayer.WMS = TileLayerWMS;
      tileLayer.wms = tileLayerWMS;
      var Renderer3 = Layer2.extend({
        // @section
        // @aka Renderer options
        options: {
          // @option padding: Number = 0.1
          // How much to extend the clip area around the map view (relative to its size)
          // e.g. 0.1 would be 10% of map view in each direction
          padding: 0.1
        },
        initialize: function(options2) {
          setOptions2(this, options2);
          stamp(this);
          this._layers = this._layers || {};
        },
        onAdd: function() {
          if (!this._container) {
            this._initContainer();
            addClass(this._container, "leaflet-zoom-animated");
          }
          this.getPane().appendChild(this._container);
          this._update();
          this.on("update", this._updatePaths, this);
        },
        onRemove: function() {
          this.off("update", this._updatePaths, this);
          this._destroyContainer();
        },
        getEvents: function() {
          var events2 = {
            viewreset: this._reset,
            zoom: this._onZoom,
            moveend: this._update,
            zoomend: this._onZoomEnd
          };
          if (this._zoomAnimated) {
            events2.zoomanim = this._onAnimZoom;
          }
          return events2;
        },
        _onAnimZoom: function(ev) {
          this._updateTransform(ev.center, ev.zoom);
        },
        _onZoom: function() {
          this._updateTransform(this._map.getCenter(), this._map.getZoom());
        },
        _updateTransform: function(center, zoom2) {
          var scale2 = this._map.getZoomScale(zoom2, this._zoom), viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding), currentCenterPoint = this._map.project(this._center, zoom2), topLeftOffset = viewHalf.multiplyBy(-scale2).add(currentCenterPoint).subtract(this._map._getNewPixelOrigin(center, zoom2));
          if (Browser.any3d) {
            setTransform(this._container, topLeftOffset, scale2);
          } else {
            setPosition(this._container, topLeftOffset);
          }
        },
        _reset: function() {
          this._update();
          this._updateTransform(this._center, this._zoom);
          for (var id in this._layers) {
            this._layers[id]._reset();
          }
        },
        _onZoomEnd: function() {
          for (var id in this._layers) {
            this._layers[id]._project();
          }
        },
        _updatePaths: function() {
          for (var id in this._layers) {
            this._layers[id]._update();
          }
        },
        _update: function() {
          var p4 = this.options.padding, size4 = this._map.getSize(), min3 = this._map.containerPointToLayerPoint(size4.multiplyBy(-p4)).round();
          this._bounds = new Bounds2(min3, min3.add(size4.multiplyBy(1 + p4 * 2)).round());
          this._center = this._map.getCenter();
          this._zoom = this._map.getZoom();
        }
      });
      var Canvas2 = Renderer3.extend({
        // @section
        // @aka Canvas options
        options: {
          // @option tolerance: Number = 0
          // How much to extend the click tolerance around a path/object on the map.
          tolerance: 0
        },
        getEvents: function() {
          var events2 = Renderer3.prototype.getEvents.call(this);
          events2.viewprereset = this._onViewPreReset;
          return events2;
        },
        _onViewPreReset: function() {
          this._postponeUpdatePaths = true;
        },
        onAdd: function() {
          Renderer3.prototype.onAdd.call(this);
          this._draw();
        },
        _initContainer: function() {
          var container = this._container = document.createElement("canvas");
          on2(container, "mousemove", this._onMouseMove, this);
          on2(container, "click dblclick mousedown mouseup contextmenu", this._onClick, this);
          on2(container, "mouseout", this._handleMouseOut, this);
          container["_leaflet_disable_events"] = true;
          this._ctx = container.getContext("2d");
        },
        _destroyContainer: function() {
          cancelAnimFrame(this._redrawRequest);
          delete this._ctx;
          remove3(this._container);
          off(this._container);
          delete this._container;
        },
        _updatePaths: function() {
          if (this._postponeUpdatePaths) {
            return;
          }
          var layer2;
          this._redrawBounds = null;
          for (var id in this._layers) {
            layer2 = this._layers[id];
            layer2._update();
          }
          this._redraw();
        },
        _update: function() {
          if (this._map._animatingZoom && this._bounds) {
            return;
          }
          Renderer3.prototype._update.call(this);
          var b3 = this._bounds, container = this._container, size4 = b3.getSize(), m3 = Browser.retina ? 2 : 1;
          setPosition(container, b3.min);
          container.width = m3 * size4.x;
          container.height = m3 * size4.y;
          container.style.width = size4.x + "px";
          container.style.height = size4.y + "px";
          if (Browser.retina) {
            this._ctx.scale(2, 2);
          }
          this._ctx.translate(-b3.min.x, -b3.min.y);
          this.fire("update");
        },
        _reset: function() {
          Renderer3.prototype._reset.call(this);
          if (this._postponeUpdatePaths) {
            this._postponeUpdatePaths = false;
            this._updatePaths();
          }
        },
        _initPath: function(layer2) {
          this._updateDashArray(layer2);
          this._layers[stamp(layer2)] = layer2;
          var order2 = layer2._order = {
            layer: layer2,
            prev: this._drawLast,
            next: null
          };
          if (this._drawLast) {
            this._drawLast.next = order2;
          }
          this._drawLast = order2;
          this._drawFirst = this._drawFirst || this._drawLast;
        },
        _addPath: function(layer2) {
          this._requestRedraw(layer2);
        },
        _removePath: function(layer2) {
          var order2 = layer2._order;
          var next2 = order2.next;
          var prev = order2.prev;
          if (next2) {
            next2.prev = prev;
          } else {
            this._drawLast = prev;
          }
          if (prev) {
            prev.next = next2;
          } else {
            this._drawFirst = next2;
          }
          delete layer2._order;
          delete this._layers[stamp(layer2)];
          this._requestRedraw(layer2);
        },
        _updatePath: function(layer2) {
          this._extendRedrawBounds(layer2);
          layer2._project();
          layer2._update();
          this._requestRedraw(layer2);
        },
        _updateStyle: function(layer2) {
          this._updateDashArray(layer2);
          this._requestRedraw(layer2);
        },
        _updateDashArray: function(layer2) {
          if (typeof layer2.options.dashArray === "string") {
            var parts = layer2.options.dashArray.split(/[, ]+/), dashArray = [], dashValue, i3;
            for (i3 = 0; i3 < parts.length; i3++) {
              dashValue = Number(parts[i3]);
              if (isNaN(dashValue)) {
                return;
              }
              dashArray.push(dashValue);
            }
            layer2.options._dashArray = dashArray;
          } else {
            layer2.options._dashArray = layer2.options.dashArray;
          }
        },
        _requestRedraw: function(layer2) {
          if (!this._map) {
            return;
          }
          this._extendRedrawBounds(layer2);
          this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
        },
        _extendRedrawBounds: function(layer2) {
          if (layer2._pxBounds) {
            var padding = (layer2.options.weight || 0) + 1;
            this._redrawBounds = this._redrawBounds || new Bounds2();
            this._redrawBounds.extend(layer2._pxBounds.min.subtract([padding, padding]));
            this._redrawBounds.extend(layer2._pxBounds.max.add([padding, padding]));
          }
        },
        _redraw: function() {
          this._redrawRequest = null;
          if (this._redrawBounds) {
            this._redrawBounds.min._floor();
            this._redrawBounds.max._ceil();
          }
          this._clear();
          this._draw();
          this._redrawBounds = null;
        },
        _clear: function() {
          var bounds = this._redrawBounds;
          if (bounds) {
            var size4 = bounds.getSize();
            this._ctx.clearRect(bounds.min.x, bounds.min.y, size4.x, size4.y);
          } else {
            this._ctx.save();
            this._ctx.setTransform(1, 0, 0, 1, 0, 0);
            this._ctx.clearRect(0, 0, this._container.width, this._container.height);
            this._ctx.restore();
          }
        },
        _draw: function() {
          var layer2, bounds = this._redrawBounds;
          this._ctx.save();
          if (bounds) {
            var size4 = bounds.getSize();
            this._ctx.beginPath();
            this._ctx.rect(bounds.min.x, bounds.min.y, size4.x, size4.y);
            this._ctx.clip();
          }
          this._drawing = true;
          for (var order2 = this._drawFirst; order2; order2 = order2.next) {
            layer2 = order2.layer;
            if (!bounds || layer2._pxBounds && layer2._pxBounds.intersects(bounds)) {
              layer2._updatePath();
            }
          }
          this._drawing = false;
          this._ctx.restore();
        },
        _updatePoly: function(layer2, closed) {
          if (!this._drawing) {
            return;
          }
          var i3, j, len2, p4, parts = layer2._parts, len = parts.length, ctx = this._ctx;
          if (!len) {
            return;
          }
          ctx.beginPath();
          for (i3 = 0; i3 < len; i3++) {
            for (j = 0, len2 = parts[i3].length; j < len2; j++) {
              p4 = parts[i3][j];
              ctx[j ? "lineTo" : "moveTo"](p4.x, p4.y);
            }
            if (closed) {
              ctx.closePath();
            }
          }
          this._fillStroke(ctx, layer2);
        },
        _updateCircle: function(layer2) {
          if (!this._drawing || layer2._empty()) {
            return;
          }
          var p4 = layer2._point, ctx = this._ctx, r3 = Math.max(Math.round(layer2._radius), 1), s3 = (Math.max(Math.round(layer2._radiusY), 1) || r3) / r3;
          if (s3 !== 1) {
            ctx.save();
            ctx.scale(1, s3);
          }
          ctx.beginPath();
          ctx.arc(p4.x, p4.y / s3, r3, 0, Math.PI * 2, false);
          if (s3 !== 1) {
            ctx.restore();
          }
          this._fillStroke(ctx, layer2);
        },
        _fillStroke: function(ctx, layer2) {
          var options2 = layer2.options;
          if (options2.fill) {
            ctx.globalAlpha = options2.fillOpacity;
            ctx.fillStyle = options2.fillColor || options2.color;
            ctx.fill(options2.fillRule || "evenodd");
          }
          if (options2.stroke && options2.weight !== 0) {
            if (ctx.setLineDash) {
              ctx.setLineDash(layer2.options && layer2.options._dashArray || []);
            }
            ctx.globalAlpha = options2.opacity;
            ctx.lineWidth = options2.weight;
            ctx.strokeStyle = options2.color;
            ctx.lineCap = options2.lineCap;
            ctx.lineJoin = options2.lineJoin;
            ctx.stroke();
          }
        },
        // Canvas obviously doesn't have mouse events for individual drawn objects,
        // so we emulate that by calculating what's under the mouse on mousemove/click manually
        _onClick: function(e3) {
          var point = this._map.mouseEventToLayerPoint(e3), layer2, clickedLayer;
          for (var order2 = this._drawFirst; order2; order2 = order2.next) {
            layer2 = order2.layer;
            if (layer2.options.interactive && layer2._containsPoint(point)) {
              if (!(e3.type === "click" || e3.type === "preclick") || !this._map._draggableMoved(layer2)) {
                clickedLayer = layer2;
              }
            }
          }
          this._fireEvent(clickedLayer ? [clickedLayer] : false, e3);
        },
        _onMouseMove: function(e3) {
          if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) {
            return;
          }
          var point = this._map.mouseEventToLayerPoint(e3);
          this._handleMouseHover(e3, point);
        },
        _handleMouseOut: function(e3) {
          var layer2 = this._hoveredLayer;
          if (layer2) {
            removeClass(this._container, "leaflet-interactive");
            this._fireEvent([layer2], e3, "mouseout");
            this._hoveredLayer = null;
            this._mouseHoverThrottled = false;
          }
        },
        _handleMouseHover: function(e3, point) {
          if (this._mouseHoverThrottled) {
            return;
          }
          var layer2, candidateHoveredLayer;
          for (var order2 = this._drawFirst; order2; order2 = order2.next) {
            layer2 = order2.layer;
            if (layer2.options.interactive && layer2._containsPoint(point)) {
              candidateHoveredLayer = layer2;
            }
          }
          if (candidateHoveredLayer !== this._hoveredLayer) {
            this._handleMouseOut(e3);
            if (candidateHoveredLayer) {
              addClass(this._container, "leaflet-interactive");
              this._fireEvent([candidateHoveredLayer], e3, "mouseover");
              this._hoveredLayer = candidateHoveredLayer;
            }
          }
          this._fireEvent(this._hoveredLayer ? [this._hoveredLayer] : false, e3);
          this._mouseHoverThrottled = true;
          setTimeout(bind2(function() {
            this._mouseHoverThrottled = false;
          }, this), 32);
        },
        _fireEvent: function(layers2, e3, type) {
          this._map._fireDOMEvent(e3, type || e3.type, layers2);
        },
        _bringToFront: function(layer2) {
          var order2 = layer2._order;
          if (!order2) {
            return;
          }
          var next2 = order2.next;
          var prev = order2.prev;
          if (next2) {
            next2.prev = prev;
          } else {
            return;
          }
          if (prev) {
            prev.next = next2;
          } else if (next2) {
            this._drawFirst = next2;
          }
          order2.prev = this._drawLast;
          this._drawLast.next = order2;
          order2.next = null;
          this._drawLast = order2;
          this._requestRedraw(layer2);
        },
        _bringToBack: function(layer2) {
          var order2 = layer2._order;
          if (!order2) {
            return;
          }
          var next2 = order2.next;
          var prev = order2.prev;
          if (prev) {
            prev.next = next2;
          } else {
            return;
          }
          if (next2) {
            next2.prev = prev;
          } else if (prev) {
            this._drawLast = prev;
          }
          order2.prev = null;
          order2.next = this._drawFirst;
          this._drawFirst.prev = order2;
          this._drawFirst = order2;
          this._requestRedraw(layer2);
        }
      });
      function canvas(options2) {
        return Browser.canvas ? new Canvas2(options2) : null;
      }
      var vmlCreate = function() {
        try {
          document.namespaces.add("lvml", "urn:schemas-microsoft-com:vml");
          return function(name2) {
            return document.createElement("<lvml:" + name2 + ' class="lvml">');
          };
        } catch (e3) {
        }
        return function(name2) {
          return document.createElement("<" + name2 + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
        };
      }();
      var vmlMixin = {
        _initContainer: function() {
          this._container = create$1("div", "leaflet-vml-container");
        },
        _update: function() {
          if (this._map._animatingZoom) {
            return;
          }
          Renderer3.prototype._update.call(this);
          this.fire("update");
        },
        _initPath: function(layer2) {
          var container = layer2._container = vmlCreate("shape");
          addClass(container, "leaflet-vml-shape " + (this.options.className || ""));
          container.coordsize = "1 1";
          layer2._path = vmlCreate("path");
          container.appendChild(layer2._path);
          this._updateStyle(layer2);
          this._layers[stamp(layer2)] = layer2;
        },
        _addPath: function(layer2) {
          var container = layer2._container;
          this._container.appendChild(container);
          if (layer2.options.interactive) {
            layer2.addInteractiveTarget(container);
          }
        },
        _removePath: function(layer2) {
          var container = layer2._container;
          remove3(container);
          layer2.removeInteractiveTarget(container);
          delete this._layers[stamp(layer2)];
        },
        _updateStyle: function(layer2) {
          var stroke = layer2._stroke, fill = layer2._fill, options2 = layer2.options, container = layer2._container;
          container.stroked = !!options2.stroke;
          container.filled = !!options2.fill;
          if (options2.stroke) {
            if (!stroke) {
              stroke = layer2._stroke = vmlCreate("stroke");
            }
            container.appendChild(stroke);
            stroke.weight = options2.weight + "px";
            stroke.color = options2.color;
            stroke.opacity = options2.opacity;
            if (options2.dashArray) {
              stroke.dashStyle = isArray3(options2.dashArray) ? options2.dashArray.join(" ") : options2.dashArray.replace(/( *, *)/g, " ");
            } else {
              stroke.dashStyle = "";
            }
            stroke.endcap = options2.lineCap.replace("butt", "flat");
            stroke.joinstyle = options2.lineJoin;
          } else if (stroke) {
            container.removeChild(stroke);
            layer2._stroke = null;
          }
          if (options2.fill) {
            if (!fill) {
              fill = layer2._fill = vmlCreate("fill");
            }
            container.appendChild(fill);
            fill.color = options2.fillColor || options2.color;
            fill.opacity = options2.fillOpacity;
          } else if (fill) {
            container.removeChild(fill);
            layer2._fill = null;
          }
        },
        _updateCircle: function(layer2) {
          var p4 = layer2._point.round(), r3 = Math.round(layer2._radius), r22 = Math.round(layer2._radiusY || r3);
          this._setPath(layer2, layer2._empty() ? "M0 0" : "AL " + p4.x + "," + p4.y + " " + r3 + "," + r22 + " 0," + 65535 * 360);
        },
        _setPath: function(layer2, path) {
          layer2._path.v = path;
        },
        _bringToFront: function(layer2) {
          toFront(layer2._container);
        },
        _bringToBack: function(layer2) {
          toBack(layer2._container);
        }
      };
      var create6 = Browser.vml ? vmlCreate : svgCreate;
      var SVG3 = Renderer3.extend({
        _initContainer: function() {
          this._container = create6("svg");
          this._container.setAttribute("pointer-events", "none");
          this._rootGroup = create6("g");
          this._container.appendChild(this._rootGroup);
        },
        _destroyContainer: function() {
          remove3(this._container);
          off(this._container);
          delete this._container;
          delete this._rootGroup;
          delete this._svgSize;
        },
        _update: function() {
          if (this._map._animatingZoom && this._bounds) {
            return;
          }
          Renderer3.prototype._update.call(this);
          var b3 = this._bounds, size4 = b3.getSize(), container = this._container;
          if (!this._svgSize || !this._svgSize.equals(size4)) {
            this._svgSize = size4;
            container.setAttribute("width", size4.x);
            container.setAttribute("height", size4.y);
          }
          setPosition(container, b3.min);
          container.setAttribute("viewBox", [b3.min.x, b3.min.y, size4.x, size4.y].join(" "));
          this.fire("update");
        },
        // methods below are called by vector layers implementations
        _initPath: function(layer2) {
          var path = layer2._path = create6("path");
          if (layer2.options.className) {
            addClass(path, layer2.options.className);
          }
          if (layer2.options.interactive) {
            addClass(path, "leaflet-interactive");
          }
          this._updateStyle(layer2);
          this._layers[stamp(layer2)] = layer2;
        },
        _addPath: function(layer2) {
          if (!this._rootGroup) {
            this._initContainer();
          }
          this._rootGroup.appendChild(layer2._path);
          layer2.addInteractiveTarget(layer2._path);
        },
        _removePath: function(layer2) {
          remove3(layer2._path);
          layer2.removeInteractiveTarget(layer2._path);
          delete this._layers[stamp(layer2)];
        },
        _updatePath: function(layer2) {
          layer2._project();
          layer2._update();
        },
        _updateStyle: function(layer2) {
          var path = layer2._path, options2 = layer2.options;
          if (!path) {
            return;
          }
          if (options2.stroke) {
            path.setAttribute("stroke", options2.color);
            path.setAttribute("stroke-opacity", options2.opacity);
            path.setAttribute("stroke-width", options2.weight);
            path.setAttribute("stroke-linecap", options2.lineCap);
            path.setAttribute("stroke-linejoin", options2.lineJoin);
            if (options2.dashArray) {
              path.setAttribute("stroke-dasharray", options2.dashArray);
            } else {
              path.removeAttribute("stroke-dasharray");
            }
            if (options2.dashOffset) {
              path.setAttribute("stroke-dashoffset", options2.dashOffset);
            } else {
              path.removeAttribute("stroke-dashoffset");
            }
          } else {
            path.setAttribute("stroke", "none");
          }
          if (options2.fill) {
            path.setAttribute("fill", options2.fillColor || options2.color);
            path.setAttribute("fill-opacity", options2.fillOpacity);
            path.setAttribute("fill-rule", options2.fillRule || "evenodd");
          } else {
            path.setAttribute("fill", "none");
          }
        },
        _updatePoly: function(layer2, closed) {
          this._setPath(layer2, pointsToPath(layer2._parts, closed));
        },
        _updateCircle: function(layer2) {
          var p4 = layer2._point, r3 = Math.max(Math.round(layer2._radius), 1), r22 = Math.max(Math.round(layer2._radiusY), 1) || r3, arc = "a" + r3 + "," + r22 + " 0 1,0 ";
          var d3 = layer2._empty() ? "M0 0" : "M" + (p4.x - r3) + "," + p4.y + arc + r3 * 2 + ",0 " + arc + -r3 * 2 + ",0 ";
          this._setPath(layer2, d3);
        },
        _setPath: function(layer2, path) {
          layer2._path.setAttribute("d", path);
        },
        // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
        _bringToFront: function(layer2) {
          toFront(layer2._path);
        },
        _bringToBack: function(layer2) {
          toBack(layer2._path);
        }
      });
      if (Browser.vml) {
        SVG3.include(vmlMixin);
      }
      function svg4(options2) {
        return Browser.svg || Browser.vml ? new SVG3(options2) : null;
      }
      Map2.include({
        // @namespace Map; @method getRenderer(layer: Path): Renderer
        // Returns the instance of `Renderer` that should be used to render the given
        // `Path`. It will ensure that the `renderer` options of the map and paths
        // are respected, and that the renderers do exist on the map.
        getRenderer: function(layer2) {
          var renderer2 = layer2.options.renderer || this._getPaneRenderer(layer2.options.pane) || this.options.renderer || this._renderer;
          if (!renderer2) {
            renderer2 = this._renderer = this._createRenderer();
          }
          if (!this.hasLayer(renderer2)) {
            this.addLayer(renderer2);
          }
          return renderer2;
        },
        _getPaneRenderer: function(name2) {
          if (name2 === "overlayPane" || name2 === void 0) {
            return false;
          }
          var renderer2 = this._paneRenderers[name2];
          if (renderer2 === void 0) {
            renderer2 = this._createRenderer({ pane: name2 });
            this._paneRenderers[name2] = renderer2;
          }
          return renderer2;
        },
        _createRenderer: function(options2) {
          return this.options.preferCanvas && canvas(options2) || svg4(options2);
        }
      });
      var Rectangle = Polygon.extend({
        initialize: function(latLngBounds, options2) {
          Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options2);
        },
        // @method setBounds(latLngBounds: LatLngBounds): this
        // Redraws the rectangle with the passed bounds.
        setBounds: function(latLngBounds) {
          return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
        },
        _boundsToLatLngs: function(latLngBounds) {
          latLngBounds = toLatLngBounds(latLngBounds);
          return [
            latLngBounds.getSouthWest(),
            latLngBounds.getNorthWest(),
            latLngBounds.getNorthEast(),
            latLngBounds.getSouthEast()
          ];
        }
      });
      function rectangle(latLngBounds, options2) {
        return new Rectangle(latLngBounds, options2);
      }
      SVG3.create = create6;
      SVG3.pointsToPath = pointsToPath;
      GeoJSON.geometryToLayer = geometryToLayer;
      GeoJSON.coordsToLatLng = coordsToLatLng;
      GeoJSON.coordsToLatLngs = coordsToLatLngs;
      GeoJSON.latLngToCoords = latLngToCoords;
      GeoJSON.latLngsToCoords = latLngsToCoords;
      GeoJSON.getFeature = getFeature;
      GeoJSON.asFeature = asFeature;
      Map2.mergeOptions({
        // @option boxZoom: Boolean = true
        // Whether the map can be zoomed to a rectangular area specified by
        // dragging the mouse while pressing the shift key.
        boxZoom: true
      });
      var BoxZoom = Handler.extend({
        initialize: function(map5) {
          this._map = map5;
          this._container = map5._container;
          this._pane = map5._panes.overlayPane;
          this._resetStateTimeout = 0;
          map5.on("unload", this._destroy, this);
        },
        addHooks: function() {
          on2(this._container, "mousedown", this._onMouseDown, this);
        },
        removeHooks: function() {
          off(this._container, "mousedown", this._onMouseDown, this);
        },
        moved: function() {
          return this._moved;
        },
        _destroy: function() {
          remove3(this._pane);
          delete this._pane;
        },
        _resetState: function() {
          this._resetStateTimeout = 0;
          this._moved = false;
        },
        _clearDeferredResetState: function() {
          if (this._resetStateTimeout !== 0) {
            clearTimeout(this._resetStateTimeout);
            this._resetStateTimeout = 0;
          }
        },
        _onMouseDown: function(e3) {
          if (!e3.shiftKey || e3.which !== 1 && e3.button !== 1) {
            return false;
          }
          this._clearDeferredResetState();
          this._resetState();
          disableTextSelection();
          disableImageDrag();
          this._startPoint = this._map.mouseEventToContainerPoint(e3);
          on2(document, {
            contextmenu: stop,
            mousemove: this._onMouseMove,
            mouseup: this._onMouseUp,
            keydown: this._onKeyDown
          }, this);
        },
        _onMouseMove: function(e3) {
          if (!this._moved) {
            this._moved = true;
            this._box = create$1("div", "leaflet-zoom-box", this._container);
            addClass(this._container, "leaflet-crosshair");
            this._map.fire("boxzoomstart");
          }
          this._point = this._map.mouseEventToContainerPoint(e3);
          var bounds = new Bounds2(this._point, this._startPoint), size4 = bounds.getSize();
          setPosition(this._box, bounds.min);
          this._box.style.width = size4.x + "px";
          this._box.style.height = size4.y + "px";
        },
        _finish: function() {
          if (this._moved) {
            remove3(this._box);
            removeClass(this._container, "leaflet-crosshair");
          }
          enableTextSelection();
          enableImageDrag();
          off(document, {
            contextmenu: stop,
            mousemove: this._onMouseMove,
            mouseup: this._onMouseUp,
            keydown: this._onKeyDown
          }, this);
        },
        _onMouseUp: function(e3) {
          if (e3.which !== 1 && e3.button !== 1) {
            return;
          }
          this._finish();
          if (!this._moved) {
            return;
          }
          this._clearDeferredResetState();
          this._resetStateTimeout = setTimeout(bind2(this._resetState, this), 0);
          var bounds = new LatLngBounds(
            this._map.containerPointToLatLng(this._startPoint),
            this._map.containerPointToLatLng(this._point)
          );
          this._map.fitBounds(bounds).fire("boxzoomend", { boxZoomBounds: bounds });
        },
        _onKeyDown: function(e3) {
          if (e3.keyCode === 27) {
            this._finish();
            this._clearDeferredResetState();
            this._resetState();
          }
        }
      });
      Map2.addInitHook("addHandler", "boxZoom", BoxZoom);
      Map2.mergeOptions({
        // @option doubleClickZoom: Boolean|String = true
        // Whether the map can be zoomed in by double clicking on it and
        // zoomed out by double clicking while holding shift. If passed
        // `'center'`, double-click zoom will zoom to the center of the
        //  view regardless of where the mouse was.
        doubleClickZoom: true
      });
      var DoubleClickZoom = Handler.extend({
        addHooks: function() {
          this._map.on("dblclick", this._onDoubleClick, this);
        },
        removeHooks: function() {
          this._map.off("dblclick", this._onDoubleClick, this);
        },
        _onDoubleClick: function(e3) {
          var map5 = this._map, oldZoom = map5.getZoom(), delta = map5.options.zoomDelta, zoom2 = e3.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
          if (map5.options.doubleClickZoom === "center") {
            map5.setZoom(zoom2);
          } else {
            map5.setZoomAround(e3.containerPoint, zoom2);
          }
        }
      });
      Map2.addInitHook("addHandler", "doubleClickZoom", DoubleClickZoom);
      Map2.mergeOptions({
        // @option dragging: Boolean = true
        // Whether the map is draggable with mouse/touch or not.
        dragging: true,
        // @section Panning Inertia Options
        // @option inertia: Boolean = *
        // If enabled, panning of the map will have an inertia effect where
        // the map builds momentum while dragging and continues moving in
        // the same direction for some time. Feels especially nice on touch
        // devices. Enabled by default.
        inertia: true,
        // @option inertiaDeceleration: Number = 3000
        // The rate with which the inertial movement slows down, in pixels/second².
        inertiaDeceleration: 3400,
        // px/s^2
        // @option inertiaMaxSpeed: Number = Infinity
        // Max speed of the inertial movement, in pixels/second.
        inertiaMaxSpeed: Infinity,
        // px/s
        // @option easeLinearity: Number = 0.2
        easeLinearity: 0.2,
        // TODO refactor, move to CRS
        // @option worldCopyJump: Boolean = false
        // With this option enabled, the map tracks when you pan to another "copy"
        // of the world and seamlessly jumps to the original one so that all overlays
        // like markers and vector layers are still visible.
        worldCopyJump: false,
        // @option maxBoundsViscosity: Number = 0.0
        // If `maxBounds` is set, this option will control how solid the bounds
        // are when dragging the map around. The default value of `0.0` allows the
        // user to drag outside the bounds at normal speed, higher values will
        // slow down map dragging outside bounds, and `1.0` makes the bounds fully
        // solid, preventing the user from dragging outside the bounds.
        maxBoundsViscosity: 0
      });
      var Drag = Handler.extend({
        addHooks: function() {
          if (!this._draggable) {
            var map5 = this._map;
            this._draggable = new Draggable(map5._mapPane, map5._container);
            this._draggable.on({
              dragstart: this._onDragStart,
              drag: this._onDrag,
              dragend: this._onDragEnd
            }, this);
            this._draggable.on("predrag", this._onPreDragLimit, this);
            if (map5.options.worldCopyJump) {
              this._draggable.on("predrag", this._onPreDragWrap, this);
              map5.on("zoomend", this._onZoomEnd, this);
              map5.whenReady(this._onZoomEnd, this);
            }
          }
          addClass(this._map._container, "leaflet-grab leaflet-touch-drag");
          this._draggable.enable();
          this._positions = [];
          this._times = [];
        },
        removeHooks: function() {
          removeClass(this._map._container, "leaflet-grab");
          removeClass(this._map._container, "leaflet-touch-drag");
          this._draggable.disable();
        },
        moved: function() {
          return this._draggable && this._draggable._moved;
        },
        moving: function() {
          return this._draggable && this._draggable._moving;
        },
        _onDragStart: function() {
          var map5 = this._map;
          map5._stop();
          if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
            var bounds = toLatLngBounds(this._map.options.maxBounds);
            this._offsetLimit = toBounds(
              this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
              this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1).add(this._map.getSize())
            );
            this._viscosity = Math.min(1, Math.max(0, this._map.options.maxBoundsViscosity));
          } else {
            this._offsetLimit = null;
          }
          map5.fire("movestart").fire("dragstart");
          if (map5.options.inertia) {
            this._positions = [];
            this._times = [];
          }
        },
        _onDrag: function(e3) {
          if (this._map.options.inertia) {
            var time3 = this._lastTime = +/* @__PURE__ */ new Date(), pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
            this._positions.push(pos);
            this._times.push(time3);
            this._prunePositions(time3);
          }
          this._map.fire("move", e3).fire("drag", e3);
        },
        _prunePositions: function(time3) {
          while (this._positions.length > 1 && time3 - this._times[0] > 50) {
            this._positions.shift();
            this._times.shift();
          }
        },
        _onZoomEnd: function() {
          var pxCenter = this._map.getSize().divideBy(2), pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
          this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
          this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
        },
        _viscousLimit: function(value2, threshold) {
          return value2 - (value2 - threshold) * this._viscosity;
        },
        _onPreDragLimit: function() {
          if (!this._viscosity || !this._offsetLimit) {
            return;
          }
          var offset = this._draggable._newPos.subtract(this._draggable._startPos);
          var limit = this._offsetLimit;
          if (offset.x < limit.min.x) {
            offset.x = this._viscousLimit(offset.x, limit.min.x);
          }
          if (offset.y < limit.min.y) {
            offset.y = this._viscousLimit(offset.y, limit.min.y);
          }
          if (offset.x > limit.max.x) {
            offset.x = this._viscousLimit(offset.x, limit.max.x);
          }
          if (offset.y > limit.max.y) {
            offset.y = this._viscousLimit(offset.y, limit.max.y);
          }
          this._draggable._newPos = this._draggable._startPos.add(offset);
        },
        _onPreDragWrap: function() {
          var worldWidth = this._worldWidth, halfWidth = Math.round(worldWidth / 2), dx = this._initialWorldOffset, x3 = this._draggable._newPos.x, newX1 = (x3 - halfWidth + dx) % worldWidth + halfWidth - dx, newX2 = (x3 + halfWidth + dx) % worldWidth - halfWidth - dx, newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
          this._draggable._absPos = this._draggable._newPos.clone();
          this._draggable._newPos.x = newX;
        },
        _onDragEnd: function(e3) {
          var map5 = this._map, options2 = map5.options, noInertia = !options2.inertia || e3.noInertia || this._times.length < 2;
          map5.fire("dragend", e3);
          if (noInertia) {
            map5.fire("moveend");
          } else {
            this._prunePositions(+/* @__PURE__ */ new Date());
            var direction = this._lastPos.subtract(this._positions[0]), duration = (this._lastTime - this._times[0]) / 1e3, ease = options2.easeLinearity, speedVector = direction.multiplyBy(ease / duration), speed = speedVector.distanceTo([0, 0]), limitedSpeed = Math.min(options2.inertiaMaxSpeed, speed), limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed), decelerationDuration = limitedSpeed / (options2.inertiaDeceleration * ease), offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
            if (!offset.x && !offset.y) {
              map5.fire("moveend");
            } else {
              offset = map5._limitOffset(offset, map5.options.maxBounds);
              requestAnimFrame(function() {
                map5.panBy(offset, {
                  duration: decelerationDuration,
                  easeLinearity: ease,
                  noMoveStart: true,
                  animate: true
                });
              });
            }
          }
        }
      });
      Map2.addInitHook("addHandler", "dragging", Drag);
      Map2.mergeOptions({
        // @option keyboard: Boolean = true
        // Makes the map focusable and allows users to navigate the map with keyboard
        // arrows and `+`/`-` keys.
        keyboard: true,
        // @option keyboardPanDelta: Number = 80
        // Amount of pixels to pan when pressing an arrow key.
        keyboardPanDelta: 80
      });
      var Keyboard = Handler.extend({
        keyCodes: {
          left: [37],
          right: [39],
          down: [40],
          up: [38],
          zoomIn: [187, 107, 61, 171],
          zoomOut: [189, 109, 54, 173]
        },
        initialize: function(map5) {
          this._map = map5;
          this._setPanDelta(map5.options.keyboardPanDelta);
          this._setZoomDelta(map5.options.zoomDelta);
        },
        addHooks: function() {
          var container = this._map._container;
          if (container.tabIndex <= 0) {
            container.tabIndex = "0";
          }
          on2(container, {
            focus: this._onFocus,
            blur: this._onBlur,
            mousedown: this._onMouseDown
          }, this);
          this._map.on({
            focus: this._addHooks,
            blur: this._removeHooks
          }, this);
        },
        removeHooks: function() {
          this._removeHooks();
          off(this._map._container, {
            focus: this._onFocus,
            blur: this._onBlur,
            mousedown: this._onMouseDown
          }, this);
          this._map.off({
            focus: this._addHooks,
            blur: this._removeHooks
          }, this);
        },
        _onMouseDown: function() {
          if (this._focused) {
            return;
          }
          var body3 = document.body, docEl = document.documentElement, top2 = body3.scrollTop || docEl.scrollTop, left = body3.scrollLeft || docEl.scrollLeft;
          this._map._container.focus();
          window.scrollTo(left, top2);
        },
        _onFocus: function() {
          this._focused = true;
          this._map.fire("focus");
        },
        _onBlur: function() {
          this._focused = false;
          this._map.fire("blur");
        },
        _setPanDelta: function(panDelta) {
          var keys5 = this._panKeys = {}, codes = this.keyCodes, i3, len;
          for (i3 = 0, len = codes.left.length; i3 < len; i3++) {
            keys5[codes.left[i3]] = [-1 * panDelta, 0];
          }
          for (i3 = 0, len = codes.right.length; i3 < len; i3++) {
            keys5[codes.right[i3]] = [panDelta, 0];
          }
          for (i3 = 0, len = codes.down.length; i3 < len; i3++) {
            keys5[codes.down[i3]] = [0, panDelta];
          }
          for (i3 = 0, len = codes.up.length; i3 < len; i3++) {
            keys5[codes.up[i3]] = [0, -1 * panDelta];
          }
        },
        _setZoomDelta: function(zoomDelta) {
          var keys5 = this._zoomKeys = {}, codes = this.keyCodes, i3, len;
          for (i3 = 0, len = codes.zoomIn.length; i3 < len; i3++) {
            keys5[codes.zoomIn[i3]] = zoomDelta;
          }
          for (i3 = 0, len = codes.zoomOut.length; i3 < len; i3++) {
            keys5[codes.zoomOut[i3]] = -zoomDelta;
          }
        },
        _addHooks: function() {
          on2(document, "keydown", this._onKeyDown, this);
        },
        _removeHooks: function() {
          off(document, "keydown", this._onKeyDown, this);
        },
        _onKeyDown: function(e3) {
          if (e3.altKey || e3.ctrlKey || e3.metaKey) {
            return;
          }
          var key2 = e3.keyCode, map5 = this._map, offset;
          if (key2 in this._panKeys) {
            if (!map5._panAnim || !map5._panAnim._inProgress) {
              offset = this._panKeys[key2];
              if (e3.shiftKey) {
                offset = toPoint(offset).multiplyBy(3);
              }
              if (map5.options.maxBounds) {
                offset = map5._limitOffset(toPoint(offset), map5.options.maxBounds);
              }
              if (map5.options.worldCopyJump) {
                var newLatLng = map5.wrapLatLng(map5.unproject(map5.project(map5.getCenter()).add(offset)));
                map5.panTo(newLatLng);
              } else {
                map5.panBy(offset);
              }
            }
          } else if (key2 in this._zoomKeys) {
            map5.setZoom(map5.getZoom() + (e3.shiftKey ? 3 : 1) * this._zoomKeys[key2]);
          } else if (key2 === 27 && map5._popup && map5._popup.options.closeOnEscapeKey) {
            map5.closePopup();
          } else {
            return;
          }
          stop(e3);
        }
      });
      Map2.addInitHook("addHandler", "keyboard", Keyboard);
      Map2.mergeOptions({
        // @section Mouse wheel options
        // @option scrollWheelZoom: Boolean|String = true
        // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
        // it will zoom to the center of the view regardless of where the mouse was.
        scrollWheelZoom: true,
        // @option wheelDebounceTime: Number = 40
        // Limits the rate at which a wheel can fire (in milliseconds). By default
        // user can't zoom via wheel more often than once per 40 ms.
        wheelDebounceTime: 40,
        // @option wheelPxPerZoomLevel: Number = 60
        // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
        // mean a change of one full zoom level. Smaller values will make wheel-zooming
        // faster (and vice versa).
        wheelPxPerZoomLevel: 60
      });
      var ScrollWheelZoom = Handler.extend({
        addHooks: function() {
          on2(this._map._container, "wheel", this._onWheelScroll, this);
          this._delta = 0;
        },
        removeHooks: function() {
          off(this._map._container, "wheel", this._onWheelScroll, this);
        },
        _onWheelScroll: function(e3) {
          var delta = getWheelDelta(e3);
          var debounce4 = this._map.options.wheelDebounceTime;
          this._delta += delta;
          this._lastMousePos = this._map.mouseEventToContainerPoint(e3);
          if (!this._startTime) {
            this._startTime = +/* @__PURE__ */ new Date();
          }
          var left = Math.max(debounce4 - (+/* @__PURE__ */ new Date() - this._startTime), 0);
          clearTimeout(this._timer);
          this._timer = setTimeout(bind2(this._performZoom, this), left);
          stop(e3);
        },
        _performZoom: function() {
          var map5 = this._map, zoom2 = map5.getZoom(), snap = this._map.options.zoomSnap || 0;
          map5._stop();
          var d22 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4), d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d22)))) / Math.LN2, d4 = snap ? Math.ceil(d3 / snap) * snap : d3, delta = map5._limitZoom(zoom2 + (this._delta > 0 ? d4 : -d4)) - zoom2;
          this._delta = 0;
          this._startTime = null;
          if (!delta) {
            return;
          }
          if (map5.options.scrollWheelZoom === "center") {
            map5.setZoom(zoom2 + delta);
          } else {
            map5.setZoomAround(this._lastMousePos, zoom2 + delta);
          }
        }
      });
      Map2.addInitHook("addHandler", "scrollWheelZoom", ScrollWheelZoom);
      var tapHoldDelay = 600;
      Map2.mergeOptions({
        // @section Touch interaction options
        // @option tapHold: Boolean
        // Enables simulation of `contextmenu` event, default is `true` for mobile Safari.
        tapHold: Browser.touchNative && Browser.safari && Browser.mobile,
        // @option tapTolerance: Number = 15
        // The max number of pixels a user can shift his finger during touch
        // for it to be considered a valid tap.
        tapTolerance: 15
      });
      var TapHold = Handler.extend({
        addHooks: function() {
          on2(this._map._container, "touchstart", this._onDown, this);
        },
        removeHooks: function() {
          off(this._map._container, "touchstart", this._onDown, this);
        },
        _onDown: function(e3) {
          clearTimeout(this._holdTimeout);
          if (e3.touches.length !== 1) {
            return;
          }
          var first2 = e3.touches[0];
          this._startPos = this._newPos = new Point2(first2.clientX, first2.clientY);
          this._holdTimeout = setTimeout(bind2(function() {
            this._cancel();
            if (!this._isTapValid()) {
              return;
            }
            on2(document, "touchend", preventDefault);
            on2(document, "touchend touchcancel", this._cancelClickPrevent);
            this._simulateEvent("contextmenu", first2);
          }, this), tapHoldDelay);
          on2(document, "touchend touchcancel contextmenu", this._cancel, this);
          on2(document, "touchmove", this._onMove, this);
        },
        _cancelClickPrevent: function cancelClickPrevent() {
          off(document, "touchend", preventDefault);
          off(document, "touchend touchcancel", cancelClickPrevent);
        },
        _cancel: function() {
          clearTimeout(this._holdTimeout);
          off(document, "touchend touchcancel contextmenu", this._cancel, this);
          off(document, "touchmove", this._onMove, this);
        },
        _onMove: function(e3) {
          var first2 = e3.touches[0];
          this._newPos = new Point2(first2.clientX, first2.clientY);
        },
        _isTapValid: function() {
          return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
        },
        _simulateEvent: function(type, e3) {
          var simulatedEvent = new MouseEvent(type, {
            bubbles: true,
            cancelable: true,
            view: window,
            // detail: 1,
            screenX: e3.screenX,
            screenY: e3.screenY,
            clientX: e3.clientX,
            clientY: e3.clientY
            // button: 2,
            // buttons: 2
          });
          simulatedEvent._simulated = true;
          e3.target.dispatchEvent(simulatedEvent);
        }
      });
      Map2.addInitHook("addHandler", "tapHold", TapHold);
      Map2.mergeOptions({
        // @section Touch interaction options
        // @option touchZoom: Boolean|String = *
        // Whether the map can be zoomed by touch-dragging with two fingers. If
        // passed `'center'`, it will zoom to the center of the view regardless of
        // where the touch events (fingers) were. Enabled for touch-capable web
        // browsers.
        touchZoom: Browser.touch,
        // @option bounceAtZoomLimits: Boolean = true
        // Set it to false if you don't want the map to zoom beyond min/max zoom
        // and then bounce back when pinch-zooming.
        bounceAtZoomLimits: true
      });
      var TouchZoom = Handler.extend({
        addHooks: function() {
          addClass(this._map._container, "leaflet-touch-zoom");
          on2(this._map._container, "touchstart", this._onTouchStart, this);
        },
        removeHooks: function() {
          removeClass(this._map._container, "leaflet-touch-zoom");
          off(this._map._container, "touchstart", this._onTouchStart, this);
        },
        _onTouchStart: function(e3) {
          var map5 = this._map;
          if (!e3.touches || e3.touches.length !== 2 || map5._animatingZoom || this._zooming) {
            return;
          }
          var p1 = map5.mouseEventToContainerPoint(e3.touches[0]), p22 = map5.mouseEventToContainerPoint(e3.touches[1]);
          this._centerPoint = map5.getSize()._divideBy(2);
          this._startLatLng = map5.containerPointToLatLng(this._centerPoint);
          if (map5.options.touchZoom !== "center") {
            this._pinchStartLatLng = map5.containerPointToLatLng(p1.add(p22)._divideBy(2));
          }
          this._startDist = p1.distanceTo(p22);
          this._startZoom = map5.getZoom();
          this._moved = false;
          this._zooming = true;
          map5._stop();
          on2(document, "touchmove", this._onTouchMove, this);
          on2(document, "touchend touchcancel", this._onTouchEnd, this);
          preventDefault(e3);
        },
        _onTouchMove: function(e3) {
          if (!e3.touches || e3.touches.length !== 2 || !this._zooming) {
            return;
          }
          var map5 = this._map, p1 = map5.mouseEventToContainerPoint(e3.touches[0]), p22 = map5.mouseEventToContainerPoint(e3.touches[1]), scale2 = p1.distanceTo(p22) / this._startDist;
          this._zoom = map5.getScaleZoom(scale2, this._startZoom);
          if (!map5.options.bounceAtZoomLimits && (this._zoom < map5.getMinZoom() && scale2 < 1 || this._zoom > map5.getMaxZoom() && scale2 > 1)) {
            this._zoom = map5._limitZoom(this._zoom);
          }
          if (map5.options.touchZoom === "center") {
            this._center = this._startLatLng;
            if (scale2 === 1) {
              return;
            }
          } else {
            var delta = p1._add(p22)._divideBy(2)._subtract(this._centerPoint);
            if (scale2 === 1 && delta.x === 0 && delta.y === 0) {
              return;
            }
            this._center = map5.unproject(map5.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
          }
          if (!this._moved) {
            map5._moveStart(true, false);
            this._moved = true;
          }
          cancelAnimFrame(this._animRequest);
          var moveFn = bind2(map5._move, map5, this._center, this._zoom, { pinch: true, round: false }, void 0);
          this._animRequest = requestAnimFrame(moveFn, this, true);
          preventDefault(e3);
        },
        _onTouchEnd: function() {
          if (!this._moved || !this._zooming) {
            this._zooming = false;
            return;
          }
          this._zooming = false;
          cancelAnimFrame(this._animRequest);
          off(document, "touchmove", this._onTouchMove, this);
          off(document, "touchend touchcancel", this._onTouchEnd, this);
          if (this._map.options.zoomAnimation) {
            this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
          } else {
            this._map._resetView(this._center, this._map._limitZoom(this._zoom));
          }
        }
      });
      Map2.addInitHook("addHandler", "touchZoom", TouchZoom);
      Map2.BoxZoom = BoxZoom;
      Map2.DoubleClickZoom = DoubleClickZoom;
      Map2.Drag = Drag;
      Map2.Keyboard = Keyboard;
      Map2.ScrollWheelZoom = ScrollWheelZoom;
      Map2.TapHold = TapHold;
      Map2.TouchZoom = TouchZoom;
      exports2.Bounds = Bounds2;
      exports2.Browser = Browser;
      exports2.CRS = CRS;
      exports2.Canvas = Canvas2;
      exports2.Circle = Circle;
      exports2.CircleMarker = CircleMarker;
      exports2.Class = Class;
      exports2.Control = Control;
      exports2.DivIcon = DivIcon;
      exports2.DivOverlay = DivOverlay;
      exports2.DomEvent = DomEvent;
      exports2.DomUtil = DomUtil;
      exports2.Draggable = Draggable;
      exports2.Evented = Evented;
      exports2.FeatureGroup = FeatureGroup;
      exports2.GeoJSON = GeoJSON;
      exports2.GridLayer = GridLayer;
      exports2.Handler = Handler;
      exports2.Icon = Icon2;
      exports2.ImageOverlay = ImageOverlay;
      exports2.LatLng = LatLng;
      exports2.LatLngBounds = LatLngBounds;
      exports2.Layer = Layer2;
      exports2.LayerGroup = LayerGroup;
      exports2.LineUtil = LineUtil;
      exports2.Map = Map2;
      exports2.Marker = Marker2;
      exports2.Mixin = Mixin;
      exports2.Path = Path;
      exports2.Point = Point2;
      exports2.PolyUtil = PolyUtil;
      exports2.Polygon = Polygon;
      exports2.Polyline = Polyline;
      exports2.Popup = Popup;
      exports2.PosAnimation = PosAnimation;
      exports2.Projection = index2;
      exports2.Rectangle = Rectangle;
      exports2.Renderer = Renderer3;
      exports2.SVG = SVG3;
      exports2.SVGOverlay = SVGOverlay;
      exports2.TileLayer = TileLayer;
      exports2.Tooltip = Tooltip3;
      exports2.Transformation = Transformation;
      exports2.Util = Util;
      exports2.VideoOverlay = VideoOverlay;
      exports2.bind = bind2;
      exports2.bounds = toBounds;
      exports2.canvas = canvas;
      exports2.circle = circle;
      exports2.circleMarker = circleMarker;
      exports2.control = control;
      exports2.divIcon = divIcon;
      exports2.extend = extend;
      exports2.featureGroup = featureGroup;
      exports2.geoJSON = geoJSON;
      exports2.geoJson = geoJson;
      exports2.gridLayer = gridLayer;
      exports2.icon = icon;
      exports2.imageOverlay = imageOverlay;
      exports2.latLng = toLatLng;
      exports2.latLngBounds = toLatLngBounds;
      exports2.layerGroup = layerGroup;
      exports2.map = createMap;
      exports2.marker = marker;
      exports2.point = toPoint;
      exports2.polygon = polygon;
      exports2.polyline = polyline;
      exports2.popup = popup;
      exports2.rectangle = rectangle;
      exports2.setOptions = setOptions2;
      exports2.stamp = stamp;
      exports2.svg = svg4;
      exports2.svgOverlay = svgOverlay;
      exports2.tileLayer = tileLayer;
      exports2.tooltip = tooltip;
      exports2.transformation = toTransformation;
      exports2.version = version;
      exports2.videoOverlay = videoOverlay;
      var oldL = window.L;
      exports2.noConflict = function() {
        window.L = oldL;
        return this;
      };
      window.L = exports2;
    });
  }
});

// node_modules/air-datepicker/air-datepicker.js
var require_air_datepicker = __commonJS({
  "node_modules/air-datepicker/air-datepicker.js"(exports, module) {
    !function(e3, t3) {
      "object" == typeof exports && "object" == typeof module ? module.exports = t3() : "function" == typeof define && define.amd ? define([], t3) : "object" == typeof exports ? exports.AirDatepicker = t3() : e3.AirDatepicker = t3();
    }(exports, function() {
      return function() {
        "use strict";
        var e3 = { d: function(t4, i4) {
          for (var s4 in i4) e3.o(i4, s4) && !e3.o(t4, s4) && Object.defineProperty(t4, s4, { enumerable: true, get: i4[s4] });
        }, o: function(e4, t4) {
          return Object.prototype.hasOwnProperty.call(e4, t4);
        } }, t3 = {};
        e3.d(t3, { default: function() {
          return R2;
        } });
        var i3 = { days: "days", months: "months", years: "years", day: "day", month: "month", year: "year", eventChangeViewDate: "changeViewDate", eventChangeCurrentView: "changeCurrentView", eventChangeFocusDate: "changeFocusDate", eventChangeSelectedDate: "changeSelectedDate", eventChangeTime: "changeTime", eventChangeLastSelectedDate: "changeLastSelectedDate", actionSelectDate: "selectDate", actionUnselectDate: "unselectDate", cssClassWeekend: "-weekend-" }, s3 = { classes: "", inline: false, locale: { days: ["\u0412\u043E\u0441\u043A\u0440\u0435\u0441\u0435\u043D\u044C\u0435", "\u041F\u043E\u043D\u0435\u0434\u0435\u043B\u044C\u043D\u0438\u043A", "\u0412\u0442\u043E\u0440\u043D\u0438\u043A", "\u0421\u0440\u0435\u0434\u0430", "\u0427\u0435\u0442\u0432\u0435\u0440\u0433", "\u041F\u044F\u0442\u043D\u0438\u0446\u0430", "\u0421\u0443\u0431\u0431\u043E\u0442\u0430"], daysShort: ["\u0412\u043E\u0441", "\u041F\u043E\u043D", "\u0412\u0442\u043E", "\u0421\u0440\u0435", "\u0427\u0435\u0442", "\u041F\u044F\u0442", "\u0421\u0443\u0431"], daysMin: ["\u0412\u0441", "\u041F\u043D", "\u0412\u0442", "\u0421\u0440", "\u0427\u0442", "\u041F\u0442", "\u0421\u0431"], months: ["\u042F\u043D\u0432\u0430\u0440\u044C", "\u0424\u0435\u0432\u0440\u0430\u043B\u044C", "\u041C\u0430\u0440\u0442", "\u0410\u043F\u0440\u0435\u043B\u044C", "\u041C\u0430\u0439", "\u0418\u044E\u043D\u044C", "\u0418\u044E\u043B\u044C", "\u0410\u0432\u0433\u0443\u0441\u0442", "\u0421\u0435\u043D\u0442\u044F\u0431\u0440\u044C", "\u041E\u043A\u0442\u044F\u0431\u0440\u044C", "\u041D\u043E\u044F\u0431\u0440\u044C", "\u0414\u0435\u043A\u0430\u0431\u0440\u044C"], monthsShort: ["\u042F\u043D\u0432", "\u0424\u0435\u0432", "\u041C\u0430\u0440", "\u0410\u043F\u0440", "\u041C\u0430\u0439", "\u0418\u044E\u043D", "\u0418\u044E\u043B", "\u0410\u0432\u0433", "\u0421\u0435\u043D", "\u041E\u043A\u0442", "\u041D\u043E\u044F", "\u0414\u0435\u043A"], today: "\u0421\u0435\u0433\u043E\u0434\u043D\u044F", clear: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C", dateFormat: "dd.MM.yyyy", timeFormat: "HH:mm", firstDay: 1 }, startDate: /* @__PURE__ */ new Date(), firstDay: "", weekends: [6, 0], dateFormat: "", altField: "", altFieldDateFormat: "T", toggleSelected: true, keyboardNav: true, selectedDates: false, container: "", isMobile: false, visible: false, position: "bottom left", offset: 12, view: i3.days, minView: i3.days, showOtherMonths: true, selectOtherMonths: true, moveToOtherMonthsOnSelect: true, showOtherYears: true, selectOtherYears: true, moveToOtherYearsOnSelect: true, minDate: "", maxDate: "", disableNavWhenOutOfRange: true, multipleDates: false, multipleDatesSeparator: ", ", range: false, dynamicRange: true, buttons: false, monthsField: "monthsShort", showEvent: "focus", autoClose: false, fixedHeight: false, prevHtml: '<svg><path d="M 17,12 l -5,5 l 5,5"></path></svg>', nextHtml: '<svg><path d="M 14,12 l 5,5 l -5,5"></path></svg>', navTitles: { days: "MMMM, <i>yyyy</i>", months: "yyyy", years: "yyyy1 - yyyy2" }, timepicker: false, onlyTimepicker: false, dateTimeSeparator: " ", timeFormat: "", minHours: 0, maxHours: 24, minMinutes: 0, maxMinutes: 59, hoursStep: 1, minutesStep: 1, onSelect: false, onChangeViewDate: false, onChangeView: false, onRenderCell: false, onShow: false, onHide: false, onClickDayName: false };
        function a3(e4) {
          let t4 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : document;
          return "string" == typeof e4 ? t4.querySelector(e4) : e4;
        }
        function n4() {
          let { tagName: e4 = "div", className: t4 = "", innerHtml: i4 = "", id: s4 = "", attrs: a4 = {} } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n5 = document.createElement(e4);
          return t4 && n5.classList.add(...t4.split(" ")), s4 && (n5.id = s4), i4 && (n5.innerHTML = i4), a4 && r3(n5, a4), n5;
        }
        function r3(e4, t4) {
          for (let [i4, s4] of Object.entries(t4)) void 0 !== s4 && e4.setAttribute(i4, s4);
          return e4;
        }
        function o3(e4) {
          return new Date(e4.getFullYear(), e4.getMonth() + 1, 0).getDate();
        }
        function h3(e4) {
          let t4 = e4.getHours(), { hours: i4, dayPeriod: s4 } = l3(t4);
          return { year: e4.getFullYear(), month: e4.getMonth(), fullMonth: e4.getMonth() + 1 < 10 ? "0" + (e4.getMonth() + 1) : e4.getMonth() + 1, date: e4.getDate(), fullDate: e4.getDate() < 10 ? "0" + e4.getDate() : e4.getDate(), day: e4.getDay(), hours: t4, fullHours: d3(t4), hours12: i4, dayPeriod: s4, fullHours12: d3(i4), minutes: e4.getMinutes(), fullMinutes: e4.getMinutes() < 10 ? "0" + e4.getMinutes() : e4.getMinutes() };
        }
        function l3(e4) {
          return { dayPeriod: e4 > 11 ? "pm" : "am", hours: e4 % 12 == 0 ? 12 : e4 % 12 };
        }
        function d3(e4) {
          return e4 < 10 ? "0" + e4 : e4;
        }
        function c3(e4) {
          let t4 = 10 * Math.floor(e4.getFullYear() / 10);
          return [t4, t4 + 9];
        }
        function u3() {
          let e4 = [];
          for (var t4 = arguments.length, i4 = new Array(t4), s4 = 0; s4 < t4; s4++) i4[s4] = arguments[s4];
          return i4.forEach((t5) => {
            if ("object" == typeof t5) for (let i5 in t5) t5[i5] && e4.push(i5);
            else t5 && e4.push(t5);
          }), e4.join(" ");
        }
        function p4(e4, t4) {
          let s4 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : i3.days;
          if (!e4 || !t4) return false;
          let a4 = h3(e4), n5 = h3(t4);
          return { [i3.days]: a4.date === n5.date && a4.month === n5.month && a4.year === n5.year, [i3.months]: a4.month === n5.month && a4.year === n5.year, [i3.years]: a4.year === n5.year }[s4];
        }
        function m3(e4, t4, i4) {
          let s4 = g3(e4, false).getTime(), a4 = g3(t4, false).getTime();
          return i4 ? s4 >= a4 : s4 > a4;
        }
        function v3(e4, t4) {
          return !m3(e4, t4, true);
        }
        function g3(e4) {
          let t4 = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1], i4 = new Date(e4.getTime());
          return "boolean" != typeof t4 || t4 || function(e5) {
            e5.setHours(0, 0, 0, 0);
          }(i4), i4;
        }
        function D3(e4, t4, i4) {
          e4.length ? e4.forEach((e5) => {
            e5.addEventListener(t4, i4);
          }) : e4.addEventListener(t4, i4);
        }
        function y3(e4, t4) {
          return !(!e4 || e4 === document || e4 instanceof DocumentFragment) && (e4.matches(t4) ? e4 : y3(e4.parentNode, t4));
        }
        function f3(e4, t4, i4) {
          return e4 > i4 ? i4 : e4 < t4 ? t4 : e4;
        }
        function w3(e4) {
          for (var t4 = arguments.length, i4 = new Array(t4 > 1 ? t4 - 1 : 0), s4 = 1; s4 < t4; s4++) i4[s4 - 1] = arguments[s4];
          return i4.filter((e5) => e5).forEach((t5) => {
            for (let [i5, s5] of Object.entries(t5)) if (void 0 !== s5 && "[object Object]" === s5.toString()) {
              let t6 = void 0 !== e4[i5] ? e4[i5].toString() : void 0, a4 = s5.toString(), n5 = Array.isArray(s5) ? [] : {};
              e4[i5] = e4[i5] ? t6 !== a4 ? n5 : e4[i5] : n5, w3(e4[i5], s5);
            } else e4[i5] = s5;
          }), e4;
        }
        function b3(e4) {
          let t4 = e4;
          return e4 instanceof Date || ("string" == typeof e4 && /^\d{4}-\d{2}-\d{2}$/.test(e4) && (e4 += "T00:00:00"), t4 = new Date(e4)), isNaN(t4.getTime()) && (console.log(`Unable to convert value "${e4}" to Date object`), t4 = false), t4;
        }
        function k2(e4) {
          let t4 = "\\s|\\.|-|/|\\\\|,|\\$|\\!|\\?|:|;";
          return new RegExp("(^|>|" + t4 + ")(" + e4 + ")($|<|" + t4 + ")", "g");
        }
        function $6(e4, t4, i4) {
          return (t4 = function(e5) {
            var t5 = function(e6, t6) {
              if ("object" != typeof e6 || null === e6) return e6;
              var i5 = e6[Symbol.toPrimitive];
              if (void 0 !== i5) {
                var s4 = i5.call(e6, "string");
                if ("object" != typeof s4) return s4;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(e6);
            }(e5);
            return "symbol" == typeof t5 ? t5 : String(t5);
          }(t4)) in e4 ? Object.defineProperty(e4, t4, { value: i4, enumerable: true, configurable: true, writable: true }) : e4[t4] = i4, e4;
        }
        class C3 {
          constructor() {
            let { type: e4, date: t4, dp: i4, opts: s4, body: a4 } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
            $6(this, "focus", () => {
              this.$cell.classList.add("-focus-"), this.focused = true;
            }), $6(this, "removeFocus", () => {
              this.$cell.classList.remove("-focus-"), this.focused = false;
            }), $6(this, "select", () => {
              this.$cell.classList.add("-selected-"), this.selected = true;
            }), $6(this, "removeSelect", () => {
              this.$cell.classList.remove("-selected-", "-range-from-", "-range-to-"), this.selected = false;
            }), $6(this, "onChangeSelectedDate", () => {
              this.isDisabled || (this._handleSelectedStatus(), this.opts.range && this._handleRangeStatus());
            }), $6(this, "onChangeFocusDate", (e5) => {
              if (!e5) return void (this.focused && this.removeFocus());
              let t5 = p4(e5, this.date, this.type);
              t5 ? this.focus() : !t5 && this.focused && this.removeFocus(), this.opts.range && this._handleRangeStatus();
            }), $6(this, "render", () => (this.$cell.innerHTML = this._getHtml(), this._handleClasses(), this.$cell)), this.type = e4, this.singleType = this.type.slice(0, -1), this.date = t4, this.dp = i4, this.opts = s4, this.body = a4, this.customData = false, this.init();
          }
          init() {
            var e4;
            let { onRenderCell: t4 } = this.opts;
            t4 && (this.customData = t4({ date: this.date, cellType: this.singleType, datepicker: this.dp })), this._createElement(), this._bindDatepickerEvents(), null !== (e4 = this.customData) && void 0 !== e4 && e4.disabled && this.dp.disableDate(this.date);
          }
          _bindDatepickerEvents() {
            this.dp.on(i3.eventChangeSelectedDate, this.onChangeSelectedDate), this.dp.on(i3.eventChangeFocusDate, this.onChangeFocusDate);
          }
          unbindDatepickerEvents() {
            this.dp.off(i3.eventChangeSelectedDate, this.onChangeSelectedDate), this.dp.off(i3.eventChangeFocusDate, this.onChangeFocusDate);
          }
          _createElement() {
            var e4;
            let { year: t4, month: i4, date: s4 } = h3(this.date), a4 = (null === (e4 = this.customData) || void 0 === e4 ? void 0 : e4.attrs) || {};
            this.$cell = n4({ attrs: { "data-year": t4, "data-month": i4, "data-date": s4, ...a4 } }), this.$cell.adpCell = this;
          }
          _getClassName() {
            var e4;
            let t4 = /* @__PURE__ */ new Date(), { selectOtherMonths: s4, selectOtherYears: a4 } = this.opts, { minDate: n5, maxDate: r4, isDateDisabled: o4 } = this.dp, { day: l4 } = h3(this.date), d4 = this._isOutOfMinMaxRange(), c4 = o4(this.date), m4 = u3("air-datepicker-cell", `-${this.singleType}-`, { "-current-": p4(t4, this.date, this.type), "-min-date-": n5 && p4(n5, this.date, this.type), "-max-date-": r4 && p4(r4, this.date, this.type) }), v4 = "";
            switch (this.type) {
              case i3.days:
                v4 = u3({ "-weekend-": this.dp.isWeekend(l4), "-other-month-": this.isOtherMonth, "-disabled-": this.isOtherMonth && !s4 || d4 || c4 });
                break;
              case i3.months:
                v4 = u3({ "-disabled-": d4 });
                break;
              case i3.years:
                v4 = u3({ "-other-decade-": this.isOtherDecade, "-disabled-": d4 || this.isOtherDecade && !a4 });
            }
            return u3(m4, v4, null === (e4 = this.customData) || void 0 === e4 ? void 0 : e4.classes).split(" ");
          }
          _getHtml() {
            var e4;
            let { year: t4, month: s4, date: a4 } = h3(this.date), { showOtherMonths: n5, showOtherYears: r4 } = this.opts;
            if (null !== (e4 = this.customData) && void 0 !== e4 && e4.html) return this.customData.html;
            switch (this.type) {
              case i3.days:
                return !n5 && this.isOtherMonth ? "" : a4;
              case i3.months:
                return this.dp.locale[this.opts.monthsField][s4];
              case i3.years:
                return !r4 && this.isOtherDecade ? "" : t4;
            }
          }
          _isOutOfMinMaxRange() {
            let { minDate: e4, maxDate: t4 } = this.dp, { type: s4, date: a4 } = this, { month: n5, year: r4, date: o4 } = h3(a4), l4 = s4 === i3.days, d4 = s4 === i3.years, c4 = !!e4 && new Date(r4, d4 ? e4.getMonth() : n5, l4 ? o4 : e4.getDate()), u4 = !!t4 && new Date(r4, d4 ? t4.getMonth() : n5, l4 ? o4 : t4.getDate());
            return e4 && t4 ? v3(c4, e4) || m3(u4, t4) : e4 ? v3(c4, e4) : t4 ? m3(u4, t4) : void 0;
          }
          destroy() {
            this.unbindDatepickerEvents();
          }
          _handleRangeStatus() {
            const { selectedDates: e4, focusDate: t4, rangeDateTo: i4, rangeDateFrom: s4 } = this.dp, a4 = e4.length;
            if (!a4) return;
            let n5 = s4, r4 = i4;
            if (1 === a4 && t4) {
              const i5 = m3(t4, e4[0]);
              n5 = i5 ? e4[0] : t4, r4 = i5 ? t4 : e4[0];
            }
            let o4 = u3({ "-in-range-": n5 && r4 && (h4 = this.date, l4 = n5, d4 = r4, m3(h4, l4) && v3(h4, d4)), "-range-from-": n5 && p4(this.date, n5, this.type), "-range-to-": r4 && p4(this.date, r4, this.type) });
            var h4, l4, d4;
            this.$cell.classList.remove("-range-from-", "-range-to-", "-in-range-"), o4 && this.$cell.classList.add(...o4.split(" "));
          }
          _handleSelectedStatus() {
            let e4 = this.dp._checkIfDateIsSelected(this.date, this.type);
            e4 ? this.select() : !e4 && this.selected && this.removeSelect();
          }
          _handleInitialFocusStatus() {
            p4(this.dp.focusDate, this.date, this.type) && this.focus();
          }
          _handleClasses() {
            this.$cell.setAttribute("class", ""), this._handleInitialFocusStatus(), this.dp.hasSelectedDates && (this._handleSelectedStatus(), this.dp.opts.range && this._handleRangeStatus()), this.$cell.classList.add(...this._getClassName());
          }
          get isDisabled() {
            return this.$cell.matches(".-disabled-");
          }
          get isOtherMonth() {
            return this.dp.isOtherMonth(this.date);
          }
          get isOtherDecade() {
            return this.dp.isOtherDecade(this.date);
          }
        }
        function _5(e4, t4, i4) {
          return (t4 = function(e5) {
            var t5 = function(e6, t6) {
              if ("object" != typeof e6 || null === e6) return e6;
              var i5 = e6[Symbol.toPrimitive];
              if (void 0 !== i5) {
                var s4 = i5.call(e6, "string");
                if ("object" != typeof s4) return s4;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(e6);
            }(e5);
            return "symbol" == typeof t5 ? t5 : String(t5);
          }(t4)) in e4 ? Object.defineProperty(e4, t4, { value: i4, enumerable: true, configurable: true, writable: true }) : e4[t4] = i4, e4;
        }
        let M = { [i3.days]: `<div class="air-datepicker-body--day-names"></div><div class="air-datepicker-body--cells -${i3.days}-"></div>`, [i3.months]: `<div class="air-datepicker-body--cells -${i3.months}-"></div>`, [i3.years]: `<div class="air-datepicker-body--cells -${i3.years}-"></div>` };
        const S2 = ".air-datepicker-cell";
        class T3 {
          constructor(e4) {
            let { dp: t4, type: s4, opts: a4 } = e4;
            _5(this, "handleClick", (e5) => {
              let t5 = e5.target.closest(S2).adpCell;
              if (t5.isDisabled) return;
              if (!this.dp.isMinViewReached) return void this.dp.down();
              let i4 = this.dp._checkIfDateIsSelected(t5.date, t5.type);
              i4 ? this.dp._handleAlreadySelectedDates(i4, t5.date) : this.dp.selectDate(t5.date);
            }), _5(this, "handleDayNameClick", (e5) => {
              let t5 = e5.target.getAttribute("data-day-index");
              this.opts.onClickDayName({ dayIndex: Number(t5), datepicker: this.dp });
            }), _5(this, "onChangeCurrentView", (e5) => {
              e5 !== this.type ? this.hide() : (this.show(), this.render());
            }), _5(this, "onMouseOverCell", (e5) => {
              let t5 = y3(e5.target, S2);
              this.dp.setFocusDate(!!t5 && t5.adpCell.date);
            }), _5(this, "onMouseOutCell", () => {
              this.dp.setFocusDate(false);
            }), _5(this, "onClickBody", (e5) => {
              let { onClickDayName: t5 } = this.opts, i4 = e5.target;
              i4.closest(S2) && this.handleClick(e5), t5 && i4.closest(".air-datepicker-body--day-name") && this.handleDayNameClick(e5);
            }), _5(this, "onMouseDown", (e5) => {
              this.pressed = true;
              let t5 = y3(e5.target, S2), i4 = t5 && t5.adpCell;
              p4(i4.date, this.dp.rangeDateFrom) && (this.rangeFromFocused = true), p4(i4.date, this.dp.rangeDateTo) && (this.rangeToFocused = true);
            }), _5(this, "onMouseMove", (e5) => {
              if (!this.pressed || !this.dp.isMinViewReached) return;
              e5.preventDefault();
              let t5 = y3(e5.target, S2), i4 = t5 && t5.adpCell, { selectedDates: s5, rangeDateTo: a5, rangeDateFrom: n5 } = this.dp;
              if (!i4 || i4.isDisabled) return;
              let { date: r4 } = i4;
              if (2 === s5.length) {
                if (this.rangeFromFocused && !m3(r4, a5)) {
                  let { hours: e6, minutes: t6 } = h3(n5);
                  r4.setHours(e6), r4.setMinutes(t6), this.dp.rangeDateFrom = r4, this.dp.replaceDate(n5, r4);
                }
                if (this.rangeToFocused && !v3(r4, n5)) {
                  let { hours: e6, minutes: t6 } = h3(a5);
                  r4.setHours(e6), r4.setMinutes(t6), this.dp.rangeDateTo = r4, this.dp.replaceDate(a5, r4);
                }
              }
            }), _5(this, "onMouseUp", () => {
              this.pressed = false, this.rangeFromFocused = false, this.rangeToFocused = false;
            }), _5(this, "onChangeViewDate", (e5, t5) => {
              if (!this.isVisible) return;
              let s5 = c3(e5), a5 = c3(t5);
              switch (this.dp.currentView) {
                case i3.days:
                  if (p4(e5, t5, i3.months)) return;
                  break;
                case i3.months:
                  if (p4(e5, t5, i3.years)) return;
                  break;
                case i3.years:
                  if (s5[0] === a5[0] && s5[1] === a5[1]) return;
              }
              this.render();
            }), _5(this, "render", () => {
              this.destroyCells(), this._generateCells(), this.cells.forEach((e5) => {
                this.$cells.appendChild(e5.render());
              });
            }), this.dp = t4, this.type = s4, this.opts = a4, this.cells = [], this.$el = "", this.pressed = false, this.isVisible = true, this.init();
          }
          init() {
            this._buildBaseHtml(), this.type === i3.days && this.renderDayNames(), this.render(), this._bindEvents(), this._bindDatepickerEvents();
          }
          _bindEvents() {
            let { range: e4, dynamicRange: t4 } = this.opts;
            D3(this.$el, "mouseover", this.onMouseOverCell), D3(this.$el, "mouseout", this.onMouseOutCell), D3(this.$el, "click", this.onClickBody), e4 && t4 && (D3(this.$el, "mousedown", this.onMouseDown), D3(this.$el, "mousemove", this.onMouseMove), D3(window.document, "mouseup", this.onMouseUp));
          }
          _bindDatepickerEvents() {
            this.dp.on(i3.eventChangeViewDate, this.onChangeViewDate), this.dp.on(i3.eventChangeCurrentView, this.onChangeCurrentView);
          }
          _buildBaseHtml() {
            this.$el = n4({ className: `air-datepicker-body -${this.type}-`, innerHtml: M[this.type] }), this.$names = a3(".air-datepicker-body--day-names", this.$el), this.$cells = a3(".air-datepicker-body--cells", this.$el);
          }
          _getDayNamesHtml() {
            let e4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.dp.locale.firstDay, t4 = "", s4 = this.dp.isWeekend, { onClickDayName: a4 } = this.opts, n5 = e4, r4 = 0;
            for (; r4 < 7; ) {
              let e5 = n5 % 7;
              t4 += `<div class="${u3("air-datepicker-body--day-name", { [i3.cssClassWeekend]: s4(e5), "-clickable-": !!a4 })}" data-day-index='${e5}'>${this.dp.locale.daysMin[e5]}</div>`, r4++, n5++;
            }
            return t4;
          }
          renderDayNames() {
            this.$names.innerHTML = this._getDayNamesHtml();
          }
          _generateCell(e4) {
            let { type: t4, dp: i4, opts: s4 } = this;
            return new C3({ type: t4, dp: i4, opts: s4, date: e4, body: this });
          }
          _generateCells() {
            T3.getDatesFunction(this.type)(this.dp, (e4) => {
              this.cells.push(this._generateCell(e4));
            });
          }
          show() {
            this.isVisible = true, this.$el.classList.remove("-hidden-");
          }
          hide() {
            this.isVisible = false, this.$el.classList.add("-hidden-");
          }
          destroyCells() {
            this.cells.forEach((e4) => e4.destroy()), this.cells = [], this.$cells.innerHTML = "";
          }
          destroy() {
            this.destroyCells(), this.dp.off(i3.eventChangeViewDate, this.onChangeViewDate), this.dp.off(i3.eventChangeCurrentView, this.onChangeCurrentView);
          }
          static getDaysDates(e4, t4) {
            let { viewDate: i4, opts: { fixedHeight: s4 }, locale: { firstDay: a4 } } = e4, n5 = o3(i4), { year: r4, month: l4 } = h3(i4), d4 = new Date(r4, l4, 1), c4 = new Date(r4, l4, n5), u4 = d4.getDay() - a4, p5 = 6 - c4.getDay() + a4;
            u4 = u4 < 0 ? u4 + 7 : u4, p5 = p5 > 6 ? p5 - 7 : p5;
            let m4 = function(e5, t5) {
              let { year: i5, month: s5, date: a5 } = h3(e5);
              return new Date(i5, s5, a5 - t5);
            }(d4, u4), v4 = n5 + u4 + p5, g4 = m4.getDate(), { year: D4, month: y4 } = h3(m4), f4 = 0;
            s4 && (v4 = 42);
            const w4 = [];
            for (; f4 < v4; ) {
              let e5 = new Date(D4, y4, g4 + f4);
              t4 && t4(e5), w4.push(e5), f4++;
            }
            return w4;
          }
          static getMonthsDates(e4, t4) {
            let { year: i4 } = e4.parsedViewDate, s4 = 0, a4 = [];
            for (; s4 < 12; ) {
              const e5 = new Date(i4, s4);
              a4.push(e5), t4 && t4(e5), s4++;
            }
            return a4;
          }
          static getYearsDates(e4, t4) {
            let i4 = c3(e4.viewDate), s4 = i4[0] - 1, a4 = i4[1] + 1, n5 = s4, r4 = [];
            for (; n5 <= a4; ) {
              const e5 = new Date(n5, 0);
              r4.push(e5), t4 && t4(e5), n5++;
            }
            return r4;
          }
          static getDatesFunction() {
            let e4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : i3.days;
            return { [i3.days]: T3.getDaysDates, [i3.months]: T3.getMonthsDates, [i3.years]: T3.getYearsDates }[e4];
          }
        }
        function F2(e4, t4, i4) {
          return (t4 = function(e5) {
            var t5 = function(e6, t6) {
              if ("object" != typeof e6 || null === e6) return e6;
              var i5 = e6[Symbol.toPrimitive];
              if (void 0 !== i5) {
                var s4 = i5.call(e6, "string");
                if ("object" != typeof s4) return s4;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(e6);
            }(e5);
            return "symbol" == typeof t5 ? t5 : String(t5);
          }(t4)) in e4 ? Object.defineProperty(e4, t4, { value: i4, enumerable: true, configurable: true, writable: true }) : e4[t4] = i4, e4;
        }
        class V2 {
          constructor(e4) {
            let { dp: t4, opts: i4 } = e4;
            F2(this, "onClickNav", (e5) => {
              let t5 = y3(e5.target, ".air-datepicker-nav--action");
              if (!t5) return;
              let i5 = t5.dataset.action;
              this.dp[i5]();
            }), F2(this, "onChangeViewDate", () => {
              this.render(), this._resetNavStatus(), this.handleNavStatus();
            }), F2(this, "onChangeCurrentView", () => {
              this.render(), this._resetNavStatus(), this.handleNavStatus();
            }), F2(this, "onClickNavTitle", () => {
              this.dp.isFinalView || this.dp.up();
            }), F2(this, "update", () => {
              let { prevHtml: e5, nextHtml: t5 } = this.opts;
              this.$prev.innerHTML = e5, this.$next.innerHTML = t5, this._resetNavStatus(), this.render(), this.handleNavStatus();
            }), F2(this, "renderDelay", () => {
              setTimeout(this.render);
            }), F2(this, "render", () => {
              this.$title.innerHTML = this._getTitle(), function(e5, t5) {
                for (let i5 in t5) t5[i5] ? e5.classList.add(i5) : e5.classList.remove(i5);
              }(this.$title, { "-disabled-": this.dp.isFinalView });
            }), this.dp = t4, this.opts = i4, this.init();
          }
          init() {
            this._createElement(), this._buildBaseHtml(), this._defineDOM(), this.render(), this.handleNavStatus(), this._bindEvents(), this._bindDatepickerEvents();
          }
          _defineDOM() {
            this.$title = a3(".air-datepicker-nav--title", this.$el), this.$prev = a3('[data-action="prev"]', this.$el), this.$next = a3('[data-action="next"]', this.$el);
          }
          _bindEvents() {
            this.$el.addEventListener("click", this.onClickNav), this.$title.addEventListener("click", this.onClickNavTitle);
          }
          _bindDatepickerEvents() {
            this.dp.on(i3.eventChangeViewDate, this.onChangeViewDate), this.dp.on(i3.eventChangeCurrentView, this.onChangeCurrentView), this.isNavIsFunction && (this.dp.on(i3.eventChangeSelectedDate, this.renderDelay), this.dp.opts.timepicker && this.dp.on(i3.eventChangeTime, this.render));
          }
          destroy() {
            this.dp.off(i3.eventChangeViewDate, this.onChangeViewDate), this.dp.off(i3.eventChangeCurrentView, this.onChangeCurrentView), this.isNavIsFunction && (this.dp.off(i3.eventChangeSelectedDate, this.renderDelay), this.dp.opts.timepicker && this.dp.off(i3.eventChangeTime, this.render));
          }
          _createElement() {
            this.$el = n4({ tagName: "nav", className: "air-datepicker-nav" });
          }
          _getTitle() {
            let { dp: e4, opts: t4 } = this, i4 = t4.navTitles[e4.currentView];
            return "function" == typeof i4 ? i4(e4) : e4.formatDate(e4.viewDate, i4);
          }
          handleNavStatus() {
            let { disableNavWhenOutOfRange: e4 } = this.opts, { minDate: t4, maxDate: s4 } = this.dp;
            if (!t4 && !s4 || !e4) return;
            let { year: a4, month: n5 } = this.dp.parsedViewDate, r4 = !!t4 && h3(t4), o4 = !!s4 && h3(s4);
            switch (this.dp.currentView) {
              case i3.days:
                t4 && r4.month >= n5 && r4.year >= a4 && this._disableNav("prev"), s4 && o4.month <= n5 && o4.year <= a4 && this._disableNav("next");
                break;
              case i3.months:
                t4 && r4.year >= a4 && this._disableNav("prev"), s4 && o4.year <= a4 && this._disableNav("next");
                break;
              case i3.years: {
                let e5 = c3(this.dp.viewDate);
                t4 && r4.year >= e5[0] && this._disableNav("prev"), s4 && o4.year <= e5[1] && this._disableNav("next");
                break;
              }
            }
          }
          _disableNav(e4) {
            a3('[data-action="' + e4 + '"]', this.$el).classList.add("-disabled-");
          }
          _resetNavStatus() {
            !function(e4) {
              for (var t4 = arguments.length, i4 = new Array(t4 > 1 ? t4 - 1 : 0), s4 = 1; s4 < t4; s4++) i4[s4 - 1] = arguments[s4];
              e4.length ? e4.forEach((e5) => {
                e5.classList.remove(...i4);
              }) : e4.classList.remove(...i4);
            }(this.$el.querySelectorAll(".air-datepicker-nav--action"), "-disabled-");
          }
          _buildBaseHtml() {
            let { prevHtml: e4, nextHtml: t4 } = this.opts;
            this.$el.innerHTML = `<div class="air-datepicker-nav--action" data-action="prev">${e4}</div><div class="air-datepicker-nav--title"></div><div class="air-datepicker-nav--action" data-action="next">${t4}</div>`;
          }
          get isNavIsFunction() {
            let { navTitles: e4 } = this.opts;
            return Object.keys(e4).find((t4) => "function" == typeof e4[t4]);
          }
        }
        var x3 = { today: { content: (e4) => e4.locale.today, onClick: (e4) => e4.setViewDate(/* @__PURE__ */ new Date()) }, clear: { content: (e4) => e4.locale.clear, onClick: (e4) => e4.clear() } };
        class H2 {
          constructor(e4) {
            let { dp: t4, opts: i4 } = e4;
            this.dp = t4, this.opts = i4, this.init();
          }
          init() {
            this.createElement(), this.render();
          }
          createElement() {
            this.$el = n4({ className: "air-datepicker-buttons" });
          }
          destroy() {
            this.$el.parentNode.removeChild(this.$el);
          }
          clearHtml() {
            return this.$el.innerHTML = "", this;
          }
          generateButtons() {
            let { buttons: e4 } = this.opts;
            Array.isArray(e4) || (e4 = [e4]), e4.forEach((e5) => {
              let t4 = e5;
              "string" == typeof e5 && x3[e5] && (t4 = x3[e5]);
              let i4 = this.createButton(t4);
              t4.onClick && this.attachEventToButton(i4, t4.onClick), this.$el.appendChild(i4);
            });
          }
          attachEventToButton(e4, t4) {
            e4.addEventListener("click", () => {
              t4(this.dp);
            });
          }
          createButton(e4) {
            let { content: t4, className: i4, tagName: s4 = "button", attrs: a4 = {} } = e4;
            return n4({ tagName: s4, innerHtml: `<span tabindex='-1'>${"function" == typeof t4 ? t4(this.dp) : t4}</span>`, className: u3("air-datepicker-button", i4), attrs: a4 });
          }
          render() {
            this.generateButtons();
          }
        }
        function E3(e4, t4, i4) {
          return (t4 = function(e5) {
            var t5 = function(e6, t6) {
              if ("object" != typeof e6 || null === e6) return e6;
              var i5 = e6[Symbol.toPrimitive];
              if (void 0 !== i5) {
                var s4 = i5.call(e6, "string");
                if ("object" != typeof s4) return s4;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(e6);
            }(e5);
            return "symbol" == typeof t5 ? t5 : String(t5);
          }(t4)) in e4 ? Object.defineProperty(e4, t4, { value: i4, enumerable: true, configurable: true, writable: true }) : e4[t4] = i4, e4;
        }
        class L5 {
          constructor() {
            let { opts: e4, dp: t4 } = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
            E3(this, "toggleTimepickerIsActive", (e5) => {
              this.dp.timepickerIsActive = e5;
            }), E3(this, "onChangeSelectedDate", (e5) => {
              let { date: t5, updateTime: i4 = false } = e5;
              t5 && (this.setMinMaxTime(t5), this.setCurrentTime(!!i4 && t5), this.addTimeToDate(t5));
            }), E3(this, "onChangeLastSelectedDate", (e5) => {
              e5 && (this.setTime(e5), this.render());
            }), E3(this, "onChangeInputRange", (e5) => {
              let t5 = e5.target;
              this[t5.getAttribute("name")] = t5.value, this.updateText(), this.dp.trigger(i3.eventChangeTime, { hours: this.hours, minutes: this.minutes });
            }), E3(this, "onMouseEnterLeave", (e5) => {
              let t5 = e5.target.getAttribute("name"), i4 = this.$minutesText;
              "hours" === t5 && (i4 = this.$hoursText), i4.classList.toggle("-focus-");
            }), E3(this, "onFocus", () => {
              this.toggleTimepickerIsActive(true);
            }), E3(this, "onBlur", () => {
              this.toggleTimepickerIsActive(false);
            }), this.opts = e4, this.dp = t4;
            let { timeFormat: s4 } = this.dp.locale;
            s4 && (s4.match(k2("h")) || s4.match(k2("hh"))) && (this.ampm = true), this.init();
          }
          init() {
            this.setTime(this.dp.lastSelectedDate || this.dp.viewDate), this.createElement(), this.buildHtml(), this.defineDOM(), this.render(), this.bindDatepickerEvents(), this.bindDOMEvents();
          }
          bindDatepickerEvents() {
            this.dp.on(i3.eventChangeSelectedDate, this.onChangeSelectedDate), this.dp.on(i3.eventChangeLastSelectedDate, this.onChangeLastSelectedDate);
          }
          bindDOMEvents() {
            let e4 = "input";
            navigator.userAgent.match(/trident/gi) && (e4 = "change"), D3(this.$ranges, e4, this.onChangeInputRange), D3(this.$ranges, "mouseenter", this.onMouseEnterLeave), D3(this.$ranges, "mouseleave", this.onMouseEnterLeave), D3(this.$ranges, "focus", this.onFocus), D3(this.$ranges, "mousedown", this.onFocus), D3(this.$ranges, "blur", this.onBlur);
          }
          createElement() {
            this.$el = n4({ className: u3("air-datepicker-time", { "-am-pm-": this.dp.ampm }) });
          }
          destroy() {
            this.dp.off(i3.eventChangeSelectedDate, this.onChangeSelectedDate), this.dp.off(i3.eventChangeLastSelectedDate, this.onChangeLastSelectedDate), this.$el.parentNode.removeChild(this.$el);
          }
          buildHtml() {
            let { ampm: e4, hours: t4, displayHours: i4, minutes: s4, minHours: a4, minMinutes: n5, maxHours: r4, maxMinutes: o4, dayPeriod: h4, opts: { hoursStep: l4, minutesStep: c4 } } = this;
            this.$el.innerHTML = `<div class="air-datepicker-time--current">   <span class="air-datepicker-time--current-hours">${d3(i4)}</span>   <span class="air-datepicker-time--current-colon">:</span>   <span class="air-datepicker-time--current-minutes">${d3(s4)}</span>   ` + (e4 ? `<span class='air-datepicker-time--current-ampm'>${h4}</span>` : "") + `</div><div class="air-datepicker-time--sliders">   <div class="air-datepicker-time--row">      <input type="range" name="hours" value="${t4}" min="${a4}" max="${r4}" step="${l4}"/>   </div>   <div class="air-datepicker-time--row">      <input type="range" name="minutes" value="${s4}" min="${n5}" max="${o4}" step="${c4}"/>   </div></div>`;
          }
          defineDOM() {
            let e4 = (e5) => a3(e5, this.$el);
            this.$ranges = this.$el.querySelectorAll('[type="range"]'), this.$hours = e4('[name="hours"]'), this.$minutes = e4('[name="minutes"]'), this.$hoursText = e4(".air-datepicker-time--current-hours"), this.$minutesText = e4(".air-datepicker-time--current-minutes"), this.$ampm = e4(".air-datepicker-time--current-ampm");
          }
          setTime(e4) {
            this.setMinMaxTime(e4), this.setCurrentTime(e4);
          }
          addTimeToDate(e4) {
            e4 && (e4.setHours(this.hours), e4.setMinutes(this.minutes));
          }
          setMinMaxTime(e4) {
            if (this.setMinMaxTimeFromOptions(), e4) {
              let { minDate: t4, maxDate: i4 } = this.dp;
              t4 && p4(e4, t4) && this.setMinTimeFromMinDate(t4), i4 && p4(e4, i4) && this.setMaxTimeFromMaxDate(i4);
            }
          }
          setCurrentTime(e4) {
            let { hours: t4, minutes: i4 } = e4 ? h3(e4) : this;
            this.hours = f3(t4, this.minHours, this.maxHours), this.minutes = f3(i4, this.minMinutes, this.maxMinutes);
          }
          setMinMaxTimeFromOptions() {
            let { minHours: e4, minMinutes: t4, maxHours: i4, maxMinutes: s4 } = this.opts;
            this.minHours = f3(e4, 0, 23), this.minMinutes = f3(t4, 0, 59), this.maxHours = f3(i4, 0, 23), this.maxMinutes = f3(s4, 0, 59);
          }
          setMinTimeFromMinDate(e4) {
            let { lastSelectedDate: t4 } = this.dp;
            this.minHours = e4.getHours(), t4 && t4.getHours() > e4.getHours() ? this.minMinutes = this.opts.minMinutes : this.minMinutes = e4.getMinutes();
          }
          setMaxTimeFromMaxDate(e4) {
            let { lastSelectedDate: t4 } = this.dp;
            this.maxHours = e4.getHours(), t4 && t4.getHours() < e4.getHours() ? this.maxMinutes = this.opts.maxMinutes : this.maxMinutes = e4.getMinutes();
          }
          updateSliders() {
            r3(this.$hours, { min: this.minHours, max: this.maxHours }).value = this.hours, r3(this.$minutes, { min: this.minMinutes, max: this.maxMinutes }).value = this.minutes;
          }
          updateText() {
            this.$hoursText.innerHTML = d3(this.displayHours), this.$minutesText.innerHTML = d3(this.minutes), this.ampm && (this.$ampm.innerHTML = this.dayPeriod);
          }
          set hours(e4) {
            this._hours = e4;
            let { hours: t4, dayPeriod: i4 } = l3(e4);
            this.displayHours = this.ampm ? t4 : e4, this.dayPeriod = i4;
          }
          get hours() {
            return this._hours;
          }
          render() {
            this.updateSliders(), this.updateText();
          }
        }
        function O4(e4, t4, i4) {
          return (t4 = function(e5) {
            var t5 = function(e6, t6) {
              if ("object" != typeof e6 || null === e6) return e6;
              var i5 = e6[Symbol.toPrimitive];
              if (void 0 !== i5) {
                var s4 = i5.call(e6, "string");
                if ("object" != typeof s4) return s4;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(e6);
            }(e5);
            return "symbol" == typeof t5 ? t5 : String(t5);
          }(t4)) in e4 ? Object.defineProperty(e4, t4, { value: i4, enumerable: true, configurable: true, writable: true }) : e4[t4] = i4, e4;
        }
        class A4 {
          constructor(e4) {
            let { dp: t4, opts: i4 } = e4;
            O4(this, "pressedKeys", /* @__PURE__ */ new Set()), O4(this, "hotKeys", /* @__PURE__ */ new Map([[[["Control", "ArrowRight"], ["Control", "ArrowUp"]], (e5) => e5.month++], [[["Control", "ArrowLeft"], ["Control", "ArrowDown"]], (e5) => e5.month--], [[["Shift", "ArrowRight"], ["Shift", "ArrowUp"]], (e5) => e5.year++], [[["Shift", "ArrowLeft"], ["Shift", "ArrowDown"]], (e5) => e5.year--], [[["Alt", "ArrowRight"], ["Alt", "ArrowUp"]], (e5) => e5.year += 10], [[["Alt", "ArrowLeft"], ["Alt", "ArrowDown"]], (e5) => e5.year -= 10], [["Control", "Shift", "ArrowUp"], (e5, t5) => t5.up()]])), O4(this, "handleHotKey", (e5) => {
              let t5 = this.hotKeys.get(e5), i5 = h3(this.getInitialFocusDate());
              t5(i5, this.dp);
              let { year: s4, month: a4, date: n5 } = i5, r4 = o3(new Date(s4, a4));
              r4 < n5 && (n5 = r4);
              let l4 = this.dp.getClampedDate(new Date(s4, a4, n5));
              this.dp.setFocusDate(l4, { viewDateTransition: true });
            }), O4(this, "isHotKeyPressed", () => {
              let e5 = false, t5 = this.pressedKeys.size, i5 = (e6) => this.pressedKeys.has(e6);
              for (let [s4] of this.hotKeys) {
                if (e5) break;
                if (Array.isArray(s4[0])) s4.forEach((a4) => {
                  e5 || t5 !== a4.length || (e5 = a4.every(i5) && s4);
                });
                else {
                  if (t5 !== s4.length) continue;
                  e5 = s4.every(i5) && s4;
                }
              }
              return e5;
            }), O4(this, "isArrow", (e5) => e5 >= 37 && e5 <= 40), O4(this, "onKeyDown", (e5) => {
              let { key: t5, which: i5 } = e5, { dp: s4, dp: { focusDate: a4 }, opts: n5 } = this;
              this.registerKey(t5);
              let r4 = this.isHotKeyPressed();
              if (r4) return e5.preventDefault(), void this.handleHotKey(r4);
              if (this.isArrow(i5)) return e5.preventDefault(), void this.focusNextCell(t5);
              if ("Enter" === t5) {
                if (s4.currentView !== n5.minView) return void s4.down();
                if (a4) {
                  let e6 = s4._checkIfDateIsSelected(a4);
                  return void (e6 ? s4._handleAlreadySelectedDates(e6, a4) : s4.selectDate(a4));
                }
              }
              "Escape" === t5 && this.dp.hide();
            }), O4(this, "onKeyUp", (e5) => {
              this.removeKey(e5.key);
            }), this.dp = t4, this.opts = i4, this.init();
          }
          init() {
            this.bindKeyboardEvents();
          }
          bindKeyboardEvents() {
            let { $el: e4 } = this.dp;
            e4.addEventListener("keydown", this.onKeyDown), e4.addEventListener("keyup", this.onKeyUp);
          }
          destroy() {
            let { $el: e4 } = this.dp;
            e4.removeEventListener("keydown", this.onKeyDown), e4.removeEventListener("keyup", this.onKeyUp), this.hotKeys = null, this.pressedKeys = null;
          }
          getInitialFocusDate() {
            let { focusDate: e4, currentView: t4, selectedDates: s4, parsedViewDate: { year: a4, month: n5 } } = this.dp, r4 = e4 || s4[s4.length - 1];
            if (!r4) switch (t4) {
              case i3.days:
                r4 = new Date(a4, n5, (/* @__PURE__ */ new Date()).getDate());
                break;
              case i3.months:
                r4 = new Date(a4, n5, 1);
                break;
              case i3.years:
                r4 = new Date(a4, 0, 1);
            }
            return r4;
          }
          focusNextCell(e4) {
            let t4 = this.getInitialFocusDate(), { currentView: s4 } = this.dp, { days: a4, months: n5, years: r4 } = i3, o4 = h3(t4), l4 = o4.year, d4 = o4.month, c4 = o4.date;
            switch (e4) {
              case "ArrowLeft":
                s4 === a4 && (c4 -= 1), s4 === n5 && (d4 -= 1), s4 === r4 && (l4 -= 1);
                break;
              case "ArrowUp":
                s4 === a4 && (c4 -= 7), s4 === n5 && (d4 -= 3), s4 === r4 && (l4 -= 4);
                break;
              case "ArrowRight":
                s4 === a4 && (c4 += 1), s4 === n5 && (d4 += 1), s4 === r4 && (l4 += 1);
                break;
              case "ArrowDown":
                s4 === a4 && (c4 += 7), s4 === n5 && (d4 += 3), s4 === r4 && (l4 += 4);
            }
            let u4 = this.dp.getClampedDate(new Date(l4, d4, c4));
            this.dp.setFocusDate(u4, { viewDateTransition: true });
          }
          registerKey(e4) {
            this.pressedKeys.add(e4);
          }
          removeKey(e4) {
            this.pressedKeys.delete(e4);
          }
        }
        let N = { on(e4, t4) {
          this.__events || (this.__events = {}), this.__events[e4] ? this.__events[e4].push(t4) : this.__events[e4] = [t4];
        }, off(e4, t4) {
          this.__events && this.__events[e4] && (this.__events[e4] = this.__events[e4].filter((e5) => e5 !== t4));
        }, removeAllEvents() {
          this.__events = {};
        }, trigger(e4) {
          for (var t4 = arguments.length, i4 = new Array(t4 > 1 ? t4 - 1 : 0), s4 = 1; s4 < t4; s4++) i4[s4 - 1] = arguments[s4];
          this.__events && this.__events[e4] && this.__events[e4].forEach((e5) => {
            e5(...i4);
          });
        } };
        function I(e4, t4, i4) {
          return (t4 = function(e5) {
            var t5 = function(e6, t6) {
              if ("object" != typeof e6 || null === e6) return e6;
              var i5 = e6[Symbol.toPrimitive];
              if (void 0 !== i5) {
                var s4 = i5.call(e6, "string");
                if ("object" != typeof s4) return s4;
                throw new TypeError("@@toPrimitive must return a primitive value.");
              }
              return String(e6);
            }(e5);
            return "symbol" == typeof t5 ? t5 : String(t5);
          }(t4)) in e4 ? Object.defineProperty(e4, t4, { value: i4, enumerable: true, configurable: true, writable: true }) : e4[t4] = i4, e4;
        }
        let P3 = "", j = "", B = false;
        class R2 {
          static buildGlobalContainer(e4) {
            B = true, P3 = n4({ className: e4, id: e4 }), a3("body").appendChild(P3);
          }
          constructor(e4, t4) {
            var r4 = this;
            if (I(this, "viewIndexes", [i3.days, i3.months, i3.years]), I(this, "next", () => {
              let { year: e5, month: t5 } = this.parsedViewDate;
              switch (this.currentView) {
                case i3.days:
                  this.setViewDate(new Date(e5, t5 + 1, 1));
                  break;
                case i3.months:
                  this.setViewDate(new Date(e5 + 1, t5, 1));
                  break;
                case i3.years:
                  this.setViewDate(new Date(e5 + 10, 0, 1));
              }
            }), I(this, "prev", () => {
              let { year: e5, month: t5 } = this.parsedViewDate;
              switch (this.currentView) {
                case i3.days:
                  this.setViewDate(new Date(e5, t5 - 1, 1));
                  break;
                case i3.months:
                  this.setViewDate(new Date(e5 - 1, t5, 1));
                  break;
                case i3.years:
                  this.setViewDate(new Date(e5 - 10, 0, 1));
              }
            }), I(this, "_finishHide", () => {
              this.hideAnimation = false, this._destroyComponents(), this.$container.removeChild(this.$datepicker);
            }), I(this, "setPosition", function(e5) {
              let t5 = arguments.length > 1 && void 0 !== arguments[1] && arguments[1];
              if ("function" == typeof (e5 = e5 || r4.opts.position)) return void (r4.customHide = e5({ $datepicker: r4.$datepicker, $target: r4.$el, $pointer: r4.$pointer, isViewChange: t5, done: r4._finishHide }));
              let i4, s4, { isMobile: a4 } = r4.opts, n5 = r4.$el.getBoundingClientRect(), o5 = r4.$el.getBoundingClientRect(), h4 = r4.$datepicker.offsetParent, l5 = r4.$el.offsetParent, d4 = r4.$datepicker.getBoundingClientRect(), c4 = e5.split(" "), u4 = window.scrollY, p5 = window.scrollX, m4 = r4.opts.offset, v4 = c4[0], g4 = c4[1];
              if (a4) r4.$datepicker.style.cssText = "left: 50%; top: 50%";
              else {
                if (h4 === l5 && h4 !== document.body && (o5 = { top: r4.$el.offsetTop, left: r4.$el.offsetLeft, width: n5.width, height: r4.$el.offsetHeight }, u4 = 0, p5 = 0), h4 !== l5 && h4 !== document.body) {
                  let e6 = h4.getBoundingClientRect();
                  o5 = { top: n5.top - e6.top, left: n5.left - e6.left, width: n5.width, height: n5.height }, u4 = 0, p5 = 0;
                }
                switch (v4) {
                  case "top":
                    i4 = o5.top - d4.height - m4;
                    break;
                  case "right":
                    s4 = o5.left + o5.width + m4;
                    break;
                  case "bottom":
                    i4 = o5.top + o5.height + m4;
                    break;
                  case "left":
                    s4 = o5.left - d4.width - m4;
                }
                switch (g4) {
                  case "top":
                    i4 = o5.top;
                    break;
                  case "right":
                    s4 = o5.left + o5.width - d4.width;
                    break;
                  case "bottom":
                    i4 = o5.top + o5.height - d4.height;
                    break;
                  case "left":
                    s4 = o5.left;
                    break;
                  case "center":
                    /left|right/.test(v4) ? i4 = o5.top + o5.height / 2 - d4.height / 2 : s4 = o5.left + o5.width / 2 - d4.width / 2;
                }
                r4.$datepicker.style.cssText = `left: ${s4 + p5}px; top: ${i4 + u4}px`;
              }
            }), I(this, "_setInputValue", () => {
              let { opts: e5, $altField: t5, locale: { dateFormat: i4 } } = this, { altFieldDateFormat: s4, altField: a4 } = e5;
              a4 && t5 && (t5.value = this._getInputValue(s4)), this.$el.value = this._getInputValue(i4);
            }), I(this, "_getInputValue", (e5) => {
              let { selectedDates: t5, opts: i4 } = this, { multipleDates: s4, multipleDatesSeparator: a4 } = i4;
              if (!t5.length) return "";
              let n5 = "function" == typeof e5, r5 = n5 ? e5(s4 ? t5 : t5[0]) : t5.map((t6) => this.formatDate(t6, e5));
              return r5 = n5 ? r5 : r5.join(a4), r5;
            }), I(this, "_checkIfDateIsSelected", function(e5) {
              let t5 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : i3.days, s4 = false;
              return r4.selectedDates.some((i4) => {
                let a4 = p4(e5, i4, t5);
                return s4 = a4 && i4, a4;
              }), s4;
            }), I(this, "_scheduleCallAfterTransition", (e5) => {
              this._cancelScheduledCall(), e5 && e5(false), this._onTransitionEnd = () => {
                e5 && e5(true);
              }, this.$datepicker.addEventListener("transitionend", this._onTransitionEnd, { once: true });
            }), I(this, "_cancelScheduledCall", () => {
              this.$datepicker.removeEventListener("transitionend", this._onTransitionEnd);
            }), I(this, "setViewDate", (e5) => {
              if (!((e5 = b3(e5)) instanceof Date)) return;
              if (p4(e5, this.viewDate)) return;
              let t5 = this.viewDate;
              this.viewDate = e5;
              let { onChangeViewDate: s4 } = this.opts;
              if (s4) {
                let { month: e6, year: t6 } = this.parsedViewDate;
                s4({ month: e6, year: t6, decade: this.curDecade });
              }
              this.trigger(i3.eventChangeViewDate, e5, t5);
            }), I(this, "setFocusDate", function(e5) {
              let t5 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
              (!e5 || (e5 = b3(e5)) instanceof Date) && (r4.focusDate = e5, r4.trigger(i3.eventChangeFocusDate, e5, t5));
            }), I(this, "setCurrentView", function(e5) {
              let t5 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
              if (r4.viewIndexes.includes(e5)) {
                if (r4.currentView = e5, r4.elIsInput && r4.visible && r4.setPosition(void 0, true), r4.trigger(i3.eventChangeCurrentView, e5), !r4.views[e5]) {
                  let t6 = r4.views[e5] = new T3({ dp: r4, opts: r4.opts, type: e5 });
                  r4.shouldUpdateDOM && r4.$content.appendChild(t6.$el);
                }
                r4.opts.onChangeView && !t5.silent && r4.opts.onChangeView(e5);
              }
            }), I(this, "_updateLastSelectedDate", (e5) => {
              this.lastSelectedDate = e5, this.trigger(i3.eventChangeLastSelectedDate, e5);
            }), I(this, "destroy", () => {
              if (this.isDestroyed) return;
              let { showEvent: e5, isMobile: t5 } = this.opts, i4 = this.$datepicker.parentNode;
              i4 && i4.removeChild(this.$datepicker), this.$el.removeEventListener(e5, this._onFocus), this.$el.removeEventListener("blur", this._onBlur), window.removeEventListener("resize", this._onResize), t5 && this._removeMobileAttributes(), this.keyboardNav && this.keyboardNav.destroy(), this.views = null, this.nav = null, this.$datepicker = null, this.opts = {}, this.$customContainer = null, this.viewDate = null, this.focusDate = null, this.selectedDates = [], this.rangeDateFrom = null, this.rangeDateTo = null, this.isDestroyed = true;
            }), I(this, "update", function() {
              let e5 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, t5 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, s4 = w3({}, r4.opts), { silent: a4 } = t5;
              w3(r4.opts, e5);
              let { timepicker: n5, buttons: o5, range: h4, selectedDates: l5, isMobile: d4 } = r4.opts, c4 = r4.visible || r4.treatAsInline;
              r4._createMinMaxDates(), r4._limitViewDateByMaxMinDates(), r4._handleLocale(), l5 && (r4.selectedDates = [], r4.selectDate(l5, { silent: a4 })), e5.view && r4.setCurrentView(e5.view, { silent: a4 }), r4._setInputValue(), s4.range && !h4 ? (r4.rangeDateTo = false, r4.rangeDateFrom = false) : !s4.range && h4 && r4.selectedDates.length && (r4.rangeDateFrom = r4.selectedDates[0], r4.rangeDateTo = r4.selectedDates[1]), s4.timepicker && !n5 ? (c4 && r4.timepicker.destroy(), r4.timepicker = false, r4.$timepicker.parentNode.removeChild(r4.$timepicker)) : !s4.timepicker && n5 && r4._addTimepicker(), !s4.buttons && o5 ? r4._addButtons() : s4.buttons && !o5 ? (r4.buttons.destroy(), r4.$buttons.parentNode.removeChild(r4.$buttons)) : c4 && s4.buttons && o5 && r4.buttons.clearHtml().render(), !s4.isMobile && d4 ? (r4.treatAsInline || j || r4._createMobileOverlay(), r4._addMobileAttributes(), r4.visible && r4._showMobileOverlay()) : s4.isMobile && !d4 && (r4._removeMobileAttributes(), r4.visible && (j.classList.remove("-active-"), "function" != typeof r4.opts.position && r4.setPosition())), c4 && (r4.nav.update(), r4.views[r4.currentView].render(), r4.currentView === i3.days && r4.views[r4.currentView].renderDayNames());
            }), I(this, "disableDate", (e5, t5) => {
              (Array.isArray(e5) ? e5 : [e5]).forEach((e6) => {
                let i4 = b3(e6);
                if (!i4) return;
                let s4 = t5 ? "delete" : "add";
                this.disabledDates[s4](this.formatDate(i4, "yyyy-MM-dd"));
                let a4 = this.getCell(i4, this.currentViewSingular);
                a4 && a4.adpCell.render();
              }, []);
            }), I(this, "enableDate", (e5) => {
              this.disableDate(e5, true);
            }), I(this, "isDateDisabled", (e5) => {
              let t5 = b3(e5);
              return this.disabledDates.has(this.formatDate(t5, "yyyy-MM-dd"));
            }), I(this, "isOtherMonth", (e5) => {
              let { month: t5 } = h3(e5);
              return t5 !== this.parsedViewDate.month;
            }), I(this, "isOtherYear", (e5) => {
              let { year: t5 } = h3(e5);
              return t5 !== this.parsedViewDate.year;
            }), I(this, "isOtherDecade", (e5) => {
              let { year: t5 } = h3(e5), [i4, s4] = c3(this.viewDate);
              return t5 < i4 || t5 > s4;
            }), I(this, "_onChangeSelectedDate", (e5) => {
              let { silent: t5 } = e5;
              setTimeout(() => {
                this._setInputValue(), this.opts.onSelect && !t5 && this._triggerOnSelect();
              });
            }), I(this, "_onChangeFocusedDate", function(e5) {
              let { viewDateTransition: t5 } = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
              if (!e5) return;
              let i4 = false;
              t5 && (i4 = r4.isOtherMonth(e5) || r4.isOtherYear(e5) || r4.isOtherDecade(e5)), i4 && r4.setViewDate(e5), r4.opts.onFocus && r4.opts.onFocus({ datepicker: r4, date: e5 });
            }), I(this, "_onChangeTime", (e5) => {
              let { hours: t5, minutes: i4 } = e5, s4 = /* @__PURE__ */ new Date(), { lastSelectedDate: a4, opts: { onSelect: n5 } } = this, r5 = a4;
              a4 || (r5 = s4);
              let o5 = this.getCell(r5, this.currentViewSingular), h4 = o5 && o5.adpCell;
              h4 && h4.isDisabled || (r5.setHours(t5), r5.setMinutes(i4), a4 ? (this._setInputValue(), n5 && this._triggerOnSelect()) : this.selectDate(r5));
            }), I(this, "_onFocus", (e5) => {
              this.visible || this.show();
            }), I(this, "_onBlur", (e5) => {
              this.inFocus || !this.visible || this.opts.isMobile || this.hide();
            }), I(this, "_onMouseDown", (e5) => {
              this.inFocus = true;
            }), I(this, "_onMouseUp", (e5) => {
              this.inFocus = false, this.$el.focus();
            }), I(this, "_onResize", () => {
              this.visible && "function" != typeof this.opts.position && this.setPosition();
            }), I(this, "_onClickOverlay", () => {
              this.visible && this.hide();
            }), I(this, "getViewDates", function() {
              let e5 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : i3.days;
              return T3.getDatesFunction(e5)(r4);
            }), I(this, "isWeekend", (e5) => this.opts.weekends.includes(e5)), I(this, "getClampedDate", (e5) => {
              let { minDate: t5, maxDate: i4 } = this, s4 = e5;
              return i4 && m3(e5, i4) ? s4 = i4 : t5 && v3(e5, t5) && (s4 = t5), s4;
            }), this.$el = a3(e4), !this.$el) return;
            this.$datepicker = n4({ className: "air-datepicker" }), this.opts = w3({}, s3, t4), this.$customContainer = !!this.opts.container && a3(this.opts.container), this.$altField = a3(this.opts.altField || false);
            let { view: o4, startDate: l4 } = this.opts;
            l4 || (this.opts.startDate = /* @__PURE__ */ new Date()), "INPUT" === this.$el.nodeName && (this.elIsInput = true), this.inited = false, this.visible = false, this.viewDate = b3(this.opts.startDate), this.focusDate = false, this.initialReadonly = this.$el.getAttribute("readonly"), this.customHide = false, this.currentView = o4, this.selectedDates = [], this.disabledDates = /* @__PURE__ */ new Set(), this.isDestroyed = false, this.views = {}, this.keys = [], this.rangeDateFrom = "", this.rangeDateTo = "", this.timepickerIsActive = false, this.treatAsInline = this.opts.inline || !this.elIsInput, this.init();
          }
          init() {
            let { opts: e4, treatAsInline: t4, opts: { inline: i4, isMobile: s4, selectedDates: n5, keyboardNav: r4, onlyTimepicker: o4 } } = this, h4 = a3("body");
            (!B || B && P3 && !h4.contains(P3)) && !i4 && this.elIsInput && !this.$customContainer && R2.buildGlobalContainer(R2.defaultGlobalContainerId), !s4 || j || t4 || this._createMobileOverlay(), this._handleLocale(), this._bindSubEvents(), this._createMinMaxDates(), this._limitViewDateByMaxMinDates(), this.elIsInput && (i4 || this._bindEvents(), r4 && !o4 && (this.keyboardNav = new A4({ dp: this, opts: e4 }))), n5 && this.selectDate(n5, { silent: true }), this.opts.visible && !t4 && this.show(), s4 && !t4 && this.$el.setAttribute("readonly", true), t4 && this._createComponents();
          }
          _createMobileOverlay() {
            j = n4({ className: "air-datepicker-overlay" }), P3.appendChild(j);
          }
          _createComponents() {
            let { opts: e4, treatAsInline: t4, opts: { inline: i4, buttons: s4, timepicker: a4, position: n5, classes: r4, onlyTimepicker: o4, isMobile: h4 } } = this;
            this._buildBaseHtml(), this.elIsInput && (i4 || this._setPositionClasses(n5)), !i4 && this.elIsInput || this.$datepicker.classList.add("-inline-"), r4 && this.$datepicker.classList.add(...r4.split(" ")), o4 && this.$datepicker.classList.add("-only-timepicker-"), h4 && !t4 && this._addMobileAttributes(), this.views[this.currentView] = new T3({ dp: this, type: this.currentView, opts: e4 }), this.nav = new V2({ dp: this, opts: e4 }), a4 && this._addTimepicker(), s4 && this._addButtons(), this.$content.appendChild(this.views[this.currentView].$el), this.$nav.appendChild(this.nav.$el);
          }
          _destroyComponents() {
            for (let e4 in this.views) this.views[e4].destroy();
            this.views = {}, this.nav.destroy(), this.timepicker && this.timepicker.destroy();
          }
          _addMobileAttributes() {
            j.addEventListener("click", this._onClickOverlay), this.$datepicker.classList.add("-is-mobile-"), this.$el.setAttribute("readonly", true);
          }
          _removeMobileAttributes() {
            j.removeEventListener("click", this._onClickOverlay), this.$datepicker.classList.remove("-is-mobile-"), this.initialReadonly || "" === this.initialReadonly || this.$el.removeAttribute("readonly");
          }
          _createMinMaxDates() {
            let { minDate: e4, maxDate: t4 } = this.opts;
            this.minDate = !!e4 && b3(e4), this.maxDate = !!t4 && b3(t4);
          }
          _addTimepicker() {
            this.$timepicker = n4({ className: "air-datepicker--time" }), this.$datepicker.appendChild(this.$timepicker), this.timepicker = new L5({ dp: this, opts: this.opts }), this.$timepicker.appendChild(this.timepicker.$el);
          }
          _addButtons() {
            this.$buttons = n4({ className: "air-datepicker--buttons" }), this.$datepicker.appendChild(this.$buttons), this.buttons = new H2({ dp: this, opts: this.opts }), this.$buttons.appendChild(this.buttons.$el);
          }
          _bindSubEvents() {
            this.on(i3.eventChangeSelectedDate, this._onChangeSelectedDate), this.on(i3.eventChangeFocusDate, this._onChangeFocusedDate), this.on(i3.eventChangeTime, this._onChangeTime);
          }
          _buildBaseHtml() {
            let { inline: e4 } = this.opts;
            var t4, i4;
            this.elIsInput ? e4 ? (t4 = this.$datepicker, (i4 = this.$el).parentNode.insertBefore(t4, i4.nextSibling)) : this.$container.appendChild(this.$datepicker) : this.$el.appendChild(this.$datepicker), this.$datepicker.innerHTML = '<i class="air-datepicker--pointer"></i><div class="air-datepicker--navigation"></div><div class="air-datepicker--content"></div>', this.$content = a3(".air-datepicker--content", this.$datepicker), this.$pointer = a3(".air-datepicker--pointer", this.$datepicker), this.$nav = a3(".air-datepicker--navigation", this.$datepicker);
          }
          _handleLocale() {
            let { locale: e4, dateFormat: t4, firstDay: i4, timepicker: s4, onlyTimepicker: a4, timeFormat: n5, dateTimeSeparator: r4 } = this.opts;
            var o4;
            this.locale = (o4 = e4, JSON.parse(JSON.stringify(o4))), t4 && (this.locale.dateFormat = t4), void 0 !== n5 && "" !== n5 && (this.locale.timeFormat = n5);
            let { timeFormat: h4 } = this.locale;
            if ("" !== i4 && (this.locale.firstDay = i4), s4 && "function" != typeof t4) {
              let e5 = h4 ? r4 : "";
              this.locale.dateFormat = [this.locale.dateFormat, h4 || ""].join(e5);
            }
            a4 && "function" != typeof t4 && (this.locale.dateFormat = this.locale.timeFormat);
          }
          _setPositionClasses(e4) {
            if ("function" == typeof e4) return void this.$datepicker.classList.add("-custom-position-");
            let t4 = (e4 = e4.split(" "))[0], i4 = `air-datepicker -${t4}-${e4[1]}- -from-${t4}-`;
            this.$datepicker.classList.add(...i4.split(" "));
          }
          _bindEvents() {
            this.$el.addEventListener(this.opts.showEvent, this._onFocus), this.$el.addEventListener("blur", this._onBlur), this.$datepicker.addEventListener("mousedown", this._onMouseDown), this.$datepicker.addEventListener("mouseup", this._onMouseUp), window.addEventListener("resize", this._onResize);
          }
          _limitViewDateByMaxMinDates() {
            let { viewDate: e4, minDate: t4, maxDate: i4 } = this;
            i4 && m3(e4, i4) && this.setViewDate(i4), t4 && v3(e4, t4) && this.setViewDate(t4);
          }
          formatDate() {
            let e4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.viewDate, t4 = arguments.length > 1 ? arguments[1] : void 0;
            if (e4 = b3(e4), !(e4 instanceof Date)) return;
            let i4 = t4, s4 = this.locale, a4 = h3(e4), n5 = a4.dayPeriod, r4 = c3(e4), o4 = R2.replacer, l4 = { T: e4.getTime(), m: a4.minutes, mm: a4.fullMinutes, h: a4.hours12, hh: a4.fullHours12, H: a4.hours, HH: a4.fullHours, aa: n5, AA: n5.toUpperCase(), E: s4.daysShort[a4.day], EEEE: s4.days[a4.day], d: a4.date, dd: a4.fullDate, M: a4.month + 1, MM: a4.fullMonth, MMM: s4.monthsShort[a4.month], MMMM: s4.months[a4.month], yy: a4.year.toString().slice(-2), yyyy: a4.year, yyyy1: r4[0], yyyy2: r4[1] };
            for (let [e5, t5] of Object.entries(l4)) i4 = o4(i4, k2(e5), t5);
            return i4;
          }
          down(e4) {
            this._handleUpDownActions(e4, "down");
          }
          up(e4) {
            this._handleUpDownActions(e4, "up");
          }
          selectDate(e4) {
            let t4, s4 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, { currentView: a4, parsedViewDate: n5, selectedDates: r4 } = this, { updateTime: o4 } = s4, { moveToOtherMonthsOnSelect: h4, moveToOtherYearsOnSelect: l4, multipleDates: d4, range: c4, autoClose: u4, onBeforeSelect: p5 } = this.opts, v4 = r4.length;
            if (Array.isArray(e4)) return e4.forEach((e5) => {
              this.selectDate(e5, s4);
            }), new Promise((e5) => {
              setTimeout(e5);
            });
            if ((e4 = b3(e4)) instanceof Date) {
              if (p5 && !p5({ date: e4, datepicker: this })) return Promise.resolve();
              if (a4 === i3.days && e4.getMonth() !== n5.month && h4 && (t4 = new Date(e4.getFullYear(), e4.getMonth(), 1)), a4 === i3.years && e4.getFullYear() !== n5.year && l4 && (t4 = new Date(e4.getFullYear(), 0, 1)), t4 && this.setViewDate(t4), d4 && !c4) {
                if (v4 === d4) return;
                this._checkIfDateIsSelected(e4) || r4.push(e4);
              } else if (c4) switch (v4) {
                case 1:
                  r4.push(e4), this.rangeDateTo || (this.rangeDateTo = e4), m3(this.rangeDateFrom, this.rangeDateTo) && (this.rangeDateTo = this.rangeDateFrom, this.rangeDateFrom = e4), this.selectedDates = [this.rangeDateFrom, this.rangeDateTo];
                  break;
                case 2:
                  this.selectedDates = [e4], this.rangeDateFrom = e4, this.rangeDateTo = "";
                  break;
                default:
                  this.selectedDates = [e4], this.rangeDateFrom = e4;
              }
              else this.selectedDates = [e4];
              return this.trigger(i3.eventChangeSelectedDate, { action: i3.actionSelectDate, silent: null == s4 ? void 0 : s4.silent, date: e4, updateTime: o4 }), this._updateLastSelectedDate(e4), u4 && !this.timepickerIsActive && this.visible && (d4 || c4 ? c4 && 1 === v4 && this.hide() : this.hide()), new Promise((e5) => {
                setTimeout(e5);
              });
            }
          }
          unselectDate(e4) {
            let t4 = this.selectedDates, s4 = this;
            if ((e4 = b3(e4)) instanceof Date) return t4.some((a4, n5) => {
              if (p4(a4, e4)) return t4.splice(n5, 1), s4.selectedDates.length ? (s4.rangeDateTo = "", s4.rangeDateFrom = t4[0], s4._updateLastSelectedDate(s4.selectedDates[s4.selectedDates.length - 1])) : (s4.rangeDateFrom = "", s4.rangeDateTo = "", s4._updateLastSelectedDate(false)), this.trigger(i3.eventChangeSelectedDate, { action: i3.actionUnselectDate, date: e4 }), true;
            });
          }
          replaceDate(e4, t4) {
            let s4 = this.selectedDates.find((t5) => p4(t5, e4, this.currentView)), a4 = this.selectedDates.indexOf(s4);
            a4 < 0 || p4(this.selectedDates[a4], t4, this.currentView) || (this.selectedDates[a4] = t4, this.trigger(i3.eventChangeSelectedDate, { action: i3.actionSelectDate, date: t4, updateTime: true }), this._updateLastSelectedDate(t4));
          }
          clear() {
            let e4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
            return this.selectedDates = [], this.rangeDateFrom = false, this.rangeDateTo = false, this.lastSelectedDate = false, this.trigger(i3.eventChangeSelectedDate, { action: i3.actionUnselectDate, silent: e4.silent }), new Promise((e5) => {
              setTimeout(e5);
            });
          }
          show() {
            let { onShow: e4, isMobile: t4 } = this.opts;
            this._cancelScheduledCall(), this.visible || this.hideAnimation || this._createComponents(), this.setPosition(this.opts.position), this.$datepicker.classList.add("-active-"), this.visible = true, e4 && this._scheduleCallAfterTransition(e4), t4 && this._showMobileOverlay();
          }
          hide() {
            let { onHide: e4, isMobile: t4 } = this.opts, i4 = this._hasTransition();
            this.visible = false, this.hideAnimation = true, this.$datepicker.classList.remove("-active-"), this.customHide && this.customHide(), this.elIsInput && this.$el.blur(), this._scheduleCallAfterTransition((t5) => {
              !this.customHide && (t5 && i4 || !t5 && !i4) && this._finishHide(), e4 && e4(t5);
            }), t4 && j.classList.remove("-active-");
          }
          _triggerOnSelect() {
            let e4 = [], t4 = [], { selectedDates: i4, locale: s4, opts: { onSelect: a4, multipleDates: n5, range: r4 } } = this, o4 = n5 || r4, h4 = "function" == typeof s4.dateFormat;
            i4.length && (e4 = i4.map(g3), t4 = h4 ? n5 ? s4.dateFormat(e4) : e4.map((e5) => s4.dateFormat(e5)) : e4.map((e5) => this.formatDate(e5, s4.dateFormat))), a4({ date: o4 ? e4 : e4[0], formattedDate: o4 ? t4 : t4[0], datepicker: this });
          }
          _handleAlreadySelectedDates(e4, t4) {
            let { selectedDates: i4, rangeDateFrom: s4, rangeDateTo: a4 } = this, { range: n5, toggleSelected: r4 } = this.opts, o4 = i4.length, h4 = "function" == typeof r4 ? r4({ datepicker: this, date: t4 }) : r4, l4 = Boolean(n5 && 1 === o4 && e4), d4 = l4 ? g3(t4) : t4;
            n5 && !h4 && (2 !== o4 && this.selectDate(d4), 2 === o4 && p4(s4, a4)) || (h4 ? this.unselectDate(d4) : this._updateLastSelectedDate(l4 ? d4 : e4));
          }
          _handleUpDownActions(e4, t4) {
            if (!((e4 = b3(e4 || this.focusDate || this.viewDate)) instanceof Date)) return;
            let i4 = "up" === t4 ? this.viewIndex + 1 : this.viewIndex - 1;
            i4 > 2 && (i4 = 2), i4 < 0 && (i4 = 0), this.setViewDate(new Date(e4.getFullYear(), e4.getMonth(), 1)), this.setCurrentView(this.viewIndexes[i4]);
          }
          getCell(e4) {
            let t4 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : i3.day;
            if (!((e4 = b3(e4)) instanceof Date)) return;
            let { year: s4, month: a4, date: n5 } = h3(e4), r4 = `[data-year="${s4}"]`, o4 = `[data-month="${a4}"]`, l4 = { [i3.day]: `${r4}${o4}[data-date="${n5}"]`, [i3.month]: `${r4}${o4}`, [i3.year]: `${r4}` };
            return this.views[this.currentView] ? this.views[this.currentView].$el.querySelector(l4[t4]) : void 0;
          }
          _showMobileOverlay() {
            j.classList.add("-active-");
          }
          _hasTransition() {
            return window.getComputedStyle(this.$datepicker).getPropertyValue("transition-duration").split(", ").reduce((e4, t4) => parseFloat(t4) + e4, 0) > 0;
          }
          get shouldUpdateDOM() {
            return this.visible || this.treatAsInline;
          }
          get parsedViewDate() {
            return h3(this.viewDate);
          }
          get currentViewSingular() {
            return this.currentView.slice(0, -1);
          }
          get curDecade() {
            return c3(this.viewDate);
          }
          get viewIndex() {
            return this.viewIndexes.indexOf(this.currentView);
          }
          get isFinalView() {
            return this.currentView === i3.years;
          }
          get hasSelectedDates() {
            return this.selectedDates.length > 0;
          }
          get isMinViewReached() {
            return this.currentView === this.opts.minView || this.currentView === i3.days;
          }
          get $container() {
            return this.$customContainer || P3;
          }
          static replacer(e4, t4, i4) {
            return e4.replace(t4, function(e5, t5, s4, a4) {
              return t5 + i4 + a4;
            });
          }
        }
        var K;
        return I(R2, "defaults", s3), I(R2, "version", "3.5.3"), I(R2, "defaultGlobalContainerId", "air-datepicker-global-container"), K = R2.prototype, Object.assign(K, N), t3.default;
      }();
    });
  }
});

// node_modules/air-datepicker/locale/en.js
var require_en = __commonJS({
  "node_modules/air-datepicker/locale/en.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;
    var _default = {
      days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
      daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
      daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
      months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
      today: "Today",
      clear: "Clear",
      dateFormat: "MM/dd/yyyy",
      timeFormat: "hh:mm aa",
      firstDay: 0
    };
    exports.default = _default;
  }
});

// node_modules/air-datepicker/locale/fr.js
var require_fr = __commonJS({
  "node_modules/air-datepicker/locale/fr.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;
    var _default = {
      days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
      daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
      daysMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
      months: ["Janvier", "F\xE9vrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Ao\xFBt", "Septembre", "Octobre", "Novembre", "D\xE9cembre"],
      monthsShort: ["Jan", "F\xE9v", "Mars", "Avr", "Mai", "Juin", "Juil", "Ao\xFBt", "Sep", "Oct", "Nov", "Dec"],
      today: "Aujourd'hui",
      clear: "Effacer",
      dateFormat: "dd/MM/yyyy",
      timeFormat: "HH:mm",
      firstDay: 1
    };
    exports.default = _default;
  }
});

// node_modules/air-datepicker/locale/de.js
var require_de = __commonJS({
  "node_modules/air-datepicker/locale/de.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;
    var _default = {
      days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
      daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam"],
      daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
      months: ["Januar", "Februar", "M\xE4rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
      monthsShort: ["Jan", "Feb", "M\xE4r", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
      today: "Heute",
      clear: "L\xF6schen",
      dateFormat: "dd.MM.yyyy",
      timeFormat: "HH:mm",
      firstDay: 1
    };
    exports.default = _default;
  }
});

// node_modules/air-datepicker/locale/es.js
var require_es = __commonJS({
  "node_modules/air-datepicker/locale/es.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;
    var _default = {
      days: ["Domingo", "Lunes", "Martes", "Mi\xE9rcoles", "Jueves", "Viernes", "S\xE1bado"],
      daysShort: ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"],
      daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"],
      months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
      monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
      today: "Hoy",
      clear: "Limpiar",
      dateFormat: "dd/MM/yyyy",
      timeFormat: "hh:mm aa",
      firstDay: 1
    };
    exports.default = _default;
  }
});

// node_modules/air-datepicker/locale/it.js
var require_it = __commonJS({
  "node_modules/air-datepicker/locale/it.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;
    var _default = {
      days: ["Domenica", "Luned\xEC", "Marted\xEC", "Mercoled\xEC", "Gioved\xEC", "Venerd\xEC", "Sabato"],
      daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"],
      daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"],
      months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
      monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
      today: "Oggi",
      clear: "Cancella",
      dateFormat: "dd/MM/yyyy",
      timeFormat: "HH:mm",
      firstDay: 1
    };
    exports.default = _default;
  }
});

// node_modules/air-datepicker/locale/pt.js
var require_pt = __commonJS({
  "node_modules/air-datepicker/locale/pt.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;
    var _default = {
      days: ["Domingo", "Segunda", "Ter\xE7a", "Quarta", "Quinta", "Sexta", "S\xE1bado"],
      daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"],
      daysMin: ["Do", "Se", "Te", "Qa", "Qi", "Sx", "Sa"],
      months: ["Janeiro", "Fevereiro", "Mar\xE7o", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
      monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
      today: "Hoje",
      clear: "Limpar",
      dateFormat: "dd/MM/yyyy",
      timeFormat: "HH:mm",
      firstDay: 1
    };
    exports.default = _default;
  }
});

// node_modules/loglevel/lib/loglevel.js
var require_loglevel = __commonJS({
  "node_modules/loglevel/lib/loglevel.js"(exports, module) {
    (function(root3, definition) {
      "use strict";
      if (typeof define === "function" && define.amd) {
        define(definition);
      } else if (typeof module === "object" && module.exports) {
        module.exports = definition();
      } else {
        root3.log = definition();
      }
    })(exports, function() {
      "use strict";
      var noop5 = function() {
      };
      var undefinedType = "undefined";
      var isIE2 = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
      var logMethods = [
        "trace",
        "debug",
        "info",
        "warn",
        "error"
      ];
      var _loggersByName = {};
      var defaultLogger = null;
      function bindMethod(obj, methodName) {
        var method = obj[methodName];
        if (typeof method.bind === "function") {
          return method.bind(obj);
        } else {
          try {
            return Function.prototype.bind.call(method, obj);
          } catch (e3) {
            return function() {
              return Function.prototype.apply.apply(method, [obj, arguments]);
            };
          }
        }
      }
      function traceForIE() {
        if (console.log) {
          if (console.log.apply) {
            console.log.apply(console, arguments);
          } else {
            Function.prototype.apply.apply(console.log, [console, arguments]);
          }
        }
        if (console.trace) console.trace();
      }
      function realMethod(methodName) {
        if (methodName === "debug") {
          methodName = "log";
        }
        if (typeof console === undefinedType) {
          return false;
        } else if (methodName === "trace" && isIE2) {
          return traceForIE;
        } else if (console[methodName] !== void 0) {
          return bindMethod(console, methodName);
        } else if (console.log !== void 0) {
          return bindMethod(console, "log");
        } else {
          return noop5;
        }
      }
      function replaceLoggingMethods() {
        var level = this.getLevel();
        for (var i3 = 0; i3 < logMethods.length; i3++) {
          var methodName = logMethods[i3];
          this[methodName] = i3 < level ? noop5 : this.methodFactory(methodName, level, this.name);
        }
        this.log = this.debug;
        if (typeof console === undefinedType && level < this.levels.SILENT) {
          return "No console available for logging";
        }
      }
      function enableLoggingWhenConsoleArrives(methodName) {
        return function() {
          if (typeof console !== undefinedType) {
            replaceLoggingMethods.call(this);
            this[methodName].apply(this, arguments);
          }
        };
      }
      function defaultMethodFactory(methodName, _level, _loggerName) {
        return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
      }
      function Logger(name2, factory) {
        var self2 = this;
        var inheritedLevel;
        var defaultLevel;
        var userLevel;
        var storageKey = "loglevel";
        if (typeof name2 === "string") {
          storageKey += ":" + name2;
        } else if (typeof name2 === "symbol") {
          storageKey = void 0;
        }
        function persistLevelIfPossible(levelNum) {
          var levelName = (logMethods[levelNum] || "silent").toUpperCase();
          if (typeof window === undefinedType || !storageKey) return;
          try {
            window.localStorage[storageKey] = levelName;
            return;
          } catch (ignore) {
          }
          try {
            window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
          } catch (ignore) {
          }
        }
        function getPersistedLevel() {
          var storedLevel;
          if (typeof window === undefinedType || !storageKey) return;
          try {
            storedLevel = window.localStorage[storageKey];
          } catch (ignore) {
          }
          if (typeof storedLevel === undefinedType) {
            try {
              var cookie = window.document.cookie;
              var cookieName = encodeURIComponent(storageKey);
              var location2 = cookie.indexOf(cookieName + "=");
              if (location2 !== -1) {
                storedLevel = /^([^;]+)/.exec(
                  cookie.slice(location2 + cookieName.length + 1)
                )[1];
              }
            } catch (ignore) {
            }
          }
          if (self2.levels[storedLevel] === void 0) {
            storedLevel = void 0;
          }
          return storedLevel;
        }
        function clearPersistedLevel() {
          if (typeof window === undefinedType || !storageKey) return;
          try {
            window.localStorage.removeItem(storageKey);
          } catch (ignore) {
          }
          try {
            window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
          } catch (ignore) {
          }
        }
        function normalizeLevel(input) {
          var level = input;
          if (typeof level === "string" && self2.levels[level.toUpperCase()] !== void 0) {
            level = self2.levels[level.toUpperCase()];
          }
          if (typeof level === "number" && level >= 0 && level <= self2.levels.SILENT) {
            return level;
          } else {
            throw new TypeError("log.setLevel() called with invalid level: " + input);
          }
        }
        self2.name = name2;
        self2.levels = {
          "TRACE": 0,
          "DEBUG": 1,
          "INFO": 2,
          "WARN": 3,
          "ERROR": 4,
          "SILENT": 5
        };
        self2.methodFactory = factory || defaultMethodFactory;
        self2.getLevel = function() {
          if (userLevel != null) {
            return userLevel;
          } else if (defaultLevel != null) {
            return defaultLevel;
          } else {
            return inheritedLevel;
          }
        };
        self2.setLevel = function(level, persist) {
          userLevel = normalizeLevel(level);
          if (persist !== false) {
            persistLevelIfPossible(userLevel);
          }
          return replaceLoggingMethods.call(self2);
        };
        self2.setDefaultLevel = function(level) {
          defaultLevel = normalizeLevel(level);
          if (!getPersistedLevel()) {
            self2.setLevel(level, false);
          }
        };
        self2.resetLevel = function() {
          userLevel = null;
          clearPersistedLevel();
          replaceLoggingMethods.call(self2);
        };
        self2.enableAll = function(persist) {
          self2.setLevel(self2.levels.TRACE, persist);
        };
        self2.disableAll = function(persist) {
          self2.setLevel(self2.levels.SILENT, persist);
        };
        self2.rebuild = function() {
          if (defaultLogger !== self2) {
            inheritedLevel = normalizeLevel(defaultLogger.getLevel());
          }
          replaceLoggingMethods.call(self2);
          if (defaultLogger === self2) {
            for (var childName in _loggersByName) {
              _loggersByName[childName].rebuild();
            }
          }
        };
        inheritedLevel = normalizeLevel(
          defaultLogger ? defaultLogger.getLevel() : "WARN"
        );
        var initialLevel = getPersistedLevel();
        if (initialLevel != null) {
          userLevel = normalizeLevel(initialLevel);
        }
        replaceLoggingMethods.call(self2);
      }
      defaultLogger = new Logger();
      defaultLogger.getLogger = function getLogger(name2) {
        if (typeof name2 !== "symbol" && typeof name2 !== "string" || name2 === "") {
          throw new TypeError("You must supply a name when creating a logger.");
        }
        var logger = _loggersByName[name2];
        if (!logger) {
          logger = _loggersByName[name2] = new Logger(
            name2,
            defaultLogger.methodFactory
          );
        }
        return logger;
      };
      var _log = typeof window !== undefinedType ? window.log : void 0;
      defaultLogger.noConflict = function() {
        if (typeof window !== undefinedType && window.log === defaultLogger) {
          window.log = _log;
        }
        return defaultLogger;
      };
      defaultLogger.getLoggers = function getLoggers() {
        return _loggersByName;
      };
      defaultLogger["default"] = defaultLogger;
      return defaultLogger;
    });
  }
});

// node_modules/deepmerge/dist/cjs.js
var require_cjs = __commonJS({
  "node_modules/deepmerge/dist/cjs.js"(exports, module) {
    "use strict";
    var isMergeableObject = function isMergeableObject2(value2) {
      return isNonNullObject(value2) && !isSpecial(value2);
    };
    function isNonNullObject(value2) {
      return !!value2 && typeof value2 === "object";
    }
    function isSpecial(value2) {
      var stringValue = Object.prototype.toString.call(value2);
      return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value2);
    }
    var canUseSymbol = typeof Symbol === "function" && Symbol.for;
    var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103;
    function isReactElement(value2) {
      return value2.$$typeof === REACT_ELEMENT_TYPE;
    }
    function emptyTarget(val) {
      return Array.isArray(val) ? [] : {};
    }
    function cloneUnlessOtherwiseSpecified(value2, options2) {
      return options2.clone !== false && options2.isMergeableObject(value2) ? deepmerge2(emptyTarget(value2), value2, options2) : value2;
    }
    function defaultArrayMerge(target, source, options2) {
      return target.concat(source).map(function(element2) {
        return cloneUnlessOtherwiseSpecified(element2, options2);
      });
    }
    function getMergeFunction(key2, options2) {
      if (!options2.customMerge) {
        return deepmerge2;
      }
      var customMerge = options2.customMerge(key2);
      return typeof customMerge === "function" ? customMerge : deepmerge2;
    }
    function getEnumerableOwnPropertySymbols(target) {
      return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
        return Object.propertyIsEnumerable.call(target, symbol);
      }) : [];
    }
    function getKeys2(target) {
      return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
    }
    function propertyIsOnObject(object2, property2) {
      try {
        return property2 in object2;
      } catch (_5) {
        return false;
      }
    }
    function propertyIsUnsafe(target, key2) {
      return propertyIsOnObject(target, key2) && !(Object.hasOwnProperty.call(target, key2) && Object.propertyIsEnumerable.call(target, key2));
    }
    function mergeObject(target, source, options2) {
      var destination = {};
      if (options2.isMergeableObject(target)) {
        getKeys2(target).forEach(function(key2) {
          destination[key2] = cloneUnlessOtherwiseSpecified(target[key2], options2);
        });
      }
      getKeys2(source).forEach(function(key2) {
        if (propertyIsUnsafe(target, key2)) {
          return;
        }
        if (propertyIsOnObject(target, key2) && options2.isMergeableObject(source[key2])) {
          destination[key2] = getMergeFunction(key2, options2)(target[key2], source[key2], options2);
        } else {
          destination[key2] = cloneUnlessOtherwiseSpecified(source[key2], options2);
        }
      });
      return destination;
    }
    function deepmerge2(target, source, options2) {
      options2 = options2 || {};
      options2.arrayMerge = options2.arrayMerge || defaultArrayMerge;
      options2.isMergeableObject = options2.isMergeableObject || isMergeableObject;
      options2.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
      var sourceIsArray = Array.isArray(source);
      var targetIsArray = Array.isArray(target);
      var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
      if (!sourceAndTargetTypesMatch) {
        return cloneUnlessOtherwiseSpecified(source, options2);
      } else if (sourceIsArray) {
        return options2.arrayMerge(target, source, options2);
      } else {
        return mergeObject(target, source, options2);
      }
    }
    deepmerge2.all = function deepmergeAll(array, options2) {
      if (!Array.isArray(array)) {
        throw new Error("first argument should be an array");
      }
      return array.reduce(function(prev, next2) {
        return deepmerge2(prev, next2, options2);
      }, {});
    };
    var deepmerge_1 = deepmerge2;
    module.exports = deepmerge_1;
  }
});

// node_modules/@sagold/json-pointer/dist/jsonPointer.js
var require_jsonPointer = __commonJS({
  "node_modules/@sagold/json-pointer/dist/jsonPointer.js"(exports, module) {
    !function(e3, t3) {
      "object" == typeof exports && "object" == typeof module ? module.exports = t3() : "function" == typeof define && define.amd ? define("jsonPointer", [], t3) : "object" == typeof exports ? exports.jsonPointer = t3() : e3.jsonPointer = t3();
    }("undefined" != typeof self ? self : exports, () => (() => {
      "use strict";
      var e3 = { d: (t4, n5) => {
        for (var r4 in n5) e3.o(n5, r4) && !e3.o(t4, r4) && Object.defineProperty(t4, r4, { enumerable: true, get: n5[r4] });
      }, o: (e4, t4) => Object.prototype.hasOwnProperty.call(e4, t4), r: (e4) => {
        "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e4, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e4, "__esModule", { value: true });
      } }, t3 = {};
      function n4(e4) {
        return "#" === e4 || "" === e4 || Array.isArray(e4) && 0 === e4.length || false;
      }
      e3.r(t3), e3.d(t3, { default: () => S2, get: () => c3, isRoot: () => n4, join: () => _5, remove: () => j, removeUndefinedItems: () => v3, set: () => y3, split: () => s3, splitLast: () => x3 });
      const r3 = /~1/g, o3 = /~0/g, i3 = /\/+/g, l3 = /(^[#/]*|\/+$)/g;
      function u3(e4) {
        return e4.replace(r3, "/").replace(o3, "~");
      }
      function f3(e4) {
        return u3(decodeURIComponent(e4));
      }
      function s3(e4) {
        if (null == e4 || "string" != typeof e4 || n4(e4)) return Array.isArray(e4) ? e4 : [];
        const t4 = e4.indexOf("#") >= 0 ? f3 : u3, r4 = (e4 = (e4 = e4.replace(i3, "/")).replace(l3, "")).split("/");
        for (let e5 = 0, n5 = r4.length; e5 < n5; e5 += 1) r4[e5] = t4(r4[e5]);
        return r4;
      }
      function c3(e4, t4, r4 = void 0) {
        if (null == t4 || null == e4) return r4;
        if (n4(t4)) return e4;
        const o4 = p4(e4, s3(t4));
        return void 0 === o4 ? r4 : o4;
      }
      function p4(e4, t4) {
        const n5 = t4.shift();
        if (void 0 !== e4) return void 0 !== n5 ? p4(e4[n5], t4) : e4;
      }
      const a3 = /^\[.*\]$/, d3 = /^\[(.+)\]$/;
      function g3(e4, t4) {
        return "__proto__" === e4 || "constructor" == e4 && t4.length > 0 && "prototype" == t4[0];
      }
      function y3(e4, t4, n5) {
        if (null == t4) return e4;
        const r4 = s3(t4);
        if (0 === r4.length) return e4;
        null == e4 && (e4 = a3.test(r4[0]) ? [] : {});
        let o4, i4, l4 = e4;
        for (; r4.length > 1; ) o4 = r4.shift(), i4 = a3.test(r4[0]), g3(o4, r4) || (l4 = m3(l4, o4, i4));
        return o4 = r4.pop(), h3(l4, o4, n5), e4;
      }
      function h3(e4, t4, n5) {
        let r4;
        const o4 = t4.match(d3);
        "[]" === t4 && Array.isArray(e4) ? e4.push(n5) : o4 ? (r4 = o4.pop(), e4[r4] = n5) : e4[t4] = n5;
      }
      function m3(e4, t4, n5) {
        if (null != e4[t4]) return e4[t4];
        const r4 = n5 ? [] : {};
        return h3(e4, t4, r4), r4;
      }
      function v3(e4) {
        let t4 = 0, n5 = 0;
        for (; t4 + n5 < e4.length; ) void 0 === e4[t4 + n5] && (n5 += 1), e4[t4] = e4[t4 + n5], t4 += 1;
        return e4.length = e4.length - n5, e4;
      }
      function j(e4, t4, n5) {
        const r4 = s3(t4), o4 = r4.pop(), i4 = c3(e4, r4);
        return i4 && delete i4[o4], Array.isArray(i4) && true !== n5 && v3(i4), e4;
      }
      const b3 = /\/+/g, A4 = /~/g, P3 = /\//g;
      function O4(e4, t4) {
        if (0 === e4.length) return t4 ? "#" : "";
        for (let n5 = 0, r4 = e4.length; n5 < r4; n5 += 1) e4[n5] = e4[n5].replace(A4, "~0").replace(P3, "~1"), t4 && (e4[n5] = encodeURIComponent(e4[n5]));
        return ((t4 ? "#/" : "/") + e4.join("/")).replace(b3, "/");
      }
      function _5(e4, ...t4) {
        const n5 = [];
        if (Array.isArray(e4)) return O4(e4, true === arguments[1]);
        const r4 = arguments[arguments.length - 1], o4 = "boolean" == typeof r4 ? r4 : e4 && "#" === e4[0];
        for (let e5 = 0, t5 = arguments.length; e5 < t5; e5 += 1) n5.push.apply(n5, s3(arguments[e5]));
        const i4 = [];
        for (let e5 = 0, t5 = n5.length; e5 < t5; e5 += 1) if (".." === n5[e5]) {
          if (0 === i4.length) return o4 ? "#" : "";
          i4.pop();
        } else i4.push(n5[e5]);
        return O4(i4, o4);
      }
      function x3(e4) {
        const t4 = s3(e4);
        if (0 === t4.length) return "string" == typeof e4 && "#" === e4[0] ? ["#", t4[0]] : ["", void 0];
        if (1 === t4.length) return "#" === e4[0] ? ["#", t4[0]] : ["", t4[0]];
        const n5 = t4.pop();
        return [_5(t4, "#" === e4[0]), n5];
      }
      const S2 = { get: c3, set: y3, remove: j, join: _5, split: s3, splitLast: x3, isRoot: n4, removeUndefinedItems: v3 };
      return t3;
    })());
  }
});

// node_modules/ebnf/dist/TokenError.js
var require_TokenError = __commonJS({
  "node_modules/ebnf/dist/TokenError.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenError = void 0;
    var TokenError = class extends Error {
      constructor(message, token) {
        super(message);
        this.message = message;
        this.token = token;
        if (token && token.errors)
          token.errors.push(this);
        else
          throw this;
      }
      inspect() {
        return "SyntaxError: " + this.message;
      }
    };
    exports.TokenError = TokenError;
  }
});

// node_modules/ebnf/dist/Parser.js
var require_Parser = __commonJS({
  "node_modules/ebnf/dist/Parser.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Parser = exports.findRuleByName = exports.parseRuleName = exports.escapeRegExp = exports.readToken = void 0;
    var UPPER_SNAKE_RE = /^[A-Z0-9_]+$/;
    var decorationRE = /(\?|\+|\*)$/;
    var preDecorationRE = /^(@|&|!)/;
    var WS_RULE = "WS";
    var TokenError_1 = require_TokenError();
    function readToken2(txt, expr) {
      let result2 = expr.exec(txt);
      if (result2 && result2.index == 0) {
        if (result2[0].length == 0 && expr.source.length > 0)
          return null;
        return {
          type: null,
          text: result2[0],
          rest: txt.substr(result2[0].length),
          start: 0,
          end: result2[0].length - 1,
          fullText: result2[0],
          errors: [],
          children: [],
          parent: null
        };
      }
      return null;
    }
    exports.readToken = readToken2;
    function escapeRegExp2(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
    exports.escapeRegExp = escapeRegExp2;
    function fixRest(token) {
      token.rest = "";
      token.children && token.children.forEach((c3) => fixRest(c3));
    }
    function fixPositions(token, start) {
      token.start += start;
      token.end += start;
      token.children && token.children.forEach((c3) => fixPositions(c3, token.start));
    }
    function agregateErrors(errors3, token) {
      if (token.errors && token.errors.length)
        token.errors.forEach((err) => errors3.push(err));
      token.children && token.children.forEach((tok) => agregateErrors(errors3, tok));
    }
    function parseRuleName(name2) {
      let postDecoration = decorationRE.exec(name2);
      let preDecoration = preDecorationRE.exec(name2);
      let postDecorationText = postDecoration && postDecoration[0] || "";
      let preDecorationText = preDecoration && preDecoration[0] || "";
      let out = {
        raw: name2,
        name: name2.replace(decorationRE, "").replace(preDecorationRE, ""),
        isOptional: postDecorationText == "?" || postDecorationText == "*",
        allowRepetition: postDecorationText == "+" || postDecorationText == "*",
        atLeastOne: postDecorationText == "+",
        lookupPositive: preDecorationText == "&",
        lookupNegative: preDecorationText == "!",
        pinned: preDecorationText == "@",
        lookup: false,
        isLiteral: false
      };
      out.isLiteral = out.name[0] == "'" || out.name[0] == '"';
      out.lookup = out.lookupNegative || out.lookupPositive;
      return out;
    }
    exports.parseRuleName = parseRuleName;
    function findRuleByName(name2, parser4) {
      let parsed = parseRuleName(name2);
      return parser4.cachedRules[parsed.name] || null;
    }
    exports.findRuleByName = findRuleByName;
    function stripRules(token, re2) {
      if (token.children) {
        let localRules = token.children.filter((x3) => x3.type && re2.test(x3.type));
        for (let i3 = 0; i3 < localRules.length; i3++) {
          let indexOnChildren = token.children.indexOf(localRules[i3]);
          if (indexOnChildren != -1) {
            token.children.splice(indexOnChildren, 1);
          }
        }
        token.children.forEach((c3) => stripRules(c3, re2));
      }
    }
    var ignoreMissingRules = ["EOF"];
    var Parser4 = class {
      constructor(grammarRules, options2) {
        this.grammarRules = grammarRules;
        this.options = options2;
        this.cachedRules = {};
        this.debug = options2 ? options2.debug === true : false;
        let errors3 = [];
        let neededRules = [];
        grammarRules.forEach((rule) => {
          let parsedName = parseRuleName(rule.name);
          if (parsedName.name in this.cachedRules) {
            errors3.push("Duplicated rule " + parsedName.name);
            return;
          } else {
            this.cachedRules[parsedName.name] = rule;
          }
          if (!rule.bnf || !rule.bnf.length) {
            let error2 = "Missing rule content, rule: " + rule.name;
            if (errors3.indexOf(error2) == -1)
              errors3.push(error2);
          } else {
            rule.bnf.forEach((options3) => {
              if (typeof options3[0] === "string") {
                let parsed = parseRuleName(options3[0]);
                if (parsed.name == rule.name) {
                  let error2 = "Left recursion is not allowed, rule: " + rule.name;
                  if (errors3.indexOf(error2) == -1)
                    errors3.push(error2);
                }
              }
              options3.forEach((option2) => {
                if (typeof option2 == "string") {
                  let name2 = parseRuleName(option2);
                  if (!name2.isLiteral && neededRules.indexOf(name2.name) == -1 && ignoreMissingRules.indexOf(name2.name) == -1)
                    neededRules.push(name2.name);
                }
              });
            });
          }
          if (WS_RULE == rule.name)
            rule.implicitWs = false;
          if (rule.implicitWs) {
            if (neededRules.indexOf(WS_RULE) == -1)
              neededRules.push(WS_RULE);
          }
          if (rule.recover) {
            if (neededRules.indexOf(rule.recover) == -1)
              neededRules.push(rule.recover);
          }
        });
        neededRules.forEach((ruleName) => {
          if (!(ruleName in this.cachedRules)) {
            errors3.push("Missing rule " + ruleName);
          }
        });
        if (errors3.length)
          throw new Error(errors3.join("\n"));
      }
      getAST(txt, target) {
        if (!target) {
          target = this.grammarRules.filter((x3) => !x3.fragment && x3.name.indexOf("%") != 0)[0].name;
        }
        let result2 = this.parse(txt, target);
        if (result2) {
          agregateErrors(result2.errors, result2);
          fixPositions(result2, 0);
          stripRules(result2, /^%/);
          if (!this.options || !this.options.keepUpperRules)
            stripRules(result2, UPPER_SNAKE_RE);
          let rest2 = result2.rest;
          if (rest2) {
            new TokenError_1.TokenError("Unexpected end of input: \n" + rest2, result2);
          }
          fixRest(result2);
          result2.rest = rest2;
        }
        return result2;
      }
      emitSource() {
        return "CANNOT EMIT SOURCE FROM BASE Parser";
      }
      parse(txt, target, recursion = 0) {
        let out = null;
        let type = parseRuleName(target);
        let expr;
        let printable = this.debug && /*!isLiteral &*/
        !UPPER_SNAKE_RE.test(type.name);
        printable && console.log(new Array(recursion).join("\u2502  ") + "Trying to get " + target + " from " + JSON.stringify(txt.split("\n")[0]));
        let realType = type.name;
        let targetLex = findRuleByName(type.name, this);
        if (type.name == "EOF") {
          if (txt.length) {
            return null;
          } else if (txt.length == 0) {
            return {
              type: "EOF",
              text: "",
              rest: "",
              start: 0,
              end: 0,
              fullText: "",
              errors: [],
              children: [],
              parent: null
            };
          }
        }
        try {
          if (!targetLex && type.isLiteral) {
            let src = type.name.trim();
            if (src.startsWith('"')) {
              src = JSON.parse(src);
            } else if (src.startsWith("'")) {
              src = src.replace(/^'(.+)'$/, "$1").replace(/\\'/g, "'");
            }
            if (src === "") {
              return {
                type: "%%EMPTY%%",
                text: "",
                rest: txt,
                start: 0,
                end: 0,
                fullText: "",
                errors: [],
                children: [],
                parent: null
              };
            }
            expr = new RegExp(escapeRegExp2(src));
            realType = null;
          }
        } catch (e3) {
          if (e3 instanceof ReferenceError) {
            console.error(e3);
          }
          return null;
        }
        if (expr) {
          let result2 = readToken2(txt, expr);
          if (result2) {
            result2.type = realType;
            return result2;
          }
        } else {
          let options2 = targetLex.bnf;
          if (options2 instanceof Array) {
            options2.forEach((phases) => {
              if (out)
                return;
              let pinned = null;
              let tmp = {
                type: type.name,
                text: "",
                children: [],
                end: 0,
                errors: [],
                fullText: "",
                parent: null,
                start: 0,
                rest: txt
              };
              if (targetLex.fragment)
                tmp.fragment = true;
              let tmpTxt = txt;
              let position = 0;
              let allOptional = phases.length > 0;
              let foundSomething = false;
              for (let i3 = 0; i3 < phases.length; i3++) {
                if (typeof phases[i3] == "string") {
                  let localTarget = parseRuleName(phases[i3]);
                  allOptional = allOptional && localTarget.isOptional;
                  let got;
                  let foundAtLeastOne = false;
                  do {
                    got = null;
                    if (targetLex.implicitWs) {
                      got = this.parse(tmpTxt, localTarget.name, recursion + 1);
                      if (!got) {
                        let WS;
                        do {
                          WS = this.parse(tmpTxt, WS_RULE, recursion + 1);
                          if (WS) {
                            tmp.text = tmp.text + WS.text;
                            tmp.end = tmp.text.length;
                            WS.parent = tmp;
                            tmp.children.push(WS);
                            tmpTxt = tmpTxt.substr(WS.text.length);
                            position += WS.text.length;
                          } else {
                            break;
                          }
                        } while (WS && WS.text.length);
                      }
                    }
                    got = got || this.parse(tmpTxt, localTarget.name, recursion + 1);
                    if (localTarget.lookupNegative) {
                      if (got)
                        return;
                      break;
                    }
                    if (localTarget.lookupPositive) {
                      if (!got)
                        return;
                    }
                    if (!got) {
                      if (localTarget.isOptional)
                        break;
                      if (localTarget.atLeastOne && foundAtLeastOne)
                        break;
                    }
                    if (got && targetLex.pinned == i3 + 1) {
                      pinned = got;
                      printable && console.log(new Array(recursion + 1).join("\u2502  ") + "\u2514\u2500 " + got.type + " PINNED");
                    }
                    if (!got)
                      got = this.parseRecovery(targetLex, tmpTxt, recursion + 1);
                    if (!got) {
                      if (pinned) {
                        out = tmp;
                        got = {
                          type: "SyntaxError",
                          text: tmpTxt,
                          children: [],
                          end: tmpTxt.length,
                          errors: [],
                          fullText: "",
                          parent: null,
                          start: 0,
                          rest: ""
                        };
                        if (tmpTxt.length) {
                          new TokenError_1.TokenError(`Unexpected end of input. Expecting ${localTarget.name} Got: ${tmpTxt}`, got);
                        } else {
                          new TokenError_1.TokenError(`Unexpected end of input. Missing ${localTarget.name}`, got);
                        }
                        printable && console.log(new Array(recursion + 1).join("\u2502  ") + "\u2514\u2500 " + got.type + " " + JSON.stringify(got.text));
                      } else {
                        return;
                      }
                    }
                    foundAtLeastOne = true;
                    foundSomething = true;
                    if (got.type == "%%EMPTY%%") {
                      break;
                    }
                    got.start += position;
                    got.end += position;
                    if (!localTarget.lookupPositive && got.type) {
                      if (got.fragment) {
                        got.children && got.children.forEach((x3) => {
                          x3.start += position;
                          x3.end += position;
                          x3.parent = tmp;
                          tmp.children.push(x3);
                        });
                      } else {
                        got.parent = tmp;
                        tmp.children.push(got);
                      }
                    }
                    if (localTarget.lookup)
                      got.lookup = true;
                    printable && console.log(new Array(recursion + 1).join("\u2502  ") + "\u2514\u2500 " + got.type + " " + JSON.stringify(got.text));
                    if (!localTarget.lookup && !got.lookup) {
                      tmp.text = tmp.text + got.text;
                      tmp.end = tmp.text.length;
                      tmpTxt = tmpTxt.substr(got.text.length);
                      position += got.text.length;
                    }
                    tmp.rest = tmpTxt;
                  } while (got && localTarget.allowRepetition && tmpTxt.length && !got.lookup);
                } else {
                  let got = readToken2(tmpTxt, phases[i3]);
                  if (!got) {
                    return;
                  }
                  printable && console.log(new Array(recursion + 1).join("\u2502  ") + "\u2514> " + JSON.stringify(got.text) + phases[i3].source);
                  foundSomething = true;
                  got.start += position;
                  got.end += position;
                  tmp.text = tmp.text + got.text;
                  tmp.end = tmp.text.length;
                  tmpTxt = tmpTxt.substr(got.text.length);
                  position += got.text.length;
                  tmp.rest = tmpTxt;
                }
              }
              if (foundSomething) {
                out = tmp;
                printable && console.log(new Array(recursion).join("\u2502  ") + "\u251C<\u2500\u2534< PUSHING " + out.type + " " + JSON.stringify(out.text));
              }
            });
          }
          if (out && targetLex.simplifyWhenOneChildren && out.children.length == 1) {
            out = out.children[0];
          }
        }
        if (!out) {
          printable && console.log(target + " NOT RESOLVED FROM " + txt);
        }
        return out;
      }
      parseRecovery(recoverableToken, tmpTxt, recursion) {
        if (recoverableToken.recover && tmpTxt.length) {
          let printable = this.debug;
          printable && console.log(new Array(recursion + 1).join("\u2502  ") + "Trying to recover until token " + recoverableToken.recover + " from " + JSON.stringify(tmpTxt.split("\n")[0] + tmpTxt.split("\n")[1]));
          let tmp = {
            type: "SyntaxError",
            text: "",
            children: [],
            end: 0,
            errors: [],
            fullText: "",
            parent: null,
            start: 0,
            rest: ""
          };
          let got;
          do {
            got = this.parse(tmpTxt, recoverableToken.recover, recursion + 1);
            if (got) {
              new TokenError_1.TokenError('Unexpected input: "' + tmp.text + `" Expecting: ${recoverableToken.name}`, tmp);
              break;
            } else {
              tmp.text = tmp.text + tmpTxt[0];
              tmp.end = tmp.text.length;
              tmpTxt = tmpTxt.substr(1);
            }
          } while (!got && tmpTxt.length > 0);
          if (tmp.text.length > 0 && got) {
            printable && console.log(new Array(recursion + 1).join("\u2502  ") + "Recovered text: " + JSON.stringify(tmp.text));
            return tmp;
          }
        }
        return null;
      }
    };
    exports.Parser = Parser4;
    exports.default = Parser4;
  }
});

// node_modules/ebnf/dist/Grammars/W3CEBNF.js
var require_W3CEBNF = __commonJS({
  "node_modules/ebnf/dist/Grammars/W3CEBNF.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Parser_1 = require_Parser();
    var BNF;
    (function(BNF2) {
      BNF2.RULES = [
        {
          name: "Grammar",
          bnf: [["RULE_S*", "%Atomic*", "EOF"]]
        },
        {
          name: "%Atomic",
          bnf: [["Production", "RULE_S*"]],
          fragment: true
        },
        {
          name: "Production",
          bnf: [["NCName", "RULE_S*", '"::="', "RULE_WHITESPACE*", "Choice", "RULE_WHITESPACE*", "RULE_EOL+", "RULE_S*"]]
        },
        {
          name: "NCName",
          bnf: [[/[a-zA-Z][a-zA-Z_0-9]*/]]
        },
        {
          name: "Choice",
          bnf: [["SequenceOrDifference", "%_Choice_1*"]],
          fragment: true
        },
        {
          name: "%_Choice_1",
          bnf: [["RULE_WHITESPACE*", '"|"', "RULE_WHITESPACE*", "SequenceOrDifference"]],
          fragment: true
        },
        {
          name: "SequenceOrDifference",
          bnf: [["Item", "RULE_WHITESPACE*", "%_Item_1?"]]
        },
        {
          name: "%_Item_1",
          bnf: [["Minus", "Item"], ["Item*"]],
          fragment: true
        },
        {
          name: "Minus",
          bnf: [['"-"']]
        },
        {
          name: "Item",
          bnf: [["RULE_WHITESPACE*", "%Primary", "PrimaryDecoration?"]],
          fragment: true
        },
        {
          name: "PrimaryDecoration",
          bnf: [['"?"'], ['"*"'], ['"+"']]
        },
        {
          name: "DecorationName",
          bnf: [['"ebnf://"', /[^\x5D#]+/]]
        },
        {
          name: "%Primary",
          bnf: [["NCName"], ["StringLiteral"], ["CharCode"], ["CharClass"], ["SubItem"]],
          fragment: true
        },
        {
          name: "SubItem",
          bnf: [['"("', "RULE_WHITESPACE*", "Choice", "RULE_WHITESPACE*", '")"']]
        },
        {
          name: "StringLiteral",
          bnf: [[`'"'`, /[^"]*/, `'"'`], [`"'"`, /[^']*/, `"'"`]],
          pinned: 1
        },
        {
          name: "CharCode",
          bnf: [['"#x"', /[0-9a-zA-Z]+/]]
        },
        {
          name: "CharClass",
          bnf: [["'['", "'^'?", "%RULE_CharClass_1+", '"]"']]
        },
        {
          name: "%RULE_CharClass_1",
          bnf: [["CharCodeRange"], ["CharRange"], ["CharCode"], ["RULE_Char"]],
          fragment: true
        },
        {
          name: "RULE_Char",
          bnf: [[/\x09/], [/\x0A/], [/\x0D/], [/[\x20-\x5c]/], [/[\x5e-\uD7FF]/], [/[\uE000-\uFFFD]/]]
        },
        {
          name: "CharRange",
          bnf: [["RULE_Char", '"-"', "RULE_Char"]]
        },
        {
          name: "CharCodeRange",
          bnf: [["CharCode", '"-"', "CharCode"]]
        },
        {
          name: "RULE_WHITESPACE",
          bnf: [["%RULE_WHITESPACE_CHAR*"], ["Comment", "RULE_WHITESPACE*"]]
        },
        {
          name: "RULE_S",
          bnf: [["RULE_WHITESPACE", "RULE_S*"], ["RULE_EOL", "RULE_S*"]]
        },
        {
          name: "%RULE_WHITESPACE_CHAR",
          bnf: [[/\x09/], [/\x20/]],
          fragment: true
        },
        {
          name: "Comment",
          bnf: [['"/*"', "%RULE_Comment_Body*", '"*/"']]
        },
        {
          name: "%RULE_Comment_Body",
          bnf: [['!"*/"', /[^*]/]],
          fragment: true
        },
        {
          name: "RULE_EOL",
          bnf: [[/\x0D/, /\x0A/], [/\x0A/], [/\x0D/]]
        },
        {
          name: "Link",
          bnf: [["'['", "Url", "']'"]]
        },
        {
          name: "Url",
          bnf: [[/[^\x5D:/?#]/, '"://"', /[^\x5D#]+/, "%Url1?"]]
        },
        {
          name: "%Url1",
          bnf: [['"#"', "NCName"]],
          fragment: true
        }
      ];
      BNF2.defaultParser = new Parser_1.Parser(BNF2.RULES, { debug: false });
      const preDecorationRE = /^(!|&)/;
      const decorationRE = /(\?|\+|\*)$/;
      const subExpressionRE = /^%/;
      function getBNFRule(name2, parser4) {
        if (typeof name2 == "string") {
          if (preDecorationRE.test(name2))
            return "";
          let subexpression = subExpressionRE.test(name2);
          if (subexpression) {
            let decoration = decorationRE.exec(name2);
            let decorationText = decoration ? decoration[0] + " " : "";
            let lonely = isLonelyRule(name2, parser4);
            if (lonely)
              return getBNFBody(name2, parser4) + decorationText;
            return "(" + getBNFBody(name2, parser4) + ")" + decorationText;
          }
          return name2;
        } else {
          return name2.source.replace(/\\(?:x|u)([a-zA-Z0-9]+)/g, "#x$1").replace(/\[\\(?:x|u)([a-zA-Z0-9]+)-\\(?:x|u)([a-zA-Z0-9]+)\]/g, "[#x$1-#x$2]");
        }
      }
      function isLonelyRule(name2, parser4) {
        let rule = Parser_1.findRuleByName(name2, parser4);
        return rule && rule.bnf.length == 1 && rule.bnf[0].length == 1 && (rule.bnf[0][0] instanceof RegExp || rule.bnf[0][0][0] == '"' || rule.bnf[0][0][0] == "'");
      }
      function getBNFChoice(rules, parser4) {
        return rules.map((x3) => getBNFRule(x3, parser4)).join(" ");
      }
      function getBNFBody(name2, parser4) {
        let rule = Parser_1.findRuleByName(name2, parser4);
        if (rule)
          return rule.bnf.map((x3) => getBNFChoice(x3, parser4)).join(" | ");
        return "RULE_NOT_FOUND {" + name2 + "}";
      }
      function emit(parser4) {
        let acumulator = [];
        parser4.grammarRules.forEach((l3) => {
          if (!/^%/.test(l3.name)) {
            let recover = l3.recover ? " /* { recoverUntil=" + l3.recover + " } */" : "";
            acumulator.push(l3.name + " ::= " + getBNFBody(l3.name, parser4) + recover);
          }
        });
        return acumulator.join("\n");
      }
      BNF2.emit = emit;
      let subitems = 0;
      function restar(total, resta) {
        console.log("reberia restar " + resta + " a " + total);
        throw new Error("Difference not supported yet");
      }
      function convertRegex(txt) {
        return new RegExp(txt.replace(/#x([a-zA-Z0-9]{4})/g, "\\u$1").replace(/#x([a-zA-Z0-9]{3})/g, "\\u0$1").replace(/#x([a-zA-Z0-9]{2})/g, "\\x$1").replace(/#x([a-zA-Z0-9]{1})/g, "\\x0$1"));
      }
      function getSubItems(tmpRules, seq2, parentName) {
        let anterior = null;
        let bnfSeq = [];
        seq2.children.forEach((x3, i3) => {
          if (x3.type == "Minus") {
            restar(anterior, x3);
          } else {
          }
          let decoration = seq2.children[i3 + 1];
          decoration = decoration && decoration.type == "PrimaryDecoration" && decoration.text || "";
          let preDecoration = "";
          switch (x3.type) {
            case "SubItem":
              let name2 = "%" + (parentName + subitems++);
              createRule(tmpRules, x3, name2);
              bnfSeq.push(preDecoration + name2 + decoration);
              break;
            case "NCName":
            case "StringLiteral":
              bnfSeq.push(preDecoration + x3.text + decoration);
              break;
            case "CharCode":
            case "CharClass":
              if (decoration || preDecoration) {
                let newRule = {
                  name: "%" + (parentName + subitems++),
                  bnf: [[convertRegex(x3.text)]]
                };
                tmpRules.push(newRule);
                bnfSeq.push(preDecoration + newRule.name + decoration);
              } else {
                bnfSeq.push(convertRegex(x3.text));
              }
              break;
            case "PrimaryDecoration":
              break;
            default:
              throw new Error(" HOW SHOULD I PARSE THIS? " + x3.type + " -> " + JSON.stringify(x3.text));
          }
          anterior = x3;
        });
        return bnfSeq;
      }
      function createRule(tmpRules, token, name2) {
        let bnf = token.children.filter((x3) => x3.type == "SequenceOrDifference").map((s3) => getSubItems(tmpRules, s3, name2));
        let rule = {
          name: name2,
          bnf
        };
        let recover = null;
        bnf.forEach((x3) => {
          recover = recover || x3["recover"];
          delete x3["recover"];
        });
        if (name2.indexOf("%") == 0)
          rule.fragment = true;
        if (recover)
          rule.recover = recover;
        tmpRules.push(rule);
      }
      function getRules(source, parser4 = BNF2.defaultParser) {
        let ast = parser4.getAST(source);
        if (!ast)
          throw new Error("Could not parse " + source);
        if (ast.errors && ast.errors.length) {
          throw ast.errors[0];
        }
        let tmpRules = [];
        ast.children.filter((x3) => x3.type == "Production").map((x3) => {
          let name2 = x3.children.filter((x4) => x4.type == "NCName")[0].text;
          createRule(tmpRules, x3, name2);
        });
        return tmpRules;
      }
      BNF2.getRules = getRules;
      function Transform2(source, subParser = BNF2.defaultParser) {
        return getRules(source.join(""), subParser);
      }
      BNF2.Transform = Transform2;
      class Parser4 extends Parser_1.Parser {
        constructor(source, options2) {
          const subParser = options2 && options2.debugRulesParser === true ? new Parser_1.Parser(BNF2.RULES, { debug: true }) : BNF2.defaultParser;
          super(getRules(source, subParser), options2);
        }
        emitSource() {
          return emit(this);
        }
      }
      BNF2.Parser = Parser4;
    })(BNF || (BNF = {}));
    exports.default = BNF;
  }
});

// node_modules/valid-url/index.js
var require_valid_url = __commonJS({
  "node_modules/valid-url/index.js"(exports, module) {
    (function(module2) {
      "use strict";
      module2.exports.is_uri = is_iri;
      module2.exports.is_http_uri = is_http_iri;
      module2.exports.is_https_uri = is_https_iri;
      module2.exports.is_web_uri = is_web_iri;
      module2.exports.isUri = is_iri;
      module2.exports.isHttpUri = is_http_iri;
      module2.exports.isHttpsUri = is_https_iri;
      module2.exports.isWebUri = is_web_iri;
      var splitUri = function(uri) {
        var splitted = uri.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
        return splitted;
      };
      function is_iri(value2) {
        if (!value2) {
          return;
        }
        if (/[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i.test(value2)) return;
        if (/%[^0-9a-f]/i.test(value2)) return;
        if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value2)) return;
        var splitted = [];
        var scheme = "";
        var authority = "";
        var path = "";
        var query2 = "";
        var fragment = "";
        var out = "";
        splitted = splitUri(value2);
        scheme = splitted[1];
        authority = splitted[2];
        path = splitted[3];
        query2 = splitted[4];
        fragment = splitted[5];
        if (!(scheme && scheme.length && path.length >= 0)) return;
        if (authority && authority.length) {
          if (!(path.length === 0 || /^\//.test(path))) return;
        } else {
          if (/^\/\//.test(path)) return;
        }
        if (!/^[a-z][a-z0-9\+\-\.]*$/.test(scheme.toLowerCase())) return;
        out += scheme + ":";
        if (authority && authority.length) {
          out += "//" + authority;
        }
        out += path;
        if (query2 && query2.length) {
          out += "?" + query2;
        }
        if (fragment && fragment.length) {
          out += "#" + fragment;
        }
        return out;
      }
      function is_http_iri(value2, allowHttps) {
        if (!is_iri(value2)) {
          return;
        }
        var splitted = [];
        var scheme = "";
        var authority = "";
        var path = "";
        var port = "";
        var query2 = "";
        var fragment = "";
        var out = "";
        splitted = splitUri(value2);
        scheme = splitted[1];
        authority = splitted[2];
        path = splitted[3];
        query2 = splitted[4];
        fragment = splitted[5];
        if (!scheme) return;
        if (allowHttps) {
          if (scheme.toLowerCase() != "https") return;
        } else {
          if (scheme.toLowerCase() != "http") return;
        }
        if (!authority) {
          return;
        }
        if (/:(\d+)$/.test(authority)) {
          port = authority.match(/:(\d+)$/)[0];
          authority = authority.replace(/:\d+$/, "");
        }
        out += scheme + ":";
        out += "//" + authority;
        if (port) {
          out += port;
        }
        out += path;
        if (query2 && query2.length) {
          out += "?" + query2;
        }
        if (fragment && fragment.length) {
          out += "#" + fragment;
        }
        return out;
      }
      function is_https_iri(value2) {
        return is_http_iri(value2, true);
      }
      function is_web_iri(value2) {
        return is_http_iri(value2) || is_https_iri(value2);
      }
    })(module);
  }
});

// node_modules/nearley/lib/nearley.js
var require_nearley = __commonJS({
  "node_modules/nearley/lib/nearley.js"(exports, module) {
    (function(root3, factory) {
      if (typeof module === "object" && module.exports) {
        module.exports = factory();
      } else {
        root3.nearley = factory();
      }
    })(exports, function() {
      function Rule3(name2, symbols, postprocess) {
        this.id = ++Rule3.highestId;
        this.name = name2;
        this.symbols = symbols;
        this.postprocess = postprocess;
        return this;
      }
      Rule3.highestId = 0;
      Rule3.prototype.toString = function(withCursorAt) {
        var symbolSequence = typeof withCursorAt === "undefined" ? this.symbols.map(getSymbolShortDisplay).join(" ") : this.symbols.slice(0, withCursorAt).map(getSymbolShortDisplay).join(" ") + " \u25CF " + this.symbols.slice(withCursorAt).map(getSymbolShortDisplay).join(" ");
        return this.name + " \u2192 " + symbolSequence;
      };
      function State(rule, dot, reference2, wantedBy) {
        this.rule = rule;
        this.dot = dot;
        this.reference = reference2;
        this.data = [];
        this.wantedBy = wantedBy;
        this.isComplete = this.dot === rule.symbols.length;
      }
      State.prototype.toString = function() {
        return "{" + this.rule.toString(this.dot) + "}, from: " + (this.reference || 0);
      };
      State.prototype.nextState = function(child) {
        var state = new State(this.rule, this.dot + 1, this.reference, this.wantedBy);
        state.left = this;
        state.right = child;
        if (state.isComplete) {
          state.data = state.build();
          state.right = void 0;
        }
        return state;
      };
      State.prototype.build = function() {
        var children2 = [];
        var node = this;
        do {
          children2.push(node.right.data);
          node = node.left;
        } while (node.left);
        children2.reverse();
        return children2;
      };
      State.prototype.finish = function() {
        if (this.rule.postprocess) {
          this.data = this.rule.postprocess(this.data, this.reference, Parser4.fail);
        }
      };
      function Column(grammar, index2) {
        this.grammar = grammar;
        this.index = index2;
        this.states = [];
        this.wants = {};
        this.scannable = [];
        this.completed = {};
      }
      Column.prototype.process = function(nextColumn) {
        var states = this.states;
        var wants = this.wants;
        var completed = this.completed;
        for (var w3 = 0; w3 < states.length; w3++) {
          var state = states[w3];
          if (state.isComplete) {
            state.finish();
            if (state.data !== Parser4.fail) {
              var wantedBy = state.wantedBy;
              for (var i3 = wantedBy.length; i3--; ) {
                var left = wantedBy[i3];
                this.complete(left, state);
              }
              if (state.reference === this.index) {
                var exp = state.rule.name;
                (this.completed[exp] = this.completed[exp] || []).push(state);
              }
            }
          } else {
            var exp = state.rule.symbols[state.dot];
            if (typeof exp !== "string") {
              this.scannable.push(state);
              continue;
            }
            if (wants[exp]) {
              wants[exp].push(state);
              if (completed.hasOwnProperty(exp)) {
                var nulls = completed[exp];
                for (var i3 = 0; i3 < nulls.length; i3++) {
                  var right = nulls[i3];
                  this.complete(state, right);
                }
              }
            } else {
              wants[exp] = [state];
              this.predict(exp);
            }
          }
        }
      };
      Column.prototype.predict = function(exp) {
        var rules = this.grammar.byName[exp] || [];
        for (var i3 = 0; i3 < rules.length; i3++) {
          var r3 = rules[i3];
          var wantedBy = this.wants[exp];
          var s3 = new State(r3, 0, this.index, wantedBy);
          this.states.push(s3);
        }
      };
      Column.prototype.complete = function(left, right) {
        var copy2 = left.nextState(right);
        this.states.push(copy2);
      };
      function Grammar2(rules, start) {
        this.rules = rules;
        this.start = start || this.rules[0].name;
        var byName = this.byName = {};
        this.rules.forEach(function(rule) {
          if (!byName.hasOwnProperty(rule.name)) {
            byName[rule.name] = [];
          }
          byName[rule.name].push(rule);
        });
      }
      Grammar2.fromCompiled = function(rules, start) {
        var lexer2 = rules.Lexer;
        if (rules.ParserStart) {
          start = rules.ParserStart;
          rules = rules.ParserRules;
        }
        var rules = rules.map(function(r3) {
          return new Rule3(r3.name, r3.symbols, r3.postprocess);
        });
        var g3 = new Grammar2(rules, start);
        g3.lexer = lexer2;
        return g3;
      };
      function StreamLexer() {
        this.reset("");
      }
      StreamLexer.prototype.reset = function(data2, state) {
        this.buffer = data2;
        this.index = 0;
        this.line = state ? state.line : 1;
        this.lastLineBreak = state ? -state.col : 0;
      };
      StreamLexer.prototype.next = function() {
        if (this.index < this.buffer.length) {
          var ch = this.buffer[this.index++];
          if (ch === "\n") {
            this.line += 1;
            this.lastLineBreak = this.index;
          }
          return { value: ch };
        }
      };
      StreamLexer.prototype.save = function() {
        return {
          line: this.line,
          col: this.index - this.lastLineBreak
        };
      };
      StreamLexer.prototype.formatError = function(token, message) {
        var buffer = this.buffer;
        if (typeof buffer === "string") {
          var lines = buffer.split("\n").slice(
            Math.max(0, this.line - 5),
            this.line
          );
          var nextLineBreak = buffer.indexOf("\n", this.index);
          if (nextLineBreak === -1) nextLineBreak = buffer.length;
          var col = this.index - this.lastLineBreak;
          var lastLineDigits = String(this.line).length;
          message += " at line " + this.line + " col " + col + ":\n\n";
          message += lines.map(function(line, i3) {
            return pad(this.line - lines.length + i3 + 1, lastLineDigits) + " " + line;
          }, this).join("\n");
          message += "\n" + pad("", lastLineDigits + col) + "^\n";
          return message;
        } else {
          return message + " at index " + (this.index - 1);
        }
        function pad(n4, length) {
          var s3 = String(n4);
          return Array(length - s3.length + 1).join(" ") + s3;
        }
      };
      function Parser4(rules, start, options2) {
        if (rules instanceof Grammar2) {
          var grammar = rules;
          var options2 = start;
        } else {
          var grammar = Grammar2.fromCompiled(rules, start);
        }
        this.grammar = grammar;
        this.options = {
          keepHistory: false,
          lexer: grammar.lexer || new StreamLexer()
        };
        for (var key2 in options2 || {}) {
          this.options[key2] = options2[key2];
        }
        this.lexer = this.options.lexer;
        this.lexerState = void 0;
        var column = new Column(grammar, 0);
        var table2 = this.table = [column];
        column.wants[grammar.start] = [];
        column.predict(grammar.start);
        column.process();
        this.current = 0;
      }
      Parser4.fail = {};
      Parser4.prototype.feed = function(chunk2) {
        var lexer2 = this.lexer;
        lexer2.reset(chunk2, this.lexerState);
        var token;
        while (true) {
          try {
            token = lexer2.next();
            if (!token) {
              break;
            }
          } catch (e3) {
            var nextColumn = new Column(this.grammar, this.current + 1);
            this.table.push(nextColumn);
            var err = new Error(this.reportLexerError(e3));
            err.offset = this.current;
            err.token = e3.token;
            throw err;
          }
          var column = this.table[this.current];
          if (!this.options.keepHistory) {
            delete this.table[this.current - 1];
          }
          var n4 = this.current + 1;
          var nextColumn = new Column(this.grammar, n4);
          this.table.push(nextColumn);
          var literal2 = token.text !== void 0 ? token.text : token.value;
          var value2 = lexer2.constructor === StreamLexer ? token.value : token;
          var scannable = column.scannable;
          for (var w3 = scannable.length; w3--; ) {
            var state = scannable[w3];
            var expect = state.rule.symbols[state.dot];
            if (expect.test ? expect.test(value2) : expect.type ? expect.type === token.type : expect.literal === literal2) {
              var next2 = state.nextState({ data: value2, token, isToken: true, reference: n4 - 1 });
              nextColumn.states.push(next2);
            }
          }
          nextColumn.process();
          if (nextColumn.states.length === 0) {
            var err = new Error(this.reportError(token));
            err.offset = this.current;
            err.token = token;
            throw err;
          }
          if (this.options.keepHistory) {
            column.lexerState = lexer2.save();
          }
          this.current++;
        }
        if (column) {
          this.lexerState = lexer2.save();
        }
        this.results = this.finish();
        return this;
      };
      Parser4.prototype.reportLexerError = function(lexerError) {
        var tokenDisplay, lexerMessage;
        var token = lexerError.token;
        if (token) {
          tokenDisplay = "input " + JSON.stringify(token.text[0]) + " (lexer error)";
          lexerMessage = this.lexer.formatError(token, "Syntax error");
        } else {
          tokenDisplay = "input (lexer error)";
          lexerMessage = lexerError.message;
        }
        return this.reportErrorCommon(lexerMessage, tokenDisplay);
      };
      Parser4.prototype.reportError = function(token) {
        var tokenDisplay = (token.type ? token.type + " token: " : "") + JSON.stringify(token.value !== void 0 ? token.value : token);
        var lexerMessage = this.lexer.formatError(token, "Syntax error");
        return this.reportErrorCommon(lexerMessage, tokenDisplay);
      };
      Parser4.prototype.reportErrorCommon = function(lexerMessage, tokenDisplay) {
        var lines = [];
        lines.push(lexerMessage);
        var lastColumnIndex = this.table.length - 2;
        var lastColumn = this.table[lastColumnIndex];
        var expectantStates = lastColumn.states.filter(function(state) {
          var nextSymbol = state.rule.symbols[state.dot];
          return nextSymbol && typeof nextSymbol !== "string";
        });
        if (expectantStates.length === 0) {
          lines.push("Unexpected " + tokenDisplay + ". I did not expect any more input. Here is the state of my parse table:\n");
          this.displayStateStack(lastColumn.states, lines);
        } else {
          lines.push("Unexpected " + tokenDisplay + ". Instead, I was expecting to see one of the following:\n");
          var stateStacks = expectantStates.map(function(state) {
            return this.buildFirstStateStack(state, []) || [state];
          }, this);
          stateStacks.forEach(function(stateStack) {
            var state = stateStack[0];
            var nextSymbol = state.rule.symbols[state.dot];
            var symbolDisplay = this.getSymbolDisplay(nextSymbol);
            lines.push("A " + symbolDisplay + " based on:");
            this.displayStateStack(stateStack, lines);
          }, this);
        }
        lines.push("");
        return lines.join("\n");
      };
      Parser4.prototype.displayStateStack = function(stateStack, lines) {
        var lastDisplay;
        var sameDisplayCount = 0;
        for (var j = 0; j < stateStack.length; j++) {
          var state = stateStack[j];
          var display = state.rule.toString(state.dot);
          if (display === lastDisplay) {
            sameDisplayCount++;
          } else {
            if (sameDisplayCount > 0) {
              lines.push("    ^ " + sameDisplayCount + " more lines identical to this");
            }
            sameDisplayCount = 0;
            lines.push("    " + display);
          }
          lastDisplay = display;
        }
      };
      Parser4.prototype.getSymbolDisplay = function(symbol) {
        return getSymbolLongDisplay(symbol);
      };
      Parser4.prototype.buildFirstStateStack = function(state, visited) {
        if (visited.indexOf(state) !== -1) {
          return null;
        }
        if (state.wantedBy.length === 0) {
          return [state];
        }
        var prevState = state.wantedBy[0];
        var childVisited = [state].concat(visited);
        var childResult = this.buildFirstStateStack(prevState, childVisited);
        if (childResult === null) {
          return null;
        }
        return [state].concat(childResult);
      };
      Parser4.prototype.save = function() {
        var column = this.table[this.current];
        column.lexerState = this.lexerState;
        return column;
      };
      Parser4.prototype.restore = function(column) {
        var index2 = column.index;
        this.current = index2;
        this.table[index2] = column;
        this.table.splice(index2 + 1);
        this.lexerState = column.lexerState;
        this.results = this.finish();
      };
      Parser4.prototype.rewind = function(index2) {
        if (!this.options.keepHistory) {
          throw new Error("set option `keepHistory` to enable rewinding");
        }
        this.restore(this.table[index2]);
      };
      Parser4.prototype.finish = function() {
        var considerations = [];
        var start = this.grammar.start;
        var column = this.table[this.table.length - 1];
        column.states.forEach(function(t3) {
          if (t3.rule.name === start && t3.dot === t3.rule.symbols.length && t3.reference === 0 && t3.data !== Parser4.fail) {
            considerations.push(t3);
          }
        });
        return considerations.map(function(c3) {
          return c3.data;
        });
      };
      function getSymbolLongDisplay(symbol) {
        var type = typeof symbol;
        if (type === "string") {
          return symbol;
        } else if (type === "object") {
          if (symbol.literal) {
            return JSON.stringify(symbol.literal);
          } else if (symbol instanceof RegExp) {
            return "character matching " + symbol;
          } else if (symbol.type) {
            return symbol.type + " token";
          } else if (symbol.test) {
            return "token matching " + String(symbol.test);
          } else {
            throw new Error("Unknown symbol type: " + symbol);
          }
        }
      }
      function getSymbolShortDisplay(symbol) {
        var type = typeof symbol;
        if (type === "string") {
          return symbol;
        } else if (type === "object") {
          if (symbol.literal) {
            return JSON.stringify(symbol.literal);
          } else if (symbol instanceof RegExp) {
            return symbol.toString();
          } else if (symbol.type) {
            return "%" + symbol.type;
          } else if (symbol.test) {
            return "<" + String(symbol.test) + ">";
          } else {
            throw new Error("Unknown symbol type: " + symbol);
          }
        }
      }
      return {
        Parser: Parser4,
        Grammar: Grammar2,
        Rule: Rule3
      };
    });
  }
});

// node_modules/smtp-address-parser/dist/lib/grammar.js
var require_grammar = __commonJS({
  "node_modules/smtp-address-parser/dist/lib/grammar.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function id(d3) {
      return d3[0];
    }
    var deepFlatten = (arr) => [].concat(...arr.map((v3) => Array.isArray(v3) ? deepFlatten(v3) : v3));
    function flat_string(d3) {
      if (d3) {
        if (Array.isArray(d3))
          return deepFlatten(d3).join("");
        return d3;
      }
      return "";
    }
    var grammar = {
      Lexer: void 0,
      ParserRules: [
        { "name": "Reverse_path", "symbols": ["Path"] },
        { "name": "Reverse_path$string$1", "symbols": [{ "literal": "<" }, { "literal": ">" }], "postprocess": (d3) => d3.join("") },
        { "name": "Reverse_path", "symbols": ["Reverse_path$string$1"] },
        { "name": "Forward_path$subexpression$1$subexpression$1", "symbols": [{ "literal": "<" }, /[pP]/, /[oO]/, /[sS]/, /[tT]/, /[mM]/, /[aA]/, /[sS]/, /[tT]/, /[eE]/, /[rR]/, { "literal": "@" }], "postprocess": function(d3) {
          return d3.join("");
        } },
        { "name": "Forward_path$subexpression$1", "symbols": ["Forward_path$subexpression$1$subexpression$1", "Domain", { "literal": ">" }] },
        { "name": "Forward_path", "symbols": ["Forward_path$subexpression$1"] },
        { "name": "Forward_path$subexpression$2", "symbols": [{ "literal": "<" }, /[pP]/, /[oO]/, /[sS]/, /[tT]/, /[mM]/, /[aA]/, /[sS]/, /[tT]/, /[eE]/, /[rR]/, { "literal": ">" }], "postprocess": function(d3) {
          return d3.join("");
        } },
        { "name": "Forward_path", "symbols": ["Forward_path$subexpression$2"] },
        { "name": "Forward_path", "symbols": ["Path"] },
        { "name": "Path$ebnf$1$subexpression$1", "symbols": ["A_d_l", { "literal": ":" }] },
        { "name": "Path$ebnf$1", "symbols": ["Path$ebnf$1$subexpression$1"], "postprocess": id },
        { "name": "Path$ebnf$1", "symbols": [], "postprocess": () => null },
        { "name": "Path", "symbols": [{ "literal": "<" }, "Path$ebnf$1", "Mailbox", { "literal": ">" }] },
        { "name": "A_d_l$ebnf$1", "symbols": [] },
        { "name": "A_d_l$ebnf$1$subexpression$1", "symbols": [{ "literal": "," }, "At_domain"] },
        { "name": "A_d_l$ebnf$1", "symbols": ["A_d_l$ebnf$1", "A_d_l$ebnf$1$subexpression$1"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "A_d_l", "symbols": ["At_domain", "A_d_l$ebnf$1"] },
        { "name": "At_domain", "symbols": [{ "literal": "@" }, "Domain"] },
        { "name": "Domain$ebnf$1", "symbols": [] },
        { "name": "Domain$ebnf$1$subexpression$1", "symbols": [{ "literal": "." }, "sub_domain"] },
        { "name": "Domain$ebnf$1", "symbols": ["Domain$ebnf$1", "Domain$ebnf$1$subexpression$1"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "Domain", "symbols": ["sub_domain", "Domain$ebnf$1"] },
        { "name": "sub_domain", "symbols": ["U_label"] },
        { "name": "Let_dig", "symbols": ["ALPHA_DIGIT"], "postprocess": id },
        { "name": "Ldh_str$ebnf$1", "symbols": [] },
        { "name": "Ldh_str$ebnf$1", "symbols": ["Ldh_str$ebnf$1", "ALPHA_DIG_DASH"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "Ldh_str", "symbols": ["Ldh_str$ebnf$1", "Let_dig"] },
        { "name": "U_Let_dig", "symbols": ["ALPHA_DIGIT_U"], "postprocess": id },
        { "name": "U_Ldh_str$ebnf$1", "symbols": [] },
        { "name": "U_Ldh_str$ebnf$1", "symbols": ["U_Ldh_str$ebnf$1", "ALPHA_DIG_DASH_U"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "U_Ldh_str", "symbols": ["U_Ldh_str$ebnf$1", "U_Let_dig"] },
        { "name": "U_label$ebnf$1$subexpression$1", "symbols": ["U_Ldh_str"] },
        { "name": "U_label$ebnf$1", "symbols": ["U_label$ebnf$1$subexpression$1"], "postprocess": id },
        { "name": "U_label$ebnf$1", "symbols": [], "postprocess": () => null },
        { "name": "U_label", "symbols": ["U_Let_dig", "U_label$ebnf$1"] },
        { "name": "address_literal$subexpression$1", "symbols": ["IPv4_address_literal"] },
        { "name": "address_literal$subexpression$1", "symbols": ["IPv6_address_literal"] },
        { "name": "address_literal$subexpression$1", "symbols": ["General_address_literal"] },
        { "name": "address_literal", "symbols": [{ "literal": "[" }, "address_literal$subexpression$1", { "literal": "]" }] },
        {
          "name": "non_local_part",
          "symbols": ["Domain"],
          "postprocess": function(d3) {
            return { DomainName: flat_string(d3[0]) };
          }
        },
        {
          "name": "non_local_part",
          "symbols": ["address_literal"],
          "postprocess": function(d3) {
            return { AddressLiteral: flat_string(d3[0]) };
          }
        },
        {
          "name": "Mailbox",
          "symbols": ["Local_part", { "literal": "@" }, "non_local_part"],
          "postprocess": function(d3) {
            return { localPart: flat_string(d3[0]), domainPart: flat_string(d3[2]) };
          }
        },
        {
          "name": "Local_part",
          "symbols": ["Dot_string"],
          "postprocess": function(d3) {
            return { DotString: flat_string(d3[0]) };
          }
        },
        {
          "name": "Local_part",
          "symbols": ["Quoted_string"],
          "postprocess": function(d3) {
            return { QuotedString: flat_string(d3[0]) };
          }
        },
        { "name": "Dot_string$ebnf$1", "symbols": [] },
        { "name": "Dot_string$ebnf$1$subexpression$1", "symbols": [{ "literal": "." }, "Atom"] },
        { "name": "Dot_string$ebnf$1", "symbols": ["Dot_string$ebnf$1", "Dot_string$ebnf$1$subexpression$1"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "Dot_string", "symbols": ["Atom", "Dot_string$ebnf$1"] },
        { "name": "Atom$ebnf$1", "symbols": [/[0-9A-Za-z!#$%&'*+\-/=?^_`{|}~\u0080-\uFFFF/]/] },
        { "name": "Atom$ebnf$1", "symbols": ["Atom$ebnf$1", /[0-9A-Za-z!#$%&'*+\-/=?^_`{|}~\u0080-\uFFFF/]/], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "Atom", "symbols": ["Atom$ebnf$1"] },
        { "name": "Quoted_string$ebnf$1", "symbols": [] },
        { "name": "Quoted_string$ebnf$1", "symbols": ["Quoted_string$ebnf$1", "QcontentSMTP"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "Quoted_string", "symbols": ["DQUOTE", "Quoted_string$ebnf$1", "DQUOTE"] },
        { "name": "QcontentSMTP", "symbols": ["qtextSMTP"] },
        { "name": "QcontentSMTP", "symbols": ["quoted_pairSMTP"] },
        { "name": "quoted_pairSMTP", "symbols": [{ "literal": "\\" }, /[\x20-\x7e]/] },
        { "name": "qtextSMTP", "symbols": [/[\x20-\x21\x23-\x5b\x5d-\x7e\u0080-\uFFFF]/], "postprocess": id },
        { "name": "IPv4_address_literal$macrocall$2", "symbols": [{ "literal": "." }, "Snum"] },
        { "name": "IPv4_address_literal$macrocall$1", "symbols": ["IPv4_address_literal$macrocall$2", "IPv4_address_literal$macrocall$2", "IPv4_address_literal$macrocall$2"] },
        { "name": "IPv4_address_literal", "symbols": ["Snum", "IPv4_address_literal$macrocall$1"] },
        { "name": "IPv6_address_literal$subexpression$1", "symbols": [/[iI]/, /[pP]/, /[vV]/, { "literal": "6" }, { "literal": ":" }], "postprocess": function(d3) {
          return d3.join("");
        } },
        { "name": "IPv6_address_literal", "symbols": ["IPv6_address_literal$subexpression$1", "IPv6_addr"] },
        { "name": "General_address_literal$ebnf$1", "symbols": ["dcontent"] },
        { "name": "General_address_literal$ebnf$1", "symbols": ["General_address_literal$ebnf$1", "dcontent"], "postprocess": (d3) => d3[0].concat([d3[1]]) },
        { "name": "General_address_literal", "symbols": ["Standardized_tag", { "literal": ":" }, "General_address_literal$ebnf$1"] },
        { "name": "Standardized_tag", "symbols": ["Ldh_str"] },
        { "name": "dcontent", "symbols": [/[\x21-\x5a\x5e-\x7e]/], "postprocess": id },
        { "name": "Snum", "symbols": ["DIGIT"] },
        { "name": "Snum$subexpression$1", "symbols": [/[1-9]/, "DIGIT"] },
        { "name": "Snum", "symbols": ["Snum$subexpression$1"] },
        { "name": "Snum$subexpression$2", "symbols": [{ "literal": "1" }, "DIGIT", "DIGIT"] },
        { "name": "Snum", "symbols": ["Snum$subexpression$2"] },
        { "name": "Snum$subexpression$3", "symbols": [{ "literal": "2" }, /[0-4]/, "DIGIT"] },
        { "name": "Snum", "symbols": ["Snum$subexpression$3"] },
        { "name": "Snum$subexpression$4", "symbols": [{ "literal": "2" }, { "literal": "5" }, /[0-5]/] },
        { "name": "Snum", "symbols": ["Snum$subexpression$4"] },
        { "name": "IPv6_addr", "symbols": ["IPv6_full"] },
        { "name": "IPv6_addr", "symbols": ["IPv6_comp"] },
        { "name": "IPv6_addr", "symbols": ["IPv6v4_full"] },
        { "name": "IPv6_addr", "symbols": ["IPv6v4_comp"] },
        { "name": "IPv6_hex", "symbols": ["HEXDIG"] },
        { "name": "IPv6_hex$subexpression$1", "symbols": ["HEXDIG", "HEXDIG"] },
        { "name": "IPv6_hex", "symbols": ["IPv6_hex$subexpression$1"] },
        { "name": "IPv6_hex$subexpression$2", "symbols": ["HEXDIG", "HEXDIG", "HEXDIG"] },
        { "name": "IPv6_hex", "symbols": ["IPv6_hex$subexpression$2"] },
        { "name": "IPv6_hex$subexpression$3", "symbols": ["HEXDIG", "HEXDIG", "HEXDIG", "HEXDIG"] },
        { "name": "IPv6_hex", "symbols": ["IPv6_hex$subexpression$3"] },
        { "name": "IPv6_full$macrocall$2", "symbols": [{ "literal": ":" }, "IPv6_hex"] },
        { "name": "IPv6_full$macrocall$1", "symbols": ["IPv6_full$macrocall$2", "IPv6_full$macrocall$2", "IPv6_full$macrocall$2", "IPv6_full$macrocall$2", "IPv6_full$macrocall$2", "IPv6_full$macrocall$2", "IPv6_full$macrocall$2"] },
        { "name": "IPv6_full", "symbols": ["IPv6_hex", "IPv6_full$macrocall$1"] },
        { "name": "IPv6_comp$ebnf$1$subexpression$1$macrocall$2", "symbols": [{ "literal": ":" }, "IPv6_hex"] },
        { "name": "IPv6_comp$ebnf$1$subexpression$1$macrocall$1", "symbols": ["IPv6_comp$ebnf$1$subexpression$1$macrocall$2", "IPv6_comp$ebnf$1$subexpression$1$macrocall$2", "IPv6_comp$ebnf$1$subexpression$1$macrocall$2", "IPv6_comp$ebnf$1$subexpression$1$macrocall$2", "IPv6_comp$ebnf$1$subexpression$1$macrocall$2"] },
        { "name": "IPv6_comp$ebnf$1$subexpression$1", "symbols": ["IPv6_hex", "IPv6_comp$ebnf$1$subexpression$1$macrocall$1"] },
        { "name": "IPv6_comp$ebnf$1", "symbols": ["IPv6_comp$ebnf$1$subexpression$1"], "postprocess": id },
        { "name": "IPv6_comp$ebnf$1", "symbols": [], "postprocess": () => null },
        { "name": "IPv6_comp$string$1", "symbols": [{ "literal": ":" }, { "literal": ":" }], "postprocess": (d3) => d3.join("") },
        { "name": "IPv6_comp$ebnf$2$subexpression$1$macrocall$2", "symbols": [{ "literal": ":" }, "IPv6_hex"] },
        { "name": "IPv6_comp$ebnf$2$subexpression$1$macrocall$1", "symbols": ["IPv6_comp$ebnf$2$subexpression$1$macrocall$2", "IPv6_comp$ebnf$2$subexpression$1$macrocall$2", "IPv6_comp$ebnf$2$subexpression$1$macrocall$2", "IPv6_comp$ebnf$2$subexpression$1$macrocall$2", "IPv6_comp$ebnf$2$subexpression$1$macrocall$2"] },
        { "name": "IPv6_comp$ebnf$2$subexpression$1", "symbols": ["IPv6_hex", "IPv6_comp$ebnf$2$subexpression$1$macrocall$1"] },
        { "name": "IPv6_comp$ebnf$2", "symbols": ["IPv6_comp$ebnf$2$subexpression$1"], "postprocess": id },
        { "name": "IPv6_comp$ebnf$2", "symbols": [], "postprocess": () => null },
        { "name": "IPv6_comp", "symbols": ["IPv6_comp$ebnf$1", "IPv6_comp$string$1", "IPv6_comp$ebnf$2"] },
        { "name": "IPv6v4_full$macrocall$2", "symbols": [{ "literal": ":" }, "IPv6_hex"] },
        { "name": "IPv6v4_full$macrocall$1", "symbols": ["IPv6v4_full$macrocall$2", "IPv6v4_full$macrocall$2", "IPv6v4_full$macrocall$2", "IPv6v4_full$macrocall$2", "IPv6v4_full$macrocall$2"] },
        { "name": "IPv6v4_full", "symbols": ["IPv6_hex", "IPv6v4_full$macrocall$1", { "literal": ":" }, "IPv4_address_literal"] },
        { "name": "IPv6v4_comp$ebnf$1$subexpression$1$macrocall$2", "symbols": [{ "literal": ":" }, "IPv6_hex"] },
        { "name": "IPv6v4_comp$ebnf$1$subexpression$1$macrocall$1", "symbols": ["IPv6v4_comp$ebnf$1$subexpression$1$macrocall$2", "IPv6v4_comp$ebnf$1$subexpression$1$macrocall$2", "IPv6v4_comp$ebnf$1$subexpression$1$macrocall$2"] },
        { "name": "IPv6v4_comp$ebnf$1$subexpression$1", "symbols": ["IPv6_hex", "IPv6v4_comp$ebnf$1$subexpression$1$macrocall$1"] },
        { "name": "IPv6v4_comp$ebnf$1", "symbols": ["IPv6v4_comp$ebnf$1$subexpression$1"], "postprocess": id },
        { "name": "IPv6v4_comp$ebnf$1", "symbols": [], "postprocess": () => null },
        { "name": "IPv6v4_comp$string$1", "symbols": [{ "literal": ":" }, { "literal": ":" }], "postprocess": (d3) => d3.join("") },
        { "name": "IPv6v4_comp$ebnf$2$subexpression$1$macrocall$2", "symbols": [{ "literal": ":" }, "IPv6_hex"] },
        { "name": "IPv6v4_comp$ebnf$2$subexpression$1$macrocall$1", "symbols": ["IPv6v4_comp$ebnf$2$subexpression$1$macrocall$2", "IPv6v4_comp$ebnf$2$subexpression$1$macrocall$2", "IPv6v4_comp$ebnf$2$subexpression$1$macrocall$2"] },
        { "name": "IPv6v4_comp$ebnf$2$subexpression$1", "symbols": ["IPv6_hex", "IPv6v4_comp$ebnf$2$subexpression$1$macrocall$1", { "literal": ":" }] },
        { "name": "IPv6v4_comp$ebnf$2", "symbols": ["IPv6v4_comp$ebnf$2$subexpression$1"], "postprocess": id },
        { "name": "IPv6v4_comp$ebnf$2", "symbols": [], "postprocess": () => null },
        { "name": "IPv6v4_comp", "symbols": ["IPv6v4_comp$ebnf$1", "IPv6v4_comp$string$1", "IPv6v4_comp$ebnf$2", "IPv4_address_literal"] },
        { "name": "DIGIT", "symbols": [/[0-9]/], "postprocess": id },
        { "name": "ALPHA_DIGIT_U", "symbols": [/[0-9A-Za-z\u0080-\uFFFF]/], "postprocess": id },
        { "name": "ALPHA_DIGIT", "symbols": [/[0-9A-Za-z]/], "postprocess": id },
        { "name": "ALPHA_DIG_DASH", "symbols": [/[-0-9A-Za-z]/], "postprocess": id },
        { "name": "ALPHA_DIG_DASH_U", "symbols": [/[-0-9A-Za-z\u0080-\uFFFF]/], "postprocess": id },
        { "name": "HEXDIG", "symbols": [/[0-9A-Fa-f]/], "postprocess": id },
        { "name": "DQUOTE", "symbols": [{ "literal": '"' }], "postprocess": id }
      ],
      ParserStart: "Reverse_path"
    };
    exports.default = grammar;
  }
});

// node_modules/smtp-address-parser/dist/lib/index.js
var require_lib = __commonJS({
  "node_modules/smtp-address-parser/dist/lib/index.js"(exports) {
    "use strict";
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.canonicalize = exports.canonicalize_quoted_string = exports.normalize = exports.normalize_dot_string = exports.parse = void 0;
    var nearley = require_nearley();
    var grammar_1 = __importDefault(require_grammar());
    grammar_1.default.ParserStart = "Mailbox";
    var grammar = nearley.Grammar.fromCompiled(grammar_1.default);
    function parse4(address) {
      const parser4 = new nearley.Parser(grammar);
      parser4.feed(address);
      if (parser4.results.length !== 1) {
        throw new Error("address parsing failed: ambiguous grammar");
      }
      return parser4.results[0];
    }
    exports.parse = parse4;
    function normalize_dot_string(dot_string) {
      const tagless = function() {
        const plus_loc = dot_string.indexOf("+");
        if (plus_loc === -1) {
          return dot_string;
        }
        return dot_string.substr(0, plus_loc);
      }();
      const dotless = tagless.replace(/\./g, "");
      return dotless.toLowerCase();
    }
    exports.normalize_dot_string = normalize_dot_string;
    function normalize5(address) {
      var _a4, _b;
      const a3 = parse4(address);
      const domain2 = (_a4 = a3.domainPart.AddressLiteral) !== null && _a4 !== void 0 ? _a4 : a3.domainPart.DomainName.toLowerCase();
      const local = (_b = a3.localPart.QuotedString) !== null && _b !== void 0 ? _b : normalize_dot_string(a3.localPart.DotString);
      return `${local}@${domain2}`;
    }
    exports.normalize = normalize5;
    function canonicalize_quoted_string(quoted_string) {
      const unquoted2 = quoted_string.substr(1).substr(0, quoted_string.length - 2);
      const unescaped = unquoted2.replace(/(?:\\(.))/g, "$1");
      const reescaped = unescaped.replace(/(?:(["\\]))/g, "\\$1");
      return `"${reescaped}"`;
    }
    exports.canonicalize_quoted_string = canonicalize_quoted_string;
    function canonicalize(address) {
      var _a4;
      const a3 = parse4(address);
      const domain2 = (_a4 = a3.domainPart.AddressLiteral) !== null && _a4 !== void 0 ? _a4 : a3.domainPart.DomainName.toLowerCase();
      const local = a3.localPart.QuotedString ? canonicalize_quoted_string(a3.localPart.QuotedString) : a3.localPart.DotString;
      return `${local}@${domain2}`;
    }
    exports.canonicalize = canonicalize;
  }
});

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

// node_modules/@shikijs/themes/dist/vitesse-light.mjs
var vitesse_light_default;
var init_vitesse_light = __esm({
  "node_modules/@shikijs/themes/dist/vitesse-light.mjs"() {
    vitesse_light_default = Object.freeze(JSON.parse('{"colors":{"activityBar.activeBorder":"#1c6b48","activityBar.background":"#ffffff","activityBar.border":"#f0f0f0","activityBar.foreground":"#393a34","activityBar.inactiveForeground":"#393a3450","activityBarBadge.background":"#4e4f47","activityBarBadge.foreground":"#ffffff","badge.background":"#393a3490","badge.foreground":"#ffffff","breadcrumb.activeSelectionForeground":"#22222218","breadcrumb.background":"#f7f7f7","breadcrumb.focusForeground":"#393a34","breadcrumb.foreground":"#6a737d","breadcrumbPicker.background":"#ffffff","button.background":"#1c6b48","button.foreground":"#ffffff","button.hoverBackground":"#1c6b48","checkbox.background":"#f7f7f7","checkbox.border":"#d1d5da","debugToolBar.background":"#ffffff","descriptionForeground":"#393a3490","diffEditor.insertedTextBackground":"#1c6b4830","diffEditor.removedTextBackground":"#ab595940","dropdown.background":"#ffffff","dropdown.border":"#f0f0f0","dropdown.foreground":"#393a34","dropdown.listBackground":"#f7f7f7","editor.background":"#ffffff","editor.findMatchBackground":"#e6cc7744","editor.findMatchHighlightBackground":"#e6cc7766","editor.focusedStackFrameHighlightBackground":"#fff5b1","editor.foldBackground":"#22222210","editor.foreground":"#393a34","editor.inactiveSelectionBackground":"#22222210","editor.lineHighlightBackground":"#f7f7f7","editor.selectionBackground":"#22222218","editor.selectionHighlightBackground":"#22222210","editor.stackFrameHighlightBackground":"#fffbdd","editor.wordHighlightBackground":"#1c6b4805","editor.wordHighlightStrongBackground":"#1c6b4810","editorBracketHighlight.foreground1":"#2993a3","editorBracketHighlight.foreground2":"#1e754f","editorBracketHighlight.foreground3":"#a65e2b","editorBracketHighlight.foreground4":"#a13865","editorBracketHighlight.foreground5":"#bda437","editorBracketHighlight.foreground6":"#296aa3","editorBracketMatch.background":"#1c6b4820","editorError.foreground":"#ab5959","editorGroup.border":"#f0f0f0","editorGroupHeader.tabsBackground":"#ffffff","editorGroupHeader.tabsBorder":"#f0f0f0","editorGutter.addedBackground":"#1e754f","editorGutter.commentRangeForeground":"#393a3450","editorGutter.deletedBackground":"#ab5959","editorGutter.foldingControlForeground":"#393a3490","editorGutter.modifiedBackground":"#296aa3","editorHint.foreground":"#1e754f","editorIndentGuide.activeBackground":"#00000030","editorIndentGuide.background":"#00000015","editorInfo.foreground":"#296aa3","editorInlayHint.background":"#f7f7f7","editorInlayHint.foreground":"#999999","editorLineNumber.activeForeground":"#4e4f47","editorLineNumber.foreground":"#393a3450","editorOverviewRuler.border":"#fff","editorStickyScroll.background":"#f7f7f7","editorStickyScrollHover.background":"#f7f7f7","editorWarning.foreground":"#a65e2b","editorWhitespace.foreground":"#00000015","editorWidget.background":"#ffffff","errorForeground":"#ab5959","focusBorder":"#00000000","foreground":"#393a34","gitDecoration.addedResourceForeground":"#1e754f","gitDecoration.conflictingResourceForeground":"#a65e2b","gitDecoration.deletedResourceForeground":"#ab5959","gitDecoration.ignoredResourceForeground":"#393a3450","gitDecoration.modifiedResourceForeground":"#296aa3","gitDecoration.submoduleResourceForeground":"#393a3490","gitDecoration.untrackedResourceForeground":"#2993a3","input.background":"#f7f7f7","input.border":"#f0f0f0","input.foreground":"#393a34","input.placeholderForeground":"#393a3490","inputOption.activeBackground":"#393a3450","list.activeSelectionBackground":"#f7f7f7","list.activeSelectionForeground":"#393a34","list.focusBackground":"#f7f7f7","list.highlightForeground":"#1c6b48","list.hoverBackground":"#f7f7f7","list.hoverForeground":"#393a34","list.inactiveFocusBackground":"#ffffff","list.inactiveSelectionBackground":"#f7f7f7","list.inactiveSelectionForeground":"#393a34","menu.separatorBackground":"#f0f0f0","notificationCenterHeader.background":"#ffffff","notificationCenterHeader.foreground":"#6a737d","notifications.background":"#ffffff","notifications.border":"#f0f0f0","notifications.foreground":"#393a34","notificationsErrorIcon.foreground":"#ab5959","notificationsInfoIcon.foreground":"#296aa3","notificationsWarningIcon.foreground":"#a65e2b","panel.background":"#ffffff","panel.border":"#f0f0f0","panelInput.border":"#e1e4e8","panelTitle.activeBorder":"#1c6b48","panelTitle.activeForeground":"#393a34","panelTitle.inactiveForeground":"#6a737d","peekViewEditor.background":"#ffffff","peekViewResult.background":"#ffffff","pickerGroup.border":"#f0f0f0","pickerGroup.foreground":"#393a34","problemsErrorIcon.foreground":"#ab5959","problemsInfoIcon.foreground":"#296aa3","problemsWarningIcon.foreground":"#a65e2b","progressBar.background":"#1c6b48","quickInput.background":"#ffffff","quickInput.foreground":"#393a34","quickInputList.focusBackground":"#f7f7f7","scrollbar.shadow":"#6a737d33","scrollbarSlider.activeBackground":"#393a3450","scrollbarSlider.background":"#393a3410","scrollbarSlider.hoverBackground":"#393a3450","settings.headerForeground":"#393a34","settings.modifiedItemIndicator":"#1c6b48","sideBar.background":"#ffffff","sideBar.border":"#f0f0f0","sideBar.foreground":"#4e4f47","sideBarSectionHeader.background":"#ffffff","sideBarSectionHeader.border":"#f0f0f0","sideBarSectionHeader.foreground":"#393a34","sideBarTitle.foreground":"#393a34","statusBar.background":"#ffffff","statusBar.border":"#f0f0f0","statusBar.debuggingBackground":"#f7f7f7","statusBar.debuggingForeground":"#4e4f47","statusBar.foreground":"#4e4f47","statusBar.noFolderBackground":"#ffffff","statusBarItem.prominentBackground":"#f7f7f7","tab.activeBackground":"#ffffff","tab.activeBorder":"#f0f0f0","tab.activeBorderTop":"#393a3490","tab.activeForeground":"#393a34","tab.border":"#f0f0f0","tab.hoverBackground":"#f7f7f7","tab.inactiveBackground":"#ffffff","tab.inactiveForeground":"#6a737d","tab.unfocusedActiveBorder":"#f0f0f0","tab.unfocusedActiveBorderTop":"#f0f0f0","tab.unfocusedHoverBackground":"#ffffff","terminal.ansiBlack":"#121212","terminal.ansiBlue":"#296aa3","terminal.ansiBrightBlack":"#aaaaaa","terminal.ansiBrightBlue":"#296aa3","terminal.ansiBrightCyan":"#2993a3","terminal.ansiBrightGreen":"#1e754f","terminal.ansiBrightMagenta":"#a13865","terminal.ansiBrightRed":"#ab5959","terminal.ansiBrightWhite":"#dddddd","terminal.ansiBrightYellow":"#bda437","terminal.ansiCyan":"#2993a3","terminal.ansiGreen":"#1e754f","terminal.ansiMagenta":"#a13865","terminal.ansiRed":"#ab5959","terminal.ansiWhite":"#dbd7ca","terminal.ansiYellow":"#bda437","terminal.foreground":"#393a34","terminal.selectionBackground":"#22222218","textBlockQuote.background":"#ffffff","textBlockQuote.border":"#f0f0f0","textCodeBlock.background":"#ffffff","textLink.activeForeground":"#1c6b48","textLink.foreground":"#1c6b48","textPreformat.foreground":"#586069","textSeparator.foreground":"#d1d5da","titleBar.activeBackground":"#ffffff","titleBar.activeForeground":"#4e4f47","titleBar.border":"#f7f7f7","titleBar.inactiveBackground":"#ffffff","titleBar.inactiveForeground":"#6a737d","tree.indentGuidesStroke":"#e1e4e8","welcomePage.buttonBackground":"#f6f8fa","welcomePage.buttonHoverBackground":"#e1e4e8"},"displayName":"Vitesse Light","name":"vitesse-light","semanticHighlighting":true,"semanticTokenColors":{"class":"#5a6aa6","interface":"#2e808f","namespace":"#b05a78","property":"#998418","type":"#2e808f"},"tokenColors":[{"scope":["comment","punctuation.definition.comment","string.comment"],"settings":{"foreground":"#a0ada0"}},{"scope":["delimiter.bracket","delimiter","invalid.illegal.character-not-allowed-here.html","keyword.operator.rest","keyword.operator.spread","keyword.operator.type.annotation","keyword.operator.relational","keyword.operator.assignment","keyword.operator.type","meta.brace","meta.tag.block.any.html","meta.tag.inline.any.html","meta.tag.structure.input.void.html","meta.type.annotation","meta.embedded.block.github-actions-expression","storage.type.function.arrow","meta.objectliteral.ts","punctuation","punctuation.definition.string.begin.html.vue","punctuation.definition.string.end.html.vue"],"settings":{"foreground":"#999999"}},{"scope":["constant","entity.name.constant","variable.language","meta.definition.variable"],"settings":{"foreground":"#a65e2b"}},{"scope":["entity","entity.name"],"settings":{"foreground":"#59873a"}},{"scope":"variable.parameter.function","settings":{"foreground":"#393a34"}},{"scope":["entity.name.tag","tag.html"],"settings":{"foreground":"#1e754f"}},{"scope":"entity.name.function","settings":{"foreground":"#59873a"}},{"scope":["keyword","storage.type.class.jsdoc","punctuation.definition.template-expression"],"settings":{"foreground":"#1e754f"}},{"scope":["storage","storage.type","support.type.builtin","constant.language.undefined","constant.language.null","constant.language.import-export-all.ts"],"settings":{"foreground":"#ab5959"}},{"scope":["text.html.derivative","storage.modifier.package","storage.modifier.import","storage.type.java"],"settings":{"foreground":"#393a34"}},{"scope":["string","string punctuation.section.embedded source","attribute.value"],"settings":{"foreground":"#b56959"}},{"scope":["punctuation.definition.string"],"settings":{"foreground":"#b5695977"}},{"scope":["punctuation.support.type.property-name"],"settings":{"foreground":"#99841877"}},{"scope":"support","settings":{"foreground":"#998418"}},{"scope":["property","meta.property-name","meta.object-literal.key","entity.name.tag.yaml","attribute.name"],"settings":{"foreground":"#998418"}},{"scope":["entity.other.attribute-name","invalid.deprecated.entity.other.attribute-name.html"],"settings":{"foreground":"#b07d48"}},{"scope":["variable","identifier"],"settings":{"foreground":"#b07d48"}},{"scope":["support.type.primitive","entity.name.type"],"settings":{"foreground":"#2e8f82"}},{"scope":"namespace","settings":{"foreground":"#b05a78"}},{"scope":["keyword.operator","keyword.operator.assignment.compound","meta.var.expr.ts"],"settings":{"foreground":"#ab5959"}},{"scope":"invalid.broken","settings":{"fontStyle":"italic","foreground":"#b31d28"}},{"scope":"invalid.deprecated","settings":{"fontStyle":"italic","foreground":"#b31d28"}},{"scope":"invalid.illegal","settings":{"fontStyle":"italic","foreground":"#b31d28"}},{"scope":"invalid.unimplemented","settings":{"fontStyle":"italic","foreground":"#b31d28"}},{"scope":"carriage-return","settings":{"background":"#d73a49","content":"^M","fontStyle":"italic underline","foreground":"#fafbfc"}},{"scope":"message.error","settings":{"foreground":"#b31d28"}},{"scope":"string variable","settings":{"foreground":"#b56959"}},{"scope":["source.regexp","string.regexp"],"settings":{"foreground":"#ab5e3f"}},{"scope":["string.regexp.character-class","string.regexp constant.character.escape","string.regexp source.ruby.embedded","string.regexp string.regexp.arbitrary-repitition"],"settings":{"foreground":"#b56959"}},{"scope":"string.regexp constant.character.escape","settings":{"foreground":"#bda437"}},{"scope":["support.constant"],"settings":{"foreground":"#a65e2b"}},{"scope":["keyword.operator.quantifier.regexp","constant.numeric","number"],"settings":{"foreground":"#2f798a"}},{"scope":["keyword.other.unit"],"settings":{"foreground":"#ab5959"}},{"scope":["constant.language.boolean","constant.language"],"settings":{"foreground":"#1e754f"}},{"scope":"meta.module-reference","settings":{"foreground":"#1c6b48"}},{"scope":"punctuation.definition.list.begin.markdown","settings":{"foreground":"#a65e2b"}},{"scope":["markup.heading","markup.heading entity.name"],"settings":{"fontStyle":"bold","foreground":"#1c6b48"}},{"scope":"markup.quote","settings":{"foreground":"#2e808f"}},{"scope":"markup.italic","settings":{"fontStyle":"italic","foreground":"#393a34"}},{"scope":"markup.bold","settings":{"fontStyle":"bold","foreground":"#393a34"}},{"scope":"markup.raw","settings":{"foreground":"#1c6b48"}},{"scope":["markup.deleted","meta.diff.header.from-file","punctuation.definition.deleted"],"settings":{"background":"#ffeef0","foreground":"#b31d28"}},{"scope":["markup.inserted","meta.diff.header.to-file","punctuation.definition.inserted"],"settings":{"background":"#f0fff4","foreground":"#22863a"}},{"scope":["markup.changed","punctuation.definition.changed"],"settings":{"background":"#ffebda","foreground":"#e36209"}},{"scope":["markup.ignored","markup.untracked"],"settings":{"background":"#005cc5","foreground":"#f6f8fa"}},{"scope":"meta.diff.range","settings":{"fontStyle":"bold","foreground":"#6f42c1"}},{"scope":"meta.diff.header","settings":{"foreground":"#005cc5"}},{"scope":"meta.separator","settings":{"fontStyle":"bold","foreground":"#005cc5"}},{"scope":"meta.output","settings":{"foreground":"#005cc5"}},{"scope":["brackethighlighter.tag","brackethighlighter.curly","brackethighlighter.round","brackethighlighter.square","brackethighlighter.angle","brackethighlighter.quote"],"settings":{"foreground":"#586069"}},{"scope":"brackethighlighter.unmatched","settings":{"foreground":"#b31d28"}},{"scope":["constant.other.reference.link","string.other.link","punctuation.definition.string.begin.markdown","punctuation.definition.string.end.markdown"],"settings":{"foreground":"#b56959"}},{"scope":["markup.underline.link.markdown","markup.underline.link.image.markdown"],"settings":{"fontStyle":"underline","foreground":"#393a3490"}},{"scope":["type.identifier","constant.other.character-class.regexp"],"settings":{"foreground":"#5a6aa6"}},{"scope":["entity.other.attribute-name.html.vue"],"settings":{"foreground":"#59873a"}},{"scope":["invalid.illegal.unrecognized-tag.html"],"settings":{"fontStyle":"normal"}}],"type":"light"}'));
  }
});

// node_modules/shiki/dist/themes/vitesse-light.mjs
var vitesse_light_exports = {};
__export(vitesse_light_exports, {
  default: () => vitesse_light_default
});
var init_vitesse_light2 = __esm({
  "node_modules/shiki/dist/themes/vitesse-light.mjs"() {
    init_vitesse_light();
  }
});

// node_modules/@shikijs/themes/dist/vitesse-dark.mjs
var vitesse_dark_default;
var init_vitesse_dark = __esm({
  "node_modules/@shikijs/themes/dist/vitesse-dark.mjs"() {
    vitesse_dark_default = Object.freeze(JSON.parse('{"colors":{"activityBar.activeBorder":"#4d9375","activityBar.background":"#121212","activityBar.border":"#191919","activityBar.foreground":"#dbd7caee","activityBar.inactiveForeground":"#dedcd550","activityBarBadge.background":"#bfbaaa","activityBarBadge.foreground":"#121212","badge.background":"#dedcd590","badge.foreground":"#121212","breadcrumb.activeSelectionForeground":"#eeeeee18","breadcrumb.background":"#181818","breadcrumb.focusForeground":"#dbd7caee","breadcrumb.foreground":"#959da5","breadcrumbPicker.background":"#121212","button.background":"#4d9375","button.foreground":"#121212","button.hoverBackground":"#4d9375","checkbox.background":"#181818","checkbox.border":"#2f363d","debugToolBar.background":"#121212","descriptionForeground":"#dedcd590","diffEditor.insertedTextBackground":"#4d937550","diffEditor.removedTextBackground":"#ab595950","dropdown.background":"#121212","dropdown.border":"#191919","dropdown.foreground":"#dbd7caee","dropdown.listBackground":"#181818","editor.background":"#121212","editor.findMatchBackground":"#e6cc7722","editor.findMatchHighlightBackground":"#e6cc7744","editor.focusedStackFrameHighlightBackground":"#b808","editor.foldBackground":"#eeeeee10","editor.foreground":"#dbd7caee","editor.inactiveSelectionBackground":"#eeeeee10","editor.lineHighlightBackground":"#181818","editor.selectionBackground":"#eeeeee18","editor.selectionHighlightBackground":"#eeeeee10","editor.stackFrameHighlightBackground":"#a707","editor.wordHighlightBackground":"#1c6b4805","editor.wordHighlightStrongBackground":"#1c6b4810","editorBracketHighlight.foreground1":"#5eaab5","editorBracketHighlight.foreground2":"#4d9375","editorBracketHighlight.foreground3":"#d4976c","editorBracketHighlight.foreground4":"#d9739f","editorBracketHighlight.foreground5":"#e6cc77","editorBracketHighlight.foreground6":"#6394bf","editorBracketMatch.background":"#4d937520","editorError.foreground":"#cb7676","editorGroup.border":"#191919","editorGroupHeader.tabsBackground":"#121212","editorGroupHeader.tabsBorder":"#191919","editorGutter.addedBackground":"#4d9375","editorGutter.commentRangeForeground":"#dedcd550","editorGutter.deletedBackground":"#cb7676","editorGutter.foldingControlForeground":"#dedcd590","editorGutter.modifiedBackground":"#6394bf","editorHint.foreground":"#4d9375","editorIndentGuide.activeBackground":"#ffffff30","editorIndentGuide.background":"#ffffff15","editorInfo.foreground":"#6394bf","editorInlayHint.background":"#181818","editorInlayHint.foreground":"#666666","editorLineNumber.activeForeground":"#bfbaaa","editorLineNumber.foreground":"#dedcd550","editorOverviewRuler.border":"#111","editorStickyScroll.background":"#181818","editorStickyScrollHover.background":"#181818","editorWarning.foreground":"#d4976c","editorWhitespace.foreground":"#ffffff15","editorWidget.background":"#121212","errorForeground":"#cb7676","focusBorder":"#00000000","foreground":"#dbd7caee","gitDecoration.addedResourceForeground":"#4d9375","gitDecoration.conflictingResourceForeground":"#d4976c","gitDecoration.deletedResourceForeground":"#cb7676","gitDecoration.ignoredResourceForeground":"#dedcd550","gitDecoration.modifiedResourceForeground":"#6394bf","gitDecoration.submoduleResourceForeground":"#dedcd590","gitDecoration.untrackedResourceForeground":"#5eaab5","input.background":"#181818","input.border":"#191919","input.foreground":"#dbd7caee","input.placeholderForeground":"#dedcd590","inputOption.activeBackground":"#dedcd550","list.activeSelectionBackground":"#181818","list.activeSelectionForeground":"#dbd7caee","list.focusBackground":"#181818","list.highlightForeground":"#4d9375","list.hoverBackground":"#181818","list.hoverForeground":"#dbd7caee","list.inactiveFocusBackground":"#121212","list.inactiveSelectionBackground":"#181818","list.inactiveSelectionForeground":"#dbd7caee","menu.separatorBackground":"#191919","notificationCenterHeader.background":"#121212","notificationCenterHeader.foreground":"#959da5","notifications.background":"#121212","notifications.border":"#191919","notifications.foreground":"#dbd7caee","notificationsErrorIcon.foreground":"#cb7676","notificationsInfoIcon.foreground":"#6394bf","notificationsWarningIcon.foreground":"#d4976c","panel.background":"#121212","panel.border":"#191919","panelInput.border":"#2f363d","panelTitle.activeBorder":"#4d9375","panelTitle.activeForeground":"#dbd7caee","panelTitle.inactiveForeground":"#959da5","peekViewEditor.background":"#121212","peekViewEditor.matchHighlightBackground":"#ffd33d33","peekViewResult.background":"#121212","peekViewResult.matchHighlightBackground":"#ffd33d33","pickerGroup.border":"#191919","pickerGroup.foreground":"#dbd7caee","problemsErrorIcon.foreground":"#cb7676","problemsInfoIcon.foreground":"#6394bf","problemsWarningIcon.foreground":"#d4976c","progressBar.background":"#4d9375","quickInput.background":"#121212","quickInput.foreground":"#dbd7caee","quickInputList.focusBackground":"#181818","scrollbar.shadow":"#0000","scrollbarSlider.activeBackground":"#dedcd550","scrollbarSlider.background":"#dedcd510","scrollbarSlider.hoverBackground":"#dedcd550","settings.headerForeground":"#dbd7caee","settings.modifiedItemIndicator":"#4d9375","sideBar.background":"#121212","sideBar.border":"#191919","sideBar.foreground":"#bfbaaa","sideBarSectionHeader.background":"#121212","sideBarSectionHeader.border":"#191919","sideBarSectionHeader.foreground":"#dbd7caee","sideBarTitle.foreground":"#dbd7caee","statusBar.background":"#121212","statusBar.border":"#191919","statusBar.debuggingBackground":"#181818","statusBar.debuggingForeground":"#bfbaaa","statusBar.foreground":"#bfbaaa","statusBar.noFolderBackground":"#121212","statusBarItem.prominentBackground":"#181818","tab.activeBackground":"#121212","tab.activeBorder":"#191919","tab.activeBorderTop":"#dedcd590","tab.activeForeground":"#dbd7caee","tab.border":"#191919","tab.hoverBackground":"#181818","tab.inactiveBackground":"#121212","tab.inactiveForeground":"#959da5","tab.unfocusedActiveBorder":"#191919","tab.unfocusedActiveBorderTop":"#191919","tab.unfocusedHoverBackground":"#121212","terminal.ansiBlack":"#393a34","terminal.ansiBlue":"#6394bf","terminal.ansiBrightBlack":"#777777","terminal.ansiBrightBlue":"#6394bf","terminal.ansiBrightCyan":"#5eaab5","terminal.ansiBrightGreen":"#4d9375","terminal.ansiBrightMagenta":"#d9739f","terminal.ansiBrightRed":"#cb7676","terminal.ansiBrightWhite":"#ffffff","terminal.ansiBrightYellow":"#e6cc77","terminal.ansiCyan":"#5eaab5","terminal.ansiGreen":"#4d9375","terminal.ansiMagenta":"#d9739f","terminal.ansiRed":"#cb7676","terminal.ansiWhite":"#dbd7ca","terminal.ansiYellow":"#e6cc77","terminal.foreground":"#dbd7caee","terminal.selectionBackground":"#eeeeee18","textBlockQuote.background":"#121212","textBlockQuote.border":"#191919","textCodeBlock.background":"#121212","textLink.activeForeground":"#4d9375","textLink.foreground":"#4d9375","textPreformat.foreground":"#d1d5da","textSeparator.foreground":"#586069","titleBar.activeBackground":"#121212","titleBar.activeForeground":"#bfbaaa","titleBar.border":"#181818","titleBar.inactiveBackground":"#121212","titleBar.inactiveForeground":"#959da5","tree.indentGuidesStroke":"#2f363d","welcomePage.buttonBackground":"#2f363d","welcomePage.buttonHoverBackground":"#444d56"},"displayName":"Vitesse Dark","name":"vitesse-dark","semanticHighlighting":true,"semanticTokenColors":{"class":"#6872ab","interface":"#5d99a9","namespace":"#db889a","property":"#b8a965","type":"#5d99a9"},"tokenColors":[{"scope":["comment","punctuation.definition.comment","string.comment"],"settings":{"foreground":"#758575dd"}},{"scope":["delimiter.bracket","delimiter","invalid.illegal.character-not-allowed-here.html","keyword.operator.rest","keyword.operator.spread","keyword.operator.type.annotation","keyword.operator.relational","keyword.operator.assignment","keyword.operator.type","meta.brace","meta.tag.block.any.html","meta.tag.inline.any.html","meta.tag.structure.input.void.html","meta.type.annotation","meta.embedded.block.github-actions-expression","storage.type.function.arrow","meta.objectliteral.ts","punctuation","punctuation.definition.string.begin.html.vue","punctuation.definition.string.end.html.vue"],"settings":{"foreground":"#666666"}},{"scope":["constant","entity.name.constant","variable.language","meta.definition.variable"],"settings":{"foreground":"#c99076"}},{"scope":["entity","entity.name"],"settings":{"foreground":"#80a665"}},{"scope":"variable.parameter.function","settings":{"foreground":"#dbd7caee"}},{"scope":["entity.name.tag","tag.html"],"settings":{"foreground":"#4d9375"}},{"scope":"entity.name.function","settings":{"foreground":"#80a665"}},{"scope":["keyword","storage.type.class.jsdoc","punctuation.definition.template-expression"],"settings":{"foreground":"#4d9375"}},{"scope":["storage","storage.type","support.type.builtin","constant.language.undefined","constant.language.null","constant.language.import-export-all.ts"],"settings":{"foreground":"#cb7676"}},{"scope":["text.html.derivative","storage.modifier.package","storage.modifier.import","storage.type.java"],"settings":{"foreground":"#dbd7caee"}},{"scope":["string","string punctuation.section.embedded source","attribute.value"],"settings":{"foreground":"#c98a7d"}},{"scope":["punctuation.definition.string"],"settings":{"foreground":"#c98a7d77"}},{"scope":["punctuation.support.type.property-name"],"settings":{"foreground":"#b8a96577"}},{"scope":"support","settings":{"foreground":"#b8a965"}},{"scope":["property","meta.property-name","meta.object-literal.key","entity.name.tag.yaml","attribute.name"],"settings":{"foreground":"#b8a965"}},{"scope":["entity.other.attribute-name","invalid.deprecated.entity.other.attribute-name.html"],"settings":{"foreground":"#bd976a"}},{"scope":["variable","identifier"],"settings":{"foreground":"#bd976a"}},{"scope":["support.type.primitive","entity.name.type"],"settings":{"foreground":"#5DA994"}},{"scope":"namespace","settings":{"foreground":"#db889a"}},{"scope":["keyword.operator","keyword.operator.assignment.compound","meta.var.expr.ts"],"settings":{"foreground":"#cb7676"}},{"scope":"invalid.broken","settings":{"fontStyle":"italic","foreground":"#fdaeb7"}},{"scope":"invalid.deprecated","settings":{"fontStyle":"italic","foreground":"#fdaeb7"}},{"scope":"invalid.illegal","settings":{"fontStyle":"italic","foreground":"#fdaeb7"}},{"scope":"invalid.unimplemented","settings":{"fontStyle":"italic","foreground":"#fdaeb7"}},{"scope":"carriage-return","settings":{"background":"#f97583","content":"^M","fontStyle":"italic underline","foreground":"#24292e"}},{"scope":"message.error","settings":{"foreground":"#fdaeb7"}},{"scope":"string variable","settings":{"foreground":"#c98a7d"}},{"scope":["source.regexp","string.regexp"],"settings":{"foreground":"#c4704f"}},{"scope":["string.regexp.character-class","string.regexp constant.character.escape","string.regexp source.ruby.embedded","string.regexp string.regexp.arbitrary-repitition"],"settings":{"foreground":"#c98a7d"}},{"scope":"string.regexp constant.character.escape","settings":{"foreground":"#e6cc77"}},{"scope":["support.constant"],"settings":{"foreground":"#c99076"}},{"scope":["keyword.operator.quantifier.regexp","constant.numeric","number"],"settings":{"foreground":"#4C9A91"}},{"scope":["keyword.other.unit"],"settings":{"foreground":"#cb7676"}},{"scope":["constant.language.boolean","constant.language"],"settings":{"foreground":"#4d9375"}},{"scope":"meta.module-reference","settings":{"foreground":"#4d9375"}},{"scope":"punctuation.definition.list.begin.markdown","settings":{"foreground":"#d4976c"}},{"scope":["markup.heading","markup.heading entity.name"],"settings":{"fontStyle":"bold","foreground":"#4d9375"}},{"scope":"markup.quote","settings":{"foreground":"#5d99a9"}},{"scope":"markup.italic","settings":{"fontStyle":"italic","foreground":"#dbd7caee"}},{"scope":"markup.bold","settings":{"fontStyle":"bold","foreground":"#dbd7caee"}},{"scope":"markup.raw","settings":{"foreground":"#4d9375"}},{"scope":["markup.deleted","meta.diff.header.from-file","punctuation.definition.deleted"],"settings":{"background":"#86181d","foreground":"#fdaeb7"}},{"scope":["markup.inserted","meta.diff.header.to-file","punctuation.definition.inserted"],"settings":{"background":"#144620","foreground":"#85e89d"}},{"scope":["markup.changed","punctuation.definition.changed"],"settings":{"background":"#c24e00","foreground":"#ffab70"}},{"scope":["markup.ignored","markup.untracked"],"settings":{"background":"#79b8ff","foreground":"#2f363d"}},{"scope":"meta.diff.range","settings":{"fontStyle":"bold","foreground":"#b392f0"}},{"scope":"meta.diff.header","settings":{"foreground":"#79b8ff"}},{"scope":"meta.separator","settings":{"fontStyle":"bold","foreground":"#79b8ff"}},{"scope":"meta.output","settings":{"foreground":"#79b8ff"}},{"scope":["brackethighlighter.tag","brackethighlighter.curly","brackethighlighter.round","brackethighlighter.square","brackethighlighter.angle","brackethighlighter.quote"],"settings":{"foreground":"#d1d5da"}},{"scope":"brackethighlighter.unmatched","settings":{"foreground":"#fdaeb7"}},{"scope":["constant.other.reference.link","string.other.link","punctuation.definition.string.begin.markdown","punctuation.definition.string.end.markdown"],"settings":{"foreground":"#c98a7d"}},{"scope":["markup.underline.link.markdown","markup.underline.link.image.markdown"],"settings":{"fontStyle":"underline","foreground":"#dedcd590"}},{"scope":["type.identifier","constant.other.character-class.regexp"],"settings":{"foreground":"#6872ab"}},{"scope":["entity.other.attribute-name.html.vue"],"settings":{"foreground":"#80a665"}},{"scope":["invalid.illegal.unrecognized-tag.html"],"settings":{"fontStyle":"normal"}}],"type":"dark"}'));
  }
});

// node_modules/shiki/dist/themes/vitesse-dark.mjs
var vitesse_dark_exports = {};
__export(vitesse_dark_exports, {
  default: () => vitesse_dark_default
});
var init_vitesse_dark2 = __esm({
  "node_modules/shiki/dist/themes/vitesse-dark.mjs"() {
    init_vitesse_dark();
  }
});

// node_modules/@shikijs/langs/dist/javascript.mjs
var lang, javascript_default;
var init_javascript = __esm({
  "node_modules/@shikijs/langs/dist/javascript.mjs"() {
    lang = Object.freeze(JSON.parse(`{"displayName":"JavaScript","name":"javascript","patterns":[{"include":"#directives"},{"include":"#statements"},{"include":"#shebang"}],"repository":{"access-modifier":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(abstract|declare|override|public|protected|private|readonly|static)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"storage.modifier.js"},"after-operator-block-as-object-literal":{"begin":"(?<!\\\\+\\\\+|--)(?<=[:=(,\\\\[?+!>]|^await|[^\\\\._$[:alnum:]]await|^return|[^\\\\._$[:alnum:]]return|^yield|[^\\\\._$[:alnum:]]yield|^throw|[^\\\\._$[:alnum:]]throw|^in|[^\\\\._$[:alnum:]]in|^of|[^\\\\._$[:alnum:]]of|^typeof|[^\\\\._$[:alnum:]]typeof|&&|\\\\|\\\\||\\\\*)\\\\s*(\\\\{)","beginCaptures":{"1":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"name":"meta.objectliteral.js","patterns":[{"include":"#object-member"}]},"array-binding-pattern":{"begin":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\[)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.array.js"}},"end":"\\\\]","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.array.js"}},"patterns":[{"include":"#binding-element"},{"include":"#punctuation-comma"}]},"array-binding-pattern-const":{"begin":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\[)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.array.js"}},"end":"\\\\]","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.array.js"}},"patterns":[{"include":"#binding-element-const"},{"include":"#punctuation-comma"}]},"array-literal":{"begin":"\\\\s*(\\\\[)","beginCaptures":{"1":{"name":"meta.brace.square.js"}},"end":"\\\\]","endCaptures":{"0":{"name":"meta.brace.square.js"}},"name":"meta.array.literal.js","patterns":[{"include":"#expression"},{"include":"#punctuation-comma"}]},"arrow-function":{"patterns":[{"captures":{"1":{"name":"storage.modifier.async.js"},"2":{"name":"variable.parameter.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(\\\\basync)\\\\s+)?([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?==>)","name":"meta.arrow.js"},{"begin":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(\\\\basync))?((?<![})!\\\\]])\\\\s*(?=((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))","beginCaptures":{"1":{"name":"storage.modifier.async.js"}},"end":"(?==>|\\\\{|(^\\\\s*(export|function|class|interface|let|var|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|const|import|enum|namespace|module|type|abstract|declare)\\\\s+))","name":"meta.arrow.js","patterns":[{"include":"#comment"},{"include":"#type-parameters"},{"include":"#function-parameters"},{"include":"#arrow-return-type"},{"include":"#possibly-arrow-return-type"}]},{"begin":"=>","beginCaptures":{"0":{"name":"storage.type.function.arrow.js"}},"end":"((?<=\\\\}|\\\\S)(?<!=>)|((?!\\\\{)(?=\\\\S)))(?!\\\\/[\\\\/\\\\*])","name":"meta.arrow.js","patterns":[{"include":"#single-line-comment-consuming-line-ending"},{"include":"#decl-block"},{"include":"#expression"}]}]},"arrow-return-type":{"begin":"(?<=\\\\))\\\\s*(:)","beginCaptures":{"1":{"name":"keyword.operator.type.annotation.js"}},"end":"(?==>|\\\\{|(^\\\\s*(export|function|class|interface|let|var|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|const|import|enum|namespace|module|type|abstract|declare)\\\\s+))","name":"meta.return.type.arrow.js","patterns":[{"include":"#arrow-return-type-body"}]},"arrow-return-type-body":{"patterns":[{"begin":"(?<=[:])(?=\\\\s*\\\\{)","end":"(?<=\\\\})","patterns":[{"include":"#type-object"}]},{"include":"#type-predicate-operator"},{"include":"#type"}]},"async-modifier":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(async)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"storage.modifier.async.js"},"binding-element":{"patterns":[{"include":"#comment"},{"include":"#string"},{"include":"#numeric-literal"},{"include":"#regex"},{"include":"#object-binding-pattern"},{"include":"#array-binding-pattern"},{"include":"#destructuring-variable-rest"},{"include":"#variable-initializer"}]},"binding-element-const":{"patterns":[{"include":"#comment"},{"include":"#string"},{"include":"#numeric-literal"},{"include":"#regex"},{"include":"#object-binding-pattern-const"},{"include":"#array-binding-pattern-const"},{"include":"#destructuring-variable-rest-const"},{"include":"#variable-initializer"}]},"boolean-literal":{"patterns":[{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))true(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"constant.language.boolean.true.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))false(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"constant.language.boolean.false.js"}]},"brackets":{"patterns":[{"begin":"{","end":"}|(?=\\\\*/)","patterns":[{"include":"#brackets"}]},{"begin":"\\\\[","end":"\\\\]|(?=\\\\*/)","patterns":[{"include":"#brackets"}]}]},"cast":{"patterns":[{"include":"#jsx"}]},"class-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(?:(abstract)\\\\s+)?\\\\b(class)\\\\b(?=\\\\s+|/[/*])","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.js"},"4":{"name":"storage.type.class.js"}},"end":"(?<=\\\\})","name":"meta.class.js","patterns":[{"include":"#class-declaration-or-expression-patterns"}]},"class-declaration-or-expression-patterns":{"patterns":[{"include":"#comment"},{"include":"#class-or-interface-heritage"},{"captures":{"0":{"name":"entity.name.type.class.js"}},"match":"[_$[:alpha:]][_$[:alnum:]]*"},{"include":"#type-parameters"},{"include":"#class-or-interface-body"}]},"class-expression":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(abstract)\\\\s+)?(class)\\\\b(?=\\\\s+|[<{]|\\\\/[\\\\/*])","beginCaptures":{"1":{"name":"storage.modifier.js"},"2":{"name":"storage.type.class.js"}},"end":"(?<=\\\\})","name":"meta.class.js","patterns":[{"include":"#class-declaration-or-expression-patterns"}]},"class-or-interface-body":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"patterns":[{"include":"#comment"},{"include":"#decorator"},{"begin":"(?<=:)\\\\s*","end":"(?=\\\\s|[;),}\\\\]:\\\\-\\\\+]|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","patterns":[{"include":"#expression"}]},{"include":"#method-declaration"},{"include":"#indexer-declaration"},{"include":"#field-declaration"},{"include":"#string"},{"include":"#type-annotation"},{"include":"#variable-initializer"},{"include":"#access-modifier"},{"include":"#property-accessor"},{"include":"#async-modifier"},{"include":"#after-operator-block-as-object-literal"},{"include":"#decl-block"},{"include":"#expression"},{"include":"#punctuation-comma"},{"include":"#punctuation-semicolon"}]},"class-or-interface-heritage":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:\\\\b(extends|implements)\\\\b)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"storage.modifier.js"}},"end":"(?=\\\\{)","patterns":[{"include":"#comment"},{"include":"#class-or-interface-heritage"},{"include":"#type-parameters"},{"include":"#expressionWithoutIdentifiers"},{"captures":{"1":{"name":"entity.name.type.module.js"},"2":{"name":"punctuation.accessor.js"},"3":{"name":"punctuation.accessor.optional.js"}},"match":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))(?=\\\\s*[_$[:alpha:]][_$[:alnum:]]*(\\\\s*\\\\??\\\\.\\\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\\\s*)"},{"captures":{"1":{"name":"entity.other.inherited-class.js"}},"match":"([_$[:alpha:]][_$[:alnum:]]*)"},{"include":"#expressionPunctuations"}]},"comment":{"patterns":[{"begin":"/\\\\*\\\\*(?!/)","beginCaptures":{"0":{"name":"punctuation.definition.comment.js"}},"end":"\\\\*/","endCaptures":{"0":{"name":"punctuation.definition.comment.js"}},"name":"comment.block.documentation.js","patterns":[{"include":"#docblock"}]},{"begin":"(/\\\\*)(?:\\\\s*((@)internal)(?=\\\\s|(\\\\*/)))?","beginCaptures":{"1":{"name":"punctuation.definition.comment.js"},"2":{"name":"storage.type.internaldeclaration.js"},"3":{"name":"punctuation.decorator.internaldeclaration.js"}},"end":"\\\\*/","endCaptures":{"0":{"name":"punctuation.definition.comment.js"}},"name":"comment.block.js"},{"begin":"(^[ \\\\t]+)?((//)(?:\\\\s*((@)internal)(?=\\\\s|$))?)","beginCaptures":{"1":{"name":"punctuation.whitespace.comment.leading.js"},"2":{"name":"comment.line.double-slash.js"},"3":{"name":"punctuation.definition.comment.js"},"4":{"name":"storage.type.internaldeclaration.js"},"5":{"name":"punctuation.decorator.internaldeclaration.js"}},"contentName":"comment.line.double-slash.js","end":"(?=$)"}]},"control-statement":{"patterns":[{"include":"#switch-statement"},{"include":"#for-loop"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(catch|finally|throw|try)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.trycatch.js"},{"captures":{"1":{"name":"keyword.control.loop.js"},"2":{"name":"entity.name.label.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(break|continue|goto)\\\\s+([_$[:alpha:]][_$[:alnum:]]*)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(break|continue|do|goto|while)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.loop.js"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(return)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"0":{"name":"keyword.control.flow.js"}},"end":"(?=[;}]|$|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","patterns":[{"include":"#expression"}]},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(case|default|switch)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.switch.js"},{"include":"#if-statement"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(else|if)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.conditional.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(with)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.with.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(package)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(debugger)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.other.debugger.js"}]},"decl-block":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"name":"meta.block.js","patterns":[{"include":"#statements"}]},"declaration":{"patterns":[{"include":"#decorator"},{"include":"#var-expr"},{"include":"#function-declaration"},{"include":"#class-declaration"},{"include":"#interface-declaration"},{"include":"#enum-declaration"},{"include":"#namespace-declaration"},{"include":"#type-alias-declaration"},{"include":"#import-equals-declaration"},{"include":"#import-declaration"},{"include":"#export-declaration"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(declare|export)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"storage.modifier.js"}]},"decorator":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))\\\\@","beginCaptures":{"0":{"name":"punctuation.decorator.js"}},"end":"(?=\\\\s)","name":"meta.decorator.js","patterns":[{"include":"#expression"}]},"destructuring-const":{"patterns":[{"begin":"(?<!=|:|^of|[^\\\\._$[:alnum:]]of|^in|[^\\\\._$[:alnum:]]in)\\\\s*(?=\\\\{)","end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+))","name":"meta.object-binding-pattern-variable.js","patterns":[{"include":"#object-binding-pattern-const"},{"include":"#type-annotation"},{"include":"#comment"}]},{"begin":"(?<!=|:|^of|[^\\\\._$[:alnum:]]of|^in|[^\\\\._$[:alnum:]]in)\\\\s*(?=\\\\[)","end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+))","name":"meta.array-binding-pattern-variable.js","patterns":[{"include":"#array-binding-pattern-const"},{"include":"#type-annotation"},{"include":"#comment"}]}]},"destructuring-parameter":{"patterns":[{"begin":"(?<!=|:)\\\\s*(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\{)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.object.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.object.js"}},"name":"meta.parameter.object-binding-pattern.js","patterns":[{"include":"#parameter-object-binding-element"}]},{"begin":"(?<!=|:)\\\\s*(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\[)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.array.js"}},"end":"\\\\]","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.array.js"}},"name":"meta.paramter.array-binding-pattern.js","patterns":[{"include":"#parameter-binding-element"},{"include":"#punctuation-comma"}]}]},"destructuring-parameter-rest":{"captures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"variable.parameter.js"}},"match":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?([_$[:alpha:]][_$[:alnum:]]*)"},"destructuring-variable":{"patterns":[{"begin":"(?<!=|:|^of|[^\\\\._$[:alnum:]]of|^in|[^\\\\._$[:alnum:]]in)\\\\s*(?=\\\\{)","end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+))","name":"meta.object-binding-pattern-variable.js","patterns":[{"include":"#object-binding-pattern"},{"include":"#type-annotation"},{"include":"#comment"}]},{"begin":"(?<!=|:|^of|[^\\\\._$[:alnum:]]of|^in|[^\\\\._$[:alnum:]]in)\\\\s*(?=\\\\[)","end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+))","name":"meta.array-binding-pattern-variable.js","patterns":[{"include":"#array-binding-pattern"},{"include":"#type-annotation"},{"include":"#comment"}]}]},"destructuring-variable-rest":{"captures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"meta.definition.variable.js variable.other.readwrite.js"}},"match":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?([_$[:alpha:]][_$[:alnum:]]*)"},"destructuring-variable-rest-const":{"captures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"meta.definition.variable.js variable.other.constant.js"}},"match":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?([_$[:alpha:]][_$[:alnum:]]*)"},"directives":{"begin":"^(///)\\\\s*(?=<(reference|amd-dependency|amd-module)(\\\\s+(path|types|no-default-lib|lib|name|resolution-mode)\\\\s*=\\\\s*((\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)))+\\\\s*/>\\\\s*$)","beginCaptures":{"1":{"name":"punctuation.definition.comment.js"}},"end":"(?=$)","name":"comment.line.triple-slash.directive.js","patterns":[{"begin":"(<)(reference|amd-dependency|amd-module)","beginCaptures":{"1":{"name":"punctuation.definition.tag.directive.js"},"2":{"name":"entity.name.tag.directive.js"}},"end":"/>","endCaptures":{"0":{"name":"punctuation.definition.tag.directive.js"}},"name":"meta.tag.js","patterns":[{"match":"path|types|no-default-lib|lib|name|resolution-mode","name":"entity.other.attribute-name.directive.js"},{"match":"=","name":"keyword.operator.assignment.js"},{"include":"#string"}]}]},"docblock":{"patterns":[{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"constant.language.access-type.jsdoc"}},"match":"((@)(?:access|api))\\\\s+(private|protected|public)\\\\b"},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"entity.name.type.instance.jsdoc"},"4":{"name":"punctuation.definition.bracket.angle.begin.jsdoc"},"5":{"name":"constant.other.email.link.underline.jsdoc"},"6":{"name":"punctuation.definition.bracket.angle.end.jsdoc"}},"match":"((@)author)\\\\s+([^@\\\\s<>*/](?:[^@<>*/]|\\\\*[^/])*)(?:\\\\s*(<)([^>\\\\s]+)(>))?"},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"entity.name.type.instance.jsdoc"},"4":{"name":"keyword.operator.control.jsdoc"},"5":{"name":"entity.name.type.instance.jsdoc"}},"match":"((@)borrows)\\\\s+((?:[^@\\\\s*/]|\\\\*[^/])+)\\\\s+(as)\\\\s+((?:[^@\\\\s*/]|\\\\*[^/])+)"},{"begin":"((@)example)\\\\s+","beginCaptures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"}},"end":"(?=@|\\\\*/)","name":"meta.example.jsdoc","patterns":[{"match":"^\\\\s\\\\*\\\\s+"},{"begin":"\\\\G(<)caption(>)","beginCaptures":{"0":{"name":"entity.name.tag.inline.jsdoc"},"1":{"name":"punctuation.definition.bracket.angle.begin.jsdoc"},"2":{"name":"punctuation.definition.bracket.angle.end.jsdoc"}},"contentName":"constant.other.description.jsdoc","end":"(</)caption(>)|(?=\\\\*/)","endCaptures":{"0":{"name":"entity.name.tag.inline.jsdoc"},"1":{"name":"punctuation.definition.bracket.angle.begin.jsdoc"},"2":{"name":"punctuation.definition.bracket.angle.end.jsdoc"}}},{"captures":{"0":{"name":"source.embedded.js"}},"match":"[^\\\\s@*](?:[^*]|\\\\*[^/])*"}]},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"constant.language.symbol-type.jsdoc"}},"match":"((@)kind)\\\\s+(class|constant|event|external|file|function|member|mixin|module|namespace|typedef)\\\\b"},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"variable.other.link.underline.jsdoc"},"4":{"name":"entity.name.type.instance.jsdoc"}},"match":"((@)see)\\\\s+(?:((?=https?://)(?:[^\\\\s*]|\\\\*[^/])+)|((?!https?://|(?:\\\\[[^\\\\[\\\\]]*\\\\])?{@(?:link|linkcode|linkplain|tutorial)\\\\b)(?:[^@\\\\s*/]|\\\\*[^/])+))"},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"variable.other.jsdoc"}},"match":"((@)template)\\\\s+([A-Za-z_$][\\\\w$.\\\\[\\\\]]*(?:\\\\s*,\\\\s*[A-Za-z_$][\\\\w$.\\\\[\\\\]]*)*)"},{"begin":"((@)template)\\\\s+(?={)","beginCaptures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"}},"end":"(?=\\\\s|\\\\*/|[^{}\\\\[\\\\]A-Za-z_$])","patterns":[{"include":"#jsdoctype"},{"match":"([A-Za-z_$][\\\\w$.\\\\[\\\\]]*)","name":"variable.other.jsdoc"}]},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"variable.other.jsdoc"}},"match":"((@)(?:arg|argument|const|constant|member|namespace|param|var))\\\\s+([A-Za-z_$][\\\\w$.\\\\[\\\\]]*)"},{"begin":"((@)typedef)\\\\s+(?={)","beginCaptures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"}},"end":"(?=\\\\s|\\\\*/|[^{}\\\\[\\\\]A-Za-z_$])","patterns":[{"include":"#jsdoctype"},{"match":"(?:[^@\\\\s*/]|\\\\*[^/])+","name":"entity.name.type.instance.jsdoc"}]},{"begin":"((@)(?:arg|argument|const|constant|member|namespace|param|prop|property|var))\\\\s+(?={)","beginCaptures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"}},"end":"(?=\\\\s|\\\\*/|[^{}\\\\[\\\\]A-Za-z_$])","patterns":[{"include":"#jsdoctype"},{"match":"([A-Za-z_$][\\\\w$.\\\\[\\\\]]*)","name":"variable.other.jsdoc"},{"captures":{"1":{"name":"punctuation.definition.optional-value.begin.bracket.square.jsdoc"},"2":{"name":"keyword.operator.assignment.jsdoc"},"3":{"name":"source.embedded.js"},"4":{"name":"punctuation.definition.optional-value.end.bracket.square.jsdoc"},"5":{"name":"invalid.illegal.syntax.jsdoc"}},"match":"(\\\\[)\\\\s*[\\\\w$]+(?:(?:\\\\[\\\\])?\\\\.[\\\\w$]+)*(?:\\\\s*(=)\\\\s*((?>\\"(?:(?:\\\\*(?!/))|(?:\\\\\\\\(?!\\"))|[^*\\\\\\\\])*?\\"|'(?:(?:\\\\*(?!/))|(?:\\\\\\\\(?!'))|[^*\\\\\\\\])*?'|\\\\[(?:(?:\\\\*(?!/))|[^*])*?\\\\]|(?:(?:\\\\*(?!/))|\\\\s(?!\\\\s*\\\\])|\\\\[.*?(?:\\\\]|(?=\\\\*/))|[^*\\\\s\\\\[\\\\]])*)*))?\\\\s*(?:(\\\\])((?:[^*\\\\s]|\\\\*[^\\\\s/])+)?|(?=\\\\*/))","name":"variable.other.jsdoc"}]},{"begin":"((@)(?:define|enum|exception|export|extends|lends|implements|modifies|namespace|private|protected|returns?|satisfies|suppress|this|throws|type|yields?))\\\\s+(?={)","beginCaptures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"}},"end":"(?=\\\\s|\\\\*/|[^{}\\\\[\\\\]A-Za-z_$])","patterns":[{"include":"#jsdoctype"}]},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"entity.name.type.instance.jsdoc"}},"match":"((@)(?:alias|augments|callback|constructs|emits|event|fires|exports?|extends|external|function|func|host|lends|listens|interface|memberof!?|method|module|mixes|mixin|name|requires|see|this|typedef|uses))\\\\s+((?:[^{}@\\\\s*]|\\\\*[^/])+)"},{"begin":"((@)(?:default(?:value)?|license|version))\\\\s+(([''\\"]))","beginCaptures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"variable.other.jsdoc"},"4":{"name":"punctuation.definition.string.begin.jsdoc"}},"contentName":"variable.other.jsdoc","end":"(\\\\3)|(?=$|\\\\*/)","endCaptures":{"0":{"name":"variable.other.jsdoc"},"1":{"name":"punctuation.definition.string.end.jsdoc"}}},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"},"3":{"name":"variable.other.jsdoc"}},"match":"((@)(?:default(?:value)?|license|tutorial|variation|version))\\\\s+([^\\\\s*]+)"},{"captures":{"1":{"name":"punctuation.definition.block.tag.jsdoc"}},"match":"(@)(?:abstract|access|alias|api|arg|argument|async|attribute|augments|author|beta|borrows|bubbles|callback|chainable|class|classdesc|code|config|const|constant|constructor|constructs|copyright|default|defaultvalue|define|deprecated|desc|description|dict|emits|enum|event|example|exception|exports?|extends|extension(?:_?for)?|external|externs|file|fileoverview|final|fires|for|func|function|generator|global|hideconstructor|host|ignore|implements|implicitCast|inherit[Dd]oc|inner|instance|interface|internal|kind|lends|license|listens|main|member|memberof!?|method|mixes|mixins?|modifies|module|name|namespace|noalias|nocollapse|nocompile|nosideeffects|override|overview|package|param|polymer(?:Behavior)?|preserve|private|prop|property|protected|public|read[Oo]nly|record|require[ds]|returns?|see|since|static|struct|submodule|summary|suppress|template|this|throws|todo|tutorial|type|typedef|unrestricted|uses|var|variation|version|virtual|writeOnce|yields?)\\\\b","name":"storage.type.class.jsdoc"},{"include":"#inline-tags"},{"captures":{"1":{"name":"storage.type.class.jsdoc"},"2":{"name":"punctuation.definition.block.tag.jsdoc"}},"match":"((@)(?:[_$[:alpha:]][_$[:alnum:]]*))(?=\\\\s+)"}]},"enum-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?(?:\\\\b(const)\\\\s+)?\\\\b(enum)\\\\s+([_$[:alpha:]][_$[:alnum:]]*)","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.js"},"4":{"name":"storage.type.enum.js"},"5":{"name":"entity.name.type.enum.js"}},"end":"(?<=\\\\})","name":"meta.enum.declaration.js","patterns":[{"include":"#comment"},{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"patterns":[{"include":"#comment"},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)","beginCaptures":{"0":{"name":"variable.other.enummember.js"}},"end":"(?=,|\\\\}|$)","patterns":[{"include":"#comment"},{"include":"#variable-initializer"}]},{"begin":"(?=((\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\])))","end":"(?=,|\\\\}|$)","patterns":[{"include":"#string"},{"include":"#array-literal"},{"include":"#comment"},{"include":"#variable-initializer"}]},{"include":"#punctuation-comma"}]}]},"export-declaration":{"patterns":[{"captures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"keyword.control.as.js"},"3":{"name":"storage.type.namespace.js"},"4":{"name":"entity.name.type.module.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(export)\\\\s+(as)\\\\s+(namespace)\\\\s+([_$[:alpha:]][_$[:alnum:]]*)"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(export)(?:\\\\s+(type))?(?:(?:\\\\s*(=))|(?:\\\\s+(default)(?=\\\\s+)))","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"keyword.control.type.js"},"3":{"name":"keyword.operator.assignment.js"},"4":{"name":"keyword.control.default.js"}},"end":"(?=$|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","name":"meta.export.default.js","patterns":[{"include":"#interface-declaration"},{"include":"#expression"}]},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(export)(?:\\\\s+(type))?\\\\b(?!(\\\\$)|(\\\\s*:))((?=\\\\s*[\\\\{*])|((?=\\\\s*[_$[:alpha:]][_$[:alnum:]]*(\\\\s|,))(?!\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b)))","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"keyword.control.type.js"}},"end":"(?=$|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","name":"meta.export.js","patterns":[{"include":"#import-export-declaration"}]}]},"expression":{"patterns":[{"include":"#expressionWithoutIdentifiers"},{"include":"#identifiers"},{"include":"#expressionPunctuations"}]},"expression-inside-possibly-arrow-parens":{"patterns":[{"include":"#expressionWithoutIdentifiers"},{"include":"#comment"},{"include":"#string"},{"include":"#decorator"},{"include":"#destructuring-parameter"},{"captures":{"1":{"name":"storage.modifier.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(override|public|protected|private|readonly)\\\\s+(?=(override|public|protected|private|readonly)\\\\s+)"},{"captures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.operator.rest.js"},"3":{"name":"entity.name.function.js variable.language.this.js"},"4":{"name":"entity.name.function.js"},"5":{"name":"keyword.operator.optional.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(override|public|private|protected|readonly)\\\\s+)?(?:(\\\\.\\\\.\\\\.)\\\\s*)?(?<!=|:)(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*(\\\\??)(?=\\\\s*(=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))))|(:\\\\s*((<)|([(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>)))))))|(:\\\\s*(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Function(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(:\\\\s*((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))))|(:\\\\s*(=>|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(<[^<>]*>)|[^<>(),=])+=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>))))))"},{"captures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.operator.rest.js"},"3":{"name":"variable.parameter.js variable.language.this.js"},"4":{"name":"variable.parameter.js"},"5":{"name":"keyword.operator.optional.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(override|public|private|protected|readonly)\\\\s+)?(?:(\\\\.\\\\.\\\\.)\\\\s*)?(?<!=|:)(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*(\\\\??)(?=\\\\s*[:,]|$)"},{"include":"#type-annotation"},{"include":"#variable-initializer"},{"match":",","name":"punctuation.separator.parameter.js"},{"include":"#identifiers"},{"include":"#expressionPunctuations"}]},"expression-operators":{"patterns":[{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(await)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.control.flow.js"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(yield)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))(?=\\\\s*\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*\\\\*)","beginCaptures":{"1":{"name":"keyword.control.flow.js"}},"end":"\\\\*","endCaptures":{"0":{"name":"keyword.generator.asterisk.js"}},"patterns":[{"include":"#comment"}]},{"captures":{"1":{"name":"keyword.control.flow.js"},"2":{"name":"keyword.generator.asterisk.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(yield)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))(?:\\\\s*(\\\\*))?"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))delete(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.expression.delete.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))in(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))(?!\\\\()","name":"keyword.operator.expression.in.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))of(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))(?!\\\\()","name":"keyword.operator.expression.of.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))instanceof(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.expression.instanceof.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))new(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.new.js"},{"include":"#typeof-operator"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))void(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.expression.void.js"},{"captures":{"1":{"name":"keyword.control.as.js"},"2":{"name":"storage.modifier.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(as)\\\\s+(const)(?=\\\\s*($|[;,:})\\\\]]))"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(as)|(satisfies))\\\\s+","beginCaptures":{"1":{"name":"keyword.control.as.js"},"2":{"name":"keyword.control.satisfies.js"}},"end":"(?=^|[;),}\\\\]:?\\\\-\\\\+\\\\>]|\\\\|\\\\||\\\\&\\\\&|\\\\!\\\\=\\\\=|$|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(as|satisfies)\\\\s+)|(\\\\s+\\\\<))","patterns":[{"include":"#type"}]},{"match":"\\\\.\\\\.\\\\.","name":"keyword.operator.spread.js"},{"match":"\\\\*=|(?<!\\\\()/=|%=|\\\\+=|\\\\-=","name":"keyword.operator.assignment.compound.js"},{"match":"\\\\&=|\\\\^=|<<=|>>=|>>>=|\\\\|=","name":"keyword.operator.assignment.compound.bitwise.js"},{"match":"<<|>>>|>>","name":"keyword.operator.bitwise.shift.js"},{"match":"===|!==|==|!=","name":"keyword.operator.comparison.js"},{"match":"<=|>=|<>|<|>","name":"keyword.operator.relational.js"},{"captures":{"1":{"name":"keyword.operator.logical.js"},"2":{"name":"keyword.operator.assignment.compound.js"},"3":{"name":"keyword.operator.arithmetic.js"}},"match":"(?<=[_$[:alnum:]])(\\\\!)\\\\s*(?:(/=)|(?:(/)(?![/*])))"},{"match":"\\\\!|&&|\\\\|\\\\||\\\\?\\\\?","name":"keyword.operator.logical.js"},{"match":"\\\\&|~|\\\\^|\\\\|","name":"keyword.operator.bitwise.js"},{"match":"\\\\=","name":"keyword.operator.assignment.js"},{"match":"--","name":"keyword.operator.decrement.js"},{"match":"\\\\+\\\\+","name":"keyword.operator.increment.js"},{"match":"%|\\\\*|/|-|\\\\+","name":"keyword.operator.arithmetic.js"},{"begin":"(?<=[_$[:alnum:])\\\\]])\\\\s*(?=(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)+(?:(/=)|(?:(/)(?![/*]))))","end":"(?:(/=)|(?:(/)(?!\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/)))","endCaptures":{"1":{"name":"keyword.operator.assignment.compound.js"},"2":{"name":"keyword.operator.arithmetic.js"}},"patterns":[{"include":"#comment"}]},{"captures":{"1":{"name":"keyword.operator.assignment.compound.js"},"2":{"name":"keyword.operator.arithmetic.js"}},"match":"(?<=[_$[:alnum:])\\\\]])\\\\s*(?:(/=)|(?:(/)(?![/*])))"}]},"expressionPunctuations":{"patterns":[{"include":"#punctuation-comma"},{"include":"#punctuation-accessor"}]},"expressionWithoutIdentifiers":{"patterns":[{"include":"#jsx"},{"include":"#string"},{"include":"#regex"},{"include":"#comment"},{"include":"#function-expression"},{"include":"#class-expression"},{"include":"#arrow-function"},{"include":"#paren-expression-possibly-arrow"},{"include":"#cast"},{"include":"#ternary-expression"},{"include":"#new-expr"},{"include":"#instanceof-expr"},{"include":"#object-literal"},{"include":"#expression-operators"},{"include":"#function-call"},{"include":"#literal"},{"include":"#support-objects"},{"include":"#paren-expression"}]},"field-declaration":{"begin":"(?<!\\\\()(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(readonly)\\\\s+)?(?=\\\\s*((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|(\\\\#?[_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(?:(?:(\\\\?)|(\\\\!))\\\\s*)?(=|:|;|,|\\\\}|$))","beginCaptures":{"1":{"name":"storage.modifier.js"}},"end":"(?=\\\\}|;|,|$|(^(?!\\\\s*((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|(\\\\#?[_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(?:(?:(\\\\?)|(\\\\!))\\\\s*)?(=|:|;|,|$))))|(?<=\\\\})","name":"meta.field.declaration.js","patterns":[{"include":"#variable-initializer"},{"include":"#type-annotation"},{"include":"#string"},{"include":"#array-literal"},{"include":"#numeric-literal"},{"include":"#comment"},{"captures":{"1":{"name":"meta.definition.property.js entity.name.function.js"},"2":{"name":"keyword.operator.optional.js"},"3":{"name":"keyword.operator.definiteassignment.js"}},"match":"(\\\\#?[_$[:alpha:]][_$[:alnum:]]*)(?:(\\\\?)|(\\\\!))?(?=\\\\s*\\\\s*(=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))))|(:\\\\s*((<)|([(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>)))))))|(:\\\\s*(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Function(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(:\\\\s*((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))))|(:\\\\s*(=>|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(<[^<>]*>)|[^<>(),=])+=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>))))))"},{"match":"\\\\#?[_$[:alpha:]][_$[:alnum:]]*","name":"meta.definition.property.js variable.object.property.js"},{"match":"\\\\?","name":"keyword.operator.optional.js"},{"match":"\\\\!","name":"keyword.operator.definiteassignment.js"}]},"for-loop":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))for(?=((\\\\s+|(\\\\s*\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*))await)?\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)?(\\\\())","beginCaptures":{"0":{"name":"keyword.control.loop.js"}},"end":"(?<=\\\\))","patterns":[{"include":"#comment"},{"match":"await","name":"keyword.control.loop.js"},{"begin":"\\\\(","beginCaptures":{"0":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#var-expr"},{"include":"#expression"},{"include":"#punctuation-semicolon"}]}]},"function-body":{"patterns":[{"include":"#comment"},{"include":"#type-parameters"},{"include":"#function-parameters"},{"include":"#return-type"},{"include":"#type-function-return-type"},{"include":"#decl-block"},{"match":"\\\\*","name":"keyword.generator.asterisk.js"}]},"function-call":{"patterns":[{"begin":"(?=(((([_$[:alpha:]][_$[:alnum:]]*)(\\\\s*\\\\??\\\\.\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\\\)]))\\\\s*(?:(\\\\?\\\\.\\\\s*)|(\\\\!))?((<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))(([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>)*(?<!=)\\\\>))*(?<!=)\\\\>)*(?<!=)>\\\\s*)?\\\\())","end":"(?<=\\\\))(?!(((([_$[:alpha:]][_$[:alnum:]]*)(\\\\s*\\\\??\\\\.\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\\\)]))\\\\s*(?:(\\\\?\\\\.\\\\s*)|(\\\\!))?((<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))(([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>)*(?<!=)\\\\>))*(?<!=)\\\\>)*(?<!=)>\\\\s*)?\\\\())","patterns":[{"begin":"(?=(([_$[:alpha:]][_$[:alnum:]]*)(\\\\s*\\\\??\\\\.\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*))","end":"(?=\\\\s*(?:(\\\\?\\\\.\\\\s*)|(\\\\!))?((<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))(([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>)*(?<!=)\\\\>))*(?<!=)\\\\>)*(?<!=)>\\\\s*)?\\\\())","name":"meta.function-call.js","patterns":[{"include":"#function-call-target"}]},{"include":"#comment"},{"include":"#function-call-optionals"},{"include":"#type-arguments"},{"include":"#paren-expression"}]},{"begin":"(?=(((([_$[:alpha:]][_$[:alnum:]]*)(\\\\s*\\\\??\\\\.\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\\\)]))(<\\\\s*[\\\\{\\\\[\\\\(]\\\\s*$))","end":"(?<=\\\\>)(?!(((([_$[:alpha:]][_$[:alnum:]]*)(\\\\s*\\\\??\\\\.\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\\\)]))(<\\\\s*[\\\\{\\\\[\\\\(]\\\\s*$))","patterns":[{"begin":"(?=(([_$[:alpha:]][_$[:alnum:]]*)(\\\\s*\\\\??\\\\.\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*))","end":"(?=(<\\\\s*[\\\\{\\\\[\\\\(]\\\\s*$))","name":"meta.function-call.js","patterns":[{"include":"#function-call-target"}]},{"include":"#comment"},{"include":"#function-call-optionals"},{"include":"#type-arguments"}]}]},"function-call-optionals":{"patterns":[{"match":"\\\\?\\\\.","name":"meta.function-call.js punctuation.accessor.optional.js"},{"match":"\\\\!","name":"meta.function-call.js keyword.operator.definiteassignment.js"}]},"function-call-target":{"patterns":[{"include":"#support-function-call-identifiers"},{"match":"(\\\\#?[_$[:alpha:]][_$[:alnum:]]*)","name":"entity.name.function.js"}]},"function-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?(?:(async)\\\\s+)?(function\\\\b)(?:\\\\s*(\\\\*))?(?:(?:\\\\s+|(?<=\\\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\\\s*","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.async.js"},"4":{"name":"storage.type.function.js"},"5":{"name":"keyword.generator.asterisk.js"},"6":{"name":"meta.definition.function.js entity.name.function.js"}},"end":"(?=;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))|(?<=\\\\})","name":"meta.function.js","patterns":[{"include":"#function-name"},{"include":"#function-body"}]},"function-expression":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(async)\\\\s+)?(function\\\\b)(?:\\\\s*(\\\\*))?(?:(?:\\\\s+|(?<=\\\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\\\s*","beginCaptures":{"1":{"name":"storage.modifier.async.js"},"2":{"name":"storage.type.function.js"},"3":{"name":"keyword.generator.asterisk.js"},"4":{"name":"meta.definition.function.js entity.name.function.js"}},"end":"(?=;)|(?<=\\\\})","name":"meta.function.expression.js","patterns":[{"include":"#function-name"},{"include":"#single-line-comment-consuming-line-ending"},{"include":"#function-body"}]},"function-name":{"match":"[_$[:alpha:]][_$[:alnum:]]*","name":"meta.definition.function.js entity.name.function.js"},"function-parameters":{"begin":"\\\\(","beginCaptures":{"0":{"name":"punctuation.definition.parameters.begin.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"punctuation.definition.parameters.end.js"}},"name":"meta.parameters.js","patterns":[{"include":"#function-parameters-body"}]},"function-parameters-body":{"patterns":[{"include":"#comment"},{"include":"#string"},{"include":"#decorator"},{"include":"#destructuring-parameter"},{"include":"#parameter-name"},{"include":"#parameter-type-annotation"},{"include":"#variable-initializer"},{"match":",","name":"punctuation.separator.parameter.js"}]},"identifiers":{"patterns":[{"include":"#object-identifiers"},{"captures":{"1":{"name":"punctuation.accessor.js"},"2":{"name":"punctuation.accessor.optional.js"},"3":{"name":"entity.name.function.js"}},"match":"(?:(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*)?([_$[:alpha:]][_$[:alnum:]]*)(?=\\\\s*=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))))"},{"captures":{"1":{"name":"punctuation.accessor.js"},"2":{"name":"punctuation.accessor.optional.js"},"3":{"name":"variable.other.constant.property.js"}},"match":"(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(\\\\#?[[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])"},{"captures":{"1":{"name":"punctuation.accessor.js"},"2":{"name":"punctuation.accessor.optional.js"},"3":{"name":"variable.other.property.js"}},"match":"(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(\\\\#?[_$[:alpha:]][_$[:alnum:]]*)"},{"match":"([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])","name":"variable.other.constant.js"},{"match":"[_$[:alpha:]][_$[:alnum:]]*","name":"variable.other.readwrite.js"}]},"if-statement":{"patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?=\\\\bif\\\\s*(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))\\\\s*(?!\\\\{))","end":"(?=;|$|\\\\})","patterns":[{"include":"#comment"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(if)\\\\s*(\\\\()","beginCaptures":{"1":{"name":"keyword.control.conditional.js"},"2":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#expression"}]},{"begin":"(?<=\\\\))\\\\s*\\\\/(?![\\\\/*])(?=(?:[^\\\\/\\\\\\\\\\\\[]|\\\\\\\\.|\\\\[([^\\\\]\\\\\\\\]|\\\\\\\\.)*\\\\])+\\\\/([dgimsuvy]+|(?![\\\\/\\\\*])|(?=\\\\/\\\\*))(?!\\\\s*[a-zA-Z0-9_$]))","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.js"}},"end":"(/)([dgimsuvy]*)","endCaptures":{"1":{"name":"punctuation.definition.string.end.js"},"2":{"name":"keyword.other.js"}},"name":"string.regexp.js","patterns":[{"include":"#regexp"}]},{"include":"#statements"}]}]},"import-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(import)(?:\\\\s+(type)(?!\\\\s+from))?(?!\\\\s*[:\\\\(])(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"keyword.control.import.js"},"4":{"name":"keyword.control.type.js"}},"end":"(?<!^import|[^\\\\._$[:alnum:]]import)(?=;|$|^)","name":"meta.import.js","patterns":[{"include":"#single-line-comment-consuming-line-ending"},{"include":"#comment"},{"include":"#string"},{"begin":"(?<=^import|[^\\\\._$[:alnum:]]import)(?!\\\\s*[\\"'])","end":"\\\\bfrom\\\\b","endCaptures":{"0":{"name":"keyword.control.from.js"}},"patterns":[{"include":"#import-export-declaration"}]},{"include":"#import-export-declaration"}]},"import-equals-declaration":{"patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(import)(?:\\\\s+(type))?\\\\s+([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(=)\\\\s*(require)\\\\s*(\\\\()","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"keyword.control.import.js"},"4":{"name":"keyword.control.type.js"},"5":{"name":"variable.other.readwrite.alias.js"},"6":{"name":"keyword.operator.assignment.js"},"7":{"name":"keyword.control.require.js"},"8":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"name":"meta.import-equals.external.js","patterns":[{"include":"#comment"},{"include":"#string"}]},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(import)(?:\\\\s+(type))?\\\\s+([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(=)\\\\s*(?!require\\\\b)","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"keyword.control.import.js"},"4":{"name":"keyword.control.type.js"},"5":{"name":"variable.other.readwrite.alias.js"},"6":{"name":"keyword.operator.assignment.js"}},"end":"(?=;|$|^)","name":"meta.import-equals.internal.js","patterns":[{"include":"#single-line-comment-consuming-line-ending"},{"include":"#comment"},{"captures":{"1":{"name":"entity.name.type.module.js"},"2":{"name":"punctuation.accessor.js"},"3":{"name":"punctuation.accessor.optional.js"}},"match":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))"},{"match":"([_$[:alpha:]][_$[:alnum:]]*)","name":"variable.other.readwrite.js"}]}]},"import-export-assert-clause":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(with)|(assert))\\\\s*(\\\\{)","beginCaptures":{"1":{"name":"keyword.control.with.js"},"2":{"name":"keyword.control.assert.js"},"3":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"patterns":[{"include":"#comment"},{"include":"#string"},{"match":"(?:[_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?=(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*:)","name":"meta.object-literal.key.js"},{"match":":","name":"punctuation.separator.key-value.js"}]},"import-export-block":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"name":"meta.block.js","patterns":[{"include":"#import-export-clause"}]},"import-export-clause":{"patterns":[{"include":"#comment"},{"captures":{"1":{"name":"keyword.control.type.js"},"2":{"name":"keyword.control.default.js"},"3":{"name":"constant.language.import-export-all.js"},"4":{"name":"variable.other.readwrite.js"},"5":{"name":"string.quoted.alias.js"},"12":{"name":"keyword.control.as.js"},"13":{"name":"keyword.control.default.js"},"14":{"name":"variable.other.readwrite.alias.js"},"15":{"name":"string.quoted.alias.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(?:(\\\\btype)\\\\s+)?(?:(\\\\bdefault)|(\\\\*)|(\\\\b[_$[:alpha:]][_$[:alnum:]]*)|((\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))))\\\\s+(as)\\\\s+(?:(default(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|([_$[:alpha:]][_$[:alnum:]]*)|((\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)))"},{"include":"#punctuation-comma"},{"match":"\\\\*","name":"constant.language.import-export-all.js"},{"match":"\\\\b(default)\\\\b","name":"keyword.control.default.js"},{"captures":{"1":{"name":"keyword.control.type.js"},"2":{"name":"variable.other.readwrite.alias.js"},"3":{"name":"string.quoted.alias.js"}},"match":"(?:(\\\\btype)\\\\s+)?(?:([_$[:alpha:]][_$[:alnum:]]*)|((\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)))"}]},"import-export-declaration":{"patterns":[{"include":"#comment"},{"include":"#string"},{"include":"#import-export-block"},{"match":"\\\\bfrom\\\\b","name":"keyword.control.from.js"},{"include":"#import-export-assert-clause"},{"include":"#import-export-clause"}]},"indexer-declaration":{"begin":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(readonly)\\\\s*)?\\\\s*(\\\\[)\\\\s*([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?=:)","beginCaptures":{"1":{"name":"storage.modifier.js"},"2":{"name":"meta.brace.square.js"},"3":{"name":"variable.parameter.js"}},"end":"(\\\\])\\\\s*(\\\\?\\\\s*)?|$","endCaptures":{"1":{"name":"meta.brace.square.js"},"2":{"name":"keyword.operator.optional.js"}},"name":"meta.indexer.declaration.js","patterns":[{"include":"#type-annotation"}]},"indexer-mapped-type-declaration":{"begin":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))([+-])?(readonly)\\\\s*)?\\\\s*(\\\\[)\\\\s*([_$[:alpha:]][_$[:alnum:]]*)\\\\s+(in)\\\\s+","beginCaptures":{"1":{"name":"keyword.operator.type.modifier.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"meta.brace.square.js"},"4":{"name":"entity.name.type.js"},"5":{"name":"keyword.operator.expression.in.js"}},"end":"(\\\\])([+-])?\\\\s*(\\\\?\\\\s*)?|$","endCaptures":{"1":{"name":"meta.brace.square.js"},"2":{"name":"keyword.operator.type.modifier.js"},"3":{"name":"keyword.operator.optional.js"}},"name":"meta.indexer.mappedtype.declaration.js","patterns":[{"captures":{"1":{"name":"keyword.control.as.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(as)\\\\s+"},{"include":"#type"}]},"inline-tags":{"patterns":[{"captures":{"1":{"name":"punctuation.definition.bracket.square.begin.jsdoc"},"2":{"name":"punctuation.definition.bracket.square.end.jsdoc"}},"match":"(\\\\[)[^\\\\]]+(\\\\])(?={@(?:link|linkcode|linkplain|tutorial))","name":"constant.other.description.jsdoc"},{"begin":"({)((@)(?:link(?:code|plain)?|tutorial))\\\\s*","beginCaptures":{"1":{"name":"punctuation.definition.bracket.curly.begin.jsdoc"},"2":{"name":"storage.type.class.jsdoc"},"3":{"name":"punctuation.definition.inline.tag.jsdoc"}},"end":"}|(?=\\\\*/)","endCaptures":{"0":{"name":"punctuation.definition.bracket.curly.end.jsdoc"}},"name":"entity.name.type.instance.jsdoc","patterns":[{"captures":{"1":{"name":"variable.other.link.underline.jsdoc"},"2":{"name":"punctuation.separator.pipe.jsdoc"}},"match":"\\\\G((?=https?://)(?:[^|}\\\\s*]|\\\\*[/])+)(\\\\|)?"},{"captures":{"1":{"name":"variable.other.description.jsdoc"},"2":{"name":"punctuation.separator.pipe.jsdoc"}},"match":"\\\\G((?:[^{}@\\\\s|*]|\\\\*[^/])+)(\\\\|)?"}]}]},"instanceof-expr":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(instanceof)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"keyword.operator.expression.instanceof.js"}},"end":"(?<=\\\\))|(?=[;),}\\\\]:?\\\\-\\\\+\\\\>]|\\\\|\\\\||\\\\&\\\\&|\\\\!\\\\=\\\\=|$|(===|!==|==|!=)|(([\\\\&\\\\~\\\\^\\\\|]\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s+instanceof(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))function((\\\\s+[_$[:alpha:]][_$[:alnum:]]*)|(\\\\s*[\\\\(]))))","patterns":[{"include":"#type"}]},"interface-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(?:(abstract)\\\\s+)?\\\\b(interface)\\\\b(?=\\\\s+|/[/*])","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.js"},"4":{"name":"storage.type.interface.js"}},"end":"(?<=\\\\})","name":"meta.interface.js","patterns":[{"include":"#comment"},{"include":"#class-or-interface-heritage"},{"captures":{"0":{"name":"entity.name.type.interface.js"}},"match":"[_$[:alpha:]][_$[:alnum:]]*"},{"include":"#type-parameters"},{"include":"#class-or-interface-body"}]},"jsdoctype":{"patterns":[{"begin":"\\\\G({)","beginCaptures":{"0":{"name":"entity.name.type.instance.jsdoc"},"1":{"name":"punctuation.definition.bracket.curly.begin.jsdoc"}},"contentName":"entity.name.type.instance.jsdoc","end":"((}))\\\\s*|(?=\\\\*/)","endCaptures":{"1":{"name":"entity.name.type.instance.jsdoc"},"2":{"name":"punctuation.definition.bracket.curly.end.jsdoc"}},"patterns":[{"include":"#brackets"}]}]},"jsx":{"patterns":[{"include":"#jsx-tag-without-attributes-in-expression"},{"include":"#jsx-tag-in-expression"}]},"jsx-children":{"patterns":[{"include":"#jsx-tag-without-attributes"},{"include":"#jsx-tag"},{"include":"#jsx-evaluated-code"},{"include":"#jsx-entities"}]},"jsx-entities":{"patterns":[{"captures":{"1":{"name":"punctuation.definition.entity.js"},"3":{"name":"punctuation.definition.entity.js"}},"match":"(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)","name":"constant.character.entity.js"}]},"jsx-evaluated-code":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.section.embedded.begin.js"}},"contentName":"meta.embedded.expression.js","end":"\\\\}","endCaptures":{"0":{"name":"punctuation.section.embedded.end.js"}},"patterns":[{"include":"#expression"}]},"jsx-string-double-quoted":{"begin":"\\"","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.js"}},"end":"\\"","endCaptures":{"0":{"name":"punctuation.definition.string.end.js"}},"name":"string.quoted.double.js","patterns":[{"include":"#jsx-entities"}]},"jsx-string-single-quoted":{"begin":"'","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.js"}},"end":"'","endCaptures":{"0":{"name":"punctuation.definition.string.end.js"}},"name":"string.quoted.single.js","patterns":[{"include":"#jsx-entities"}]},"jsx-tag":{"begin":"(?=(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))(?=((<\\\\s*)|(\\\\s+))(?!\\\\?)|\\\\/?>))","end":"(/>)|(?:(</)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))?\\\\s*(>))","endCaptures":{"1":{"name":"punctuation.definition.tag.end.js"},"2":{"name":"punctuation.definition.tag.begin.js"},"3":{"name":"entity.name.tag.namespace.js"},"4":{"name":"punctuation.separator.namespace.js"},"5":{"name":"entity.name.tag.js"},"6":{"name":"support.class.component.js"},"7":{"name":"punctuation.definition.tag.end.js"}},"name":"meta.tag.js","patterns":[{"begin":"(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))(?=((<\\\\s*)|(\\\\s+))(?!\\\\?)|\\\\/?>)","beginCaptures":{"1":{"name":"punctuation.definition.tag.begin.js"},"2":{"name":"entity.name.tag.namespace.js"},"3":{"name":"punctuation.separator.namespace.js"},"4":{"name":"entity.name.tag.js"},"5":{"name":"support.class.component.js"}},"end":"(?=[/]?>)","patterns":[{"include":"#comment"},{"include":"#type-arguments"},{"include":"#jsx-tag-attributes"}]},{"begin":"(>)","beginCaptures":{"1":{"name":"punctuation.definition.tag.end.js"}},"contentName":"meta.jsx.children.js","end":"(?=</)","patterns":[{"include":"#jsx-children"}]}]},"jsx-tag-attribute-assignment":{"match":"=(?=\\\\s*(?:'|\\"|{|/\\\\*|//|\\\\n))","name":"keyword.operator.assignment.js"},"jsx-tag-attribute-name":{"captures":{"1":{"name":"entity.other.attribute-name.namespace.js"},"2":{"name":"punctuation.separator.namespace.js"},"3":{"name":"entity.other.attribute-name.js"}},"match":"\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(:))?([_$[:alpha:]][-_$[:alnum:]]*)(?=\\\\s|=|/?>|/\\\\*|//)"},"jsx-tag-attributes":{"begin":"\\\\s+","end":"(?=[/]?>)","name":"meta.tag.attributes.js","patterns":[{"include":"#comment"},{"include":"#jsx-tag-attribute-name"},{"include":"#jsx-tag-attribute-assignment"},{"include":"#jsx-string-double-quoted"},{"include":"#jsx-string-single-quoted"},{"include":"#jsx-evaluated-code"},{"include":"#jsx-tag-attributes-illegal"}]},"jsx-tag-attributes-illegal":{"match":"\\\\S+","name":"invalid.illegal.attribute.js"},"jsx-tag-in-expression":{"begin":"(?<!\\\\+\\\\+|--)(?<=[({\\\\[,?=>:*]|&&|\\\\|\\\\||\\\\?|\\\\*\\\\/|^await|[^\\\\._$[:alnum:]]await|^return|[^\\\\._$[:alnum:]]return|^default|[^\\\\._$[:alnum:]]default|^yield|[^\\\\._$[:alnum:]]yield|^)\\\\s*(?!<\\\\s*[_$[:alpha:]][_$[:alnum:]]*((\\\\s+extends\\\\s+[^=>])|,))(?=(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))(?=((<\\\\s*)|(\\\\s+))(?!\\\\?)|\\\\/?>))","end":"(?!(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))(?=((<\\\\s*)|(\\\\s+))(?!\\\\?)|\\\\/?>))","patterns":[{"include":"#jsx-tag"}]},"jsx-tag-without-attributes":{"begin":"(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))?\\\\s*(>)","beginCaptures":{"1":{"name":"punctuation.definition.tag.begin.js"},"2":{"name":"entity.name.tag.namespace.js"},"3":{"name":"punctuation.separator.namespace.js"},"4":{"name":"entity.name.tag.js"},"5":{"name":"support.class.component.js"},"6":{"name":"punctuation.definition.tag.end.js"}},"contentName":"meta.jsx.children.js","end":"(</)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))?\\\\s*(>)","endCaptures":{"1":{"name":"punctuation.definition.tag.begin.js"},"2":{"name":"entity.name.tag.namespace.js"},"3":{"name":"punctuation.separator.namespace.js"},"4":{"name":"entity.name.tag.js"},"5":{"name":"support.class.component.js"},"6":{"name":"punctuation.definition.tag.end.js"}},"name":"meta.tag.without-attributes.js","patterns":[{"include":"#jsx-children"}]},"jsx-tag-without-attributes-in-expression":{"begin":"(?<!\\\\+\\\\+|--)(?<=[({\\\\[,?=>:*]|&&|\\\\|\\\\||\\\\?|\\\\*\\\\/|^await|[^\\\\._$[:alnum:]]await|^return|[^\\\\._$[:alnum:]]return|^default|[^\\\\._$[:alnum:]]default|^yield|[^\\\\._$[:alnum:]]yield|^)\\\\s*(?=(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))?\\\\s*(>))","end":"(?!(<)\\\\s*(?:([_$[:alpha:]][-_$[:alnum:].]*)(?<!\\\\.|-)(:))?((?:[a-z][a-z0-9]*|([_$[:alpha:]][-_$[:alnum:].]*))(?<!\\\\.|-))?\\\\s*(>))","patterns":[{"include":"#jsx-tag-without-attributes"}]},"label":{"patterns":[{"begin":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(:)(?=\\\\s*\\\\{)","beginCaptures":{"1":{"name":"entity.name.label.js"},"2":{"name":"punctuation.separator.label.js"}},"end":"(?<=\\\\})","patterns":[{"include":"#decl-block"}]},{"captures":{"1":{"name":"entity.name.label.js"},"2":{"name":"punctuation.separator.label.js"}},"match":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(:)"}]},"literal":{"patterns":[{"include":"#numeric-literal"},{"include":"#boolean-literal"},{"include":"#null-literal"},{"include":"#undefined-literal"},{"include":"#numericConstant-literal"},{"include":"#array-literal"},{"include":"#this-literal"},{"include":"#super-literal"}]},"method-declaration":{"patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:\\\\b(override)\\\\s+)?(?:\\\\b(public|private|protected)\\\\s+)?(?:\\\\b(abstract)\\\\s+)?(?:\\\\b(async)\\\\s+)?\\\\s*\\\\b(constructor)\\\\b(?!:)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"storage.modifier.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.js"},"4":{"name":"storage.modifier.async.js"},"5":{"name":"storage.type.js"}},"end":"(?=\\\\}|;|,|$)|(?<=\\\\})","name":"meta.method.declaration.js","patterns":[{"include":"#method-declaration-name"},{"include":"#function-body"}]},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:\\\\b(override)\\\\s+)?(?:\\\\b(public|private|protected)\\\\s+)?(?:\\\\b(abstract)\\\\s+)?(?:\\\\b(async)\\\\s+)?(?:(?:\\\\s*\\\\b(new)\\\\b(?!:)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(?:(\\\\*)\\\\s*)?)(?=\\\\s*((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*))?[\\\\(])","beginCaptures":{"1":{"name":"storage.modifier.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.js"},"4":{"name":"storage.modifier.async.js"},"5":{"name":"keyword.operator.new.js"},"6":{"name":"keyword.generator.asterisk.js"}},"end":"(?=\\\\}|;|,|$)|(?<=\\\\})","name":"meta.method.declaration.js","patterns":[{"include":"#method-declaration-name"},{"include":"#function-body"}]},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:\\\\b(override)\\\\s+)?(?:\\\\b(public|private|protected)\\\\s+)?(?:\\\\b(abstract)\\\\s+)?(?:\\\\b(async)\\\\s+)?(?:\\\\b(get|set)\\\\s+)?(?:(\\\\*)\\\\s*)?(?=\\\\s*(((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(\\\\??))\\\\s*((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*))?[\\\\(])","beginCaptures":{"1":{"name":"storage.modifier.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.modifier.js"},"4":{"name":"storage.modifier.async.js"},"5":{"name":"storage.type.property.js"},"6":{"name":"keyword.generator.asterisk.js"}},"end":"(?=\\\\}|;|,|$)|(?<=\\\\})","name":"meta.method.declaration.js","patterns":[{"include":"#method-declaration-name"},{"include":"#function-body"}]}]},"method-declaration-name":{"begin":"(?=((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(\\\\??)\\\\s*[\\\\(\\\\<])","end":"(?=\\\\(|\\\\<)","patterns":[{"include":"#string"},{"include":"#array-literal"},{"include":"#numeric-literal"},{"match":"[_$[:alpha:]][_$[:alnum:]]*","name":"meta.definition.method.js entity.name.function.js"},{"match":"\\\\?","name":"keyword.operator.optional.js"}]},"namespace-declaration":{"begin":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(namespace|module)\\\\s+(?=[_$[:alpha:]\\"'\`]))","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.namespace.js"}},"end":"(?<=\\\\})|(?=;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","name":"meta.namespace.declaration.js","patterns":[{"include":"#comment"},{"include":"#string"},{"match":"([_$[:alpha:]][_$[:alnum:]]*)","name":"entity.name.type.module.js"},{"include":"#punctuation-accessor"},{"include":"#decl-block"}]},"new-expr":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(new)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"keyword.operator.new.js"}},"end":"(?<=\\\\))|(?=[;),}\\\\]:?\\\\-\\\\+\\\\>]|\\\\|\\\\||\\\\&\\\\&|\\\\!\\\\=\\\\=|$|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))new(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))function((\\\\s+[_$[:alpha:]][_$[:alnum:]]*)|(\\\\s*[\\\\(]))))","name":"new.expr.js","patterns":[{"include":"#expression"}]},"null-literal":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))null(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"constant.language.null.js"},"numeric-literal":{"patterns":[{"captures":{"1":{"name":"storage.type.numeric.bigint.js"}},"match":"\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$)","name":"constant.numeric.hex.js"},{"captures":{"1":{"name":"storage.type.numeric.bigint.js"}},"match":"\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$)","name":"constant.numeric.binary.js"},{"captures":{"1":{"name":"storage.type.numeric.bigint.js"}},"match":"\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$)","name":"constant.numeric.octal.js"},{"captures":{"0":{"name":"constant.numeric.decimal.js"},"1":{"name":"meta.delimiter.decimal.period.js"},"2":{"name":"storage.type.numeric.bigint.js"},"3":{"name":"meta.delimiter.decimal.period.js"},"4":{"name":"storage.type.numeric.bigint.js"},"5":{"name":"meta.delimiter.decimal.period.js"},"6":{"name":"storage.type.numeric.bigint.js"},"7":{"name":"storage.type.numeric.bigint.js"},"8":{"name":"meta.delimiter.decimal.period.js"},"9":{"name":"storage.type.numeric.bigint.js"},"10":{"name":"meta.delimiter.decimal.period.js"},"11":{"name":"storage.type.numeric.bigint.js"},"12":{"name":"meta.delimiter.decimal.period.js"},"13":{"name":"storage.type.numeric.bigint.js"},"14":{"name":"storage.type.numeric.bigint.js"}},"match":"(?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$)"}]},"numericConstant-literal":{"patterns":[{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))NaN(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"constant.language.nan.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Infinity(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"constant.language.infinity.js"}]},"object-binding-element":{"patterns":[{"include":"#comment"},{"begin":"(?=((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(:))","end":"(?=,|\\\\})","patterns":[{"include":"#object-binding-element-propertyName"},{"include":"#binding-element"}]},{"include":"#object-binding-pattern"},{"include":"#destructuring-variable-rest"},{"include":"#variable-initializer"},{"include":"#punctuation-comma"}]},"object-binding-element-const":{"patterns":[{"include":"#comment"},{"begin":"(?=((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(:))","end":"(?=,|\\\\})","patterns":[{"include":"#object-binding-element-propertyName"},{"include":"#binding-element-const"}]},{"include":"#object-binding-pattern-const"},{"include":"#destructuring-variable-rest-const"},{"include":"#variable-initializer"},{"include":"#punctuation-comma"}]},"object-binding-element-propertyName":{"begin":"(?=((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(:))","end":"(:)","endCaptures":{"0":{"name":"punctuation.destructuring.js"}},"patterns":[{"include":"#string"},{"include":"#array-literal"},{"include":"#numeric-literal"},{"match":"([_$[:alpha:]][_$[:alnum:]]*)","name":"variable.object.property.js"}]},"object-binding-pattern":{"begin":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\{)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.object.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.object.js"}},"patterns":[{"include":"#object-binding-element"}]},"object-binding-pattern-const":{"begin":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\{)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.object.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.object.js"}},"patterns":[{"include":"#object-binding-element-const"}]},"object-identifiers":{"patterns":[{"match":"([_$[:alpha:]][_$[:alnum:]]*)(?=\\\\s*\\\\??\\\\.\\\\s*prototype\\\\b(?!\\\\$))","name":"support.class.js"},{"captures":{"1":{"name":"punctuation.accessor.js"},"2":{"name":"punctuation.accessor.optional.js"},"3":{"name":"variable.other.constant.object.property.js"},"4":{"name":"variable.other.object.property.js"}},"match":"(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(?:(\\\\#?[[:upper:]][_$[:digit:][:upper:]]*)|(\\\\#?[_$[:alpha:]][_$[:alnum:]]*))(?=\\\\s*\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*)"},{"captures":{"1":{"name":"variable.other.constant.object.js"},"2":{"name":"variable.other.object.js"}},"match":"(?:([[:upper:]][_$[:digit:][:upper:]]*)|([_$[:alpha:]][_$[:alnum:]]*))(?=\\\\s*\\\\??\\\\.\\\\s*\\\\#?[_$[:alpha:]][_$[:alnum:]]*)"}]},"object-literal":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"name":"meta.objectliteral.js","patterns":[{"include":"#object-member"}]},"object-literal-method-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:\\\\b(async)\\\\s+)?(?:\\\\b(get|set)\\\\s+)?(?:(\\\\*)\\\\s*)?(?=\\\\s*(((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(\\\\??))\\\\s*((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*))?[\\\\(])","beginCaptures":{"1":{"name":"storage.modifier.async.js"},"2":{"name":"storage.type.property.js"},"3":{"name":"keyword.generator.asterisk.js"}},"end":"(?=\\\\}|;|,)|(?<=\\\\})","name":"meta.method.declaration.js","patterns":[{"include":"#method-declaration-name"},{"include":"#function-body"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:\\\\b(async)\\\\s+)?(?:\\\\b(get|set)\\\\s+)?(?:(\\\\*)\\\\s*)?(?=\\\\s*(((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(\\\\??))\\\\s*((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*))?[\\\\(])","beginCaptures":{"1":{"name":"storage.modifier.async.js"},"2":{"name":"storage.type.property.js"},"3":{"name":"keyword.generator.asterisk.js"}},"end":"(?=\\\\(|\\\\<)","patterns":[{"include":"#method-declaration-name"}]}]},"object-member":{"patterns":[{"include":"#comment"},{"include":"#object-literal-method-declaration"},{"begin":"(?=\\\\[)","end":"(?=:)|((?<=[\\\\]])(?=\\\\s*[\\\\(\\\\<]))","name":"meta.object.member.js meta.object-literal.key.js","patterns":[{"include":"#comment"},{"include":"#array-literal"}]},{"begin":"(?=[\\\\'\\\\\\"\\\\\`])","end":"(?=:)|((?<=[\\\\'\\\\\\"\\\\\`])(?=((\\\\s*[\\\\(\\\\<,}])|(\\\\s+(as|satisifies)\\\\s+))))","name":"meta.object.member.js meta.object-literal.key.js","patterns":[{"include":"#comment"},{"include":"#string"}]},{"begin":"(?=(\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$)))","end":"(?=:)|(?=\\\\s*([\\\\(\\\\<,}])|(\\\\s+as|satisifies\\\\s+))","name":"meta.object.member.js meta.object-literal.key.js","patterns":[{"include":"#comment"},{"include":"#numeric-literal"}]},{"begin":"(?<=[\\\\]\\\\'\\\\\\"\\\\\`])(?=\\\\s*[\\\\(\\\\<])","end":"(?=\\\\}|;|,)|(?<=\\\\})","name":"meta.method.declaration.js","patterns":[{"include":"#function-body"}]},{"captures":{"0":{"name":"meta.object-literal.key.js"},"1":{"name":"constant.numeric.decimal.js"}},"match":"(?![_$[:alpha:]])([[:digit:]]+)\\\\s*(?=(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*:)","name":"meta.object.member.js"},{"captures":{"0":{"name":"meta.object-literal.key.js"},"1":{"name":"entity.name.function.js"}},"match":"(?:([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?=(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*:(\\\\s*\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/)*\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>))))))","name":"meta.object.member.js"},{"captures":{"0":{"name":"meta.object-literal.key.js"}},"match":"(?:[_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?=(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*:)","name":"meta.object.member.js"},{"begin":"\\\\.\\\\.\\\\.","beginCaptures":{"0":{"name":"keyword.operator.spread.js"}},"end":"(?=,|\\\\})","name":"meta.object.member.js","patterns":[{"include":"#expression"}]},{"captures":{"1":{"name":"variable.other.readwrite.js"}},"match":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?=,|\\\\}|$|\\\\/\\\\/|\\\\/\\\\*)","name":"meta.object.member.js"},{"captures":{"1":{"name":"keyword.control.as.js"},"2":{"name":"storage.modifier.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(as)\\\\s+(const)(?=\\\\s*([,}]|$))","name":"meta.object.member.js"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(as)|(satisfies))\\\\s+","beginCaptures":{"1":{"name":"keyword.control.as.js"},"2":{"name":"keyword.control.satisfies.js"}},"end":"(?=[;),}\\\\]:?\\\\-\\\\+\\\\>]|\\\\|\\\\||\\\\&\\\\&|\\\\!\\\\=\\\\=|$|^|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(as|satisifies)\\\\s+))","name":"meta.object.member.js","patterns":[{"include":"#type"}]},{"begin":"(?=[_$[:alpha:]][_$[:alnum:]]*\\\\s*=)","end":"(?=,|\\\\}|$|\\\\/\\\\/|\\\\/\\\\*)","name":"meta.object.member.js","patterns":[{"include":"#expression"}]},{"begin":":","beginCaptures":{"0":{"name":"meta.object-literal.key.js punctuation.separator.key-value.js"}},"end":"(?=,|\\\\})","name":"meta.object.member.js","patterns":[{"begin":"(?<=:)\\\\s*(async)?(?=\\\\s*(<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)\\\\(\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))","beginCaptures":{"1":{"name":"storage.modifier.async.js"}},"end":"(?<=\\\\))","patterns":[{"include":"#type-parameters"},{"begin":"\\\\(","beginCaptures":{"0":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#expression-inside-possibly-arrow-parens"}]}]},{"begin":"(?<=:)\\\\s*(async)?\\\\s*(\\\\()(?=\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))","beginCaptures":{"1":{"name":"storage.modifier.async.js"},"2":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#expression-inside-possibly-arrow-parens"}]},{"begin":"(?<=:)\\\\s*(async)?\\\\s*(?=\\\\<\\\\s*$)","beginCaptures":{"1":{"name":"storage.modifier.async.js"}},"end":"(?<=\\\\>)","patterns":[{"include":"#type-parameters"}]},{"begin":"(?<=\\\\>)\\\\s*(\\\\()(?=\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))","beginCaptures":{"1":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#expression-inside-possibly-arrow-parens"}]},{"include":"#possibly-arrow-return-type"},{"include":"#expression"}]},{"include":"#punctuation-comma"},{"include":"#decl-block"}]},"parameter-array-binding-pattern":{"begin":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\[)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.array.js"}},"end":"\\\\]","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.array.js"}},"patterns":[{"include":"#parameter-binding-element"},{"include":"#punctuation-comma"}]},"parameter-binding-element":{"patterns":[{"include":"#comment"},{"include":"#string"},{"include":"#numeric-literal"},{"include":"#regex"},{"include":"#parameter-object-binding-pattern"},{"include":"#parameter-array-binding-pattern"},{"include":"#destructuring-parameter-rest"},{"include":"#variable-initializer"}]},"parameter-name":{"patterns":[{"captures":{"1":{"name":"storage.modifier.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(override|public|protected|private|readonly)\\\\s+(?=(override|public|protected|private|readonly)\\\\s+)"},{"captures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.operator.rest.js"},"3":{"name":"entity.name.function.js variable.language.this.js"},"4":{"name":"entity.name.function.js"},"5":{"name":"keyword.operator.optional.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(override|public|private|protected|readonly)\\\\s+)?(?:(\\\\.\\\\.\\\\.)\\\\s*)?(?<!=|:)(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*(\\\\??)(?=\\\\s*(=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))))|(:\\\\s*((<)|([(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>)))))))|(:\\\\s*(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Function(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(:\\\\s*((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))))|(:\\\\s*(=>|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(<[^<>]*>)|[^<>(),=])+=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>))))))"},{"captures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.operator.rest.js"},"3":{"name":"variable.parameter.js variable.language.this.js"},"4":{"name":"variable.parameter.js"},"5":{"name":"keyword.operator.optional.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(override|public|private|protected|readonly)\\\\s+)?(?:(\\\\.\\\\.\\\\.)\\\\s*)?(?<!=|:)(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*(\\\\??)"}]},"parameter-object-binding-element":{"patterns":[{"include":"#comment"},{"begin":"(?=((\\\\b(?<!\\\\$)0(?:x|X)[0-9a-fA-F][0-9a-fA-F_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:b|B)[01][01_]*(n)?\\\\b(?!\\\\$))|(\\\\b(?<!\\\\$)0(?:o|O)?[0-7][0-7_]*(n)?\\\\b(?!\\\\$))|((?<!\\\\$)(?:(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\B(\\\\.)[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*[eE][+-]?[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(\\\\.)(n)?\\\\B)|(?:\\\\B(\\\\.)[0-9][0-9_]*(n)?\\\\b)|(?:\\\\b[0-9][0-9_]*(n)?\\\\b(?!\\\\.)))(?!\\\\$))|([_$[:alpha:]][_$[:alnum:]]*)|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`)|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])+\\\\]))\\\\s*(:))","end":"(?=,|\\\\})","patterns":[{"include":"#object-binding-element-propertyName"},{"include":"#parameter-binding-element"},{"include":"#paren-expression"}]},{"include":"#parameter-object-binding-pattern"},{"include":"#destructuring-parameter-rest"},{"include":"#variable-initializer"},{"include":"#punctuation-comma"}]},"parameter-object-binding-pattern":{"begin":"(?:(\\\\.\\\\.\\\\.)\\\\s*)?(\\\\{)","beginCaptures":{"1":{"name":"keyword.operator.rest.js"},"2":{"name":"punctuation.definition.binding-pattern.object.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.binding-pattern.object.js"}},"patterns":[{"include":"#parameter-object-binding-element"}]},"parameter-type-annotation":{"patterns":[{"begin":"(:)","beginCaptures":{"1":{"name":"keyword.operator.type.annotation.js"}},"end":"(?=[,)])|(?==[^>])","name":"meta.type.annotation.js","patterns":[{"include":"#type"}]}]},"paren-expression":{"begin":"\\\\(","beginCaptures":{"0":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#expression"}]},"paren-expression-possibly-arrow":{"patterns":[{"begin":"(?<=[(=,])\\\\s*(async)?(?=\\\\s*((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*))?\\\\(\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))","beginCaptures":{"1":{"name":"storage.modifier.async.js"}},"end":"(?<=\\\\))","patterns":[{"include":"#paren-expression-possibly-arrow-with-typeparameters"}]},{"begin":"(?<=[(=,]|=>|^return|[^\\\\._$[:alnum:]]return)\\\\s*(async)?(?=\\\\s*((((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*))?\\\\()|(<)|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)))\\\\s*$)","beginCaptures":{"1":{"name":"storage.modifier.async.js"}},"end":"(?<=\\\\))","patterns":[{"include":"#paren-expression-possibly-arrow-with-typeparameters"}]},{"include":"#possibly-arrow-return-type"}]},"paren-expression-possibly-arrow-with-typeparameters":{"patterns":[{"include":"#type-parameters"},{"begin":"\\\\(","beginCaptures":{"0":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"patterns":[{"include":"#expression-inside-possibly-arrow-parens"}]}]},"possibly-arrow-return-type":{"begin":"(?<=\\\\)|^)\\\\s*(:)(?=\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*=>)","beginCaptures":{"1":{"name":"meta.arrow.js meta.return.type.arrow.js keyword.operator.type.annotation.js"}},"contentName":"meta.arrow.js meta.return.type.arrow.js","end":"(?==>|\\\\{|(^\\\\s*(export|function|class|interface|let|var|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|const|import|enum|namespace|module|type|abstract|declare)\\\\s+))","patterns":[{"include":"#arrow-return-type-body"}]},"property-accessor":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(accessor|get|set)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"storage.type.property.js"},"punctuation-accessor":{"captures":{"1":{"name":"punctuation.accessor.js"},"2":{"name":"punctuation.accessor.optional.js"}},"match":"(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))"},"punctuation-comma":{"match":",","name":"punctuation.separator.comma.js"},"punctuation-semicolon":{"match":";","name":"punctuation.terminator.statement.js"},"qstring-double":{"begin":"\\"","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.js"}},"end":"(\\")|((?:[^\\\\\\\\\\\\n])$)","endCaptures":{"1":{"name":"punctuation.definition.string.end.js"},"2":{"name":"invalid.illegal.newline.js"}},"name":"string.quoted.double.js","patterns":[{"include":"#string-character-escape"}]},"qstring-single":{"begin":"'","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.js"}},"end":"(\\\\')|((?:[^\\\\\\\\\\\\n])$)","endCaptures":{"1":{"name":"punctuation.definition.string.end.js"},"2":{"name":"invalid.illegal.newline.js"}},"name":"string.quoted.single.js","patterns":[{"include":"#string-character-escape"}]},"regex":{"patterns":[{"begin":"(?<!\\\\+\\\\+|--|})(?<=[=(:,\\\\[?+!]|^return|[^\\\\._$[:alnum:]]return|^case|[^\\\\._$[:alnum:]]case|=>|&&|\\\\|\\\\||\\\\*\\\\/)\\\\s*(\\\\/)(?![\\\\/*])(?=(?:[^\\\\/\\\\\\\\\\\\[\\\\()]|\\\\\\\\.|\\\\[([^\\\\]\\\\\\\\]|\\\\\\\\.)+\\\\]|\\\\(([^\\\\)\\\\\\\\]|\\\\\\\\.)+\\\\))+\\\\/([dgimsuvy]+|(?![\\\\/\\\\*])|(?=\\\\/\\\\*))(?!\\\\s*[a-zA-Z0-9_$]))","beginCaptures":{"1":{"name":"punctuation.definition.string.begin.js"}},"end":"(/)([dgimsuvy]*)","endCaptures":{"1":{"name":"punctuation.definition.string.end.js"},"2":{"name":"keyword.other.js"}},"name":"string.regexp.js","patterns":[{"include":"#regexp"}]},{"begin":"((?<![_$[:alnum:])\\\\]]|\\\\+\\\\+|--|}|\\\\*\\\\/)|((?<=^return|[^\\\\._$[:alnum:]]return|^case|[^\\\\._$[:alnum:]]case))\\\\s*)\\\\/(?![\\\\/*])(?=(?:[^\\\\/\\\\\\\\\\\\[]|\\\\\\\\.|\\\\[([^\\\\]\\\\\\\\]|\\\\\\\\.)*\\\\])+\\\\/([dgimsuvy]+|(?![\\\\/\\\\*])|(?=\\\\/\\\\*))(?!\\\\s*[a-zA-Z0-9_$]))","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.js"}},"end":"(/)([dgimsuvy]*)","endCaptures":{"1":{"name":"punctuation.definition.string.end.js"},"2":{"name":"keyword.other.js"}},"name":"string.regexp.js","patterns":[{"include":"#regexp"}]}]},"regex-character-class":{"patterns":[{"match":"\\\\\\\\[wWsSdDtrnvf]|\\\\.","name":"constant.other.character-class.regexp"},{"match":"\\\\\\\\([0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4})","name":"constant.character.numeric.regexp"},{"match":"\\\\\\\\c[A-Z]","name":"constant.character.control.regexp"},{"match":"\\\\\\\\.","name":"constant.character.escape.backslash.regexp"}]},"regexp":{"patterns":[{"match":"\\\\\\\\[bB]|\\\\^|\\\\$","name":"keyword.control.anchor.regexp"},{"captures":{"0":{"name":"keyword.other.back-reference.regexp"},"1":{"name":"variable.other.regexp"}},"match":"\\\\\\\\[1-9]\\\\d*|\\\\\\\\k<([a-zA-Z_$][\\\\w$]*)>"},{"match":"[?+*]|\\\\{(\\\\d+,\\\\d+|\\\\d+,|,\\\\d+|\\\\d+)\\\\}\\\\??","name":"keyword.operator.quantifier.regexp"},{"match":"\\\\|","name":"keyword.operator.or.regexp"},{"begin":"(\\\\()((\\\\?=)|(\\\\?!)|(\\\\?<=)|(\\\\?<!))","beginCaptures":{"1":{"name":"punctuation.definition.group.regexp"},"2":{"name":"punctuation.definition.group.assertion.regexp"},"3":{"name":"meta.assertion.look-ahead.regexp"},"4":{"name":"meta.assertion.negative-look-ahead.regexp"},"5":{"name":"meta.assertion.look-behind.regexp"},"6":{"name":"meta.assertion.negative-look-behind.regexp"}},"end":"(\\\\))","endCaptures":{"1":{"name":"punctuation.definition.group.regexp"}},"name":"meta.group.assertion.regexp","patterns":[{"include":"#regexp"}]},{"begin":"\\\\((?:(\\\\?:)|(?:\\\\?<([a-zA-Z_$][\\\\w$]*)>))?","beginCaptures":{"0":{"name":"punctuation.definition.group.regexp"},"1":{"name":"punctuation.definition.group.no-capture.regexp"},"2":{"name":"variable.other.regexp"}},"end":"\\\\)","endCaptures":{"0":{"name":"punctuation.definition.group.regexp"}},"name":"meta.group.regexp","patterns":[{"include":"#regexp"}]},{"begin":"(\\\\[)(\\\\^)?","beginCaptures":{"1":{"name":"punctuation.definition.character-class.regexp"},"2":{"name":"keyword.operator.negation.regexp"}},"end":"(\\\\])","endCaptures":{"1":{"name":"punctuation.definition.character-class.regexp"}},"name":"constant.other.character-class.set.regexp","patterns":[{"captures":{"1":{"name":"constant.character.numeric.regexp"},"2":{"name":"constant.character.control.regexp"},"3":{"name":"constant.character.escape.backslash.regexp"},"4":{"name":"constant.character.numeric.regexp"},"5":{"name":"constant.character.control.regexp"},"6":{"name":"constant.character.escape.backslash.regexp"}},"match":"(?:.|(\\\\\\\\(?:[0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}))|(\\\\\\\\c[A-Z])|(\\\\\\\\.))\\\\-(?:[^\\\\]\\\\\\\\]|(\\\\\\\\(?:[0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}))|(\\\\\\\\c[A-Z])|(\\\\\\\\.))","name":"constant.other.character-class.range.regexp"},{"include":"#regex-character-class"}]},{"include":"#regex-character-class"}]},"return-type":{"patterns":[{"begin":"(?<=\\\\))\\\\s*(:)(?=\\\\s*\\\\S)","beginCaptures":{"1":{"name":"keyword.operator.type.annotation.js"}},"end":"(?<![:|&])(?=$|^|[{};,]|//)","name":"meta.return.type.js","patterns":[{"include":"#return-type-core"}]},{"begin":"(?<=\\\\))\\\\s*(:)","beginCaptures":{"1":{"name":"keyword.operator.type.annotation.js"}},"end":"(?<![:|&])((?=[{};,]|//|^\\\\s*$)|((?<=\\\\S)(?=\\\\s*$)))","name":"meta.return.type.js","patterns":[{"include":"#return-type-core"}]}]},"return-type-core":{"patterns":[{"include":"#comment"},{"begin":"(?<=[:|&])(?=\\\\s*\\\\{)","end":"(?<=\\\\})","patterns":[{"include":"#type-object"}]},{"include":"#type-predicate-operator"},{"include":"#type"}]},"shebang":{"captures":{"1":{"name":"punctuation.definition.comment.js"}},"match":"\\\\A(#!).*(?=$)","name":"comment.line.shebang.js"},"single-line-comment-consuming-line-ending":{"begin":"(^[ \\\\t]+)?((//)(?:\\\\s*((@)internal)(?=\\\\s|$))?)","beginCaptures":{"1":{"name":"punctuation.whitespace.comment.leading.js"},"2":{"name":"comment.line.double-slash.js"},"3":{"name":"punctuation.definition.comment.js"},"4":{"name":"storage.type.internaldeclaration.js"},"5":{"name":"punctuation.decorator.internaldeclaration.js"}},"contentName":"comment.line.double-slash.js","end":"(?=^)"},"statements":{"patterns":[{"include":"#declaration"},{"include":"#control-statement"},{"include":"#after-operator-block-as-object-literal"},{"include":"#decl-block"},{"include":"#label"},{"include":"#expression"},{"include":"#punctuation-semicolon"},{"include":"#string"},{"include":"#comment"}]},"string":{"patterns":[{"include":"#qstring-single"},{"include":"#qstring-double"},{"include":"#template"}]},"string-character-escape":{"match":"\\\\\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|u\\\\{[0-9A-Fa-f]+\\\\}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.|$)","name":"constant.character.escape.js"},"super-literal":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))super\\\\b(?!\\\\$)","name":"variable.language.super.js"},"support-function-call-identifiers":{"patterns":[{"include":"#literal"},{"include":"#support-objects"},{"include":"#object-identifiers"},{"include":"#punctuation-accessor"},{"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))import(?=\\\\s*[\\\\(]\\\\s*[\\\\\\"\\\\'\\\\\`]))","name":"keyword.operator.expression.import.js"}]},"support-objects":{"patterns":[{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(arguments)\\\\b(?!\\\\$)","name":"variable.language.arguments.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(Promise)\\\\b(?!\\\\$)","name":"support.class.promise.js"},{"captures":{"1":{"name":"keyword.control.import.js"},"2":{"name":"punctuation.accessor.js"},"3":{"name":"punctuation.accessor.optional.js"},"4":{"name":"support.variable.property.importmeta.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(import)\\\\s*(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(meta)\\\\b(?!\\\\$)"},{"captures":{"1":{"name":"keyword.operator.new.js"},"2":{"name":"punctuation.accessor.js"},"3":{"name":"punctuation.accessor.optional.js"},"4":{"name":"support.variable.property.target.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(new)\\\\s*(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(target)\\\\b(?!\\\\$)"},{"captures":{"1":{"name":"punctuation.accessor.js"},"2":{"name":"punctuation.accessor.optional.js"},"3":{"name":"support.variable.property.js"},"4":{"name":"support.constant.js"}},"match":"(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(?:(?:(constructor|length|prototype|__proto__)\\\\b(?!\\\\$|\\\\s*(<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\())|(?:(EPSILON|MAX_SAFE_INTEGER|MAX_VALUE|MIN_SAFE_INTEGER|MIN_VALUE|NEGATIVE_INFINITY|POSITIVE_INFINITY)\\\\b(?!\\\\$)))"},{"captures":{"1":{"name":"support.type.object.module.js"},"2":{"name":"support.type.object.module.js"},"3":{"name":"punctuation.accessor.js"},"4":{"name":"punctuation.accessor.optional.js"},"5":{"name":"support.type.object.module.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(exports)|(module)(?:(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))(exports|id|filename|loaded|parent|children))?)\\\\b(?!\\\\$)"}]},"switch-statement":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?=\\\\bswitch\\\\s*\\\\()","end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"name":"switch-statement.expr.js","patterns":[{"include":"#comment"},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(switch)\\\\s*(\\\\()","beginCaptures":{"1":{"name":"keyword.control.switch.js"},"2":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"name":"switch-expression.expr.js","patterns":[{"include":"#expression"}]},{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"(?=\\\\})","name":"switch-block.expr.js","patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(case|default(?=:))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"keyword.control.switch.js"}},"end":"(?=:)","name":"case-clause.expr.js","patterns":[{"include":"#expression"}]},{"begin":"(:)\\\\s*(\\\\{)","beginCaptures":{"1":{"name":"case-clause.expr.js punctuation.definition.section.case-statement.js"},"2":{"name":"meta.block.js punctuation.definition.block.js"}},"contentName":"meta.block.js","end":"\\\\}","endCaptures":{"0":{"name":"meta.block.js punctuation.definition.block.js"}},"patterns":[{"include":"#statements"}]},{"captures":{"0":{"name":"case-clause.expr.js punctuation.definition.section.case-statement.js"}},"match":"(:)"},{"include":"#statements"}]}]},"template":{"patterns":[{"include":"#template-call"},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)?(\`)","beginCaptures":{"1":{"name":"entity.name.function.tagged-template.js"},"2":{"name":"string.template.js punctuation.definition.string.template.begin.js"}},"contentName":"string.template.js","end":"\`","endCaptures":{"0":{"name":"string.template.js punctuation.definition.string.template.end.js"}},"patterns":[{"include":"#template-substitution-element"},{"include":"#string-character-escape"}]}]},"template-call":{"patterns":[{"begin":"(?=(([_$[:alpha:]][_$[:alnum:]]*\\\\s*\\\\??\\\\.\\\\s*)*|(\\\\??\\\\.\\\\s*)?)([_$[:alpha:]][_$[:alnum:]]*)(<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))(([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>)*(?<!=)\\\\>))*(?<!=)\\\\>)*(?<!=)>\\\\s*)?\`)","end":"(?=\`)","patterns":[{"begin":"(?=(([_$[:alpha:]][_$[:alnum:]]*\\\\s*\\\\??\\\\.\\\\s*)*|(\\\\??\\\\.\\\\s*)?)([_$[:alpha:]][_$[:alnum:]]*))","end":"(?=(<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))(([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>)*(?<!=)\\\\>))*(?<!=)\\\\>)*(?<!=)>\\\\s*)?\`)","patterns":[{"include":"#support-function-call-identifiers"},{"match":"([_$[:alpha:]][_$[:alnum:]]*)","name":"entity.name.function.tagged-template.js"}]},{"include":"#type-arguments"}]},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)?\\\\s*(?=(<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))(([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>|\\\\<\\\\s*(((keyof|infer|typeof|readonly)\\\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))(?=\\\\s*([\\\\<\\\\>\\\\,\\\\.\\\\[]|=>|&(?!&)|\\\\|(?!\\\\|)))))([^<>\\\\(]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(?<==)\\\\>)*(?<!=)\\\\>))*(?<!=)\\\\>)*(?<!=)>\\\\s*)\`)","beginCaptures":{"1":{"name":"entity.name.function.tagged-template.js"}},"end":"(?=\`)","patterns":[{"include":"#type-arguments"}]}]},"template-substitution-element":{"begin":"\\\\$\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.template-expression.begin.js"}},"contentName":"meta.embedded.line.js","end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.template-expression.end.js"}},"name":"meta.template.expression.js","patterns":[{"include":"#expression"}]},"template-type":{"patterns":[{"include":"#template-call"},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)?(\`)","beginCaptures":{"1":{"name":"entity.name.function.tagged-template.js"},"2":{"name":"string.template.js punctuation.definition.string.template.begin.js"}},"contentName":"string.template.js","end":"\`","endCaptures":{"0":{"name":"string.template.js punctuation.definition.string.template.end.js"}},"patterns":[{"include":"#template-type-substitution-element"},{"include":"#string-character-escape"}]}]},"template-type-substitution-element":{"begin":"\\\\$\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.template-expression.begin.js"}},"contentName":"meta.embedded.line.js","end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.template-expression.end.js"}},"name":"meta.template.expression.js","patterns":[{"include":"#type"}]},"ternary-expression":{"begin":"(?!\\\\?\\\\.\\\\s*[^[:digit:]])(\\\\?)(?!\\\\?)","beginCaptures":{"1":{"name":"keyword.operator.ternary.js"}},"end":"\\\\s*(:)","endCaptures":{"1":{"name":"keyword.operator.ternary.js"}},"patterns":[{"include":"#expression"}]},"this-literal":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))this\\\\b(?!\\\\$)","name":"variable.language.this.js"},"type":{"patterns":[{"include":"#comment"},{"include":"#type-string"},{"include":"#numeric-literal"},{"include":"#type-primitive"},{"include":"#type-builtin-literals"},{"include":"#type-parameters"},{"include":"#type-tuple"},{"include":"#type-object"},{"include":"#type-operators"},{"include":"#type-conditional"},{"include":"#type-fn-type-parameters"},{"include":"#type-paren-or-function-parameters"},{"include":"#type-function-return-type"},{"captures":{"1":{"name":"storage.modifier.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(readonly)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*"},{"include":"#type-name"}]},"type-alias-declaration":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(type)\\\\b\\\\s+([_$[:alpha:]][_$[:alnum:]]*)\\\\s*","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.type.js"},"4":{"name":"entity.name.type.alias.js"}},"end":"(?=\\\\}|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","name":"meta.type.declaration.js","patterns":[{"include":"#comment"},{"include":"#type-parameters"},{"begin":"(=)\\\\s*(intrinsic)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"1":{"name":"keyword.operator.assignment.js"},"2":{"name":"keyword.control.intrinsic.js"}},"end":"(?=\\\\}|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","patterns":[{"include":"#type"}]},{"begin":"(=)\\\\s*","beginCaptures":{"1":{"name":"keyword.operator.assignment.js"}},"end":"(?=\\\\}|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","patterns":[{"include":"#type"}]}]},"type-annotation":{"patterns":[{"begin":"(:)(?=\\\\s*\\\\S)","beginCaptures":{"1":{"name":"keyword.operator.type.annotation.js"}},"end":"(?<![:|&])(?!\\\\s*[|&]\\\\s+)((?=^|[,);\\\\}\\\\]]|//)|(?==[^>])|((?<=[\\\\}>\\\\]\\\\)]|[_$[:alpha:]])\\\\s*(?=\\\\{)))","name":"meta.type.annotation.js","patterns":[{"include":"#type"}]},{"begin":"(:)","beginCaptures":{"1":{"name":"keyword.operator.type.annotation.js"}},"end":"(?<![:|&])((?=[,);\\\\}\\\\]]|\\\\/\\\\/)|(?==[^>])|(?=^\\\\s*$)|((?<=[\\\\}>\\\\]\\\\)]|[_$[:alpha:]])\\\\s*(?=\\\\{)))","name":"meta.type.annotation.js","patterns":[{"include":"#type"}]}]},"type-arguments":{"begin":"\\\\<","beginCaptures":{"0":{"name":"punctuation.definition.typeparameters.begin.js"}},"end":"\\\\>","endCaptures":{"0":{"name":"punctuation.definition.typeparameters.end.js"}},"name":"meta.type.parameters.js","patterns":[{"include":"#type-arguments-body"}]},"type-arguments-body":{"patterns":[{"captures":{"0":{"name":"keyword.operator.type.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(_)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))"},{"include":"#type"},{"include":"#punctuation-comma"}]},"type-builtin-literals":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(this|true|false|undefined|null|object)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"support.type.builtin.js"},"type-conditional":{"patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(extends)\\\\s+","beginCaptures":{"1":{"name":"storage.modifier.js"}},"end":"(?<=:)","patterns":[{"begin":"\\\\?","beginCaptures":{"0":{"name":"keyword.operator.ternary.js"}},"end":":","endCaptures":{"0":{"name":"keyword.operator.ternary.js"}},"patterns":[{"include":"#type"}]},{"include":"#type"}]}]},"type-fn-type-parameters":{"patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(abstract)\\\\s+)?(new)\\\\b(?=\\\\s*\\\\<)","beginCaptures":{"1":{"name":"meta.type.constructor.js storage.modifier.js"},"2":{"name":"meta.type.constructor.js keyword.control.new.js"}},"end":"(?<=>)","patterns":[{"include":"#comment"},{"include":"#type-parameters"}]},{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(abstract)\\\\s+)?(new)\\\\b\\\\s*(?=\\\\()","beginCaptures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.control.new.js"}},"end":"(?<=\\\\))","name":"meta.type.constructor.js","patterns":[{"include":"#function-parameters"}]},{"begin":"((?=[(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>))))))","end":"(?<=\\\\))","name":"meta.type.function.js","patterns":[{"include":"#function-parameters"}]}]},"type-function-return-type":{"patterns":[{"begin":"(=>)(?=\\\\s*\\\\S)","beginCaptures":{"1":{"name":"storage.type.function.arrow.js"}},"end":"(?<!=>)(?<![|&])(?=[,\\\\]\\\\)\\\\{\\\\}=;>:\\\\?]|//|$)","name":"meta.type.function.return.js","patterns":[{"include":"#type-function-return-type-core"}]},{"begin":"=>","beginCaptures":{"0":{"name":"storage.type.function.arrow.js"}},"end":"(?<!=>)(?<![|&])((?=[,\\\\]\\\\)\\\\{\\\\}=;:\\\\?>]|//|^\\\\s*$)|((?<=\\\\S)(?=\\\\s*$)))","name":"meta.type.function.return.js","patterns":[{"include":"#type-function-return-type-core"}]}]},"type-function-return-type-core":{"patterns":[{"include":"#comment"},{"begin":"(?<==>)(?=\\\\s*\\\\{)","end":"(?<=\\\\})","patterns":[{"include":"#type-object"}]},{"include":"#type-predicate-operator"},{"include":"#type"}]},"type-infer":{"patterns":[{"captures":{"1":{"name":"keyword.operator.expression.infer.js"},"2":{"name":"entity.name.type.js"},"3":{"name":"keyword.operator.expression.extends.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(infer)\\\\s+([_$[:alpha:]][_$[:alnum:]]*)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))(?:\\\\s+(extends)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))?","name":"meta.type.infer.js"}]},"type-name":{"patterns":[{"begin":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))\\\\s*(<)","captures":{"1":{"name":"entity.name.type.module.js"},"2":{"name":"punctuation.accessor.js"},"3":{"name":"punctuation.accessor.optional.js"},"4":{"name":"meta.type.parameters.js punctuation.definition.typeparameters.begin.js"}},"contentName":"meta.type.parameters.js","end":"(>)","endCaptures":{"1":{"name":"meta.type.parameters.js punctuation.definition.typeparameters.end.js"}},"patterns":[{"include":"#type-arguments-body"}]},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(<)","beginCaptures":{"1":{"name":"entity.name.type.js"},"2":{"name":"meta.type.parameters.js punctuation.definition.typeparameters.begin.js"}},"contentName":"meta.type.parameters.js","end":"(>)","endCaptures":{"1":{"name":"meta.type.parameters.js punctuation.definition.typeparameters.end.js"}},"patterns":[{"include":"#type-arguments-body"}]},{"captures":{"1":{"name":"entity.name.type.module.js"},"2":{"name":"punctuation.accessor.js"},"3":{"name":"punctuation.accessor.optional.js"}},"match":"([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(?:(\\\\.)|(\\\\?\\\\.(?!\\\\s*[[:digit:]])))"},{"match":"[_$[:alpha:]][_$[:alnum:]]*","name":"entity.name.type.js"}]},"type-object":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.block.js"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.block.js"}},"name":"meta.object.type.js","patterns":[{"include":"#comment"},{"include":"#method-declaration"},{"include":"#indexer-declaration"},{"include":"#indexer-mapped-type-declaration"},{"include":"#field-declaration"},{"include":"#type-annotation"},{"begin":"\\\\.\\\\.\\\\.","beginCaptures":{"0":{"name":"keyword.operator.spread.js"}},"end":"(?=\\\\}|;|,|$)|(?<=\\\\})","patterns":[{"include":"#type"}]},{"include":"#punctuation-comma"},{"include":"#punctuation-semicolon"},{"include":"#type"}]},"type-operators":{"patterns":[{"include":"#typeof-operator"},{"include":"#type-infer"},{"begin":"([&|])(?=\\\\s*\\\\{)","beginCaptures":{"0":{"name":"keyword.operator.type.js"}},"end":"(?<=\\\\})","patterns":[{"include":"#type-object"}]},{"begin":"[&|]","beginCaptures":{"0":{"name":"keyword.operator.type.js"}},"end":"(?=\\\\S)"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))keyof(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.expression.keyof.js"},{"match":"(\\\\?|\\\\:)","name":"keyword.operator.ternary.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))import(?=\\\\s*\\\\()","name":"keyword.operator.expression.import.js"}]},"type-parameters":{"begin":"(<)","beginCaptures":{"1":{"name":"punctuation.definition.typeparameters.begin.js"}},"end":"(>)","endCaptures":{"1":{"name":"punctuation.definition.typeparameters.end.js"}},"name":"meta.type.parameters.js","patterns":[{"include":"#comment"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(extends|in|out|const)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"storage.modifier.js"},{"include":"#type"},{"include":"#punctuation-comma"},{"match":"(=)(?!>)","name":"keyword.operator.assignment.js"}]},"type-paren-or-function-parameters":{"begin":"\\\\(","beginCaptures":{"0":{"name":"meta.brace.round.js"}},"end":"\\\\)","endCaptures":{"0":{"name":"meta.brace.round.js"}},"name":"meta.type.paren.cover.js","patterns":[{"captures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.operator.rest.js"},"3":{"name":"entity.name.function.js variable.language.this.js"},"4":{"name":"entity.name.function.js"},"5":{"name":"keyword.operator.optional.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(public|private|protected|readonly)\\\\s+)?(?:(\\\\.\\\\.\\\\.)\\\\s*)?(?<!=|:)(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))\\\\s*(\\\\??)(?=\\\\s*(:\\\\s*((<)|([(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>)))))))|(:\\\\s*(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Function(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(:\\\\s*((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))))"},{"captures":{"1":{"name":"storage.modifier.js"},"2":{"name":"keyword.operator.rest.js"},"3":{"name":"variable.parameter.js variable.language.this.js"},"4":{"name":"variable.parameter.js"},"5":{"name":"keyword.operator.optional.js"}},"match":"(?:(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(public|private|protected|readonly)\\\\s+)?(?:(\\\\.\\\\.\\\\.)\\\\s*)?(?<!=|:)(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))\\\\s*(\\\\??)(?=:)"},{"include":"#type-annotation"},{"match":",","name":"punctuation.separator.parameter.js"},{"include":"#type"}]},"type-predicate-operator":{"patterns":[{"captures":{"1":{"name":"keyword.operator.type.asserts.js"},"2":{"name":"variable.parameter.js variable.language.this.js"},"3":{"name":"variable.parameter.js"},"4":{"name":"keyword.operator.expression.is.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(asserts)\\\\s+)?(?!asserts)(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))\\\\s(is)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))"},{"captures":{"1":{"name":"keyword.operator.type.asserts.js"},"2":{"name":"variable.parameter.js variable.language.this.js"},"3":{"name":"variable.parameter.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(asserts)\\\\s+(?!is)(?:(this)|([_$[:alpha:]][_$[:alnum:]]*))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))asserts(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.type.asserts.js"},{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))is(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"keyword.operator.expression.is.js"}]},"type-primitive":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(string|number|bigint|boolean|symbol|any|void|never|unknown)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"support.type.primitive.js"},"type-string":{"patterns":[{"include":"#qstring-single"},{"include":"#qstring-double"},{"include":"#template-type"}]},"type-tuple":{"begin":"\\\\[","beginCaptures":{"0":{"name":"meta.brace.square.js"}},"end":"\\\\]","endCaptures":{"0":{"name":"meta.brace.square.js"}},"name":"meta.type.tuple.js","patterns":[{"match":"\\\\.\\\\.\\\\.","name":"keyword.operator.rest.js"},{"captures":{"1":{"name":"entity.name.label.js"},"2":{"name":"keyword.operator.optional.js"},"3":{"name":"punctuation.separator.label.js"}},"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))([_$[:alpha:]][_$[:alnum:]]*)\\\\s*(\\\\?)?\\\\s*(:)"},{"include":"#type"},{"include":"#punctuation-comma"}]},"typeof-operator":{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))typeof(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","beginCaptures":{"0":{"name":"keyword.operator.expression.typeof.js"}},"end":"(?=[,);}\\\\]=>:&|{\\\\?]|(extends\\\\s+)|$|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))","patterns":[{"include":"#type-arguments"},{"include":"#expression"}]},"undefined-literal":{"match":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))undefined(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))","name":"constant.language.undefined.js"},"var-expr":{"patterns":[{"begin":"(?=(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(var|let)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))","end":"(?!(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(var|let)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))((?=^|;|}|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))|((?<!^let|[^\\\\._$[:alnum:]]let|^var|[^\\\\._$[:alnum:]]var)(?=\\\\s*$)))","name":"meta.var.expr.js","patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(var|let)(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.js"}},"end":"(?=\\\\S)"},{"include":"#destructuring-variable"},{"include":"#var-single-variable"},{"include":"#variable-initializer"},{"include":"#comment"},{"begin":"(,)\\\\s*(?=$|\\\\/\\\\/)","beginCaptures":{"1":{"name":"punctuation.separator.comma.js"}},"end":"(?<!,)(((?==|;|}|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|^\\\\s*$))|((?<=\\\\S)(?=\\\\s*$)))","patterns":[{"include":"#single-line-comment-consuming-line-ending"},{"include":"#comment"},{"include":"#destructuring-variable"},{"include":"#var-single-variable"},{"include":"#punctuation-comma"}]},{"include":"#punctuation-comma"}]},{"begin":"(?=(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(const(?!\\\\s+enum\\\\b))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.js"}},"end":"(?!(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(const(?!\\\\s+enum\\\\b))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))((?=^|;|}|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))|((?<!^const|[^\\\\._$[:alnum:]]const)(?=\\\\s*$)))","name":"meta.var.expr.js","patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b(const(?!\\\\s+enum\\\\b))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.js"}},"end":"(?=\\\\S)"},{"include":"#destructuring-const"},{"include":"#var-single-const"},{"include":"#variable-initializer"},{"include":"#comment"},{"begin":"(,)\\\\s*(?=$|\\\\/\\\\/)","beginCaptures":{"1":{"name":"punctuation.separator.comma.js"}},"end":"(?<!,)(((?==|;|}|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|^\\\\s*$))|((?<=\\\\S)(?=\\\\s*$)))","patterns":[{"include":"#single-line-comment-consuming-line-ending"},{"include":"#comment"},{"include":"#destructuring-const"},{"include":"#var-single-const"},{"include":"#punctuation-comma"}]},{"include":"#punctuation-comma"}]},{"begin":"(?=(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b((?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.js"}},"end":"(?!(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b((?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))((?=;|}|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b))|((?<!^using|[^\\\\._$[:alnum:]]using|^await\\\\s+using|[^\\\\._$[:alnum:]]await\\\\s+using)(?=\\\\s*$)))","name":"meta.var.expr.js","patterns":[{"begin":"(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(?:(\\\\bexport)\\\\s+)?(?:(\\\\bdeclare)\\\\s+)?\\\\b((?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b))(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.))\\\\s*","beginCaptures":{"1":{"name":"keyword.control.export.js"},"2":{"name":"storage.modifier.js"},"3":{"name":"storage.type.js"}},"end":"(?=\\\\S)"},{"include":"#var-single-const"},{"include":"#variable-initializer"},{"include":"#comment"},{"begin":"(,)\\\\s*((?!\\\\S)|(?=\\\\/\\\\/))","beginCaptures":{"1":{"name":"punctuation.separator.comma.js"}},"end":"(?<!,)(((?==|;|}|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|^\\\\s*$))|((?<=\\\\S)(?=\\\\s*$)))","patterns":[{"include":"#single-line-comment-consuming-line-ending"},{"include":"#comment"},{"include":"#var-single-const"},{"include":"#punctuation-comma"}]},{"include":"#punctuation-comma"}]}]},"var-single-const":{"patterns":[{"begin":"([_$[:alpha:]][_$[:alnum:]]*)(?=\\\\s*(=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))))|(:\\\\s*((<)|([(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>)))))))|(:\\\\s*(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Function(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(:\\\\s*((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))))|(:\\\\s*(=>|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(<[^<>]*>)|[^<>(),=])+=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>))))))","beginCaptures":{"1":{"name":"meta.definition.variable.js variable.other.constant.js entity.name.function.js"}},"end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|(;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b)))","name":"meta.var-single-variable.expr.js","patterns":[{"include":"#var-single-variable-type-annotation"}]},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)","beginCaptures":{"1":{"name":"meta.definition.variable.js variable.other.constant.js"}},"end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|(;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b)))","name":"meta.var-single-variable.expr.js","patterns":[{"include":"#var-single-variable-type-annotation"}]}]},"var-single-variable":{"patterns":[{"begin":"([_$[:alpha:]][_$[:alnum:]]*)(\\\\!)?(?=\\\\s*(=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>)))))|(:\\\\s*((<)|([(]\\\\s*(([)])|(\\\\.\\\\.\\\\.)|([_$[:alnum:]]+\\\\s*(([:,?=])|([)]\\\\s*=>)))))))|(:\\\\s*(?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))Function(?![_$[:alnum:]])(?:(?=\\\\.\\\\.\\\\.)|(?!\\\\.)))|(:\\\\s*((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))))))|(:\\\\s*(=>|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(<[^<>]*>)|[^<>(),=])+=\\\\s*(((async\\\\s+)?((function\\\\s*[(<*])|(function\\\\s+)|([_$[:alpha:]][_$[:alnum:]]*\\\\s*=>)))|((async\\\\s*)?(((<\\\\s*$)|([\\\\(]\\\\s*((([\\\\{\\\\[]\\\\s*)?$)|((\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})\\\\s*((:\\\\s*\\\\{?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*)))|((\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])\\\\s*((:\\\\s*\\\\[?$)|((\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+\\\\s*)?=\\\\s*))))))|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?[(]\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([)]\\\\s*:)|((\\\\.\\\\.\\\\.\\\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\\\s*:)))|([<]\\\\s*[_$[:alpha:]][_$[:alnum:]]*\\\\s+extends\\\\s*[^=>])|((<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<]|\\\\<\\\\s*(((const\\\\s+)?[_$[:alpha:]])|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\]))([^=<>]|=[^<])*\\\\>)*\\\\>)*>\\\\s*)?\\\\(\\\\s*(\\\\/\\\\*([^\\\\*]|(\\\\*[^\\\\/]))*\\\\*\\\\/\\\\s*)*(([_$[:alpha:]]|(\\\\{([^\\\\{\\\\}]|(\\\\{([^\\\\{\\\\}]|\\\\{[^\\\\{\\\\}]*\\\\})*\\\\}))*\\\\})|(\\\\[([^\\\\[\\\\]]|(\\\\[([^\\\\[\\\\]]|\\\\[[^\\\\[\\\\]]*\\\\])*\\\\]))*\\\\])|(\\\\.\\\\.\\\\.\\\\s*[_$[:alpha:]]))([^()\\\\'\\\\\\"\\\\\`]|(\\\\(([^\\\\(\\\\)]|(\\\\(([^\\\\(\\\\)]|\\\\([^\\\\(\\\\)]*\\\\))*\\\\)))*\\\\))|(\\\\'([^\\\\'\\\\\\\\]|\\\\\\\\.)*\\\\')|(\\\\\\"([^\\\\\\"\\\\\\\\]|\\\\\\\\.)*\\\\\\")|(\\\\\`([^\\\\\`\\\\\\\\]|\\\\\\\\.)*\\\\\`))*)?\\\\)(\\\\s*:\\\\s*([^<>\\\\(\\\\)\\\\{\\\\}]|\\\\<([^<>]|\\\\<([^<>]|\\\\<[^<>]+\\\\>)+\\\\>)+\\\\>|\\\\([^\\\\(\\\\)]+\\\\)|\\\\{[^\\\\{\\\\}]+\\\\})+)?\\\\s*=>))))))","beginCaptures":{"1":{"name":"meta.definition.variable.js entity.name.function.js"},"2":{"name":"keyword.operator.definiteassignment.js"}},"end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|(;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b)))","name":"meta.var-single-variable.expr.js","patterns":[{"include":"#var-single-variable-type-annotation"}]},{"begin":"([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])(\\\\!)?","beginCaptures":{"1":{"name":"meta.definition.variable.js variable.other.constant.js"},"2":{"name":"keyword.operator.definiteassignment.js"}},"end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|(;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b)))","name":"meta.var-single-variable.expr.js","patterns":[{"include":"#var-single-variable-type-annotation"}]},{"begin":"([_$[:alpha:]][_$[:alnum:]]*)(\\\\!)?","beginCaptures":{"1":{"name":"meta.definition.variable.js variable.other.readwrite.js"},"2":{"name":"keyword.operator.definiteassignment.js"}},"end":"(?=$|^|[;,=}]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+)|(;|^\\\\s*$|(?:^\\\\s*(?:abstract|async|(?:\\\\bawait\\\\s+(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)\\\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|function|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|(?:\\\\busing(?=\\\\s+(?!in\\\\b|of\\\\b(?!\\\\s*(?:of\\\\b|=)))[_$[:alpha:]])\\\\b)|var|while)\\\\b)))","name":"meta.var-single-variable.expr.js","patterns":[{"include":"#var-single-variable-type-annotation"}]}]},"var-single-variable-type-annotation":{"patterns":[{"include":"#type-annotation"},{"include":"#string"},{"include":"#comment"}]},"variable-initializer":{"patterns":[{"begin":"(?<!=|!)(=)(?!=)(?=\\\\s*\\\\S)(?!\\\\s*.*=>\\\\s*$)","beginCaptures":{"1":{"name":"keyword.operator.assignment.js"}},"end":"(?=$|^|[,);}\\\\]]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+))","patterns":[{"include":"#expression"}]},{"begin":"(?<!=|!)(=)(?!=)","beginCaptures":{"1":{"name":"keyword.operator.assignment.js"}},"end":"(?=[,);}\\\\]]|((?<![_$[:alnum:]])(?:(?<=\\\\.\\\\.\\\\.)|(?<!\\\\.))(of|in)\\\\s+))|(?=^\\\\s*$)|(?<![\\\\|\\\\&\\\\+\\\\-\\\\*\\\\/])(?<=\\\\S)(?<!=)(?=\\\\s*$)","patterns":[{"include":"#expression"}]}]}},"scopeName":"source.js","aliases":["js"]}`));
    javascript_default = [
      lang
    ];
  }
});

// node_modules/shiki/dist/langs/javascript.mjs
var javascript_exports = {};
__export(javascript_exports, {
  default: () => javascript_default
});
var init_javascript2 = __esm({
  "node_modules/shiki/dist/langs/javascript.mjs"() {
    init_javascript();
  }
});

// node_modules/best-effort-json-parser/dist/parse.js
var require_parse = __commonJS({
  "node_modules/best-effort-json-parser/dist/parse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.parse = exports.enableErrorLogging = exports.disableErrorLogging = exports.setErrorLogger = void 0;
    var logError = console.error;
    function setErrorLogger(logger) {
      logError = logger;
    }
    exports.setErrorLogger = setErrorLogger;
    function disableErrorLogging() {
      logError = () => {
      };
    }
    exports.disableErrorLogging = disableErrorLogging;
    function enableErrorLogging() {
      logError = console.error;
    }
    exports.enableErrorLogging = enableErrorLogging;
    function parse4(s3) {
      if (s3 === void 0) {
        return void 0;
      }
      if (s3 === null) {
        return null;
      }
      if (s3 === "") {
        return "";
      }
      s3 = s3.replace(/\\+$/, (match2) => match2.length % 2 === 0 ? match2 : match2.slice(0, -1));
      try {
        return JSON.parse(s3);
      } catch (e3) {
        const [data2, reminding] = s3.trimLeft()[0] === ":" ? parseAny(s3, e3) : parseAny(s3, e3, parseStringWithoutQuote);
        parse4.lastParseReminding = reminding;
        if (parse4.onExtraToken && reminding.length > 0) {
          const trimmedReminding = reminding.trimRight();
          parse4.lastParseReminding = trimmedReminding;
          if (trimmedReminding.length > 0) {
            parse4.onExtraToken(s3, data2, trimmedReminding);
          }
        }
        return data2;
      }
    }
    exports.parse = parse4;
    (function(parse5) {
      parse5.onExtraToken = (text3, data2, reminding) => {
        logError("parsed json with extra tokens:", {
          text: text3,
          data: data2,
          reminding
        });
      };
    })(parse4 = exports.parse || (exports.parse = {}));
    function parseAny(s3, e3, fallback) {
      const parser4 = parsers[s3[0]] || fallback;
      if (!parser4) {
        logError(`no parser registered for ${JSON.stringify(s3[0])}:`, { s: s3 });
        throw e3;
      }
      return parser4(s3, e3);
    }
    function parseStringCasual(s3, e3, delimiters) {
      if (s3[0] === '"') {
        return parseString(s3);
      }
      if (s3[0] === "'") {
        return parseSingleQuoteString(s3);
      }
      return parseStringWithoutQuote(s3, e3, delimiters);
    }
    var parsers = {};
    function skipSpace(s3) {
      return s3.trimLeft();
    }
    parsers[" "] = parseSpace;
    parsers["\r"] = parseSpace;
    parsers["\n"] = parseSpace;
    parsers["	"] = parseSpace;
    function parseSpace(s3, e3) {
      s3 = skipSpace(s3);
      return parseAny(s3, e3);
    }
    parsers["["] = parseArray;
    function parseArray(s3, e3) {
      s3 = s3.substr(1);
      const acc = [];
      s3 = skipSpace(s3);
      for (; s3.length > 0; ) {
        if (s3[0] === "]") {
          s3 = s3.substr(1);
          break;
        }
        const res = parseAny(s3, e3, (s4, e4) => parseStringWithoutQuote(s4, e4, [",", "]"]));
        acc.push(res[0]);
        s3 = res[1];
        s3 = skipSpace(s3);
        if (s3[0] === ",") {
          s3 = s3.substring(1);
          s3 = skipSpace(s3);
        }
      }
      return [acc, s3];
    }
    for (const c3 of "0123456789.-".slice()) {
      parsers[c3] = parseNumber;
    }
    function parseNumber(s3) {
      for (let i3 = 0; i3 < s3.length; i3++) {
        const c3 = s3[i3];
        if (parsers[c3] === parseNumber) {
          continue;
        }
        const num = s3.substring(0, i3);
        s3 = s3.substring(i3);
        return [numToStr(num), s3];
      }
      return [numToStr(s3), ""];
    }
    function numToStr(s3) {
      if (s3 === "-") {
        return -0;
      }
      const num = +s3;
      if (Number.isNaN(num)) {
        return s3;
      }
      return num;
    }
    parsers['"'] = parseString;
    function parseString(s3) {
      for (let i3 = 1; i3 < s3.length; i3++) {
        const c3 = s3[i3];
        if (c3 === "\\") {
          i3++;
          continue;
        }
        if (c3 === '"') {
          const str = fixEscapedCharacters(s3.substring(0, i3 + 1));
          s3 = s3.substring(i3 + 1);
          return [JSON.parse(str), s3];
        }
      }
      return [JSON.parse(fixEscapedCharacters(s3) + '"'), ""];
    }
    function fixEscapedCharacters(s3) {
      return s3.replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
    }
    parsers["'"] = parseSingleQuoteString;
    function parseSingleQuoteString(s3) {
      for (let i3 = 1; i3 < s3.length; i3++) {
        const c3 = s3[i3];
        if (c3 === "\\") {
          i3++;
          continue;
        }
        if (c3 === "'") {
          const str = fixEscapedCharacters(s3.substring(0, i3 + 1));
          s3 = s3.substring(i3 + 1);
          return [JSON.parse('"' + str.slice(1, -1) + '"'), s3];
        }
      }
      return [JSON.parse('"' + fixEscapedCharacters(s3.slice(1)) + '"'), ""];
    }
    function parseStringWithoutQuote(s3, e3, delimiters = [" "]) {
      const index2 = Math.min(...delimiters.map((delimiter2) => {
        const index3 = s3.indexOf(delimiter2);
        return index3 === -1 ? s3.length : index3;
      }));
      const value2 = s3.substring(0, index2).trim();
      const rest2 = s3.substring(index2);
      return [value2, rest2];
    }
    parsers["{"] = parseObject;
    function parseObject(s3, e3) {
      s3 = s3.substr(1);
      const acc = {};
      s3 = skipSpace(s3);
      for (; s3.length > 0; ) {
        if (s3[0] === "}") {
          s3 = s3.substr(1);
          break;
        }
        const keyRes = parseStringCasual(s3, e3, [":", "}"]);
        const key2 = keyRes[0];
        s3 = keyRes[1];
        s3 = skipSpace(s3);
        if (s3[0] !== ":") {
          acc[key2] = void 0;
          break;
        }
        s3 = s3.substr(1);
        s3 = skipSpace(s3);
        if (s3.length === 0) {
          acc[key2] = void 0;
          break;
        }
        const valueRes = parseAny(s3, e3);
        acc[key2] = valueRes[0];
        s3 = valueRes[1];
        s3 = skipSpace(s3);
        if (s3[0] === ",") {
          s3 = s3.substr(1);
          s3 = skipSpace(s3);
        }
      }
      return [acc, s3];
    }
    parsers["t"] = parseTrue;
    function parseTrue(s3, e3) {
      return parseToken(s3, `true`, true, e3);
    }
    parsers["f"] = parseFalse;
    function parseFalse(s3, e3) {
      return parseToken(s3, `false`, false, e3);
    }
    parsers["n"] = parseNull;
    function parseNull(s3, e3) {
      return parseToken(s3, `null`, null, e3);
    }
    function parseToken(s3, tokenStr, tokenVal, e3) {
      for (let i3 = tokenStr.length; i3 >= 1; i3--) {
        if (s3.startsWith(tokenStr.slice(0, i3))) {
          return [tokenVal, s3.slice(i3)];
        }
      }
      {
        const prefix5 = JSON.stringify(s3.slice(0, tokenStr.length));
        logError(`unknown token starting with ${prefix5}:`, { s: s3 });
        throw e3;
      }
    }
  }
});

// node_modules/json5/dist/index.js
var require_dist = __commonJS({
  "node_modules/json5/dist/index.js"(exports, module) {
    (function(global5, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global5.JSON5 = factory();
    })(exports, function() {
      "use strict";
      function createCommonjsModule2(fn, module2) {
        return module2 = { exports: {} }, fn(module2, module2.exports), module2.exports;
      }
      var _global = createCommonjsModule2(function(module2) {
        var global5 = module2.exports = typeof window != "undefined" && window.Math == Math ? window : typeof self != "undefined" && self.Math == Math ? self : Function("return this")();
        if (typeof __g == "number") {
          __g = global5;
        }
      });
      var _core = createCommonjsModule2(function(module2) {
        var core2 = module2.exports = { version: "2.6.5" };
        if (typeof __e == "number") {
          __e = core2;
        }
      });
      var _core_1 = _core.version;
      var _isObject = function(it2) {
        return typeof it2 === "object" ? it2 !== null : typeof it2 === "function";
      };
      var _anObject = function(it2) {
        if (!_isObject(it2)) {
          throw TypeError(it2 + " is not an object!");
        }
        return it2;
      };
      var _fails = function(exec) {
        try {
          return !!exec();
        } catch (e3) {
          return true;
        }
      };
      var _descriptors = !_fails(function() {
        return Object.defineProperty({}, "a", { get: function() {
          return 7;
        } }).a != 7;
      });
      var document2 = _global.document;
      var is = _isObject(document2) && _isObject(document2.createElement);
      var _domCreate = function(it2) {
        return is ? document2.createElement(it2) : {};
      };
      var _ie8DomDefine = !_descriptors && !_fails(function() {
        return Object.defineProperty(_domCreate("div"), "a", { get: function() {
          return 7;
        } }).a != 7;
      });
      var _toPrimitive = function(it2, S2) {
        if (!_isObject(it2)) {
          return it2;
        }
        var fn, val;
        if (S2 && typeof (fn = it2.toString) == "function" && !_isObject(val = fn.call(it2))) {
          return val;
        }
        if (typeof (fn = it2.valueOf) == "function" && !_isObject(val = fn.call(it2))) {
          return val;
        }
        if (!S2 && typeof (fn = it2.toString) == "function" && !_isObject(val = fn.call(it2))) {
          return val;
        }
        throw TypeError("Can't convert object to primitive value");
      };
      var dP = Object.defineProperty;
      var f3 = _descriptors ? Object.defineProperty : function defineProperty3(O4, P3, Attributes) {
        _anObject(O4);
        P3 = _toPrimitive(P3, true);
        _anObject(Attributes);
        if (_ie8DomDefine) {
          try {
            return dP(O4, P3, Attributes);
          } catch (e3) {
          }
        }
        if ("get" in Attributes || "set" in Attributes) {
          throw TypeError("Accessors not supported!");
        }
        if ("value" in Attributes) {
          O4[P3] = Attributes.value;
        }
        return O4;
      };
      var _objectDp = {
        f: f3
      };
      var _propertyDesc = function(bitmap, value2) {
        return {
          enumerable: !(bitmap & 1),
          configurable: !(bitmap & 2),
          writable: !(bitmap & 4),
          value: value2
        };
      };
      var _hide = _descriptors ? function(object2, key3, value2) {
        return _objectDp.f(object2, key3, _propertyDesc(1, value2));
      } : function(object2, key3, value2) {
        object2[key3] = value2;
        return object2;
      };
      var hasOwnProperty5 = {}.hasOwnProperty;
      var _has = function(it2, key3) {
        return hasOwnProperty5.call(it2, key3);
      };
      var id = 0;
      var px = Math.random();
      var _uid = function(key3) {
        return "Symbol(".concat(key3 === void 0 ? "" : key3, ")_", (++id + px).toString(36));
      };
      var _library = false;
      var _shared = createCommonjsModule2(function(module2) {
        var SHARED = "__core-js_shared__";
        var store2 = _global[SHARED] || (_global[SHARED] = {});
        (module2.exports = function(key3, value2) {
          return store2[key3] || (store2[key3] = value2 !== void 0 ? value2 : {});
        })("versions", []).push({
          version: _core.version,
          mode: _library ? "pure" : "global",
          copyright: "\xA9 2019 Denis Pushkarev (zloirock.ru)"
        });
      });
      var _functionToString = _shared("native-function-to-string", Function.toString);
      var _redefine = createCommonjsModule2(function(module2) {
        var SRC = _uid("src");
        var TO_STRING = "toString";
        var TPL = ("" + _functionToString).split(TO_STRING);
        _core.inspectSource = function(it2) {
          return _functionToString.call(it2);
        };
        (module2.exports = function(O4, key3, val, safe) {
          var isFunction4 = typeof val == "function";
          if (isFunction4) {
            _has(val, "name") || _hide(val, "name", key3);
          }
          if (O4[key3] === val) {
            return;
          }
          if (isFunction4) {
            _has(val, SRC) || _hide(val, SRC, O4[key3] ? "" + O4[key3] : TPL.join(String(key3)));
          }
          if (O4 === _global) {
            O4[key3] = val;
          } else if (!safe) {
            delete O4[key3];
            _hide(O4, key3, val);
          } else if (O4[key3]) {
            O4[key3] = val;
          } else {
            _hide(O4, key3, val);
          }
        })(Function.prototype, TO_STRING, function toString9() {
          return typeof this == "function" && this[SRC] || _functionToString.call(this);
        });
      });
      var _aFunction = function(it2) {
        if (typeof it2 != "function") {
          throw TypeError(it2 + " is not a function!");
        }
        return it2;
      };
      var _ctx = function(fn, that, length) {
        _aFunction(fn);
        if (that === void 0) {
          return fn;
        }
        switch (length) {
          case 1:
            return function(a3) {
              return fn.call(that, a3);
            };
          case 2:
            return function(a3, b3) {
              return fn.call(that, a3, b3);
            };
          case 3:
            return function(a3, b3, c4) {
              return fn.call(that, a3, b3, c4);
            };
        }
        return function() {
          return fn.apply(that, arguments);
        };
      };
      var PROTOTYPE = "prototype";
      var $export = function(type, name2, source2) {
        var IS_FORCED = type & $export.F;
        var IS_GLOBAL = type & $export.G;
        var IS_STATIC = type & $export.S;
        var IS_PROTO = type & $export.P;
        var IS_BIND = type & $export.B;
        var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name2] || (_global[name2] = {}) : (_global[name2] || {})[PROTOTYPE];
        var exports2 = IS_GLOBAL ? _core : _core[name2] || (_core[name2] = {});
        var expProto = exports2[PROTOTYPE] || (exports2[PROTOTYPE] = {});
        var key3, own4, out, exp;
        if (IS_GLOBAL) {
          source2 = name2;
        }
        for (key3 in source2) {
          own4 = !IS_FORCED && target && target[key3] !== void 0;
          out = (own4 ? target : source2)[key3];
          exp = IS_BIND && own4 ? _ctx(out, _global) : IS_PROTO && typeof out == "function" ? _ctx(Function.call, out) : out;
          if (target) {
            _redefine(target, key3, out, type & $export.U);
          }
          if (exports2[key3] != out) {
            _hide(exports2, key3, exp);
          }
          if (IS_PROTO && expProto[key3] != out) {
            expProto[key3] = out;
          }
        }
      };
      _global.core = _core;
      $export.F = 1;
      $export.G = 2;
      $export.S = 4;
      $export.P = 8;
      $export.B = 16;
      $export.W = 32;
      $export.U = 64;
      $export.R = 128;
      var _export = $export;
      var ceil = Math.ceil;
      var floor2 = Math.floor;
      var _toInteger = function(it2) {
        return isNaN(it2 = +it2) ? 0 : (it2 > 0 ? floor2 : ceil)(it2);
      };
      var _defined = function(it2) {
        if (it2 == void 0) {
          throw TypeError("Can't call method on  " + it2);
        }
        return it2;
      };
      var _stringAt = function(TO_STRING) {
        return function(that, pos2) {
          var s3 = String(_defined(that));
          var i3 = _toInteger(pos2);
          var l3 = s3.length;
          var a3, b3;
          if (i3 < 0 || i3 >= l3) {
            return TO_STRING ? "" : void 0;
          }
          a3 = s3.charCodeAt(i3);
          return a3 < 55296 || a3 > 56319 || i3 + 1 === l3 || (b3 = s3.charCodeAt(i3 + 1)) < 56320 || b3 > 57343 ? TO_STRING ? s3.charAt(i3) : a3 : TO_STRING ? s3.slice(i3, i3 + 2) : (a3 - 55296 << 10) + (b3 - 56320) + 65536;
        };
      };
      var $at = _stringAt(false);
      _export(_export.P, "String", {
        // 21.1.3.3 String.prototype.codePointAt(pos)
        codePointAt: function codePointAt4(pos2) {
          return $at(this, pos2);
        }
      });
      var codePointAt3 = _core.String.codePointAt;
      var max3 = Math.max;
      var min3 = Math.min;
      var _toAbsoluteIndex = function(index2, length) {
        index2 = _toInteger(index2);
        return index2 < 0 ? max3(index2 + length, 0) : min3(index2, length);
      };
      var fromCharCode = String.fromCharCode;
      var $fromCodePoint = String.fromCodePoint;
      _export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), "String", {
        // 21.1.2.2 String.fromCodePoint(...codePoints)
        fromCodePoint: function fromCodePoint5(x3) {
          var arguments$1 = arguments;
          var res = [];
          var aLen = arguments.length;
          var i3 = 0;
          var code2;
          while (aLen > i3) {
            code2 = +arguments$1[i3++];
            if (_toAbsoluteIndex(code2, 1114111) !== code2) {
              throw RangeError(code2 + " is not a valid code point");
            }
            res.push(
              code2 < 65536 ? fromCharCode(code2) : fromCharCode(((code2 -= 65536) >> 10) + 55296, code2 % 1024 + 56320)
            );
          }
          return res.join("");
        }
      });
      var fromCodePoint4 = _core.String.fromCodePoint;
      var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
      var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
      var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
      var unicode = {
        Space_Separator,
        ID_Start,
        ID_Continue
      };
      var util = {
        isSpaceSeparator: function isSpaceSeparator(c4) {
          return typeof c4 === "string" && unicode.Space_Separator.test(c4);
        },
        isIdStartChar: function isIdStartChar(c4) {
          return typeof c4 === "string" && (c4 >= "a" && c4 <= "z" || c4 >= "A" && c4 <= "Z" || c4 === "$" || c4 === "_" || unicode.ID_Start.test(c4));
        },
        isIdContinueChar: function isIdContinueChar(c4) {
          return typeof c4 === "string" && (c4 >= "a" && c4 <= "z" || c4 >= "A" && c4 <= "Z" || c4 >= "0" && c4 <= "9" || c4 === "$" || c4 === "_" || c4 === "\u200C" || c4 === "\u200D" || unicode.ID_Continue.test(c4));
        },
        isDigit: function isDigit(c4) {
          return typeof c4 === "string" && /[0-9]/.test(c4);
        },
        isHexDigit: function isHexDigit(c4) {
          return typeof c4 === "string" && /[0-9A-Fa-f]/.test(c4);
        }
      };
      var source;
      var parseState;
      var stack;
      var pos;
      var line;
      var column;
      var token;
      var key2;
      var root3;
      var parse4 = function parse5(text3, reviver) {
        source = String(text3);
        parseState = "start";
        stack = [];
        pos = 0;
        line = 1;
        column = 0;
        token = void 0;
        key2 = void 0;
        root3 = void 0;
        do {
          token = lex();
          parseStates[parseState]();
        } while (token.type !== "eof");
        if (typeof reviver === "function") {
          return internalize({ "": root3 }, "", reviver);
        }
        return root3;
      };
      function internalize(holder, name2, reviver) {
        var value2 = holder[name2];
        if (value2 != null && typeof value2 === "object") {
          if (Array.isArray(value2)) {
            for (var i3 = 0; i3 < value2.length; i3++) {
              var key3 = String(i3);
              var replacement = internalize(value2, key3, reviver);
              if (replacement === void 0) {
                delete value2[key3];
              } else {
                Object.defineProperty(value2, key3, {
                  value: replacement,
                  writable: true,
                  enumerable: true,
                  configurable: true
                });
              }
            }
          } else {
            for (var key$1 in value2) {
              var replacement$1 = internalize(value2, key$1, reviver);
              if (replacement$1 === void 0) {
                delete value2[key$1];
              } else {
                Object.defineProperty(value2, key$1, {
                  value: replacement$1,
                  writable: true,
                  enumerable: true,
                  configurable: true
                });
              }
            }
          }
        }
        return reviver.call(holder, name2, value2);
      }
      var lexState;
      var buffer;
      var doubleQuote;
      var sign;
      var c3;
      function lex() {
        lexState = "default";
        buffer = "";
        doubleQuote = false;
        sign = 1;
        for (; ; ) {
          c3 = peek();
          var token2 = lexStates[lexState]();
          if (token2) {
            return token2;
          }
        }
      }
      function peek() {
        if (source[pos]) {
          return String.fromCodePoint(source.codePointAt(pos));
        }
      }
      function read() {
        var c4 = peek();
        if (c4 === "\n") {
          line++;
          column = 0;
        } else if (c4) {
          column += c4.length;
        } else {
          column++;
        }
        if (c4) {
          pos += c4.length;
        }
        return c4;
      }
      var lexStates = {
        default: function default$1() {
          switch (c3) {
            case "	":
            case "\v":
            case "\f":
            case " ":
            case "\xA0":
            case "\uFEFF":
            case "\n":
            case "\r":
            case "\u2028":
            case "\u2029":
              read();
              return;
            case "/":
              read();
              lexState = "comment";
              return;
            case void 0:
              read();
              return newToken("eof");
          }
          if (util.isSpaceSeparator(c3)) {
            read();
            return;
          }
          return lexStates[parseState]();
        },
        comment: function comment4() {
          switch (c3) {
            case "*":
              read();
              lexState = "multiLineComment";
              return;
            case "/":
              read();
              lexState = "singleLineComment";
              return;
          }
          throw invalidChar(read());
        },
        multiLineComment: function multiLineComment() {
          switch (c3) {
            case "*":
              read();
              lexState = "multiLineCommentAsterisk";
              return;
            case void 0:
              throw invalidChar(read());
          }
          read();
        },
        multiLineCommentAsterisk: function multiLineCommentAsterisk() {
          switch (c3) {
            case "*":
              read();
              return;
            case "/":
              read();
              lexState = "default";
              return;
            case void 0:
              throw invalidChar(read());
          }
          read();
          lexState = "multiLineComment";
        },
        singleLineComment: function singleLineComment() {
          switch (c3) {
            case "\n":
            case "\r":
            case "\u2028":
            case "\u2029":
              read();
              lexState = "default";
              return;
            case void 0:
              read();
              return newToken("eof");
          }
          read();
        },
        value: function value2() {
          switch (c3) {
            case "{":
            case "[":
              return newToken("punctuator", read());
            case "n":
              read();
              literal2("ull");
              return newToken("null", null);
            case "t":
              read();
              literal2("rue");
              return newToken("boolean", true);
            case "f":
              read();
              literal2("alse");
              return newToken("boolean", false);
            case "-":
            case "+":
              if (read() === "-") {
                sign = -1;
              }
              lexState = "sign";
              return;
            case ".":
              buffer = read();
              lexState = "decimalPointLeading";
              return;
            case "0":
              buffer = read();
              lexState = "zero";
              return;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
              buffer = read();
              lexState = "decimalInteger";
              return;
            case "I":
              read();
              literal2("nfinity");
              return newToken("numeric", Infinity);
            case "N":
              read();
              literal2("aN");
              return newToken("numeric", NaN);
            case '"':
            case "'":
              doubleQuote = read() === '"';
              buffer = "";
              lexState = "string";
              return;
          }
          throw invalidChar(read());
        },
        identifierNameStartEscape: function identifierNameStartEscape() {
          if (c3 !== "u") {
            throw invalidChar(read());
          }
          read();
          var u3 = unicodeEscape();
          switch (u3) {
            case "$":
            case "_":
              break;
            default:
              if (!util.isIdStartChar(u3)) {
                throw invalidIdentifier();
              }
              break;
          }
          buffer += u3;
          lexState = "identifierName";
        },
        identifierName: function identifierName() {
          switch (c3) {
            case "$":
            case "_":
            case "\u200C":
            case "\u200D":
              buffer += read();
              return;
            case "\\":
              read();
              lexState = "identifierNameEscape";
              return;
          }
          if (util.isIdContinueChar(c3)) {
            buffer += read();
            return;
          }
          return newToken("identifier", buffer);
        },
        identifierNameEscape: function identifierNameEscape() {
          if (c3 !== "u") {
            throw invalidChar(read());
          }
          read();
          var u3 = unicodeEscape();
          switch (u3) {
            case "$":
            case "_":
            case "\u200C":
            case "\u200D":
              break;
            default:
              if (!util.isIdContinueChar(u3)) {
                throw invalidIdentifier();
              }
              break;
          }
          buffer += u3;
          lexState = "identifierName";
        },
        sign: function sign$1() {
          switch (c3) {
            case ".":
              buffer = read();
              lexState = "decimalPointLeading";
              return;
            case "0":
              buffer = read();
              lexState = "zero";
              return;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
              buffer = read();
              lexState = "decimalInteger";
              return;
            case "I":
              read();
              literal2("nfinity");
              return newToken("numeric", sign * Infinity);
            case "N":
              read();
              literal2("aN");
              return newToken("numeric", NaN);
          }
          throw invalidChar(read());
        },
        zero: function zero() {
          switch (c3) {
            case ".":
              buffer += read();
              lexState = "decimalPoint";
              return;
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
            case "x":
            case "X":
              buffer += read();
              lexState = "hexadecimal";
              return;
          }
          return newToken("numeric", sign * 0);
        },
        decimalInteger: function decimalInteger() {
          switch (c3) {
            case ".":
              buffer += read();
              lexState = "decimalPoint";
              return;
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util.isDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalPointLeading: function decimalPointLeading() {
          if (util.isDigit(c3)) {
            buffer += read();
            lexState = "decimalFraction";
            return;
          }
          throw invalidChar(read());
        },
        decimalPoint: function decimalPoint() {
          switch (c3) {
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util.isDigit(c3)) {
            buffer += read();
            lexState = "decimalFraction";
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalFraction: function decimalFraction() {
          switch (c3) {
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util.isDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalExponent: function decimalExponent() {
          switch (c3) {
            case "+":
            case "-":
              buffer += read();
              lexState = "decimalExponentSign";
              return;
          }
          if (util.isDigit(c3)) {
            buffer += read();
            lexState = "decimalExponentInteger";
            return;
          }
          throw invalidChar(read());
        },
        decimalExponentSign: function decimalExponentSign() {
          if (util.isDigit(c3)) {
            buffer += read();
            lexState = "decimalExponentInteger";
            return;
          }
          throw invalidChar(read());
        },
        decimalExponentInteger: function decimalExponentInteger() {
          if (util.isDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        hexadecimal: function hexadecimal() {
          if (util.isHexDigit(c3)) {
            buffer += read();
            lexState = "hexadecimalInteger";
            return;
          }
          throw invalidChar(read());
        },
        hexadecimalInteger: function hexadecimalInteger() {
          if (util.isHexDigit(c3)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        string: function string3() {
          switch (c3) {
            case "\\":
              read();
              buffer += escape4();
              return;
            case '"':
              if (doubleQuote) {
                read();
                return newToken("string", buffer);
              }
              buffer += read();
              return;
            case "'":
              if (!doubleQuote) {
                read();
                return newToken("string", buffer);
              }
              buffer += read();
              return;
            case "\n":
            case "\r":
              throw invalidChar(read());
            case "\u2028":
            case "\u2029":
              separatorChar(c3);
              break;
            case void 0:
              throw invalidChar(read());
          }
          buffer += read();
        },
        start: function start() {
          switch (c3) {
            case "{":
            case "[":
              return newToken("punctuator", read());
          }
          lexState = "value";
        },
        beforePropertyName: function beforePropertyName() {
          switch (c3) {
            case "$":
            case "_":
              buffer = read();
              lexState = "identifierName";
              return;
            case "\\":
              read();
              lexState = "identifierNameStartEscape";
              return;
            case "}":
              return newToken("punctuator", read());
            case '"':
            case "'":
              doubleQuote = read() === '"';
              lexState = "string";
              return;
          }
          if (util.isIdStartChar(c3)) {
            buffer += read();
            lexState = "identifierName";
            return;
          }
          throw invalidChar(read());
        },
        afterPropertyName: function afterPropertyName() {
          if (c3 === ":") {
            return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        beforePropertyValue: function beforePropertyValue() {
          lexState = "value";
        },
        afterPropertyValue: function afterPropertyValue() {
          switch (c3) {
            case ",":
            case "}":
              return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        beforeArrayValue: function beforeArrayValue() {
          if (c3 === "]") {
            return newToken("punctuator", read());
          }
          lexState = "value";
        },
        afterArrayValue: function afterArrayValue() {
          switch (c3) {
            case ",":
            case "]":
              return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        end: function end() {
          throw invalidChar(read());
        }
      };
      function newToken(type, value2) {
        return {
          type,
          value: value2,
          line,
          column
        };
      }
      function literal2(s3) {
        for (var i3 = 0, list2 = s3; i3 < list2.length; i3 += 1) {
          var c4 = list2[i3];
          var p4 = peek();
          if (p4 !== c4) {
            throw invalidChar(read());
          }
          read();
        }
      }
      function escape4() {
        var c4 = peek();
        switch (c4) {
          case "b":
            read();
            return "\b";
          case "f":
            read();
            return "\f";
          case "n":
            read();
            return "\n";
          case "r":
            read();
            return "\r";
          case "t":
            read();
            return "	";
          case "v":
            read();
            return "\v";
          case "0":
            read();
            if (util.isDigit(peek())) {
              throw invalidChar(read());
            }
            return "\0";
          case "x":
            read();
            return hexEscape();
          case "u":
            read();
            return unicodeEscape();
          case "\n":
          case "\u2028":
          case "\u2029":
            read();
            return "";
          case "\r":
            read();
            if (peek() === "\n") {
              read();
            }
            return "";
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            throw invalidChar(read());
          case void 0:
            throw invalidChar(read());
        }
        return read();
      }
      function hexEscape() {
        var buffer2 = "";
        var c4 = peek();
        if (!util.isHexDigit(c4)) {
          throw invalidChar(read());
        }
        buffer2 += read();
        c4 = peek();
        if (!util.isHexDigit(c4)) {
          throw invalidChar(read());
        }
        buffer2 += read();
        return String.fromCodePoint(parseInt(buffer2, 16));
      }
      function unicodeEscape() {
        var buffer2 = "";
        var count = 4;
        while (count-- > 0) {
          var c4 = peek();
          if (!util.isHexDigit(c4)) {
            throw invalidChar(read());
          }
          buffer2 += read();
        }
        return String.fromCodePoint(parseInt(buffer2, 16));
      }
      var parseStates = {
        start: function start() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          push3();
        },
        beforePropertyName: function beforePropertyName() {
          switch (token.type) {
            case "identifier":
            case "string":
              key2 = token.value;
              parseState = "afterPropertyName";
              return;
            case "punctuator":
              pop();
              return;
            case "eof":
              throw invalidEOF();
          }
        },
        afterPropertyName: function afterPropertyName() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          parseState = "beforePropertyValue";
        },
        beforePropertyValue: function beforePropertyValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          push3();
        },
        beforeArrayValue: function beforeArrayValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          if (token.type === "punctuator" && token.value === "]") {
            pop();
            return;
          }
          push3();
        },
        afterPropertyValue: function afterPropertyValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          switch (token.value) {
            case ",":
              parseState = "beforePropertyName";
              return;
            case "}":
              pop();
          }
        },
        afterArrayValue: function afterArrayValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          switch (token.value) {
            case ",":
              parseState = "beforeArrayValue";
              return;
            case "]":
              pop();
          }
        },
        end: function end() {
        }
      };
      function push3() {
        var value2;
        switch (token.type) {
          case "punctuator":
            switch (token.value) {
              case "{":
                value2 = {};
                break;
              case "[":
                value2 = [];
                break;
            }
            break;
          case "null":
          case "boolean":
          case "numeric":
          case "string":
            value2 = token.value;
            break;
        }
        if (root3 === void 0) {
          root3 = value2;
        } else {
          var parent = stack[stack.length - 1];
          if (Array.isArray(parent)) {
            parent.push(value2);
          } else {
            Object.defineProperty(parent, key2, {
              value: value2,
              writable: true,
              enumerable: true,
              configurable: true
            });
          }
        }
        if (value2 !== null && typeof value2 === "object") {
          stack.push(value2);
          if (Array.isArray(value2)) {
            parseState = "beforeArrayValue";
          } else {
            parseState = "beforePropertyName";
          }
        } else {
          var current = stack[stack.length - 1];
          if (current == null) {
            parseState = "end";
          } else if (Array.isArray(current)) {
            parseState = "afterArrayValue";
          } else {
            parseState = "afterPropertyValue";
          }
        }
      }
      function pop() {
        stack.pop();
        var current = stack[stack.length - 1];
        if (current == null) {
          parseState = "end";
        } else if (Array.isArray(current)) {
          parseState = "afterArrayValue";
        } else {
          parseState = "afterPropertyValue";
        }
      }
      function invalidChar(c4) {
        if (c4 === void 0) {
          return syntaxError("JSON5: invalid end of input at " + line + ":" + column);
        }
        return syntaxError("JSON5: invalid character '" + formatChar(c4) + "' at " + line + ":" + column);
      }
      function invalidEOF() {
        return syntaxError("JSON5: invalid end of input at " + line + ":" + column);
      }
      function invalidIdentifier() {
        column -= 5;
        return syntaxError("JSON5: invalid identifier character at " + line + ":" + column);
      }
      function separatorChar(c4) {
        console.warn("JSON5: '" + formatChar(c4) + "' in strings is not valid ECMAScript; consider escaping");
      }
      function formatChar(c4) {
        var replacements = {
          "'": "\\'",
          '"': '\\"',
          "\\": "\\\\",
          "\b": "\\b",
          "\f": "\\f",
          "\n": "\\n",
          "\r": "\\r",
          "	": "\\t",
          "\v": "\\v",
          "\0": "\\0",
          "\u2028": "\\u2028",
          "\u2029": "\\u2029"
        };
        if (replacements[c4]) {
          return replacements[c4];
        }
        if (c4 < " ") {
          var hexString = c4.charCodeAt(0).toString(16);
          return "\\x" + ("00" + hexString).substring(hexString.length);
        }
        return c4;
      }
      function syntaxError(message) {
        var err = new SyntaxError(message);
        err.lineNumber = line;
        err.columnNumber = column;
        return err;
      }
      var stringify7 = function stringify8(value2, replacer, space) {
        var stack2 = [];
        var indent = "";
        var propertyList;
        var replacerFunc;
        var gap = "";
        var quote;
        if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
          space = replacer.space;
          quote = replacer.quote;
          replacer = replacer.replacer;
        }
        if (typeof replacer === "function") {
          replacerFunc = replacer;
        } else if (Array.isArray(replacer)) {
          propertyList = [];
          for (var i3 = 0, list2 = replacer; i3 < list2.length; i3 += 1) {
            var v3 = list2[i3];
            var item = void 0;
            if (typeof v3 === "string") {
              item = v3;
            } else if (typeof v3 === "number" || v3 instanceof String || v3 instanceof Number) {
              item = String(v3);
            }
            if (item !== void 0 && propertyList.indexOf(item) < 0) {
              propertyList.push(item);
            }
          }
        }
        if (space instanceof Number) {
          space = Number(space);
        } else if (space instanceof String) {
          space = String(space);
        }
        if (typeof space === "number") {
          if (space > 0) {
            space = Math.min(10, Math.floor(space));
            gap = "          ".substr(0, space);
          }
        } else if (typeof space === "string") {
          gap = space.substr(0, 10);
        }
        return serializeProperty("", { "": value2 });
        function serializeProperty(key3, holder) {
          var value3 = holder[key3];
          if (value3 != null) {
            if (typeof value3.toJSON5 === "function") {
              value3 = value3.toJSON5(key3);
            } else if (typeof value3.toJSON === "function") {
              value3 = value3.toJSON(key3);
            }
          }
          if (replacerFunc) {
            value3 = replacerFunc.call(holder, key3, value3);
          }
          if (value3 instanceof Number) {
            value3 = Number(value3);
          } else if (value3 instanceof String) {
            value3 = String(value3);
          } else if (value3 instanceof Boolean) {
            value3 = value3.valueOf();
          }
          switch (value3) {
            case null:
              return "null";
            case true:
              return "true";
            case false:
              return "false";
          }
          if (typeof value3 === "string") {
            return quoteString(value3, false);
          }
          if (typeof value3 === "number") {
            return String(value3);
          }
          if (typeof value3 === "object") {
            return Array.isArray(value3) ? serializeArray(value3) : serializeObject(value3);
          }
          return void 0;
        }
        function quoteString(value3) {
          var quotes = {
            "'": 0.1,
            '"': 0.2
          };
          var replacements = {
            "'": "\\'",
            '"': '\\"',
            "\\": "\\\\",
            "\b": "\\b",
            "\f": "\\f",
            "\n": "\\n",
            "\r": "\\r",
            "	": "\\t",
            "\v": "\\v",
            "\0": "\\0",
            "\u2028": "\\u2028",
            "\u2029": "\\u2029"
          };
          var product = "";
          for (var i4 = 0; i4 < value3.length; i4++) {
            var c4 = value3[i4];
            switch (c4) {
              case "'":
              case '"':
                quotes[c4]++;
                product += c4;
                continue;
              case "\0":
                if (util.isDigit(value3[i4 + 1])) {
                  product += "\\x00";
                  continue;
                }
            }
            if (replacements[c4]) {
              product += replacements[c4];
              continue;
            }
            if (c4 < " ") {
              var hexString = c4.charCodeAt(0).toString(16);
              product += "\\x" + ("00" + hexString).substring(hexString.length);
              continue;
            }
            product += c4;
          }
          var quoteChar = quote || Object.keys(quotes).reduce(function(a3, b3) {
            return quotes[a3] < quotes[b3] ? a3 : b3;
          });
          product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]);
          return quoteChar + product + quoteChar;
        }
        function serializeObject(value3) {
          if (stack2.indexOf(value3) >= 0) {
            throw TypeError("Converting circular structure to JSON5");
          }
          stack2.push(value3);
          var stepback = indent;
          indent = indent + gap;
          var keys5 = propertyList || Object.keys(value3);
          var partial2 = [];
          for (var i4 = 0, list3 = keys5; i4 < list3.length; i4 += 1) {
            var key3 = list3[i4];
            var propertyString = serializeProperty(key3, value3);
            if (propertyString !== void 0) {
              var member = serializeKey(key3) + ":";
              if (gap !== "") {
                member += " ";
              }
              member += propertyString;
              partial2.push(member);
            }
          }
          var final;
          if (partial2.length === 0) {
            final = "{}";
          } else {
            var properties;
            if (gap === "") {
              properties = partial2.join(",");
              final = "{" + properties + "}";
            } else {
              var separator3 = ",\n" + indent;
              properties = partial2.join(separator3);
              final = "{\n" + indent + properties + ",\n" + stepback + "}";
            }
          }
          stack2.pop();
          indent = stepback;
          return final;
        }
        function serializeKey(key3) {
          if (key3.length === 0) {
            return quoteString(key3, true);
          }
          var firstChar = String.fromCodePoint(key3.codePointAt(0));
          if (!util.isIdStartChar(firstChar)) {
            return quoteString(key3, true);
          }
          for (var i4 = firstChar.length; i4 < key3.length; i4++) {
            if (!util.isIdContinueChar(String.fromCodePoint(key3.codePointAt(i4)))) {
              return quoteString(key3, true);
            }
          }
          return key3;
        }
        function serializeArray(value3) {
          if (stack2.indexOf(value3) >= 0) {
            throw TypeError("Converting circular structure to JSON5");
          }
          stack2.push(value3);
          var stepback = indent;
          indent = indent + gap;
          var partial2 = [];
          for (var i4 = 0; i4 < value3.length; i4++) {
            var propertyString = serializeProperty(String(i4), value3);
            partial2.push(propertyString !== void 0 ? propertyString : "null");
          }
          var final;
          if (partial2.length === 0) {
            final = "[]";
          } else {
            if (gap === "") {
              var properties = partial2.join(",");
              final = "[" + properties + "]";
            } else {
              var separator3 = ",\n" + indent;
              var properties$1 = partial2.join(separator3);
              final = "[\n" + indent + properties$1 + ",\n" + stepback + "]";
            }
          }
          stack2.pop();
          indent = stepback;
          return final;
        }
      };
      var JSON5 = {
        parse: parse4,
        stringify: stringify7
      };
      var lib2 = JSON5;
      var es5 = lib2;
      return es5;
    });
  }
});

// node_modules/entities/lib/maps/entities.json
var require_entities = __commonJS({
  "node_modules/entities/lib/maps/entities.json"(exports, module) {
    module.exports = { Aacute: "\xC1", aacute: "\xE1", Abreve: "\u0102", abreve: "\u0103", ac: "\u223E", acd: "\u223F", acE: "\u223E\u0333", Acirc: "\xC2", acirc: "\xE2", acute: "\xB4", Acy: "\u0410", acy: "\u0430", AElig: "\xC6", aelig: "\xE6", af: "\u2061", Afr: "\u{1D504}", afr: "\u{1D51E}", Agrave: "\xC0", agrave: "\xE0", alefsym: "\u2135", aleph: "\u2135", Alpha: "\u0391", alpha: "\u03B1", Amacr: "\u0100", amacr: "\u0101", amalg: "\u2A3F", amp: "&", AMP: "&", andand: "\u2A55", And: "\u2A53", and: "\u2227", andd: "\u2A5C", andslope: "\u2A58", andv: "\u2A5A", ang: "\u2220", ange: "\u29A4", angle: "\u2220", angmsdaa: "\u29A8", angmsdab: "\u29A9", angmsdac: "\u29AA", angmsdad: "\u29AB", angmsdae: "\u29AC", angmsdaf: "\u29AD", angmsdag: "\u29AE", angmsdah: "\u29AF", angmsd: "\u2221", angrt: "\u221F", angrtvb: "\u22BE", angrtvbd: "\u299D", angsph: "\u2222", angst: "\xC5", angzarr: "\u237C", Aogon: "\u0104", aogon: "\u0105", Aopf: "\u{1D538}", aopf: "\u{1D552}", apacir: "\u2A6F", ap: "\u2248", apE: "\u2A70", ape: "\u224A", apid: "\u224B", apos: "'", ApplyFunction: "\u2061", approx: "\u2248", approxeq: "\u224A", Aring: "\xC5", aring: "\xE5", Ascr: "\u{1D49C}", ascr: "\u{1D4B6}", Assign: "\u2254", ast: "*", asymp: "\u2248", asympeq: "\u224D", Atilde: "\xC3", atilde: "\xE3", Auml: "\xC4", auml: "\xE4", awconint: "\u2233", awint: "\u2A11", backcong: "\u224C", backepsilon: "\u03F6", backprime: "\u2035", backsim: "\u223D", backsimeq: "\u22CD", Backslash: "\u2216", Barv: "\u2AE7", barvee: "\u22BD", barwed: "\u2305", Barwed: "\u2306", barwedge: "\u2305", bbrk: "\u23B5", bbrktbrk: "\u23B6", bcong: "\u224C", Bcy: "\u0411", bcy: "\u0431", bdquo: "\u201E", becaus: "\u2235", because: "\u2235", Because: "\u2235", bemptyv: "\u29B0", bepsi: "\u03F6", bernou: "\u212C", Bernoullis: "\u212C", Beta: "\u0392", beta: "\u03B2", beth: "\u2136", between: "\u226C", Bfr: "\u{1D505}", bfr: "\u{1D51F}", bigcap: "\u22C2", bigcirc: "\u25EF", bigcup: "\u22C3", bigodot: "\u2A00", bigoplus: "\u2A01", bigotimes: "\u2A02", bigsqcup: "\u2A06", bigstar: "\u2605", bigtriangledown: "\u25BD", bigtriangleup: "\u25B3", biguplus: "\u2A04", bigvee: "\u22C1", bigwedge: "\u22C0", bkarow: "\u290D", blacklozenge: "\u29EB", blacksquare: "\u25AA", blacktriangle: "\u25B4", blacktriangledown: "\u25BE", blacktriangleleft: "\u25C2", blacktriangleright: "\u25B8", blank: "\u2423", blk12: "\u2592", blk14: "\u2591", blk34: "\u2593", block: "\u2588", bne: "=\u20E5", bnequiv: "\u2261\u20E5", bNot: "\u2AED", bnot: "\u2310", Bopf: "\u{1D539}", bopf: "\u{1D553}", bot: "\u22A5", bottom: "\u22A5", bowtie: "\u22C8", boxbox: "\u29C9", boxdl: "\u2510", boxdL: "\u2555", boxDl: "\u2556", boxDL: "\u2557", boxdr: "\u250C", boxdR: "\u2552", boxDr: "\u2553", boxDR: "\u2554", boxh: "\u2500", boxH: "\u2550", boxhd: "\u252C", boxHd: "\u2564", boxhD: "\u2565", boxHD: "\u2566", boxhu: "\u2534", boxHu: "\u2567", boxhU: "\u2568", boxHU: "\u2569", boxminus: "\u229F", boxplus: "\u229E", boxtimes: "\u22A0", boxul: "\u2518", boxuL: "\u255B", boxUl: "\u255C", boxUL: "\u255D", boxur: "\u2514", boxuR: "\u2558", boxUr: "\u2559", boxUR: "\u255A", boxv: "\u2502", boxV: "\u2551", boxvh: "\u253C", boxvH: "\u256A", boxVh: "\u256B", boxVH: "\u256C", boxvl: "\u2524", boxvL: "\u2561", boxVl: "\u2562", boxVL: "\u2563", boxvr: "\u251C", boxvR: "\u255E", boxVr: "\u255F", boxVR: "\u2560", bprime: "\u2035", breve: "\u02D8", Breve: "\u02D8", brvbar: "\xA6", bscr: "\u{1D4B7}", Bscr: "\u212C", bsemi: "\u204F", bsim: "\u223D", bsime: "\u22CD", bsolb: "\u29C5", bsol: "\\", bsolhsub: "\u27C8", bull: "\u2022", bullet: "\u2022", bump: "\u224E", bumpE: "\u2AAE", bumpe: "\u224F", Bumpeq: "\u224E", bumpeq: "\u224F", Cacute: "\u0106", cacute: "\u0107", capand: "\u2A44", capbrcup: "\u2A49", capcap: "\u2A4B", cap: "\u2229", Cap: "\u22D2", capcup: "\u2A47", capdot: "\u2A40", CapitalDifferentialD: "\u2145", caps: "\u2229\uFE00", caret: "\u2041", caron: "\u02C7", Cayleys: "\u212D", ccaps: "\u2A4D", Ccaron: "\u010C", ccaron: "\u010D", Ccedil: "\xC7", ccedil: "\xE7", Ccirc: "\u0108", ccirc: "\u0109", Cconint: "\u2230", ccups: "\u2A4C", ccupssm: "\u2A50", Cdot: "\u010A", cdot: "\u010B", cedil: "\xB8", Cedilla: "\xB8", cemptyv: "\u29B2", cent: "\xA2", centerdot: "\xB7", CenterDot: "\xB7", cfr: "\u{1D520}", Cfr: "\u212D", CHcy: "\u0427", chcy: "\u0447", check: "\u2713", checkmark: "\u2713", Chi: "\u03A7", chi: "\u03C7", circ: "\u02C6", circeq: "\u2257", circlearrowleft: "\u21BA", circlearrowright: "\u21BB", circledast: "\u229B", circledcirc: "\u229A", circleddash: "\u229D", CircleDot: "\u2299", circledR: "\xAE", circledS: "\u24C8", CircleMinus: "\u2296", CirclePlus: "\u2295", CircleTimes: "\u2297", cir: "\u25CB", cirE: "\u29C3", cire: "\u2257", cirfnint: "\u2A10", cirmid: "\u2AEF", cirscir: "\u29C2", ClockwiseContourIntegral: "\u2232", CloseCurlyDoubleQuote: "\u201D", CloseCurlyQuote: "\u2019", clubs: "\u2663", clubsuit: "\u2663", colon: ":", Colon: "\u2237", Colone: "\u2A74", colone: "\u2254", coloneq: "\u2254", comma: ",", commat: "@", comp: "\u2201", compfn: "\u2218", complement: "\u2201", complexes: "\u2102", cong: "\u2245", congdot: "\u2A6D", Congruent: "\u2261", conint: "\u222E", Conint: "\u222F", ContourIntegral: "\u222E", copf: "\u{1D554}", Copf: "\u2102", coprod: "\u2210", Coproduct: "\u2210", copy: "\xA9", COPY: "\xA9", copysr: "\u2117", CounterClockwiseContourIntegral: "\u2233", crarr: "\u21B5", cross: "\u2717", Cross: "\u2A2F", Cscr: "\u{1D49E}", cscr: "\u{1D4B8}", csub: "\u2ACF", csube: "\u2AD1", csup: "\u2AD0", csupe: "\u2AD2", ctdot: "\u22EF", cudarrl: "\u2938", cudarrr: "\u2935", cuepr: "\u22DE", cuesc: "\u22DF", cularr: "\u21B6", cularrp: "\u293D", cupbrcap: "\u2A48", cupcap: "\u2A46", CupCap: "\u224D", cup: "\u222A", Cup: "\u22D3", cupcup: "\u2A4A", cupdot: "\u228D", cupor: "\u2A45", cups: "\u222A\uFE00", curarr: "\u21B7", curarrm: "\u293C", curlyeqprec: "\u22DE", curlyeqsucc: "\u22DF", curlyvee: "\u22CE", curlywedge: "\u22CF", curren: "\xA4", curvearrowleft: "\u21B6", curvearrowright: "\u21B7", cuvee: "\u22CE", cuwed: "\u22CF", cwconint: "\u2232", cwint: "\u2231", cylcty: "\u232D", dagger: "\u2020", Dagger: "\u2021", daleth: "\u2138", darr: "\u2193", Darr: "\u21A1", dArr: "\u21D3", dash: "\u2010", Dashv: "\u2AE4", dashv: "\u22A3", dbkarow: "\u290F", dblac: "\u02DD", Dcaron: "\u010E", dcaron: "\u010F", Dcy: "\u0414", dcy: "\u0434", ddagger: "\u2021", ddarr: "\u21CA", DD: "\u2145", dd: "\u2146", DDotrahd: "\u2911", ddotseq: "\u2A77", deg: "\xB0", Del: "\u2207", Delta: "\u0394", delta: "\u03B4", demptyv: "\u29B1", dfisht: "\u297F", Dfr: "\u{1D507}", dfr: "\u{1D521}", dHar: "\u2965", dharl: "\u21C3", dharr: "\u21C2", DiacriticalAcute: "\xB4", DiacriticalDot: "\u02D9", DiacriticalDoubleAcute: "\u02DD", DiacriticalGrave: "`", DiacriticalTilde: "\u02DC", diam: "\u22C4", diamond: "\u22C4", Diamond: "\u22C4", diamondsuit: "\u2666", diams: "\u2666", die: "\xA8", DifferentialD: "\u2146", digamma: "\u03DD", disin: "\u22F2", div: "\xF7", divide: "\xF7", divideontimes: "\u22C7", divonx: "\u22C7", DJcy: "\u0402", djcy: "\u0452", dlcorn: "\u231E", dlcrop: "\u230D", dollar: "$", Dopf: "\u{1D53B}", dopf: "\u{1D555}", Dot: "\xA8", dot: "\u02D9", DotDot: "\u20DC", doteq: "\u2250", doteqdot: "\u2251", DotEqual: "\u2250", dotminus: "\u2238", dotplus: "\u2214", dotsquare: "\u22A1", doublebarwedge: "\u2306", DoubleContourIntegral: "\u222F", DoubleDot: "\xA8", DoubleDownArrow: "\u21D3", DoubleLeftArrow: "\u21D0", DoubleLeftRightArrow: "\u21D4", DoubleLeftTee: "\u2AE4", DoubleLongLeftArrow: "\u27F8", DoubleLongLeftRightArrow: "\u27FA", DoubleLongRightArrow: "\u27F9", DoubleRightArrow: "\u21D2", DoubleRightTee: "\u22A8", DoubleUpArrow: "\u21D1", DoubleUpDownArrow: "\u21D5", DoubleVerticalBar: "\u2225", DownArrowBar: "\u2913", downarrow: "\u2193", DownArrow: "\u2193", Downarrow: "\u21D3", DownArrowUpArrow: "\u21F5", DownBreve: "\u0311", downdownarrows: "\u21CA", downharpoonleft: "\u21C3", downharpoonright: "\u21C2", DownLeftRightVector: "\u2950", DownLeftTeeVector: "\u295E", DownLeftVectorBar: "\u2956", DownLeftVector: "\u21BD", DownRightTeeVector: "\u295F", DownRightVectorBar: "\u2957", DownRightVector: "\u21C1", DownTeeArrow: "\u21A7", DownTee: "\u22A4", drbkarow: "\u2910", drcorn: "\u231F", drcrop: "\u230C", Dscr: "\u{1D49F}", dscr: "\u{1D4B9}", DScy: "\u0405", dscy: "\u0455", dsol: "\u29F6", Dstrok: "\u0110", dstrok: "\u0111", dtdot: "\u22F1", dtri: "\u25BF", dtrif: "\u25BE", duarr: "\u21F5", duhar: "\u296F", dwangle: "\u29A6", DZcy: "\u040F", dzcy: "\u045F", dzigrarr: "\u27FF", Eacute: "\xC9", eacute: "\xE9", easter: "\u2A6E", Ecaron: "\u011A", ecaron: "\u011B", Ecirc: "\xCA", ecirc: "\xEA", ecir: "\u2256", ecolon: "\u2255", Ecy: "\u042D", ecy: "\u044D", eDDot: "\u2A77", Edot: "\u0116", edot: "\u0117", eDot: "\u2251", ee: "\u2147", efDot: "\u2252", Efr: "\u{1D508}", efr: "\u{1D522}", eg: "\u2A9A", Egrave: "\xC8", egrave: "\xE8", egs: "\u2A96", egsdot: "\u2A98", el: "\u2A99", Element: "\u2208", elinters: "\u23E7", ell: "\u2113", els: "\u2A95", elsdot: "\u2A97", Emacr: "\u0112", emacr: "\u0113", empty: "\u2205", emptyset: "\u2205", EmptySmallSquare: "\u25FB", emptyv: "\u2205", EmptyVerySmallSquare: "\u25AB", emsp13: "\u2004", emsp14: "\u2005", emsp: "\u2003", ENG: "\u014A", eng: "\u014B", ensp: "\u2002", Eogon: "\u0118", eogon: "\u0119", Eopf: "\u{1D53C}", eopf: "\u{1D556}", epar: "\u22D5", eparsl: "\u29E3", eplus: "\u2A71", epsi: "\u03B5", Epsilon: "\u0395", epsilon: "\u03B5", epsiv: "\u03F5", eqcirc: "\u2256", eqcolon: "\u2255", eqsim: "\u2242", eqslantgtr: "\u2A96", eqslantless: "\u2A95", Equal: "\u2A75", equals: "=", EqualTilde: "\u2242", equest: "\u225F", Equilibrium: "\u21CC", equiv: "\u2261", equivDD: "\u2A78", eqvparsl: "\u29E5", erarr: "\u2971", erDot: "\u2253", escr: "\u212F", Escr: "\u2130", esdot: "\u2250", Esim: "\u2A73", esim: "\u2242", Eta: "\u0397", eta: "\u03B7", ETH: "\xD0", eth: "\xF0", Euml: "\xCB", euml: "\xEB", euro: "\u20AC", excl: "!", exist: "\u2203", Exists: "\u2203", expectation: "\u2130", exponentiale: "\u2147", ExponentialE: "\u2147", fallingdotseq: "\u2252", Fcy: "\u0424", fcy: "\u0444", female: "\u2640", ffilig: "\uFB03", fflig: "\uFB00", ffllig: "\uFB04", Ffr: "\u{1D509}", ffr: "\u{1D523}", filig: "\uFB01", FilledSmallSquare: "\u25FC", FilledVerySmallSquare: "\u25AA", fjlig: "fj", flat: "\u266D", fllig: "\uFB02", fltns: "\u25B1", fnof: "\u0192", Fopf: "\u{1D53D}", fopf: "\u{1D557}", forall: "\u2200", ForAll: "\u2200", fork: "\u22D4", forkv: "\u2AD9", Fouriertrf: "\u2131", fpartint: "\u2A0D", frac12: "\xBD", frac13: "\u2153", frac14: "\xBC", frac15: "\u2155", frac16: "\u2159", frac18: "\u215B", frac23: "\u2154", frac25: "\u2156", frac34: "\xBE", frac35: "\u2157", frac38: "\u215C", frac45: "\u2158", frac56: "\u215A", frac58: "\u215D", frac78: "\u215E", frasl: "\u2044", frown: "\u2322", fscr: "\u{1D4BB}", Fscr: "\u2131", gacute: "\u01F5", Gamma: "\u0393", gamma: "\u03B3", Gammad: "\u03DC", gammad: "\u03DD", gap: "\u2A86", Gbreve: "\u011E", gbreve: "\u011F", Gcedil: "\u0122", Gcirc: "\u011C", gcirc: "\u011D", Gcy: "\u0413", gcy: "\u0433", Gdot: "\u0120", gdot: "\u0121", ge: "\u2265", gE: "\u2267", gEl: "\u2A8C", gel: "\u22DB", geq: "\u2265", geqq: "\u2267", geqslant: "\u2A7E", gescc: "\u2AA9", ges: "\u2A7E", gesdot: "\u2A80", gesdoto: "\u2A82", gesdotol: "\u2A84", gesl: "\u22DB\uFE00", gesles: "\u2A94", Gfr: "\u{1D50A}", gfr: "\u{1D524}", gg: "\u226B", Gg: "\u22D9", ggg: "\u22D9", gimel: "\u2137", GJcy: "\u0403", gjcy: "\u0453", gla: "\u2AA5", gl: "\u2277", glE: "\u2A92", glj: "\u2AA4", gnap: "\u2A8A", gnapprox: "\u2A8A", gne: "\u2A88", gnE: "\u2269", gneq: "\u2A88", gneqq: "\u2269", gnsim: "\u22E7", Gopf: "\u{1D53E}", gopf: "\u{1D558}", grave: "`", GreaterEqual: "\u2265", GreaterEqualLess: "\u22DB", GreaterFullEqual: "\u2267", GreaterGreater: "\u2AA2", GreaterLess: "\u2277", GreaterSlantEqual: "\u2A7E", GreaterTilde: "\u2273", Gscr: "\u{1D4A2}", gscr: "\u210A", gsim: "\u2273", gsime: "\u2A8E", gsiml: "\u2A90", gtcc: "\u2AA7", gtcir: "\u2A7A", gt: ">", GT: ">", Gt: "\u226B", gtdot: "\u22D7", gtlPar: "\u2995", gtquest: "\u2A7C", gtrapprox: "\u2A86", gtrarr: "\u2978", gtrdot: "\u22D7", gtreqless: "\u22DB", gtreqqless: "\u2A8C", gtrless: "\u2277", gtrsim: "\u2273", gvertneqq: "\u2269\uFE00", gvnE: "\u2269\uFE00", Hacek: "\u02C7", hairsp: "\u200A", half: "\xBD", hamilt: "\u210B", HARDcy: "\u042A", hardcy: "\u044A", harrcir: "\u2948", harr: "\u2194", hArr: "\u21D4", harrw: "\u21AD", Hat: "^", hbar: "\u210F", Hcirc: "\u0124", hcirc: "\u0125", hearts: "\u2665", heartsuit: "\u2665", hellip: "\u2026", hercon: "\u22B9", hfr: "\u{1D525}", Hfr: "\u210C", HilbertSpace: "\u210B", hksearow: "\u2925", hkswarow: "\u2926", hoarr: "\u21FF", homtht: "\u223B", hookleftarrow: "\u21A9", hookrightarrow: "\u21AA", hopf: "\u{1D559}", Hopf: "\u210D", horbar: "\u2015", HorizontalLine: "\u2500", hscr: "\u{1D4BD}", Hscr: "\u210B", hslash: "\u210F", Hstrok: "\u0126", hstrok: "\u0127", HumpDownHump: "\u224E", HumpEqual: "\u224F", hybull: "\u2043", hyphen: "\u2010", Iacute: "\xCD", iacute: "\xED", ic: "\u2063", Icirc: "\xCE", icirc: "\xEE", Icy: "\u0418", icy: "\u0438", Idot: "\u0130", IEcy: "\u0415", iecy: "\u0435", iexcl: "\xA1", iff: "\u21D4", ifr: "\u{1D526}", Ifr: "\u2111", Igrave: "\xCC", igrave: "\xEC", ii: "\u2148", iiiint: "\u2A0C", iiint: "\u222D", iinfin: "\u29DC", iiota: "\u2129", IJlig: "\u0132", ijlig: "\u0133", Imacr: "\u012A", imacr: "\u012B", image: "\u2111", ImaginaryI: "\u2148", imagline: "\u2110", imagpart: "\u2111", imath: "\u0131", Im: "\u2111", imof: "\u22B7", imped: "\u01B5", Implies: "\u21D2", incare: "\u2105", in: "\u2208", infin: "\u221E", infintie: "\u29DD", inodot: "\u0131", intcal: "\u22BA", int: "\u222B", Int: "\u222C", integers: "\u2124", Integral: "\u222B", intercal: "\u22BA", Intersection: "\u22C2", intlarhk: "\u2A17", intprod: "\u2A3C", InvisibleComma: "\u2063", InvisibleTimes: "\u2062", IOcy: "\u0401", iocy: "\u0451", Iogon: "\u012E", iogon: "\u012F", Iopf: "\u{1D540}", iopf: "\u{1D55A}", Iota: "\u0399", iota: "\u03B9", iprod: "\u2A3C", iquest: "\xBF", iscr: "\u{1D4BE}", Iscr: "\u2110", isin: "\u2208", isindot: "\u22F5", isinE: "\u22F9", isins: "\u22F4", isinsv: "\u22F3", isinv: "\u2208", it: "\u2062", Itilde: "\u0128", itilde: "\u0129", Iukcy: "\u0406", iukcy: "\u0456", Iuml: "\xCF", iuml: "\xEF", Jcirc: "\u0134", jcirc: "\u0135", Jcy: "\u0419", jcy: "\u0439", Jfr: "\u{1D50D}", jfr: "\u{1D527}", jmath: "\u0237", Jopf: "\u{1D541}", jopf: "\u{1D55B}", Jscr: "\u{1D4A5}", jscr: "\u{1D4BF}", Jsercy: "\u0408", jsercy: "\u0458", Jukcy: "\u0404", jukcy: "\u0454", Kappa: "\u039A", kappa: "\u03BA", kappav: "\u03F0", Kcedil: "\u0136", kcedil: "\u0137", Kcy: "\u041A", kcy: "\u043A", Kfr: "\u{1D50E}", kfr: "\u{1D528}", kgreen: "\u0138", KHcy: "\u0425", khcy: "\u0445", KJcy: "\u040C", kjcy: "\u045C", Kopf: "\u{1D542}", kopf: "\u{1D55C}", Kscr: "\u{1D4A6}", kscr: "\u{1D4C0}", lAarr: "\u21DA", Lacute: "\u0139", lacute: "\u013A", laemptyv: "\u29B4", lagran: "\u2112", Lambda: "\u039B", lambda: "\u03BB", lang: "\u27E8", Lang: "\u27EA", langd: "\u2991", langle: "\u27E8", lap: "\u2A85", Laplacetrf: "\u2112", laquo: "\xAB", larrb: "\u21E4", larrbfs: "\u291F", larr: "\u2190", Larr: "\u219E", lArr: "\u21D0", larrfs: "\u291D", larrhk: "\u21A9", larrlp: "\u21AB", larrpl: "\u2939", larrsim: "\u2973", larrtl: "\u21A2", latail: "\u2919", lAtail: "\u291B", lat: "\u2AAB", late: "\u2AAD", lates: "\u2AAD\uFE00", lbarr: "\u290C", lBarr: "\u290E", lbbrk: "\u2772", lbrace: "{", lbrack: "[", lbrke: "\u298B", lbrksld: "\u298F", lbrkslu: "\u298D", Lcaron: "\u013D", lcaron: "\u013E", Lcedil: "\u013B", lcedil: "\u013C", lceil: "\u2308", lcub: "{", Lcy: "\u041B", lcy: "\u043B", ldca: "\u2936", ldquo: "\u201C", ldquor: "\u201E", ldrdhar: "\u2967", ldrushar: "\u294B", ldsh: "\u21B2", le: "\u2264", lE: "\u2266", LeftAngleBracket: "\u27E8", LeftArrowBar: "\u21E4", leftarrow: "\u2190", LeftArrow: "\u2190", Leftarrow: "\u21D0", LeftArrowRightArrow: "\u21C6", leftarrowtail: "\u21A2", LeftCeiling: "\u2308", LeftDoubleBracket: "\u27E6", LeftDownTeeVector: "\u2961", LeftDownVectorBar: "\u2959", LeftDownVector: "\u21C3", LeftFloor: "\u230A", leftharpoondown: "\u21BD", leftharpoonup: "\u21BC", leftleftarrows: "\u21C7", leftrightarrow: "\u2194", LeftRightArrow: "\u2194", Leftrightarrow: "\u21D4", leftrightarrows: "\u21C6", leftrightharpoons: "\u21CB", leftrightsquigarrow: "\u21AD", LeftRightVector: "\u294E", LeftTeeArrow: "\u21A4", LeftTee: "\u22A3", LeftTeeVector: "\u295A", leftthreetimes: "\u22CB", LeftTriangleBar: "\u29CF", LeftTriangle: "\u22B2", LeftTriangleEqual: "\u22B4", LeftUpDownVector: "\u2951", LeftUpTeeVector: "\u2960", LeftUpVectorBar: "\u2958", LeftUpVector: "\u21BF", LeftVectorBar: "\u2952", LeftVector: "\u21BC", lEg: "\u2A8B", leg: "\u22DA", leq: "\u2264", leqq: "\u2266", leqslant: "\u2A7D", lescc: "\u2AA8", les: "\u2A7D", lesdot: "\u2A7F", lesdoto: "\u2A81", lesdotor: "\u2A83", lesg: "\u22DA\uFE00", lesges: "\u2A93", lessapprox: "\u2A85", lessdot: "\u22D6", lesseqgtr: "\u22DA", lesseqqgtr: "\u2A8B", LessEqualGreater: "\u22DA", LessFullEqual: "\u2266", LessGreater: "\u2276", lessgtr: "\u2276", LessLess: "\u2AA1", lesssim: "\u2272", LessSlantEqual: "\u2A7D", LessTilde: "\u2272", lfisht: "\u297C", lfloor: "\u230A", Lfr: "\u{1D50F}", lfr: "\u{1D529}", lg: "\u2276", lgE: "\u2A91", lHar: "\u2962", lhard: "\u21BD", lharu: "\u21BC", lharul: "\u296A", lhblk: "\u2584", LJcy: "\u0409", ljcy: "\u0459", llarr: "\u21C7", ll: "\u226A", Ll: "\u22D8", llcorner: "\u231E", Lleftarrow: "\u21DA", llhard: "\u296B", lltri: "\u25FA", Lmidot: "\u013F", lmidot: "\u0140", lmoustache: "\u23B0", lmoust: "\u23B0", lnap: "\u2A89", lnapprox: "\u2A89", lne: "\u2A87", lnE: "\u2268", lneq: "\u2A87", lneqq: "\u2268", lnsim: "\u22E6", loang: "\u27EC", loarr: "\u21FD", lobrk: "\u27E6", longleftarrow: "\u27F5", LongLeftArrow: "\u27F5", Longleftarrow: "\u27F8", longleftrightarrow: "\u27F7", LongLeftRightArrow: "\u27F7", Longleftrightarrow: "\u27FA", longmapsto: "\u27FC", longrightarrow: "\u27F6", LongRightArrow: "\u27F6", Longrightarrow: "\u27F9", looparrowleft: "\u21AB", looparrowright: "\u21AC", lopar: "\u2985", Lopf: "\u{1D543}", lopf: "\u{1D55D}", loplus: "\u2A2D", lotimes: "\u2A34", lowast: "\u2217", lowbar: "_", LowerLeftArrow: "\u2199", LowerRightArrow: "\u2198", loz: "\u25CA", lozenge: "\u25CA", lozf: "\u29EB", lpar: "(", lparlt: "\u2993", lrarr: "\u21C6", lrcorner: "\u231F", lrhar: "\u21CB", lrhard: "\u296D", lrm: "\u200E", lrtri: "\u22BF", lsaquo: "\u2039", lscr: "\u{1D4C1}", Lscr: "\u2112", lsh: "\u21B0", Lsh: "\u21B0", lsim: "\u2272", lsime: "\u2A8D", lsimg: "\u2A8F", lsqb: "[", lsquo: "\u2018", lsquor: "\u201A", Lstrok: "\u0141", lstrok: "\u0142", ltcc: "\u2AA6", ltcir: "\u2A79", lt: "<", LT: "<", Lt: "\u226A", ltdot: "\u22D6", lthree: "\u22CB", ltimes: "\u22C9", ltlarr: "\u2976", ltquest: "\u2A7B", ltri: "\u25C3", ltrie: "\u22B4", ltrif: "\u25C2", ltrPar: "\u2996", lurdshar: "\u294A", luruhar: "\u2966", lvertneqq: "\u2268\uFE00", lvnE: "\u2268\uFE00", macr: "\xAF", male: "\u2642", malt: "\u2720", maltese: "\u2720", Map: "\u2905", map: "\u21A6", mapsto: "\u21A6", mapstodown: "\u21A7", mapstoleft: "\u21A4", mapstoup: "\u21A5", marker: "\u25AE", mcomma: "\u2A29", Mcy: "\u041C", mcy: "\u043C", mdash: "\u2014", mDDot: "\u223A", measuredangle: "\u2221", MediumSpace: "\u205F", Mellintrf: "\u2133", Mfr: "\u{1D510}", mfr: "\u{1D52A}", mho: "\u2127", micro: "\xB5", midast: "*", midcir: "\u2AF0", mid: "\u2223", middot: "\xB7", minusb: "\u229F", minus: "\u2212", minusd: "\u2238", minusdu: "\u2A2A", MinusPlus: "\u2213", mlcp: "\u2ADB", mldr: "\u2026", mnplus: "\u2213", models: "\u22A7", Mopf: "\u{1D544}", mopf: "\u{1D55E}", mp: "\u2213", mscr: "\u{1D4C2}", Mscr: "\u2133", mstpos: "\u223E", Mu: "\u039C", mu: "\u03BC", multimap: "\u22B8", mumap: "\u22B8", nabla: "\u2207", Nacute: "\u0143", nacute: "\u0144", nang: "\u2220\u20D2", nap: "\u2249", napE: "\u2A70\u0338", napid: "\u224B\u0338", napos: "\u0149", napprox: "\u2249", natural: "\u266E", naturals: "\u2115", natur: "\u266E", nbsp: "\xA0", nbump: "\u224E\u0338", nbumpe: "\u224F\u0338", ncap: "\u2A43", Ncaron: "\u0147", ncaron: "\u0148", Ncedil: "\u0145", ncedil: "\u0146", ncong: "\u2247", ncongdot: "\u2A6D\u0338", ncup: "\u2A42", Ncy: "\u041D", ncy: "\u043D", ndash: "\u2013", nearhk: "\u2924", nearr: "\u2197", neArr: "\u21D7", nearrow: "\u2197", ne: "\u2260", nedot: "\u2250\u0338", NegativeMediumSpace: "\u200B", NegativeThickSpace: "\u200B", NegativeThinSpace: "\u200B", NegativeVeryThinSpace: "\u200B", nequiv: "\u2262", nesear: "\u2928", nesim: "\u2242\u0338", NestedGreaterGreater: "\u226B", NestedLessLess: "\u226A", NewLine: "\n", nexist: "\u2204", nexists: "\u2204", Nfr: "\u{1D511}", nfr: "\u{1D52B}", ngE: "\u2267\u0338", nge: "\u2271", ngeq: "\u2271", ngeqq: "\u2267\u0338", ngeqslant: "\u2A7E\u0338", nges: "\u2A7E\u0338", nGg: "\u22D9\u0338", ngsim: "\u2275", nGt: "\u226B\u20D2", ngt: "\u226F", ngtr: "\u226F", nGtv: "\u226B\u0338", nharr: "\u21AE", nhArr: "\u21CE", nhpar: "\u2AF2", ni: "\u220B", nis: "\u22FC", nisd: "\u22FA", niv: "\u220B", NJcy: "\u040A", njcy: "\u045A", nlarr: "\u219A", nlArr: "\u21CD", nldr: "\u2025", nlE: "\u2266\u0338", nle: "\u2270", nleftarrow: "\u219A", nLeftarrow: "\u21CD", nleftrightarrow: "\u21AE", nLeftrightarrow: "\u21CE", nleq: "\u2270", nleqq: "\u2266\u0338", nleqslant: "\u2A7D\u0338", nles: "\u2A7D\u0338", nless: "\u226E", nLl: "\u22D8\u0338", nlsim: "\u2274", nLt: "\u226A\u20D2", nlt: "\u226E", nltri: "\u22EA", nltrie: "\u22EC", nLtv: "\u226A\u0338", nmid: "\u2224", NoBreak: "\u2060", NonBreakingSpace: "\xA0", nopf: "\u{1D55F}", Nopf: "\u2115", Not: "\u2AEC", not: "\xAC", NotCongruent: "\u2262", NotCupCap: "\u226D", NotDoubleVerticalBar: "\u2226", NotElement: "\u2209", NotEqual: "\u2260", NotEqualTilde: "\u2242\u0338", NotExists: "\u2204", NotGreater: "\u226F", NotGreaterEqual: "\u2271", NotGreaterFullEqual: "\u2267\u0338", NotGreaterGreater: "\u226B\u0338", NotGreaterLess: "\u2279", NotGreaterSlantEqual: "\u2A7E\u0338", NotGreaterTilde: "\u2275", NotHumpDownHump: "\u224E\u0338", NotHumpEqual: "\u224F\u0338", notin: "\u2209", notindot: "\u22F5\u0338", notinE: "\u22F9\u0338", notinva: "\u2209", notinvb: "\u22F7", notinvc: "\u22F6", NotLeftTriangleBar: "\u29CF\u0338", NotLeftTriangle: "\u22EA", NotLeftTriangleEqual: "\u22EC", NotLess: "\u226E", NotLessEqual: "\u2270", NotLessGreater: "\u2278", NotLessLess: "\u226A\u0338", NotLessSlantEqual: "\u2A7D\u0338", NotLessTilde: "\u2274", NotNestedGreaterGreater: "\u2AA2\u0338", NotNestedLessLess: "\u2AA1\u0338", notni: "\u220C", notniva: "\u220C", notnivb: "\u22FE", notnivc: "\u22FD", NotPrecedes: "\u2280", NotPrecedesEqual: "\u2AAF\u0338", NotPrecedesSlantEqual: "\u22E0", NotReverseElement: "\u220C", NotRightTriangleBar: "\u29D0\u0338", NotRightTriangle: "\u22EB", NotRightTriangleEqual: "\u22ED", NotSquareSubset: "\u228F\u0338", NotSquareSubsetEqual: "\u22E2", NotSquareSuperset: "\u2290\u0338", NotSquareSupersetEqual: "\u22E3", NotSubset: "\u2282\u20D2", NotSubsetEqual: "\u2288", NotSucceeds: "\u2281", NotSucceedsEqual: "\u2AB0\u0338", NotSucceedsSlantEqual: "\u22E1", NotSucceedsTilde: "\u227F\u0338", NotSuperset: "\u2283\u20D2", NotSupersetEqual: "\u2289", NotTilde: "\u2241", NotTildeEqual: "\u2244", NotTildeFullEqual: "\u2247", NotTildeTilde: "\u2249", NotVerticalBar: "\u2224", nparallel: "\u2226", npar: "\u2226", nparsl: "\u2AFD\u20E5", npart: "\u2202\u0338", npolint: "\u2A14", npr: "\u2280", nprcue: "\u22E0", nprec: "\u2280", npreceq: "\u2AAF\u0338", npre: "\u2AAF\u0338", nrarrc: "\u2933\u0338", nrarr: "\u219B", nrArr: "\u21CF", nrarrw: "\u219D\u0338", nrightarrow: "\u219B", nRightarrow: "\u21CF", nrtri: "\u22EB", nrtrie: "\u22ED", nsc: "\u2281", nsccue: "\u22E1", nsce: "\u2AB0\u0338", Nscr: "\u{1D4A9}", nscr: "\u{1D4C3}", nshortmid: "\u2224", nshortparallel: "\u2226", nsim: "\u2241", nsime: "\u2244", nsimeq: "\u2244", nsmid: "\u2224", nspar: "\u2226", nsqsube: "\u22E2", nsqsupe: "\u22E3", nsub: "\u2284", nsubE: "\u2AC5\u0338", nsube: "\u2288", nsubset: "\u2282\u20D2", nsubseteq: "\u2288", nsubseteqq: "\u2AC5\u0338", nsucc: "\u2281", nsucceq: "\u2AB0\u0338", nsup: "\u2285", nsupE: "\u2AC6\u0338", nsupe: "\u2289", nsupset: "\u2283\u20D2", nsupseteq: "\u2289", nsupseteqq: "\u2AC6\u0338", ntgl: "\u2279", Ntilde: "\xD1", ntilde: "\xF1", ntlg: "\u2278", ntriangleleft: "\u22EA", ntrianglelefteq: "\u22EC", ntriangleright: "\u22EB", ntrianglerighteq: "\u22ED", Nu: "\u039D", nu: "\u03BD", num: "#", numero: "\u2116", numsp: "\u2007", nvap: "\u224D\u20D2", nvdash: "\u22AC", nvDash: "\u22AD", nVdash: "\u22AE", nVDash: "\u22AF", nvge: "\u2265\u20D2", nvgt: ">\u20D2", nvHarr: "\u2904", nvinfin: "\u29DE", nvlArr: "\u2902", nvle: "\u2264\u20D2", nvlt: "<\u20D2", nvltrie: "\u22B4\u20D2", nvrArr: "\u2903", nvrtrie: "\u22B5\u20D2", nvsim: "\u223C\u20D2", nwarhk: "\u2923", nwarr: "\u2196", nwArr: "\u21D6", nwarrow: "\u2196", nwnear: "\u2927", Oacute: "\xD3", oacute: "\xF3", oast: "\u229B", Ocirc: "\xD4", ocirc: "\xF4", ocir: "\u229A", Ocy: "\u041E", ocy: "\u043E", odash: "\u229D", Odblac: "\u0150", odblac: "\u0151", odiv: "\u2A38", odot: "\u2299", odsold: "\u29BC", OElig: "\u0152", oelig: "\u0153", ofcir: "\u29BF", Ofr: "\u{1D512}", ofr: "\u{1D52C}", ogon: "\u02DB", Ograve: "\xD2", ograve: "\xF2", ogt: "\u29C1", ohbar: "\u29B5", ohm: "\u03A9", oint: "\u222E", olarr: "\u21BA", olcir: "\u29BE", olcross: "\u29BB", oline: "\u203E", olt: "\u29C0", Omacr: "\u014C", omacr: "\u014D", Omega: "\u03A9", omega: "\u03C9", Omicron: "\u039F", omicron: "\u03BF", omid: "\u29B6", ominus: "\u2296", Oopf: "\u{1D546}", oopf: "\u{1D560}", opar: "\u29B7", OpenCurlyDoubleQuote: "\u201C", OpenCurlyQuote: "\u2018", operp: "\u29B9", oplus: "\u2295", orarr: "\u21BB", Or: "\u2A54", or: "\u2228", ord: "\u2A5D", order: "\u2134", orderof: "\u2134", ordf: "\xAA", ordm: "\xBA", origof: "\u22B6", oror: "\u2A56", orslope: "\u2A57", orv: "\u2A5B", oS: "\u24C8", Oscr: "\u{1D4AA}", oscr: "\u2134", Oslash: "\xD8", oslash: "\xF8", osol: "\u2298", Otilde: "\xD5", otilde: "\xF5", otimesas: "\u2A36", Otimes: "\u2A37", otimes: "\u2297", Ouml: "\xD6", ouml: "\xF6", ovbar: "\u233D", OverBar: "\u203E", OverBrace: "\u23DE", OverBracket: "\u23B4", OverParenthesis: "\u23DC", para: "\xB6", parallel: "\u2225", par: "\u2225", parsim: "\u2AF3", parsl: "\u2AFD", part: "\u2202", PartialD: "\u2202", Pcy: "\u041F", pcy: "\u043F", percnt: "%", period: ".", permil: "\u2030", perp: "\u22A5", pertenk: "\u2031", Pfr: "\u{1D513}", pfr: "\u{1D52D}", Phi: "\u03A6", phi: "\u03C6", phiv: "\u03D5", phmmat: "\u2133", phone: "\u260E", Pi: "\u03A0", pi: "\u03C0", pitchfork: "\u22D4", piv: "\u03D6", planck: "\u210F", planckh: "\u210E", plankv: "\u210F", plusacir: "\u2A23", plusb: "\u229E", pluscir: "\u2A22", plus: "+", plusdo: "\u2214", plusdu: "\u2A25", pluse: "\u2A72", PlusMinus: "\xB1", plusmn: "\xB1", plussim: "\u2A26", plustwo: "\u2A27", pm: "\xB1", Poincareplane: "\u210C", pointint: "\u2A15", popf: "\u{1D561}", Popf: "\u2119", pound: "\xA3", prap: "\u2AB7", Pr: "\u2ABB", pr: "\u227A", prcue: "\u227C", precapprox: "\u2AB7", prec: "\u227A", preccurlyeq: "\u227C", Precedes: "\u227A", PrecedesEqual: "\u2AAF", PrecedesSlantEqual: "\u227C", PrecedesTilde: "\u227E", preceq: "\u2AAF", precnapprox: "\u2AB9", precneqq: "\u2AB5", precnsim: "\u22E8", pre: "\u2AAF", prE: "\u2AB3", precsim: "\u227E", prime: "\u2032", Prime: "\u2033", primes: "\u2119", prnap: "\u2AB9", prnE: "\u2AB5", prnsim: "\u22E8", prod: "\u220F", Product: "\u220F", profalar: "\u232E", profline: "\u2312", profsurf: "\u2313", prop: "\u221D", Proportional: "\u221D", Proportion: "\u2237", propto: "\u221D", prsim: "\u227E", prurel: "\u22B0", Pscr: "\u{1D4AB}", pscr: "\u{1D4C5}", Psi: "\u03A8", psi: "\u03C8", puncsp: "\u2008", Qfr: "\u{1D514}", qfr: "\u{1D52E}", qint: "\u2A0C", qopf: "\u{1D562}", Qopf: "\u211A", qprime: "\u2057", Qscr: "\u{1D4AC}", qscr: "\u{1D4C6}", quaternions: "\u210D", quatint: "\u2A16", quest: "?", questeq: "\u225F", quot: '"', QUOT: '"', rAarr: "\u21DB", race: "\u223D\u0331", Racute: "\u0154", racute: "\u0155", radic: "\u221A", raemptyv: "\u29B3", rang: "\u27E9", Rang: "\u27EB", rangd: "\u2992", range: "\u29A5", rangle: "\u27E9", raquo: "\xBB", rarrap: "\u2975", rarrb: "\u21E5", rarrbfs: "\u2920", rarrc: "\u2933", rarr: "\u2192", Rarr: "\u21A0", rArr: "\u21D2", rarrfs: "\u291E", rarrhk: "\u21AA", rarrlp: "\u21AC", rarrpl: "\u2945", rarrsim: "\u2974", Rarrtl: "\u2916", rarrtl: "\u21A3", rarrw: "\u219D", ratail: "\u291A", rAtail: "\u291C", ratio: "\u2236", rationals: "\u211A", rbarr: "\u290D", rBarr: "\u290F", RBarr: "\u2910", rbbrk: "\u2773", rbrace: "}", rbrack: "]", rbrke: "\u298C", rbrksld: "\u298E", rbrkslu: "\u2990", Rcaron: "\u0158", rcaron: "\u0159", Rcedil: "\u0156", rcedil: "\u0157", rceil: "\u2309", rcub: "}", Rcy: "\u0420", rcy: "\u0440", rdca: "\u2937", rdldhar: "\u2969", rdquo: "\u201D", rdquor: "\u201D", rdsh: "\u21B3", real: "\u211C", realine: "\u211B", realpart: "\u211C", reals: "\u211D", Re: "\u211C", rect: "\u25AD", reg: "\xAE", REG: "\xAE", ReverseElement: "\u220B", ReverseEquilibrium: "\u21CB", ReverseUpEquilibrium: "\u296F", rfisht: "\u297D", rfloor: "\u230B", rfr: "\u{1D52F}", Rfr: "\u211C", rHar: "\u2964", rhard: "\u21C1", rharu: "\u21C0", rharul: "\u296C", Rho: "\u03A1", rho: "\u03C1", rhov: "\u03F1", RightAngleBracket: "\u27E9", RightArrowBar: "\u21E5", rightarrow: "\u2192", RightArrow: "\u2192", Rightarrow: "\u21D2", RightArrowLeftArrow: "\u21C4", rightarrowtail: "\u21A3", RightCeiling: "\u2309", RightDoubleBracket: "\u27E7", RightDownTeeVector: "\u295D", RightDownVectorBar: "\u2955", RightDownVector: "\u21C2", RightFloor: "\u230B", rightharpoondown: "\u21C1", rightharpoonup: "\u21C0", rightleftarrows: "\u21C4", rightleftharpoons: "\u21CC", rightrightarrows: "\u21C9", rightsquigarrow: "\u219D", RightTeeArrow: "\u21A6", RightTee: "\u22A2", RightTeeVector: "\u295B", rightthreetimes: "\u22CC", RightTriangleBar: "\u29D0", RightTriangle: "\u22B3", RightTriangleEqual: "\u22B5", RightUpDownVector: "\u294F", RightUpTeeVector: "\u295C", RightUpVectorBar: "\u2954", RightUpVector: "\u21BE", RightVectorBar: "\u2953", RightVector: "\u21C0", ring: "\u02DA", risingdotseq: "\u2253", rlarr: "\u21C4", rlhar: "\u21CC", rlm: "\u200F", rmoustache: "\u23B1", rmoust: "\u23B1", rnmid: "\u2AEE", roang: "\u27ED", roarr: "\u21FE", robrk: "\u27E7", ropar: "\u2986", ropf: "\u{1D563}", Ropf: "\u211D", roplus: "\u2A2E", rotimes: "\u2A35", RoundImplies: "\u2970", rpar: ")", rpargt: "\u2994", rppolint: "\u2A12", rrarr: "\u21C9", Rrightarrow: "\u21DB", rsaquo: "\u203A", rscr: "\u{1D4C7}", Rscr: "\u211B", rsh: "\u21B1", Rsh: "\u21B1", rsqb: "]", rsquo: "\u2019", rsquor: "\u2019", rthree: "\u22CC", rtimes: "\u22CA", rtri: "\u25B9", rtrie: "\u22B5", rtrif: "\u25B8", rtriltri: "\u29CE", RuleDelayed: "\u29F4", ruluhar: "\u2968", rx: "\u211E", Sacute: "\u015A", sacute: "\u015B", sbquo: "\u201A", scap: "\u2AB8", Scaron: "\u0160", scaron: "\u0161", Sc: "\u2ABC", sc: "\u227B", sccue: "\u227D", sce: "\u2AB0", scE: "\u2AB4", Scedil: "\u015E", scedil: "\u015F", Scirc: "\u015C", scirc: "\u015D", scnap: "\u2ABA", scnE: "\u2AB6", scnsim: "\u22E9", scpolint: "\u2A13", scsim: "\u227F", Scy: "\u0421", scy: "\u0441", sdotb: "\u22A1", sdot: "\u22C5", sdote: "\u2A66", searhk: "\u2925", searr: "\u2198", seArr: "\u21D8", searrow: "\u2198", sect: "\xA7", semi: ";", seswar: "\u2929", setminus: "\u2216", setmn: "\u2216", sext: "\u2736", Sfr: "\u{1D516}", sfr: "\u{1D530}", sfrown: "\u2322", sharp: "\u266F", SHCHcy: "\u0429", shchcy: "\u0449", SHcy: "\u0428", shcy: "\u0448", ShortDownArrow: "\u2193", ShortLeftArrow: "\u2190", shortmid: "\u2223", shortparallel: "\u2225", ShortRightArrow: "\u2192", ShortUpArrow: "\u2191", shy: "\xAD", Sigma: "\u03A3", sigma: "\u03C3", sigmaf: "\u03C2", sigmav: "\u03C2", sim: "\u223C", simdot: "\u2A6A", sime: "\u2243", simeq: "\u2243", simg: "\u2A9E", simgE: "\u2AA0", siml: "\u2A9D", simlE: "\u2A9F", simne: "\u2246", simplus: "\u2A24", simrarr: "\u2972", slarr: "\u2190", SmallCircle: "\u2218", smallsetminus: "\u2216", smashp: "\u2A33", smeparsl: "\u29E4", smid: "\u2223", smile: "\u2323", smt: "\u2AAA", smte: "\u2AAC", smtes: "\u2AAC\uFE00", SOFTcy: "\u042C", softcy: "\u044C", solbar: "\u233F", solb: "\u29C4", sol: "/", Sopf: "\u{1D54A}", sopf: "\u{1D564}", spades: "\u2660", spadesuit: "\u2660", spar: "\u2225", sqcap: "\u2293", sqcaps: "\u2293\uFE00", sqcup: "\u2294", sqcups: "\u2294\uFE00", Sqrt: "\u221A", sqsub: "\u228F", sqsube: "\u2291", sqsubset: "\u228F", sqsubseteq: "\u2291", sqsup: "\u2290", sqsupe: "\u2292", sqsupset: "\u2290", sqsupseteq: "\u2292", square: "\u25A1", Square: "\u25A1", SquareIntersection: "\u2293", SquareSubset: "\u228F", SquareSubsetEqual: "\u2291", SquareSuperset: "\u2290", SquareSupersetEqual: "\u2292", SquareUnion: "\u2294", squarf: "\u25AA", squ: "\u25A1", squf: "\u25AA", srarr: "\u2192", Sscr: "\u{1D4AE}", sscr: "\u{1D4C8}", ssetmn: "\u2216", ssmile: "\u2323", sstarf: "\u22C6", Star: "\u22C6", star: "\u2606", starf: "\u2605", straightepsilon: "\u03F5", straightphi: "\u03D5", strns: "\xAF", sub: "\u2282", Sub: "\u22D0", subdot: "\u2ABD", subE: "\u2AC5", sube: "\u2286", subedot: "\u2AC3", submult: "\u2AC1", subnE: "\u2ACB", subne: "\u228A", subplus: "\u2ABF", subrarr: "\u2979", subset: "\u2282", Subset: "\u22D0", subseteq: "\u2286", subseteqq: "\u2AC5", SubsetEqual: "\u2286", subsetneq: "\u228A", subsetneqq: "\u2ACB", subsim: "\u2AC7", subsub: "\u2AD5", subsup: "\u2AD3", succapprox: "\u2AB8", succ: "\u227B", succcurlyeq: "\u227D", Succeeds: "\u227B", SucceedsEqual: "\u2AB0", SucceedsSlantEqual: "\u227D", SucceedsTilde: "\u227F", succeq: "\u2AB0", succnapprox: "\u2ABA", succneqq: "\u2AB6", succnsim: "\u22E9", succsim: "\u227F", SuchThat: "\u220B", sum: "\u2211", Sum: "\u2211", sung: "\u266A", sup1: "\xB9", sup2: "\xB2", sup3: "\xB3", sup: "\u2283", Sup: "\u22D1", supdot: "\u2ABE", supdsub: "\u2AD8", supE: "\u2AC6", supe: "\u2287", supedot: "\u2AC4", Superset: "\u2283", SupersetEqual: "\u2287", suphsol: "\u27C9", suphsub: "\u2AD7", suplarr: "\u297B", supmult: "\u2AC2", supnE: "\u2ACC", supne: "\u228B", supplus: "\u2AC0", supset: "\u2283", Supset: "\u22D1", supseteq: "\u2287", supseteqq: "\u2AC6", supsetneq: "\u228B", supsetneqq: "\u2ACC", supsim: "\u2AC8", supsub: "\u2AD4", supsup: "\u2AD6", swarhk: "\u2926", swarr: "\u2199", swArr: "\u21D9", swarrow: "\u2199", swnwar: "\u292A", szlig: "\xDF", Tab: "	", target: "\u2316", Tau: "\u03A4", tau: "\u03C4", tbrk: "\u23B4", Tcaron: "\u0164", tcaron: "\u0165", Tcedil: "\u0162", tcedil: "\u0163", Tcy: "\u0422", tcy: "\u0442", tdot: "\u20DB", telrec: "\u2315", Tfr: "\u{1D517}", tfr: "\u{1D531}", there4: "\u2234", therefore: "\u2234", Therefore: "\u2234", Theta: "\u0398", theta: "\u03B8", thetasym: "\u03D1", thetav: "\u03D1", thickapprox: "\u2248", thicksim: "\u223C", ThickSpace: "\u205F\u200A", ThinSpace: "\u2009", thinsp: "\u2009", thkap: "\u2248", thksim: "\u223C", THORN: "\xDE", thorn: "\xFE", tilde: "\u02DC", Tilde: "\u223C", TildeEqual: "\u2243", TildeFullEqual: "\u2245", TildeTilde: "\u2248", timesbar: "\u2A31", timesb: "\u22A0", times: "\xD7", timesd: "\u2A30", tint: "\u222D", toea: "\u2928", topbot: "\u2336", topcir: "\u2AF1", top: "\u22A4", Topf: "\u{1D54B}", topf: "\u{1D565}", topfork: "\u2ADA", tosa: "\u2929", tprime: "\u2034", trade: "\u2122", TRADE: "\u2122", triangle: "\u25B5", triangledown: "\u25BF", triangleleft: "\u25C3", trianglelefteq: "\u22B4", triangleq: "\u225C", triangleright: "\u25B9", trianglerighteq: "\u22B5", tridot: "\u25EC", trie: "\u225C", triminus: "\u2A3A", TripleDot: "\u20DB", triplus: "\u2A39", trisb: "\u29CD", tritime: "\u2A3B", trpezium: "\u23E2", Tscr: "\u{1D4AF}", tscr: "\u{1D4C9}", TScy: "\u0426", tscy: "\u0446", TSHcy: "\u040B", tshcy: "\u045B", Tstrok: "\u0166", tstrok: "\u0167", twixt: "\u226C", twoheadleftarrow: "\u219E", twoheadrightarrow: "\u21A0", Uacute: "\xDA", uacute: "\xFA", uarr: "\u2191", Uarr: "\u219F", uArr: "\u21D1", Uarrocir: "\u2949", Ubrcy: "\u040E", ubrcy: "\u045E", Ubreve: "\u016C", ubreve: "\u016D", Ucirc: "\xDB", ucirc: "\xFB", Ucy: "\u0423", ucy: "\u0443", udarr: "\u21C5", Udblac: "\u0170", udblac: "\u0171", udhar: "\u296E", ufisht: "\u297E", Ufr: "\u{1D518}", ufr: "\u{1D532}", Ugrave: "\xD9", ugrave: "\xF9", uHar: "\u2963", uharl: "\u21BF", uharr: "\u21BE", uhblk: "\u2580", ulcorn: "\u231C", ulcorner: "\u231C", ulcrop: "\u230F", ultri: "\u25F8", Umacr: "\u016A", umacr: "\u016B", uml: "\xA8", UnderBar: "_", UnderBrace: "\u23DF", UnderBracket: "\u23B5", UnderParenthesis: "\u23DD", Union: "\u22C3", UnionPlus: "\u228E", Uogon: "\u0172", uogon: "\u0173", Uopf: "\u{1D54C}", uopf: "\u{1D566}", UpArrowBar: "\u2912", uparrow: "\u2191", UpArrow: "\u2191", Uparrow: "\u21D1", UpArrowDownArrow: "\u21C5", updownarrow: "\u2195", UpDownArrow: "\u2195", Updownarrow: "\u21D5", UpEquilibrium: "\u296E", upharpoonleft: "\u21BF", upharpoonright: "\u21BE", uplus: "\u228E", UpperLeftArrow: "\u2196", UpperRightArrow: "\u2197", upsi: "\u03C5", Upsi: "\u03D2", upsih: "\u03D2", Upsilon: "\u03A5", upsilon: "\u03C5", UpTeeArrow: "\u21A5", UpTee: "\u22A5", upuparrows: "\u21C8", urcorn: "\u231D", urcorner: "\u231D", urcrop: "\u230E", Uring: "\u016E", uring: "\u016F", urtri: "\u25F9", Uscr: "\u{1D4B0}", uscr: "\u{1D4CA}", utdot: "\u22F0", Utilde: "\u0168", utilde: "\u0169", utri: "\u25B5", utrif: "\u25B4", uuarr: "\u21C8", Uuml: "\xDC", uuml: "\xFC", uwangle: "\u29A7", vangrt: "\u299C", varepsilon: "\u03F5", varkappa: "\u03F0", varnothing: "\u2205", varphi: "\u03D5", varpi: "\u03D6", varpropto: "\u221D", varr: "\u2195", vArr: "\u21D5", varrho: "\u03F1", varsigma: "\u03C2", varsubsetneq: "\u228A\uFE00", varsubsetneqq: "\u2ACB\uFE00", varsupsetneq: "\u228B\uFE00", varsupsetneqq: "\u2ACC\uFE00", vartheta: "\u03D1", vartriangleleft: "\u22B2", vartriangleright: "\u22B3", vBar: "\u2AE8", Vbar: "\u2AEB", vBarv: "\u2AE9", Vcy: "\u0412", vcy: "\u0432", vdash: "\u22A2", vDash: "\u22A8", Vdash: "\u22A9", VDash: "\u22AB", Vdashl: "\u2AE6", veebar: "\u22BB", vee: "\u2228", Vee: "\u22C1", veeeq: "\u225A", vellip: "\u22EE", verbar: "|", Verbar: "\u2016", vert: "|", Vert: "\u2016", VerticalBar: "\u2223", VerticalLine: "|", VerticalSeparator: "\u2758", VerticalTilde: "\u2240", VeryThinSpace: "\u200A", Vfr: "\u{1D519}", vfr: "\u{1D533}", vltri: "\u22B2", vnsub: "\u2282\u20D2", vnsup: "\u2283\u20D2", Vopf: "\u{1D54D}", vopf: "\u{1D567}", vprop: "\u221D", vrtri: "\u22B3", Vscr: "\u{1D4B1}", vscr: "\u{1D4CB}", vsubnE: "\u2ACB\uFE00", vsubne: "\u228A\uFE00", vsupnE: "\u2ACC\uFE00", vsupne: "\u228B\uFE00", Vvdash: "\u22AA", vzigzag: "\u299A", Wcirc: "\u0174", wcirc: "\u0175", wedbar: "\u2A5F", wedge: "\u2227", Wedge: "\u22C0", wedgeq: "\u2259", weierp: "\u2118", Wfr: "\u{1D51A}", wfr: "\u{1D534}", Wopf: "\u{1D54E}", wopf: "\u{1D568}", wp: "\u2118", wr: "\u2240", wreath: "\u2240", Wscr: "\u{1D4B2}", wscr: "\u{1D4CC}", xcap: "\u22C2", xcirc: "\u25EF", xcup: "\u22C3", xdtri: "\u25BD", Xfr: "\u{1D51B}", xfr: "\u{1D535}", xharr: "\u27F7", xhArr: "\u27FA", Xi: "\u039E", xi: "\u03BE", xlarr: "\u27F5", xlArr: "\u27F8", xmap: "\u27FC", xnis: "\u22FB", xodot: "\u2A00", Xopf: "\u{1D54F}", xopf: "\u{1D569}", xoplus: "\u2A01", xotime: "\u2A02", xrarr: "\u27F6", xrArr: "\u27F9", Xscr: "\u{1D4B3}", xscr: "\u{1D4CD}", xsqcup: "\u2A06", xuplus: "\u2A04", xutri: "\u25B3", xvee: "\u22C1", xwedge: "\u22C0", Yacute: "\xDD", yacute: "\xFD", YAcy: "\u042F", yacy: "\u044F", Ycirc: "\u0176", ycirc: "\u0177", Ycy: "\u042B", ycy: "\u044B", yen: "\xA5", Yfr: "\u{1D51C}", yfr: "\u{1D536}", YIcy: "\u0407", yicy: "\u0457", Yopf: "\u{1D550}", yopf: "\u{1D56A}", Yscr: "\u{1D4B4}", yscr: "\u{1D4CE}", YUcy: "\u042E", yucy: "\u044E", yuml: "\xFF", Yuml: "\u0178", Zacute: "\u0179", zacute: "\u017A", Zcaron: "\u017D", zcaron: "\u017E", Zcy: "\u0417", zcy: "\u0437", Zdot: "\u017B", zdot: "\u017C", zeetrf: "\u2128", ZeroWidthSpace: "\u200B", Zeta: "\u0396", zeta: "\u03B6", zfr: "\u{1D537}", Zfr: "\u2128", ZHcy: "\u0416", zhcy: "\u0436", zigrarr: "\u21DD", zopf: "\u{1D56B}", Zopf: "\u2124", Zscr: "\u{1D4B5}", zscr: "\u{1D4CF}", zwj: "\u200D", zwnj: "\u200C" };
  }
});

// node_modules/markdown-it/lib/common/entities.js
var require_entities2 = __commonJS({
  "node_modules/markdown-it/lib/common/entities.js"(exports, module) {
    "use strict";
    module.exports = require_entities();
  }
});

// node_modules/uc.micro/categories/P/regex.js
var require_regex = __commonJS({
  "node_modules/uc.micro/categories/P/regex.js"(exports, module) {
    module.exports = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;
  }
});

// node_modules/mdurl/encode.js
var require_encode = __commonJS({
  "node_modules/mdurl/encode.js"(exports, module) {
    "use strict";
    var encodeCache2 = {};
    function getEncodeCache2(exclude) {
      var i3, ch, cache5 = encodeCache2[exclude];
      if (cache5) {
        return cache5;
      }
      cache5 = encodeCache2[exclude] = [];
      for (i3 = 0; i3 < 128; i3++) {
        ch = String.fromCharCode(i3);
        if (/^[0-9a-z]$/i.test(ch)) {
          cache5.push(ch);
        } else {
          cache5.push("%" + ("0" + i3.toString(16).toUpperCase()).slice(-2));
        }
      }
      for (i3 = 0; i3 < exclude.length; i3++) {
        cache5[exclude.charCodeAt(i3)] = exclude[i3];
      }
      return cache5;
    }
    function encode3(string3, exclude, keepEscaped) {
      var i3, l3, code2, nextCode, cache5, result2 = "";
      if (typeof exclude !== "string") {
        keepEscaped = exclude;
        exclude = encode3.defaultChars;
      }
      if (typeof keepEscaped === "undefined") {
        keepEscaped = true;
      }
      cache5 = getEncodeCache2(exclude);
      for (i3 = 0, l3 = string3.length; i3 < l3; i3++) {
        code2 = string3.charCodeAt(i3);
        if (keepEscaped && code2 === 37 && i3 + 2 < l3) {
          if (/^[0-9a-f]{2}$/i.test(string3.slice(i3 + 1, i3 + 3))) {
            result2 += string3.slice(i3, i3 + 3);
            i3 += 2;
            continue;
          }
        }
        if (code2 < 128) {
          result2 += cache5[code2];
          continue;
        }
        if (code2 >= 55296 && code2 <= 57343) {
          if (code2 >= 55296 && code2 <= 56319 && i3 + 1 < l3) {
            nextCode = string3.charCodeAt(i3 + 1);
            if (nextCode >= 56320 && nextCode <= 57343) {
              result2 += encodeURIComponent(string3[i3] + string3[i3 + 1]);
              i3++;
              continue;
            }
          }
          result2 += "%EF%BF%BD";
          continue;
        }
        result2 += encodeURIComponent(string3[i3]);
      }
      return result2;
    }
    encode3.defaultChars = ";/?:@&=+$,-_.!~*'()#";
    encode3.componentChars = "-_.!~*'()";
    module.exports = encode3;
  }
});

// node_modules/mdurl/decode.js
var require_decode = __commonJS({
  "node_modules/mdurl/decode.js"(exports, module) {
    "use strict";
    var decodeCache2 = {};
    function getDecodeCache2(exclude) {
      var i3, ch, cache5 = decodeCache2[exclude];
      if (cache5) {
        return cache5;
      }
      cache5 = decodeCache2[exclude] = [];
      for (i3 = 0; i3 < 128; i3++) {
        ch = String.fromCharCode(i3);
        cache5.push(ch);
      }
      for (i3 = 0; i3 < exclude.length; i3++) {
        ch = exclude.charCodeAt(i3);
        cache5[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
      }
      return cache5;
    }
    function decode3(string3, exclude) {
      var cache5;
      if (typeof exclude !== "string") {
        exclude = decode3.defaultChars;
      }
      cache5 = getDecodeCache2(exclude);
      return string3.replace(/(%[a-f0-9]{2})+/gi, function(seq2) {
        var i3, l3, b1, b22, b3, b4, chr, result2 = "";
        for (i3 = 0, l3 = seq2.length; i3 < l3; i3 += 3) {
          b1 = parseInt(seq2.slice(i3 + 1, i3 + 3), 16);
          if (b1 < 128) {
            result2 += cache5[b1];
            continue;
          }
          if ((b1 & 224) === 192 && i3 + 3 < l3) {
            b22 = parseInt(seq2.slice(i3 + 4, i3 + 6), 16);
            if ((b22 & 192) === 128) {
              chr = b1 << 6 & 1984 | b22 & 63;
              if (chr < 128) {
                result2 += "\uFFFD\uFFFD";
              } else {
                result2 += String.fromCharCode(chr);
              }
              i3 += 3;
              continue;
            }
          }
          if ((b1 & 240) === 224 && i3 + 6 < l3) {
            b22 = parseInt(seq2.slice(i3 + 4, i3 + 6), 16);
            b3 = parseInt(seq2.slice(i3 + 7, i3 + 9), 16);
            if ((b22 & 192) === 128 && (b3 & 192) === 128) {
              chr = b1 << 12 & 61440 | b22 << 6 & 4032 | b3 & 63;
              if (chr < 2048 || chr >= 55296 && chr <= 57343) {
                result2 += "\uFFFD\uFFFD\uFFFD";
              } else {
                result2 += String.fromCharCode(chr);
              }
              i3 += 6;
              continue;
            }
          }
          if ((b1 & 248) === 240 && i3 + 9 < l3) {
            b22 = parseInt(seq2.slice(i3 + 4, i3 + 6), 16);
            b3 = parseInt(seq2.slice(i3 + 7, i3 + 9), 16);
            b4 = parseInt(seq2.slice(i3 + 10, i3 + 12), 16);
            if ((b22 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
              chr = b1 << 18 & 1835008 | b22 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
              if (chr < 65536 || chr > 1114111) {
                result2 += "\uFFFD\uFFFD\uFFFD\uFFFD";
              } else {
                chr -= 65536;
                result2 += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
              }
              i3 += 9;
              continue;
            }
          }
          result2 += "\uFFFD";
        }
        return result2;
      });
    }
    decode3.defaultChars = ";/?:@&=+$,#";
    decode3.componentChars = "";
    module.exports = decode3;
  }
});

// node_modules/mdurl/format.js
var require_format = __commonJS({
  "node_modules/mdurl/format.js"(exports, module) {
    "use strict";
    module.exports = function format2(url2) {
      var result2 = "";
      result2 += url2.protocol || "";
      result2 += url2.slashes ? "//" : "";
      result2 += url2.auth ? url2.auth + "@" : "";
      if (url2.hostname && url2.hostname.indexOf(":") !== -1) {
        result2 += "[" + url2.hostname + "]";
      } else {
        result2 += url2.hostname || "";
      }
      result2 += url2.port ? ":" + url2.port : "";
      result2 += url2.pathname || "";
      result2 += url2.search || "";
      result2 += url2.hash || "";
      return result2;
    };
  }
});

// node_modules/mdurl/parse.js
var require_parse2 = __commonJS({
  "node_modules/mdurl/parse.js"(exports, module) {
    "use strict";
    function Url2() {
      this.protocol = null;
      this.slashes = null;
      this.auth = null;
      this.port = null;
      this.hostname = null;
      this.hash = null;
      this.search = null;
      this.pathname = null;
    }
    var protocolPattern2 = /^([a-z0-9.+-]+:)/i;
    var portPattern2 = /:[0-9]*$/;
    var simplePathPattern2 = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
    var delims2 = ["<", ">", '"', "`", " ", "\r", "\n", "	"];
    var unwise2 = ["{", "}", "|", "\\", "^", "`"].concat(delims2);
    var autoEscape2 = ["'"].concat(unwise2);
    var nonHostChars2 = ["%", "/", "?", ";", "#"].concat(autoEscape2);
    var hostEndingChars2 = ["/", "?", "#"];
    var hostnameMaxLen2 = 255;
    var hostnamePartPattern2 = /^[+a-z0-9A-Z_-]{0,63}$/;
    var hostnamePartStart2 = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
    var hostlessProtocol2 = {
      "javascript": true,
      "javascript:": true
    };
    var slashedProtocol2 = {
      "http": true,
      "https": true,
      "ftp": true,
      "gopher": true,
      "file": true,
      "http:": true,
      "https:": true,
      "ftp:": true,
      "gopher:": true,
      "file:": true
    };
    function urlParse2(url2, slashesDenoteHost) {
      if (url2 && url2 instanceof Url2) {
        return url2;
      }
      var u3 = new Url2();
      u3.parse(url2, slashesDenoteHost);
      return u3;
    }
    Url2.prototype.parse = function(url2, slashesDenoteHost) {
      var i3, l3, lowerProto, hec, slashes, rest2 = url2;
      rest2 = rest2.trim();
      if (!slashesDenoteHost && url2.split("#").length === 1) {
        var simplePath = simplePathPattern2.exec(rest2);
        if (simplePath) {
          this.pathname = simplePath[1];
          if (simplePath[2]) {
            this.search = simplePath[2];
          }
          return this;
        }
      }
      var proto = protocolPattern2.exec(rest2);
      if (proto) {
        proto = proto[0];
        lowerProto = proto.toLowerCase();
        this.protocol = proto;
        rest2 = rest2.substr(proto.length);
      }
      if (slashesDenoteHost || proto || rest2.match(/^\/\/[^@\/]+@[^@\/]+/)) {
        slashes = rest2.substr(0, 2) === "//";
        if (slashes && !(proto && hostlessProtocol2[proto])) {
          rest2 = rest2.substr(2);
          this.slashes = true;
        }
      }
      if (!hostlessProtocol2[proto] && (slashes || proto && !slashedProtocol2[proto])) {
        var hostEnd = -1;
        for (i3 = 0; i3 < hostEndingChars2.length; i3++) {
          hec = rest2.indexOf(hostEndingChars2[i3]);
          if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
            hostEnd = hec;
          }
        }
        var auth, atSign;
        if (hostEnd === -1) {
          atSign = rest2.lastIndexOf("@");
        } else {
          atSign = rest2.lastIndexOf("@", hostEnd);
        }
        if (atSign !== -1) {
          auth = rest2.slice(0, atSign);
          rest2 = rest2.slice(atSign + 1);
          this.auth = auth;
        }
        hostEnd = -1;
        for (i3 = 0; i3 < nonHostChars2.length; i3++) {
          hec = rest2.indexOf(nonHostChars2[i3]);
          if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
            hostEnd = hec;
          }
        }
        if (hostEnd === -1) {
          hostEnd = rest2.length;
        }
        if (rest2[hostEnd - 1] === ":") {
          hostEnd--;
        }
        var host = rest2.slice(0, hostEnd);
        rest2 = rest2.slice(hostEnd);
        this.parseHost(host);
        this.hostname = this.hostname || "";
        var ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
        if (!ipv6Hostname) {
          var hostparts = this.hostname.split(/\./);
          for (i3 = 0, l3 = hostparts.length; i3 < l3; i3++) {
            var part = hostparts[i3];
            if (!part) {
              continue;
            }
            if (!part.match(hostnamePartPattern2)) {
              var newpart = "";
              for (var j = 0, k2 = part.length; j < k2; j++) {
                if (part.charCodeAt(j) > 127) {
                  newpart += "x";
                } else {
                  newpart += part[j];
                }
              }
              if (!newpart.match(hostnamePartPattern2)) {
                var validParts = hostparts.slice(0, i3);
                var notHost = hostparts.slice(i3 + 1);
                var bit = part.match(hostnamePartStart2);
                if (bit) {
                  validParts.push(bit[1]);
                  notHost.unshift(bit[2]);
                }
                if (notHost.length) {
                  rest2 = notHost.join(".") + rest2;
                }
                this.hostname = validParts.join(".");
                break;
              }
            }
          }
        }
        if (this.hostname.length > hostnameMaxLen2) {
          this.hostname = "";
        }
        if (ipv6Hostname) {
          this.hostname = this.hostname.substr(1, this.hostname.length - 2);
        }
      }
      var hash = rest2.indexOf("#");
      if (hash !== -1) {
        this.hash = rest2.substr(hash);
        rest2 = rest2.slice(0, hash);
      }
      var qm = rest2.indexOf("?");
      if (qm !== -1) {
        this.search = rest2.substr(qm);
        rest2 = rest2.slice(0, qm);
      }
      if (rest2) {
        this.pathname = rest2;
      }
      if (slashedProtocol2[lowerProto] && this.hostname && !this.pathname) {
        this.pathname = "";
      }
      return this;
    };
    Url2.prototype.parseHost = function(host) {
      var port = portPattern2.exec(host);
      if (port) {
        port = port[0];
        if (port !== ":") {
          this.port = port.substr(1);
        }
        host = host.substr(0, host.length - port.length);
      }
      if (host) {
        this.hostname = host;
      }
    };
    module.exports = urlParse2;
  }
});

// node_modules/mdurl/index.js
var require_mdurl = __commonJS({
  "node_modules/mdurl/index.js"(exports, module) {
    "use strict";
    module.exports.encode = require_encode();
    module.exports.decode = require_decode();
    module.exports.format = require_format();
    module.exports.parse = require_parse2();
  }
});

// node_modules/uc.micro/properties/Any/regex.js
var require_regex2 = __commonJS({
  "node_modules/uc.micro/properties/Any/regex.js"(exports, module) {
    module.exports = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  }
});

// node_modules/uc.micro/categories/Cc/regex.js
var require_regex3 = __commonJS({
  "node_modules/uc.micro/categories/Cc/regex.js"(exports, module) {
    module.exports = /[\0-\x1F\x7F-\x9F]/;
  }
});

// node_modules/uc.micro/categories/Cf/regex.js
var require_regex4 = __commonJS({
  "node_modules/uc.micro/categories/Cf/regex.js"(exports, module) {
    module.exports = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
  }
});

// node_modules/uc.micro/categories/Z/regex.js
var require_regex5 = __commonJS({
  "node_modules/uc.micro/categories/Z/regex.js"(exports, module) {
    module.exports = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
  }
});

// node_modules/uc.micro/index.js
var require_uc = __commonJS({
  "node_modules/uc.micro/index.js"(exports) {
    "use strict";
    exports.Any = require_regex2();
    exports.Cc = require_regex3();
    exports.Cf = require_regex4();
    exports.P = require_regex();
    exports.Z = require_regex5();
  }
});

// node_modules/markdown-it/lib/common/utils.js
var require_utils = __commonJS({
  "node_modules/markdown-it/lib/common/utils.js"(exports) {
    "use strict";
    function _class3(obj) {
      return Object.prototype.toString.call(obj);
    }
    function isString5(obj) {
      return _class3(obj) === "[object String]";
    }
    var _hasOwnProperty2 = Object.prototype.hasOwnProperty;
    function has4(object2, key2) {
      return _hasOwnProperty2.call(object2, key2);
    }
    function assign6(obj) {
      var sources = Array.prototype.slice.call(arguments, 1);
      sources.forEach(function(source) {
        if (!source) {
          return;
        }
        if (typeof source !== "object") {
          throw new TypeError(source + "must be object");
        }
        Object.keys(source).forEach(function(key2) {
          obj[key2] = source[key2];
        });
      });
      return obj;
    }
    function arrayReplaceAt2(src, pos, newElements) {
      return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
    }
    function isValidEntityCode2(c3) {
      if (c3 >= 55296 && c3 <= 57343) {
        return false;
      }
      if (c3 >= 64976 && c3 <= 65007) {
        return false;
      }
      if ((c3 & 65535) === 65535 || (c3 & 65535) === 65534) {
        return false;
      }
      if (c3 >= 0 && c3 <= 8) {
        return false;
      }
      if (c3 === 11) {
        return false;
      }
      if (c3 >= 14 && c3 <= 31) {
        return false;
      }
      if (c3 >= 127 && c3 <= 159) {
        return false;
      }
      if (c3 > 1114111) {
        return false;
      }
      return true;
    }
    function fromCodePoint4(c3) {
      if (c3 > 65535) {
        c3 -= 65536;
        var surrogate1 = 55296 + (c3 >> 10), surrogate2 = 56320 + (c3 & 1023);
        return String.fromCharCode(surrogate1, surrogate2);
      }
      return String.fromCharCode(c3);
    }
    var UNESCAPE_MD_RE2 = /\\([!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])/g;
    var ENTITY_RE2 = /&([a-z#][a-z0-9]{1,31});/gi;
    var UNESCAPE_ALL_RE2 = new RegExp(UNESCAPE_MD_RE2.source + "|" + ENTITY_RE2.source, "gi");
    var DIGITAL_ENTITY_TEST_RE2 = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;
    var entities = require_entities2();
    function replaceEntityPattern2(match2, name2) {
      var code2 = 0;
      if (has4(entities, name2)) {
        return entities[name2];
      }
      if (name2.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE2.test(name2)) {
        code2 = name2[1].toLowerCase() === "x" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
        if (isValidEntityCode2(code2)) {
          return fromCodePoint4(code2);
        }
      }
      return match2;
    }
    function unescapeMd2(str) {
      if (str.indexOf("\\") < 0) {
        return str;
      }
      return str.replace(UNESCAPE_MD_RE2, "$1");
    }
    function unescapeAll2(str) {
      if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
        return str;
      }
      return str.replace(UNESCAPE_ALL_RE2, function(match2, escaped, entity2) {
        if (escaped) {
          return escaped;
        }
        return replaceEntityPattern2(match2, entity2);
      });
    }
    var HTML_ESCAPE_TEST_RE2 = /[&<>"]/;
    var HTML_ESCAPE_REPLACE_RE2 = /[&<>"]/g;
    var HTML_REPLACEMENTS2 = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;"
    };
    function replaceUnsafeChar2(ch) {
      return HTML_REPLACEMENTS2[ch];
    }
    function escapeHtml2(str) {
      if (HTML_ESCAPE_TEST_RE2.test(str)) {
        return str.replace(HTML_ESCAPE_REPLACE_RE2, replaceUnsafeChar2);
      }
      return str;
    }
    var REGEXP_ESCAPE_RE2 = /[.?*+^$[\]\\(){}|-]/g;
    function escapeRE3(str) {
      return str.replace(REGEXP_ESCAPE_RE2, "\\$&");
    }
    function isSpace2(code2) {
      switch (code2) {
        case 9:
        case 32:
          return true;
      }
      return false;
    }
    function isWhiteSpace2(code2) {
      if (code2 >= 8192 && code2 <= 8202) {
        return true;
      }
      switch (code2) {
        case 9:
        // \t
        case 10:
        // \n
        case 11:
        // \v
        case 12:
        // \f
        case 13:
        // \r
        case 32:
        case 160:
        case 5760:
        case 8239:
        case 8287:
        case 12288:
          return true;
      }
      return false;
    }
    var UNICODE_PUNCT_RE = require_regex();
    function isPunctChar2(ch) {
      return UNICODE_PUNCT_RE.test(ch);
    }
    function isMdAsciiPunct2(ch) {
      switch (ch) {
        case 33:
        case 34:
        case 35:
        case 36:
        case 37:
        case 38:
        case 39:
        case 40:
        case 41:
        case 42:
        case 43:
        case 44:
        case 45:
        case 46:
        case 47:
        case 58:
        case 59:
        case 60:
        case 61:
        case 62:
        case 63:
        case 64:
        case 91:
        case 92:
        case 93:
        case 94:
        case 95:
        case 96:
        case 123:
        case 124:
        case 125:
        case 126:
          return true;
        default:
          return false;
      }
    }
    function normalizeReference2(str) {
      str = str.trim().replace(/\s+/g, " ");
      if ("\u1E9E".toLowerCase() === "\u1E7E") {
        str = str.replace(/ẞ/g, "\xDF");
      }
      return str.toLowerCase().toUpperCase();
    }
    exports.lib = {};
    exports.lib.mdurl = require_mdurl();
    exports.lib.ucmicro = require_uc();
    exports.assign = assign6;
    exports.isString = isString5;
    exports.has = has4;
    exports.unescapeMd = unescapeMd2;
    exports.unescapeAll = unescapeAll2;
    exports.isValidEntityCode = isValidEntityCode2;
    exports.fromCodePoint = fromCodePoint4;
    exports.escapeHtml = escapeHtml2;
    exports.arrayReplaceAt = arrayReplaceAt2;
    exports.isSpace = isSpace2;
    exports.isWhiteSpace = isWhiteSpace2;
    exports.isMdAsciiPunct = isMdAsciiPunct2;
    exports.isPunctChar = isPunctChar2;
    exports.escapeRE = escapeRE3;
    exports.normalizeReference = normalizeReference2;
  }
});

// node_modules/markdown-it/lib/helpers/parse_link_label.js
var require_parse_link_label = __commonJS({
  "node_modules/markdown-it/lib/helpers/parse_link_label.js"(exports, module) {
    "use strict";
    module.exports = function parseLinkLabel2(state, start, disableNested) {
      var level, found2, marker, prevPos, labelEnd = -1, max3 = state.posMax, oldPos = state.pos;
      state.pos = start + 1;
      level = 1;
      while (state.pos < max3) {
        marker = state.src.charCodeAt(state.pos);
        if (marker === 93) {
          level--;
          if (level === 0) {
            found2 = true;
            break;
          }
        }
        prevPos = state.pos;
        state.md.inline.skipToken(state);
        if (marker === 91) {
          if (prevPos === state.pos - 1) {
            level++;
          } else if (disableNested) {
            state.pos = oldPos;
            return -1;
          }
        }
      }
      if (found2) {
        labelEnd = state.pos;
      }
      state.pos = oldPos;
      return labelEnd;
    };
  }
});

// node_modules/markdown-it/lib/helpers/parse_link_destination.js
var require_parse_link_destination = __commonJS({
  "node_modules/markdown-it/lib/helpers/parse_link_destination.js"(exports, module) {
    "use strict";
    var unescapeAll2 = require_utils().unescapeAll;
    module.exports = function parseLinkDestination2(str, pos, max3) {
      var code2, level, lines = 0, start = pos, result2 = {
        ok: false,
        pos: 0,
        lines: 0,
        str: ""
      };
      if (str.charCodeAt(pos) === 60) {
        pos++;
        while (pos < max3) {
          code2 = str.charCodeAt(pos);
          if (code2 === 10) {
            return result2;
          }
          if (code2 === 60) {
            return result2;
          }
          if (code2 === 62) {
            result2.pos = pos + 1;
            result2.str = unescapeAll2(str.slice(start + 1, pos));
            result2.ok = true;
            return result2;
          }
          if (code2 === 92 && pos + 1 < max3) {
            pos += 2;
            continue;
          }
          pos++;
        }
        return result2;
      }
      level = 0;
      while (pos < max3) {
        code2 = str.charCodeAt(pos);
        if (code2 === 32) {
          break;
        }
        if (code2 < 32 || code2 === 127) {
          break;
        }
        if (code2 === 92 && pos + 1 < max3) {
          if (str.charCodeAt(pos + 1) === 32) {
            break;
          }
          pos += 2;
          continue;
        }
        if (code2 === 40) {
          level++;
          if (level > 32) {
            return result2;
          }
        }
        if (code2 === 41) {
          if (level === 0) {
            break;
          }
          level--;
        }
        pos++;
      }
      if (start === pos) {
        return result2;
      }
      if (level !== 0) {
        return result2;
      }
      result2.str = unescapeAll2(str.slice(start, pos));
      result2.lines = lines;
      result2.pos = pos;
      result2.ok = true;
      return result2;
    };
  }
});

// node_modules/markdown-it/lib/helpers/parse_link_title.js
var require_parse_link_title = __commonJS({
  "node_modules/markdown-it/lib/helpers/parse_link_title.js"(exports, module) {
    "use strict";
    var unescapeAll2 = require_utils().unescapeAll;
    module.exports = function parseLinkTitle2(str, pos, max3) {
      var code2, marker, lines = 0, start = pos, result2 = {
        ok: false,
        pos: 0,
        lines: 0,
        str: ""
      };
      if (pos >= max3) {
        return result2;
      }
      marker = str.charCodeAt(pos);
      if (marker !== 34 && marker !== 39 && marker !== 40) {
        return result2;
      }
      pos++;
      if (marker === 40) {
        marker = 41;
      }
      while (pos < max3) {
        code2 = str.charCodeAt(pos);
        if (code2 === marker) {
          result2.pos = pos + 1;
          result2.lines = lines;
          result2.str = unescapeAll2(str.slice(start + 1, pos));
          result2.ok = true;
          return result2;
        } else if (code2 === 40 && marker === 41) {
          return result2;
        } else if (code2 === 10) {
          lines++;
        } else if (code2 === 92 && pos + 1 < max3) {
          pos++;
          if (str.charCodeAt(pos) === 10) {
            lines++;
          }
        }
        pos++;
      }
      return result2;
    };
  }
});

// node_modules/markdown-it/lib/helpers/index.js
var require_helpers = __commonJS({
  "node_modules/markdown-it/lib/helpers/index.js"(exports) {
    "use strict";
    exports.parseLinkLabel = require_parse_link_label();
    exports.parseLinkDestination = require_parse_link_destination();
    exports.parseLinkTitle = require_parse_link_title();
  }
});

// node_modules/markdown-it/lib/renderer.js
var require_renderer = __commonJS({
  "node_modules/markdown-it/lib/renderer.js"(exports, module) {
    "use strict";
    var assign6 = require_utils().assign;
    var unescapeAll2 = require_utils().unescapeAll;
    var escapeHtml2 = require_utils().escapeHtml;
    var default_rules2 = {};
    default_rules2.code_inline = function(tokens, idx, options2, env, slf) {
      var token = tokens[idx];
      return "<code" + slf.renderAttrs(token) + ">" + escapeHtml2(tokens[idx].content) + "</code>";
    };
    default_rules2.code_block = function(tokens, idx, options2, env, slf) {
      var token = tokens[idx];
      return "<pre" + slf.renderAttrs(token) + "><code>" + escapeHtml2(tokens[idx].content) + "</code></pre>\n";
    };
    default_rules2.fence = function(tokens, idx, options2, env, slf) {
      var token = tokens[idx], info = token.info ? unescapeAll2(token.info).trim() : "", langName = "", langAttrs = "", highlighted, i3, arr, tmpAttrs, tmpToken;
      if (info) {
        arr = info.split(/(\s+)/g);
        langName = arr[0];
        langAttrs = arr.slice(2).join("");
      }
      if (options2.highlight) {
        highlighted = options2.highlight(token.content, langName, langAttrs) || escapeHtml2(token.content);
      } else {
        highlighted = escapeHtml2(token.content);
      }
      if (highlighted.indexOf("<pre") === 0) {
        return highlighted + "\n";
      }
      if (info) {
        i3 = token.attrIndex("class");
        tmpAttrs = token.attrs ? token.attrs.slice() : [];
        if (i3 < 0) {
          tmpAttrs.push(["class", options2.langPrefix + langName]);
        } else {
          tmpAttrs[i3] = tmpAttrs[i3].slice();
          tmpAttrs[i3][1] += " " + options2.langPrefix + langName;
        }
        tmpToken = {
          attrs: tmpAttrs
        };
        return "<pre><code" + slf.renderAttrs(tmpToken) + ">" + highlighted + "</code></pre>\n";
      }
      return "<pre><code" + slf.renderAttrs(token) + ">" + highlighted + "</code></pre>\n";
    };
    default_rules2.image = function(tokens, idx, options2, env, slf) {
      var token = tokens[idx];
      token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText(token.children, options2, env);
      return slf.renderToken(tokens, idx, options2);
    };
    default_rules2.hardbreak = function(tokens, idx, options2) {
      return options2.xhtmlOut ? "<br />\n" : "<br>\n";
    };
    default_rules2.softbreak = function(tokens, idx, options2) {
      return options2.breaks ? options2.xhtmlOut ? "<br />\n" : "<br>\n" : "\n";
    };
    default_rules2.text = function(tokens, idx) {
      return escapeHtml2(tokens[idx].content);
    };
    default_rules2.html_block = function(tokens, idx) {
      return tokens[idx].content;
    };
    default_rules2.html_inline = function(tokens, idx) {
      return tokens[idx].content;
    };
    function Renderer3() {
      this.rules = assign6({}, default_rules2);
    }
    Renderer3.prototype.renderAttrs = function renderAttrs2(token) {
      var i3, l3, result2;
      if (!token.attrs) {
        return "";
      }
      result2 = "";
      for (i3 = 0, l3 = token.attrs.length; i3 < l3; i3++) {
        result2 += " " + escapeHtml2(token.attrs[i3][0]) + '="' + escapeHtml2(token.attrs[i3][1]) + '"';
      }
      return result2;
    };
    Renderer3.prototype.renderToken = function renderToken2(tokens, idx, options2) {
      var nextToken, result2 = "", needLf = false, token = tokens[idx];
      if (token.hidden) {
        return "";
      }
      if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) {
        result2 += "\n";
      }
      result2 += (token.nesting === -1 ? "</" : "<") + token.tag;
      result2 += this.renderAttrs(token);
      if (token.nesting === 0 && options2.xhtmlOut) {
        result2 += " /";
      }
      if (token.block) {
        needLf = true;
        if (token.nesting === 1) {
          if (idx + 1 < tokens.length) {
            nextToken = tokens[idx + 1];
            if (nextToken.type === "inline" || nextToken.hidden) {
              needLf = false;
            } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
              needLf = false;
            }
          }
        }
      }
      result2 += needLf ? ">\n" : ">";
      return result2;
    };
    Renderer3.prototype.renderInline = function(tokens, options2, env) {
      var type, result2 = "", rules = this.rules;
      for (var i3 = 0, len = tokens.length; i3 < len; i3++) {
        type = tokens[i3].type;
        if (typeof rules[type] !== "undefined") {
          result2 += rules[type](tokens, i3, options2, env, this);
        } else {
          result2 += this.renderToken(tokens, i3, options2);
        }
      }
      return result2;
    };
    Renderer3.prototype.renderInlineAsText = function(tokens, options2, env) {
      var result2 = "";
      for (var i3 = 0, len = tokens.length; i3 < len; i3++) {
        if (tokens[i3].type === "text") {
          result2 += tokens[i3].content;
        } else if (tokens[i3].type === "image") {
          result2 += this.renderInlineAsText(tokens[i3].children, options2, env);
        } else if (tokens[i3].type === "softbreak") {
          result2 += "\n";
        }
      }
      return result2;
    };
    Renderer3.prototype.render = function(tokens, options2, env) {
      var i3, len, type, result2 = "", rules = this.rules;
      for (i3 = 0, len = tokens.length; i3 < len; i3++) {
        type = tokens[i3].type;
        if (type === "inline") {
          result2 += this.renderInline(tokens[i3].children, options2, env);
        } else if (typeof rules[type] !== "undefined") {
          result2 += rules[tokens[i3].type](tokens, i3, options2, env, this);
        } else {
          result2 += this.renderToken(tokens, i3, options2, env);
        }
      }
      return result2;
    };
    module.exports = Renderer3;
  }
});

// node_modules/markdown-it/lib/ruler.js
var require_ruler = __commonJS({
  "node_modules/markdown-it/lib/ruler.js"(exports, module) {
    "use strict";
    function Ruler2() {
      this.__rules__ = [];
      this.__cache__ = null;
    }
    Ruler2.prototype.__find__ = function(name2) {
      for (var i3 = 0; i3 < this.__rules__.length; i3++) {
        if (this.__rules__[i3].name === name2) {
          return i3;
        }
      }
      return -1;
    };
    Ruler2.prototype.__compile__ = function() {
      var self2 = this;
      var chains = [""];
      self2.__rules__.forEach(function(rule) {
        if (!rule.enabled) {
          return;
        }
        rule.alt.forEach(function(altName) {
          if (chains.indexOf(altName) < 0) {
            chains.push(altName);
          }
        });
      });
      self2.__cache__ = {};
      chains.forEach(function(chain3) {
        self2.__cache__[chain3] = [];
        self2.__rules__.forEach(function(rule) {
          if (!rule.enabled) {
            return;
          }
          if (chain3 && rule.alt.indexOf(chain3) < 0) {
            return;
          }
          self2.__cache__[chain3].push(rule.fn);
        });
      });
    };
    Ruler2.prototype.at = function(name2, fn, options2) {
      var index2 = this.__find__(name2);
      var opt = options2 || {};
      if (index2 === -1) {
        throw new Error("Parser rule not found: " + name2);
      }
      this.__rules__[index2].fn = fn;
      this.__rules__[index2].alt = opt.alt || [];
      this.__cache__ = null;
    };
    Ruler2.prototype.before = function(beforeName, ruleName, fn, options2) {
      var index2 = this.__find__(beforeName);
      var opt = options2 || {};
      if (index2 === -1) {
        throw new Error("Parser rule not found: " + beforeName);
      }
      this.__rules__.splice(index2, 0, {
        name: ruleName,
        enabled: true,
        fn,
        alt: opt.alt || []
      });
      this.__cache__ = null;
    };
    Ruler2.prototype.after = function(afterName, ruleName, fn, options2) {
      var index2 = this.__find__(afterName);
      var opt = options2 || {};
      if (index2 === -1) {
        throw new Error("Parser rule not found: " + afterName);
      }
      this.__rules__.splice(index2 + 1, 0, {
        name: ruleName,
        enabled: true,
        fn,
        alt: opt.alt || []
      });
      this.__cache__ = null;
    };
    Ruler2.prototype.push = function(ruleName, fn, options2) {
      var opt = options2 || {};
      this.__rules__.push({
        name: ruleName,
        enabled: true,
        fn,
        alt: opt.alt || []
      });
      this.__cache__ = null;
    };
    Ruler2.prototype.enable = function(list2, ignoreInvalid) {
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      var result2 = [];
      list2.forEach(function(name2) {
        var idx = this.__find__(name2);
        if (idx < 0) {
          if (ignoreInvalid) {
            return;
          }
          throw new Error("Rules manager: invalid rule name " + name2);
        }
        this.__rules__[idx].enabled = true;
        result2.push(name2);
      }, this);
      this.__cache__ = null;
      return result2;
    };
    Ruler2.prototype.enableOnly = function(list2, ignoreInvalid) {
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      this.__rules__.forEach(function(rule) {
        rule.enabled = false;
      });
      this.enable(list2, ignoreInvalid);
    };
    Ruler2.prototype.disable = function(list2, ignoreInvalid) {
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      var result2 = [];
      list2.forEach(function(name2) {
        var idx = this.__find__(name2);
        if (idx < 0) {
          if (ignoreInvalid) {
            return;
          }
          throw new Error("Rules manager: invalid rule name " + name2);
        }
        this.__rules__[idx].enabled = false;
        result2.push(name2);
      }, this);
      this.__cache__ = null;
      return result2;
    };
    Ruler2.prototype.getRules = function(chainName) {
      if (this.__cache__ === null) {
        this.__compile__();
      }
      return this.__cache__[chainName] || [];
    };
    module.exports = Ruler2;
  }
});

// node_modules/markdown-it/lib/rules_core/normalize.js
var require_normalize = __commonJS({
  "node_modules/markdown-it/lib/rules_core/normalize.js"(exports, module) {
    "use strict";
    var NEWLINES_RE2 = /\r\n?|\n/g;
    var NULL_RE2 = /\0/g;
    module.exports = function normalize5(state) {
      var str;
      str = state.src.replace(NEWLINES_RE2, "\n");
      str = str.replace(NULL_RE2, "\uFFFD");
      state.src = str;
    };
  }
});

// node_modules/markdown-it/lib/rules_core/block.js
var require_block = __commonJS({
  "node_modules/markdown-it/lib/rules_core/block.js"(exports, module) {
    "use strict";
    module.exports = function block3(state) {
      var token;
      if (state.inlineMode) {
        token = new state.Token("inline", "", 0);
        token.content = state.src;
        token.map = [0, 1];
        token.children = [];
        state.tokens.push(token);
      } else {
        state.md.block.parse(state.src, state.md, state.env, state.tokens);
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_core/inline.js
var require_inline = __commonJS({
  "node_modules/markdown-it/lib/rules_core/inline.js"(exports, module) {
    "use strict";
    module.exports = function inline3(state) {
      var tokens = state.tokens, tok, i3, l3;
      for (i3 = 0, l3 = tokens.length; i3 < l3; i3++) {
        tok = tokens[i3];
        if (tok.type === "inline") {
          state.md.inline.parse(tok.content, state.md, state.env, tok.children);
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_core/linkify.js
var require_linkify = __commonJS({
  "node_modules/markdown-it/lib/rules_core/linkify.js"(exports, module) {
    "use strict";
    var arrayReplaceAt2 = require_utils().arrayReplaceAt;
    function isLinkOpen3(str) {
      return /^<a[>\s]/i.test(str);
    }
    function isLinkClose3(str) {
      return /^<\/a\s*>/i.test(str);
    }
    module.exports = function linkify3(state) {
      var i3, j, l3, tokens, token, currentToken, nodes2, ln, text3, pos, lastPos, level, htmlLinkLevel, url2, fullUrl, urlText, blockTokens = state.tokens, links;
      if (!state.md.options.linkify) {
        return;
      }
      for (j = 0, l3 = blockTokens.length; j < l3; j++) {
        if (blockTokens[j].type !== "inline" || !state.md.linkify.pretest(blockTokens[j].content)) {
          continue;
        }
        tokens = blockTokens[j].children;
        htmlLinkLevel = 0;
        for (i3 = tokens.length - 1; i3 >= 0; i3--) {
          currentToken = tokens[i3];
          if (currentToken.type === "link_close") {
            i3--;
            while (tokens[i3].level !== currentToken.level && tokens[i3].type !== "link_open") {
              i3--;
            }
            continue;
          }
          if (currentToken.type === "html_inline") {
            if (isLinkOpen3(currentToken.content) && htmlLinkLevel > 0) {
              htmlLinkLevel--;
            }
            if (isLinkClose3(currentToken.content)) {
              htmlLinkLevel++;
            }
          }
          if (htmlLinkLevel > 0) {
            continue;
          }
          if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
            text3 = currentToken.content;
            links = state.md.linkify.match(text3);
            nodes2 = [];
            level = currentToken.level;
            lastPos = 0;
            if (links.length > 0 && links[0].index === 0 && i3 > 0 && tokens[i3 - 1].type === "text_special") {
              links = links.slice(1);
            }
            for (ln = 0; ln < links.length; ln++) {
              url2 = links[ln].url;
              fullUrl = state.md.normalizeLink(url2);
              if (!state.md.validateLink(fullUrl)) {
                continue;
              }
              urlText = links[ln].text;
              if (!links[ln].schema) {
                urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
              } else if (links[ln].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
                urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
              } else {
                urlText = state.md.normalizeLinkText(urlText);
              }
              pos = links[ln].index;
              if (pos > lastPos) {
                token = new state.Token("text", "", 0);
                token.content = text3.slice(lastPos, pos);
                token.level = level;
                nodes2.push(token);
              }
              token = new state.Token("link_open", "a", 1);
              token.attrs = [["href", fullUrl]];
              token.level = level++;
              token.markup = "linkify";
              token.info = "auto";
              nodes2.push(token);
              token = new state.Token("text", "", 0);
              token.content = urlText;
              token.level = level;
              nodes2.push(token);
              token = new state.Token("link_close", "a", -1);
              token.level = --level;
              token.markup = "linkify";
              token.info = "auto";
              nodes2.push(token);
              lastPos = links[ln].lastIndex;
            }
            if (lastPos < text3.length) {
              token = new state.Token("text", "", 0);
              token.content = text3.slice(lastPos);
              token.level = level;
              nodes2.push(token);
            }
            blockTokens[j].children = tokens = arrayReplaceAt2(tokens, i3, nodes2);
          }
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_core/replacements.js
var require_replacements = __commonJS({
  "node_modules/markdown-it/lib/rules_core/replacements.js"(exports, module) {
    "use strict";
    var RARE_RE2 = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
    var SCOPED_ABBR_TEST_RE2 = /\((c|tm|r)\)/i;
    var SCOPED_ABBR_RE2 = /\((c|tm|r)\)/ig;
    var SCOPED_ABBR2 = {
      c: "\xA9",
      r: "\xAE",
      tm: "\u2122"
    };
    function replaceFn2(match2, name2) {
      return SCOPED_ABBR2[name2.toLowerCase()];
    }
    function replace_scoped2(inlineTokens) {
      var i3, token, inside_autolink = 0;
      for (i3 = inlineTokens.length - 1; i3 >= 0; i3--) {
        token = inlineTokens[i3];
        if (token.type === "text" && !inside_autolink) {
          token.content = token.content.replace(SCOPED_ABBR_RE2, replaceFn2);
        }
        if (token.type === "link_open" && token.info === "auto") {
          inside_autolink--;
        }
        if (token.type === "link_close" && token.info === "auto") {
          inside_autolink++;
        }
      }
    }
    function replace_rare2(inlineTokens) {
      var i3, token, inside_autolink = 0;
      for (i3 = inlineTokens.length - 1; i3 >= 0; i3--) {
        token = inlineTokens[i3];
        if (token.type === "text" && !inside_autolink) {
          if (RARE_RE2.test(token.content)) {
            token.content = token.content.replace(/\+-/g, "\xB1").replace(/\.{2,}/g, "\u2026").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1\u2014").replace(/(^|\s)--(?=\s|$)/mg, "$1\u2013").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1\u2013");
          }
        }
        if (token.type === "link_open" && token.info === "auto") {
          inside_autolink--;
        }
        if (token.type === "link_close" && token.info === "auto") {
          inside_autolink++;
        }
      }
    }
    module.exports = function replace4(state) {
      var blkIdx;
      if (!state.md.options.typographer) {
        return;
      }
      for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
        if (state.tokens[blkIdx].type !== "inline") {
          continue;
        }
        if (SCOPED_ABBR_TEST_RE2.test(state.tokens[blkIdx].content)) {
          replace_scoped2(state.tokens[blkIdx].children);
        }
        if (RARE_RE2.test(state.tokens[blkIdx].content)) {
          replace_rare2(state.tokens[blkIdx].children);
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_core/smartquotes.js
var require_smartquotes = __commonJS({
  "node_modules/markdown-it/lib/rules_core/smartquotes.js"(exports, module) {
    "use strict";
    var isWhiteSpace2 = require_utils().isWhiteSpace;
    var isPunctChar2 = require_utils().isPunctChar;
    var isMdAsciiPunct2 = require_utils().isMdAsciiPunct;
    var QUOTE_TEST_RE2 = /['"]/;
    var QUOTE_RE2 = /['"]/g;
    var APOSTROPHE2 = "\u2019";
    function replaceAt2(str, index2, ch) {
      return str.slice(0, index2) + ch + str.slice(index2 + 1);
    }
    function process_inlines2(tokens, state) {
      var i3, token, text3, t3, pos, max3, thisLevel, item, lastChar, nextChar2, isLastPunctChar, isNextPunctChar, isLastWhiteSpace, isNextWhiteSpace, canOpen, canClose, j, isSingle, stack, openQuote, closeQuote;
      stack = [];
      for (i3 = 0; i3 < tokens.length; i3++) {
        token = tokens[i3];
        thisLevel = tokens[i3].level;
        for (j = stack.length - 1; j >= 0; j--) {
          if (stack[j].level <= thisLevel) {
            break;
          }
        }
        stack.length = j + 1;
        if (token.type !== "text") {
          continue;
        }
        text3 = token.content;
        pos = 0;
        max3 = text3.length;
        OUTER:
          while (pos < max3) {
            QUOTE_RE2.lastIndex = pos;
            t3 = QUOTE_RE2.exec(text3);
            if (!t3) {
              break;
            }
            canOpen = canClose = true;
            pos = t3.index + 1;
            isSingle = t3[0] === "'";
            lastChar = 32;
            if (t3.index - 1 >= 0) {
              lastChar = text3.charCodeAt(t3.index - 1);
            } else {
              for (j = i3 - 1; j >= 0; j--) {
                if (tokens[j].type === "softbreak" || tokens[j].type === "hardbreak") break;
                if (!tokens[j].content) continue;
                lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1);
                break;
              }
            }
            nextChar2 = 32;
            if (pos < max3) {
              nextChar2 = text3.charCodeAt(pos);
            } else {
              for (j = i3 + 1; j < tokens.length; j++) {
                if (tokens[j].type === "softbreak" || tokens[j].type === "hardbreak") break;
                if (!tokens[j].content) continue;
                nextChar2 = tokens[j].content.charCodeAt(0);
                break;
              }
            }
            isLastPunctChar = isMdAsciiPunct2(lastChar) || isPunctChar2(String.fromCharCode(lastChar));
            isNextPunctChar = isMdAsciiPunct2(nextChar2) || isPunctChar2(String.fromCharCode(nextChar2));
            isLastWhiteSpace = isWhiteSpace2(lastChar);
            isNextWhiteSpace = isWhiteSpace2(nextChar2);
            if (isNextWhiteSpace) {
              canOpen = false;
            } else if (isNextPunctChar) {
              if (!(isLastWhiteSpace || isLastPunctChar)) {
                canOpen = false;
              }
            }
            if (isLastWhiteSpace) {
              canClose = false;
            } else if (isLastPunctChar) {
              if (!(isNextWhiteSpace || isNextPunctChar)) {
                canClose = false;
              }
            }
            if (nextChar2 === 34 && t3[0] === '"') {
              if (lastChar >= 48 && lastChar <= 57) {
                canClose = canOpen = false;
              }
            }
            if (canOpen && canClose) {
              canOpen = isLastPunctChar;
              canClose = isNextPunctChar;
            }
            if (!canOpen && !canClose) {
              if (isSingle) {
                token.content = replaceAt2(token.content, t3.index, APOSTROPHE2);
              }
              continue;
            }
            if (canClose) {
              for (j = stack.length - 1; j >= 0; j--) {
                item = stack[j];
                if (stack[j].level < thisLevel) {
                  break;
                }
                if (item.single === isSingle && stack[j].level === thisLevel) {
                  item = stack[j];
                  if (isSingle) {
                    openQuote = state.md.options.quotes[2];
                    closeQuote = state.md.options.quotes[3];
                  } else {
                    openQuote = state.md.options.quotes[0];
                    closeQuote = state.md.options.quotes[1];
                  }
                  token.content = replaceAt2(token.content, t3.index, closeQuote);
                  tokens[item.token].content = replaceAt2(
                    tokens[item.token].content,
                    item.pos,
                    openQuote
                  );
                  pos += closeQuote.length - 1;
                  if (item.token === i3) {
                    pos += openQuote.length - 1;
                  }
                  text3 = token.content;
                  max3 = text3.length;
                  stack.length = j;
                  continue OUTER;
                }
              }
            }
            if (canOpen) {
              stack.push({
                token: i3,
                pos: t3.index,
                single: isSingle,
                level: thisLevel
              });
            } else if (canClose && isSingle) {
              token.content = replaceAt2(token.content, t3.index, APOSTROPHE2);
            }
          }
      }
    }
    module.exports = function smartquotes2(state) {
      var blkIdx;
      if (!state.md.options.typographer) {
        return;
      }
      for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
        if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE2.test(state.tokens[blkIdx].content)) {
          continue;
        }
        process_inlines2(state.tokens[blkIdx].children, state);
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_core/text_join.js
var require_text_join = __commonJS({
  "node_modules/markdown-it/lib/rules_core/text_join.js"(exports, module) {
    "use strict";
    module.exports = function text_join2(state) {
      var j, l3, tokens, curr, max3, last3, blockTokens = state.tokens;
      for (j = 0, l3 = blockTokens.length; j < l3; j++) {
        if (blockTokens[j].type !== "inline") continue;
        tokens = blockTokens[j].children;
        max3 = tokens.length;
        for (curr = 0; curr < max3; curr++) {
          if (tokens[curr].type === "text_special") {
            tokens[curr].type = "text";
          }
        }
        for (curr = last3 = 0; curr < max3; curr++) {
          if (tokens[curr].type === "text" && curr + 1 < max3 && tokens[curr + 1].type === "text") {
            tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
          } else {
            if (curr !== last3) {
              tokens[last3] = tokens[curr];
            }
            last3++;
          }
        }
        if (curr !== last3) {
          tokens.length = last3;
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/token.js
var require_token = __commonJS({
  "node_modules/markdown-it/lib/token.js"(exports, module) {
    "use strict";
    function Token2(type, tag, nesting) {
      this.type = type;
      this.tag = tag;
      this.attrs = null;
      this.map = null;
      this.nesting = nesting;
      this.level = 0;
      this.children = null;
      this.content = "";
      this.markup = "";
      this.info = "";
      this.meta = null;
      this.block = false;
      this.hidden = false;
    }
    Token2.prototype.attrIndex = function attrIndex2(name2) {
      var attrs2, i3, len;
      if (!this.attrs) {
        return -1;
      }
      attrs2 = this.attrs;
      for (i3 = 0, len = attrs2.length; i3 < len; i3++) {
        if (attrs2[i3][0] === name2) {
          return i3;
        }
      }
      return -1;
    };
    Token2.prototype.attrPush = function attrPush2(attrData) {
      if (this.attrs) {
        this.attrs.push(attrData);
      } else {
        this.attrs = [attrData];
      }
    };
    Token2.prototype.attrSet = function attrSet2(name2, value2) {
      var idx = this.attrIndex(name2), attrData = [name2, value2];
      if (idx < 0) {
        this.attrPush(attrData);
      } else {
        this.attrs[idx] = attrData;
      }
    };
    Token2.prototype.attrGet = function attrGet2(name2) {
      var idx = this.attrIndex(name2), value2 = null;
      if (idx >= 0) {
        value2 = this.attrs[idx][1];
      }
      return value2;
    };
    Token2.prototype.attrJoin = function attrJoin2(name2, value2) {
      var idx = this.attrIndex(name2);
      if (idx < 0) {
        this.attrPush([name2, value2]);
      } else {
        this.attrs[idx][1] = this.attrs[idx][1] + " " + value2;
      }
    };
    module.exports = Token2;
  }
});

// node_modules/markdown-it/lib/rules_core/state_core.js
var require_state_core = __commonJS({
  "node_modules/markdown-it/lib/rules_core/state_core.js"(exports, module) {
    "use strict";
    var Token2 = require_token();
    function StateCore2(src, md2, env) {
      this.src = src;
      this.env = env;
      this.tokens = [];
      this.inlineMode = false;
      this.md = md2;
    }
    StateCore2.prototype.Token = Token2;
    module.exports = StateCore2;
  }
});

// node_modules/markdown-it/lib/parser_core.js
var require_parser_core = __commonJS({
  "node_modules/markdown-it/lib/parser_core.js"(exports, module) {
    "use strict";
    var Ruler2 = require_ruler();
    var _rules4 = [
      ["normalize", require_normalize()],
      ["block", require_block()],
      ["inline", require_inline()],
      ["linkify", require_linkify()],
      ["replacements", require_replacements()],
      ["smartquotes", require_smartquotes()],
      // `text_join` finds `text_special` tokens (for escape sequences)
      // and joins them with the rest of the text
      ["text_join", require_text_join()]
    ];
    function Core2() {
      this.ruler = new Ruler2();
      for (var i3 = 0; i3 < _rules4.length; i3++) {
        this.ruler.push(_rules4[i3][0], _rules4[i3][1]);
      }
    }
    Core2.prototype.process = function(state) {
      var i3, l3, rules;
      rules = this.ruler.getRules("");
      for (i3 = 0, l3 = rules.length; i3 < l3; i3++) {
        rules[i3](state);
      }
    };
    Core2.prototype.State = require_state_core();
    module.exports = Core2;
  }
});

// node_modules/markdown-it/lib/rules_block/table.js
var require_table = __commonJS({
  "node_modules/markdown-it/lib/rules_block/table.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    function getLine2(state, line) {
      var pos = state.bMarks[line] + state.tShift[line], max3 = state.eMarks[line];
      return state.src.slice(pos, max3);
    }
    function escapedSplit2(str) {
      var result2 = [], pos = 0, max3 = str.length, ch, isEscaped2 = false, lastPos = 0, current = "";
      ch = str.charCodeAt(pos);
      while (pos < max3) {
        if (ch === 124) {
          if (!isEscaped2) {
            result2.push(current + str.substring(lastPos, pos));
            current = "";
            lastPos = pos + 1;
          } else {
            current += str.substring(lastPos, pos - 1);
            lastPos = pos;
          }
        }
        isEscaped2 = ch === 92;
        pos++;
        ch = str.charCodeAt(pos);
      }
      result2.push(current + str.substring(lastPos));
      return result2;
    }
    module.exports = function table2(state, startLine, endLine, silent) {
      var ch, lineText, pos, i3, l3, nextLine, columns2, columnCount, token, aligns, t3, tableLines, tbodyLines, oldParentType, terminate, terminatorRules, firstCh, secondCh;
      if (startLine + 2 > endLine) {
        return false;
      }
      nextLine = startLine + 1;
      if (state.sCount[nextLine] < state.blkIndent) {
        return false;
      }
      if (state.sCount[nextLine] - state.blkIndent >= 4) {
        return false;
      }
      pos = state.bMarks[nextLine] + state.tShift[nextLine];
      if (pos >= state.eMarks[nextLine]) {
        return false;
      }
      firstCh = state.src.charCodeAt(pos++);
      if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
        return false;
      }
      if (pos >= state.eMarks[nextLine]) {
        return false;
      }
      secondCh = state.src.charCodeAt(pos++);
      if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace2(secondCh)) {
        return false;
      }
      if (firstCh === 45 && isSpace2(secondCh)) {
        return false;
      }
      while (pos < state.eMarks[nextLine]) {
        ch = state.src.charCodeAt(pos);
        if (ch !== 124 && ch !== 45 && ch !== 58 && !isSpace2(ch)) {
          return false;
        }
        pos++;
      }
      lineText = getLine2(state, startLine + 1);
      columns2 = lineText.split("|");
      aligns = [];
      for (i3 = 0; i3 < columns2.length; i3++) {
        t3 = columns2[i3].trim();
        if (!t3) {
          if (i3 === 0 || i3 === columns2.length - 1) {
            continue;
          } else {
            return false;
          }
        }
        if (!/^:?-+:?$/.test(t3)) {
          return false;
        }
        if (t3.charCodeAt(t3.length - 1) === 58) {
          aligns.push(t3.charCodeAt(0) === 58 ? "center" : "right");
        } else if (t3.charCodeAt(0) === 58) {
          aligns.push("left");
        } else {
          aligns.push("");
        }
      }
      lineText = getLine2(state, startLine).trim();
      if (lineText.indexOf("|") === -1) {
        return false;
      }
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      columns2 = escapedSplit2(lineText);
      if (columns2.length && columns2[0] === "") columns2.shift();
      if (columns2.length && columns2[columns2.length - 1] === "") columns2.pop();
      columnCount = columns2.length;
      if (columnCount === 0 || columnCount !== aligns.length) {
        return false;
      }
      if (silent) {
        return true;
      }
      oldParentType = state.parentType;
      state.parentType = "table";
      terminatorRules = state.md.block.ruler.getRules("blockquote");
      token = state.push("table_open", "table", 1);
      token.map = tableLines = [startLine, 0];
      token = state.push("thead_open", "thead", 1);
      token.map = [startLine, startLine + 1];
      token = state.push("tr_open", "tr", 1);
      token.map = [startLine, startLine + 1];
      for (i3 = 0; i3 < columns2.length; i3++) {
        token = state.push("th_open", "th", 1);
        if (aligns[i3]) {
          token.attrs = [["style", "text-align:" + aligns[i3]]];
        }
        token = state.push("inline", "", 0);
        token.content = columns2[i3].trim();
        token.children = [];
        token = state.push("th_close", "th", -1);
      }
      token = state.push("tr_close", "tr", -1);
      token = state.push("thead_close", "thead", -1);
      for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
        if (state.sCount[nextLine] < state.blkIndent) {
          break;
        }
        terminate = false;
        for (i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
          if (terminatorRules[i3](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
        lineText = getLine2(state, nextLine).trim();
        if (!lineText) {
          break;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          break;
        }
        columns2 = escapedSplit2(lineText);
        if (columns2.length && columns2[0] === "") columns2.shift();
        if (columns2.length && columns2[columns2.length - 1] === "") columns2.pop();
        if (nextLine === startLine + 2) {
          token = state.push("tbody_open", "tbody", 1);
          token.map = tbodyLines = [startLine + 2, 0];
        }
        token = state.push("tr_open", "tr", 1);
        token.map = [nextLine, nextLine + 1];
        for (i3 = 0; i3 < columnCount; i3++) {
          token = state.push("td_open", "td", 1);
          if (aligns[i3]) {
            token.attrs = [["style", "text-align:" + aligns[i3]]];
          }
          token = state.push("inline", "", 0);
          token.content = columns2[i3] ? columns2[i3].trim() : "";
          token.children = [];
          token = state.push("td_close", "td", -1);
        }
        token = state.push("tr_close", "tr", -1);
      }
      if (tbodyLines) {
        token = state.push("tbody_close", "tbody", -1);
        tbodyLines[1] = nextLine;
      }
      token = state.push("table_close", "table", -1);
      tableLines[1] = nextLine;
      state.parentType = oldParentType;
      state.line = nextLine;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/code.js
var require_code = __commonJS({
  "node_modules/markdown-it/lib/rules_block/code.js"(exports, module) {
    "use strict";
    module.exports = function code2(state, startLine, endLine) {
      var nextLine, last3, token;
      if (state.sCount[startLine] - state.blkIndent < 4) {
        return false;
      }
      last3 = nextLine = startLine + 1;
      while (nextLine < endLine) {
        if (state.isEmpty(nextLine)) {
          nextLine++;
          continue;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          nextLine++;
          last3 = nextLine;
          continue;
        }
        break;
      }
      state.line = last3;
      token = state.push("code_block", "code", 0);
      token.content = state.getLines(startLine, last3, 4 + state.blkIndent, false) + "\n";
      token.map = [startLine, state.line];
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/fence.js
var require_fence = __commonJS({
  "node_modules/markdown-it/lib/rules_block/fence.js"(exports, module) {
    "use strict";
    module.exports = function fence2(state, startLine, endLine, silent) {
      var marker, len, params, nextLine, mem, token, markup, haveEndMarker = false, pos = state.bMarks[startLine] + state.tShift[startLine], max3 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (pos + 3 > max3) {
        return false;
      }
      marker = state.src.charCodeAt(pos);
      if (marker !== 126 && marker !== 96) {
        return false;
      }
      mem = pos;
      pos = state.skipChars(pos, marker);
      len = pos - mem;
      if (len < 3) {
        return false;
      }
      markup = state.src.slice(mem, pos);
      params = state.src.slice(pos, max3);
      if (marker === 96) {
        if (params.indexOf(String.fromCharCode(marker)) >= 0) {
          return false;
        }
      }
      if (silent) {
        return true;
      }
      nextLine = startLine;
      for (; ; ) {
        nextLine++;
        if (nextLine >= endLine) {
          break;
        }
        pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
        max3 = state.eMarks[nextLine];
        if (pos < max3 && state.sCount[nextLine] < state.blkIndent) {
          break;
        }
        if (state.src.charCodeAt(pos) !== marker) {
          continue;
        }
        if (state.sCount[nextLine] - state.blkIndent >= 4) {
          continue;
        }
        pos = state.skipChars(pos, marker);
        if (pos - mem < len) {
          continue;
        }
        pos = state.skipSpaces(pos);
        if (pos < max3) {
          continue;
        }
        haveEndMarker = true;
        break;
      }
      len = state.sCount[startLine];
      state.line = nextLine + (haveEndMarker ? 1 : 0);
      token = state.push("fence", "code", 0);
      token.info = params;
      token.content = state.getLines(startLine + 1, nextLine, len, true);
      token.markup = markup;
      token.map = [startLine, state.line];
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/blockquote.js
var require_blockquote = __commonJS({
  "node_modules/markdown-it/lib/rules_block/blockquote.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    module.exports = function blockquote2(state, startLine, endLine, silent) {
      var adjustTab, ch, i3, initial2, l3, lastLineEmpty, lines, nextLine, offset, oldBMarks, oldBSCount, oldIndent, oldParentType, oldSCount, oldTShift, spaceAfterMarker, terminate, terminatorRules, token, isOutdented, oldLineMax = state.lineMax, pos = state.bMarks[startLine] + state.tShift[startLine], max3 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (state.src.charCodeAt(pos++) !== 62) {
        return false;
      }
      if (silent) {
        return true;
      }
      initial2 = offset = state.sCount[startLine] + 1;
      if (state.src.charCodeAt(pos) === 32) {
        pos++;
        initial2++;
        offset++;
        adjustTab = false;
        spaceAfterMarker = true;
      } else if (state.src.charCodeAt(pos) === 9) {
        spaceAfterMarker = true;
        if ((state.bsCount[startLine] + offset) % 4 === 3) {
          pos++;
          initial2++;
          offset++;
          adjustTab = false;
        } else {
          adjustTab = true;
        }
      } else {
        spaceAfterMarker = false;
      }
      oldBMarks = [state.bMarks[startLine]];
      state.bMarks[startLine] = pos;
      while (pos < max3) {
        ch = state.src.charCodeAt(pos);
        if (isSpace2(ch)) {
          if (ch === 9) {
            offset += 4 - (offset + state.bsCount[startLine] + (adjustTab ? 1 : 0)) % 4;
          } else {
            offset++;
          }
        } else {
          break;
        }
        pos++;
      }
      oldBSCount = [state.bsCount[startLine]];
      state.bsCount[startLine] = state.sCount[startLine] + 1 + (spaceAfterMarker ? 1 : 0);
      lastLineEmpty = pos >= max3;
      oldSCount = [state.sCount[startLine]];
      state.sCount[startLine] = offset - initial2;
      oldTShift = [state.tShift[startLine]];
      state.tShift[startLine] = pos - state.bMarks[startLine];
      terminatorRules = state.md.block.ruler.getRules("blockquote");
      oldParentType = state.parentType;
      state.parentType = "blockquote";
      for (nextLine = startLine + 1; nextLine < endLine; nextLine++) {
        isOutdented = state.sCount[nextLine] < state.blkIndent;
        pos = state.bMarks[nextLine] + state.tShift[nextLine];
        max3 = state.eMarks[nextLine];
        if (pos >= max3) {
          break;
        }
        if (state.src.charCodeAt(pos++) === 62 && !isOutdented) {
          initial2 = offset = state.sCount[nextLine] + 1;
          if (state.src.charCodeAt(pos) === 32) {
            pos++;
            initial2++;
            offset++;
            adjustTab = false;
            spaceAfterMarker = true;
          } else if (state.src.charCodeAt(pos) === 9) {
            spaceAfterMarker = true;
            if ((state.bsCount[nextLine] + offset) % 4 === 3) {
              pos++;
              initial2++;
              offset++;
              adjustTab = false;
            } else {
              adjustTab = true;
            }
          } else {
            spaceAfterMarker = false;
          }
          oldBMarks.push(state.bMarks[nextLine]);
          state.bMarks[nextLine] = pos;
          while (pos < max3) {
            ch = state.src.charCodeAt(pos);
            if (isSpace2(ch)) {
              if (ch === 9) {
                offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
              } else {
                offset++;
              }
            } else {
              break;
            }
            pos++;
          }
          lastLineEmpty = pos >= max3;
          oldBSCount.push(state.bsCount[nextLine]);
          state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
          oldSCount.push(state.sCount[nextLine]);
          state.sCount[nextLine] = offset - initial2;
          oldTShift.push(state.tShift[nextLine]);
          state.tShift[nextLine] = pos - state.bMarks[nextLine];
          continue;
        }
        if (lastLineEmpty) {
          break;
        }
        terminate = false;
        for (i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
          if (terminatorRules[i3](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          state.lineMax = nextLine;
          if (state.blkIndent !== 0) {
            oldBMarks.push(state.bMarks[nextLine]);
            oldBSCount.push(state.bsCount[nextLine]);
            oldTShift.push(state.tShift[nextLine]);
            oldSCount.push(state.sCount[nextLine]);
            state.sCount[nextLine] -= state.blkIndent;
          }
          break;
        }
        oldBMarks.push(state.bMarks[nextLine]);
        oldBSCount.push(state.bsCount[nextLine]);
        oldTShift.push(state.tShift[nextLine]);
        oldSCount.push(state.sCount[nextLine]);
        state.sCount[nextLine] = -1;
      }
      oldIndent = state.blkIndent;
      state.blkIndent = 0;
      token = state.push("blockquote_open", "blockquote", 1);
      token.markup = ">";
      token.map = lines = [startLine, 0];
      state.md.block.tokenize(state, startLine, nextLine);
      token = state.push("blockquote_close", "blockquote", -1);
      token.markup = ">";
      state.lineMax = oldLineMax;
      state.parentType = oldParentType;
      lines[1] = state.line;
      for (i3 = 0; i3 < oldTShift.length; i3++) {
        state.bMarks[i3 + startLine] = oldBMarks[i3];
        state.tShift[i3 + startLine] = oldTShift[i3];
        state.sCount[i3 + startLine] = oldSCount[i3];
        state.bsCount[i3 + startLine] = oldBSCount[i3];
      }
      state.blkIndent = oldIndent;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/hr.js
var require_hr = __commonJS({
  "node_modules/markdown-it/lib/rules_block/hr.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    module.exports = function hr2(state, startLine, endLine, silent) {
      var marker, cnt, ch, token, pos = state.bMarks[startLine] + state.tShift[startLine], max3 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      marker = state.src.charCodeAt(pos++);
      if (marker !== 42 && marker !== 45 && marker !== 95) {
        return false;
      }
      cnt = 1;
      while (pos < max3) {
        ch = state.src.charCodeAt(pos++);
        if (ch !== marker && !isSpace2(ch)) {
          return false;
        }
        if (ch === marker) {
          cnt++;
        }
      }
      if (cnt < 3) {
        return false;
      }
      if (silent) {
        return true;
      }
      state.line = startLine + 1;
      token = state.push("hr", "hr", 0);
      token.map = [startLine, state.line];
      token.markup = Array(cnt + 1).join(String.fromCharCode(marker));
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/list.js
var require_list = __commonJS({
  "node_modules/markdown-it/lib/rules_block/list.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    function skipBulletListMarker2(state, startLine) {
      var marker, pos, max3, ch;
      pos = state.bMarks[startLine] + state.tShift[startLine];
      max3 = state.eMarks[startLine];
      marker = state.src.charCodeAt(pos++);
      if (marker !== 42 && marker !== 45 && marker !== 43) {
        return -1;
      }
      if (pos < max3) {
        ch = state.src.charCodeAt(pos);
        if (!isSpace2(ch)) {
          return -1;
        }
      }
      return pos;
    }
    function skipOrderedListMarker2(state, startLine) {
      var ch, start = state.bMarks[startLine] + state.tShift[startLine], pos = start, max3 = state.eMarks[startLine];
      if (pos + 1 >= max3) {
        return -1;
      }
      ch = state.src.charCodeAt(pos++);
      if (ch < 48 || ch > 57) {
        return -1;
      }
      for (; ; ) {
        if (pos >= max3) {
          return -1;
        }
        ch = state.src.charCodeAt(pos++);
        if (ch >= 48 && ch <= 57) {
          if (pos - start >= 10) {
            return -1;
          }
          continue;
        }
        if (ch === 41 || ch === 46) {
          break;
        }
        return -1;
      }
      if (pos < max3) {
        ch = state.src.charCodeAt(pos);
        if (!isSpace2(ch)) {
          return -1;
        }
      }
      return pos;
    }
    function markTightParagraphs2(state, idx) {
      var i3, l3, level = state.level + 2;
      for (i3 = idx + 2, l3 = state.tokens.length - 2; i3 < l3; i3++) {
        if (state.tokens[i3].level === level && state.tokens[i3].type === "paragraph_open") {
          state.tokens[i3 + 2].hidden = true;
          state.tokens[i3].hidden = true;
          i3 += 2;
        }
      }
    }
    module.exports = function list2(state, startLine, endLine, silent) {
      var ch, contentStart, i3, indent, indentAfterMarker, initial2, isOrdered, itemLines, l3, listLines, listTokIdx, markerCharCode, markerValue, max3, nextLine, offset, oldListIndent, oldParentType, oldSCount, oldTShift, oldTight, pos, posAfterMarker, prevEmptyEnd, start, terminate, terminatorRules, token, isTerminatingParagraph = false, tight = true;
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (state.listIndent >= 0 && state.sCount[startLine] - state.listIndent >= 4 && state.sCount[startLine] < state.blkIndent) {
        return false;
      }
      if (silent && state.parentType === "paragraph") {
        if (state.sCount[startLine] >= state.blkIndent) {
          isTerminatingParagraph = true;
        }
      }
      if ((posAfterMarker = skipOrderedListMarker2(state, startLine)) >= 0) {
        isOrdered = true;
        start = state.bMarks[startLine] + state.tShift[startLine];
        markerValue = Number(state.src.slice(start, posAfterMarker - 1));
        if (isTerminatingParagraph && markerValue !== 1) return false;
      } else if ((posAfterMarker = skipBulletListMarker2(state, startLine)) >= 0) {
        isOrdered = false;
      } else {
        return false;
      }
      if (isTerminatingParagraph) {
        if (state.skipSpaces(posAfterMarker) >= state.eMarks[startLine]) return false;
      }
      markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
      if (silent) {
        return true;
      }
      listTokIdx = state.tokens.length;
      if (isOrdered) {
        token = state.push("ordered_list_open", "ol", 1);
        if (markerValue !== 1) {
          token.attrs = [["start", markerValue]];
        }
      } else {
        token = state.push("bullet_list_open", "ul", 1);
      }
      token.map = listLines = [startLine, 0];
      token.markup = String.fromCharCode(markerCharCode);
      nextLine = startLine;
      prevEmptyEnd = false;
      terminatorRules = state.md.block.ruler.getRules("list");
      oldParentType = state.parentType;
      state.parentType = "list";
      while (nextLine < endLine) {
        pos = posAfterMarker;
        max3 = state.eMarks[nextLine];
        initial2 = offset = state.sCount[nextLine] + posAfterMarker - (state.bMarks[startLine] + state.tShift[startLine]);
        while (pos < max3) {
          ch = state.src.charCodeAt(pos);
          if (ch === 9) {
            offset += 4 - (offset + state.bsCount[nextLine]) % 4;
          } else if (ch === 32) {
            offset++;
          } else {
            break;
          }
          pos++;
        }
        contentStart = pos;
        if (contentStart >= max3) {
          indentAfterMarker = 1;
        } else {
          indentAfterMarker = offset - initial2;
        }
        if (indentAfterMarker > 4) {
          indentAfterMarker = 1;
        }
        indent = initial2 + indentAfterMarker;
        token = state.push("list_item_open", "li", 1);
        token.markup = String.fromCharCode(markerCharCode);
        token.map = itemLines = [startLine, 0];
        if (isOrdered) {
          token.info = state.src.slice(start, posAfterMarker - 1);
        }
        oldTight = state.tight;
        oldTShift = state.tShift[startLine];
        oldSCount = state.sCount[startLine];
        oldListIndent = state.listIndent;
        state.listIndent = state.blkIndent;
        state.blkIndent = indent;
        state.tight = true;
        state.tShift[startLine] = contentStart - state.bMarks[startLine];
        state.sCount[startLine] = offset;
        if (contentStart >= max3 && state.isEmpty(startLine + 1)) {
          state.line = Math.min(state.line + 2, endLine);
        } else {
          state.md.block.tokenize(state, startLine, endLine, true);
        }
        if (!state.tight || prevEmptyEnd) {
          tight = false;
        }
        prevEmptyEnd = state.line - startLine > 1 && state.isEmpty(state.line - 1);
        state.blkIndent = state.listIndent;
        state.listIndent = oldListIndent;
        state.tShift[startLine] = oldTShift;
        state.sCount[startLine] = oldSCount;
        state.tight = oldTight;
        token = state.push("list_item_close", "li", -1);
        token.markup = String.fromCharCode(markerCharCode);
        nextLine = startLine = state.line;
        itemLines[1] = nextLine;
        contentStart = state.bMarks[startLine];
        if (nextLine >= endLine) {
          break;
        }
        if (state.sCount[nextLine] < state.blkIndent) {
          break;
        }
        if (state.sCount[startLine] - state.blkIndent >= 4) {
          break;
        }
        terminate = false;
        for (i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
          if (terminatorRules[i3](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
        if (isOrdered) {
          posAfterMarker = skipOrderedListMarker2(state, nextLine);
          if (posAfterMarker < 0) {
            break;
          }
          start = state.bMarks[nextLine] + state.tShift[nextLine];
        } else {
          posAfterMarker = skipBulletListMarker2(state, nextLine);
          if (posAfterMarker < 0) {
            break;
          }
        }
        if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
          break;
        }
      }
      if (isOrdered) {
        token = state.push("ordered_list_close", "ol", -1);
      } else {
        token = state.push("bullet_list_close", "ul", -1);
      }
      token.markup = String.fromCharCode(markerCharCode);
      listLines[1] = nextLine;
      state.line = nextLine;
      state.parentType = oldParentType;
      if (tight) {
        markTightParagraphs2(state, listTokIdx);
      }
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/reference.js
var require_reference = __commonJS({
  "node_modules/markdown-it/lib/rules_block/reference.js"(exports, module) {
    "use strict";
    var normalizeReference2 = require_utils().normalizeReference;
    var isSpace2 = require_utils().isSpace;
    module.exports = function reference2(state, startLine, _endLine, silent) {
      var ch, destEndPos, destEndLineNo, endLine, href, i3, l3, label, labelEnd, oldParentType, res, start, str, terminate, terminatorRules, title, lines = 0, pos = state.bMarks[startLine] + state.tShift[startLine], max3 = state.eMarks[startLine], nextLine = startLine + 1;
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (state.src.charCodeAt(pos) !== 91) {
        return false;
      }
      while (++pos < max3) {
        if (state.src.charCodeAt(pos) === 93 && state.src.charCodeAt(pos - 1) !== 92) {
          if (pos + 1 === max3) {
            return false;
          }
          if (state.src.charCodeAt(pos + 1) !== 58) {
            return false;
          }
          break;
        }
      }
      endLine = state.lineMax;
      terminatorRules = state.md.block.ruler.getRules("reference");
      oldParentType = state.parentType;
      state.parentType = "reference";
      for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
        if (state.sCount[nextLine] - state.blkIndent > 3) {
          continue;
        }
        if (state.sCount[nextLine] < 0) {
          continue;
        }
        terminate = false;
        for (i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
          if (terminatorRules[i3](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
      }
      str = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
      max3 = str.length;
      for (pos = 1; pos < max3; pos++) {
        ch = str.charCodeAt(pos);
        if (ch === 91) {
          return false;
        } else if (ch === 93) {
          labelEnd = pos;
          break;
        } else if (ch === 10) {
          lines++;
        } else if (ch === 92) {
          pos++;
          if (pos < max3 && str.charCodeAt(pos) === 10) {
            lines++;
          }
        }
      }
      if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 58) {
        return false;
      }
      for (pos = labelEnd + 2; pos < max3; pos++) {
        ch = str.charCodeAt(pos);
        if (ch === 10) {
          lines++;
        } else if (isSpace2(ch)) {
        } else {
          break;
        }
      }
      res = state.md.helpers.parseLinkDestination(str, pos, max3);
      if (!res.ok) {
        return false;
      }
      href = state.md.normalizeLink(res.str);
      if (!state.md.validateLink(href)) {
        return false;
      }
      pos = res.pos;
      lines += res.lines;
      destEndPos = pos;
      destEndLineNo = lines;
      start = pos;
      for (; pos < max3; pos++) {
        ch = str.charCodeAt(pos);
        if (ch === 10) {
          lines++;
        } else if (isSpace2(ch)) {
        } else {
          break;
        }
      }
      res = state.md.helpers.parseLinkTitle(str, pos, max3);
      if (pos < max3 && start !== pos && res.ok) {
        title = res.str;
        pos = res.pos;
        lines += res.lines;
      } else {
        title = "";
        pos = destEndPos;
        lines = destEndLineNo;
      }
      while (pos < max3) {
        ch = str.charCodeAt(pos);
        if (!isSpace2(ch)) {
          break;
        }
        pos++;
      }
      if (pos < max3 && str.charCodeAt(pos) !== 10) {
        if (title) {
          title = "";
          pos = destEndPos;
          lines = destEndLineNo;
          while (pos < max3) {
            ch = str.charCodeAt(pos);
            if (!isSpace2(ch)) {
              break;
            }
            pos++;
          }
        }
      }
      if (pos < max3 && str.charCodeAt(pos) !== 10) {
        return false;
      }
      label = normalizeReference2(str.slice(1, labelEnd));
      if (!label) {
        return false;
      }
      if (silent) {
        return true;
      }
      if (typeof state.env.references === "undefined") {
        state.env.references = {};
      }
      if (typeof state.env.references[label] === "undefined") {
        state.env.references[label] = { title, href };
      }
      state.parentType = oldParentType;
      state.line = startLine + lines + 1;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/common/html_blocks.js
var require_html_blocks = __commonJS({
  "node_modules/markdown-it/lib/common/html_blocks.js"(exports, module) {
    "use strict";
    module.exports = [
      "address",
      "article",
      "aside",
      "base",
      "basefont",
      "blockquote",
      "body",
      "caption",
      "center",
      "col",
      "colgroup",
      "dd",
      "details",
      "dialog",
      "dir",
      "div",
      "dl",
      "dt",
      "fieldset",
      "figcaption",
      "figure",
      "footer",
      "form",
      "frame",
      "frameset",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
      "head",
      "header",
      "hr",
      "html",
      "iframe",
      "legend",
      "li",
      "link",
      "main",
      "menu",
      "menuitem",
      "nav",
      "noframes",
      "ol",
      "optgroup",
      "option",
      "p",
      "param",
      "section",
      "source",
      "summary",
      "table",
      "tbody",
      "td",
      "tfoot",
      "th",
      "thead",
      "title",
      "tr",
      "track",
      "ul"
    ];
  }
});

// node_modules/markdown-it/lib/common/html_re.js
var require_html_re = __commonJS({
  "node_modules/markdown-it/lib/common/html_re.js"(exports, module) {
    "use strict";
    var attr_name2 = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
    var unquoted2 = "[^\"'=<>`\\x00-\\x20]+";
    var single_quoted2 = "'[^']*'";
    var double_quoted2 = '"[^"]*"';
    var attr_value2 = "(?:" + unquoted2 + "|" + single_quoted2 + "|" + double_quoted2 + ")";
    var attribute2 = "(?:\\s+" + attr_name2 + "(?:\\s*=\\s*" + attr_value2 + ")?)";
    var open_tag2 = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute2 + "*\\s*\\/?>";
    var close_tag2 = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
    var comment4 = "<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->";
    var processing2 = "<[?][\\s\\S]*?[?]>";
    var declaration2 = "<![A-Z]+\\s+[^>]*>";
    var cdata2 = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
    var HTML_TAG_RE2 = new RegExp("^(?:" + open_tag2 + "|" + close_tag2 + "|" + comment4 + "|" + processing2 + "|" + declaration2 + "|" + cdata2 + ")");
    var HTML_OPEN_CLOSE_TAG_RE2 = new RegExp("^(?:" + open_tag2 + "|" + close_tag2 + ")");
    module.exports.HTML_TAG_RE = HTML_TAG_RE2;
    module.exports.HTML_OPEN_CLOSE_TAG_RE = HTML_OPEN_CLOSE_TAG_RE2;
  }
});

// node_modules/markdown-it/lib/rules_block/html_block.js
var require_html_block = __commonJS({
  "node_modules/markdown-it/lib/rules_block/html_block.js"(exports, module) {
    "use strict";
    var block_names = require_html_blocks();
    var HTML_OPEN_CLOSE_TAG_RE2 = require_html_re().HTML_OPEN_CLOSE_TAG_RE;
    var HTML_SEQUENCES2 = [
      [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
      [/^<!--/, /-->/, true],
      [/^<\?/, /\?>/, true],
      [/^<![A-Z]/, />/, true],
      [/^<!\[CDATA\[/, /\]\]>/, true],
      [new RegExp("^</?(" + block_names.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
      [new RegExp(HTML_OPEN_CLOSE_TAG_RE2.source + "\\s*$"), /^$/, false]
    ];
    module.exports = function html_block2(state, startLine, endLine, silent) {
      var i3, nextLine, token, lineText, pos = state.bMarks[startLine] + state.tShift[startLine], max3 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      if (!state.md.options.html) {
        return false;
      }
      if (state.src.charCodeAt(pos) !== 60) {
        return false;
      }
      lineText = state.src.slice(pos, max3);
      for (i3 = 0; i3 < HTML_SEQUENCES2.length; i3++) {
        if (HTML_SEQUENCES2[i3][0].test(lineText)) {
          break;
        }
      }
      if (i3 === HTML_SEQUENCES2.length) {
        return false;
      }
      if (silent) {
        return HTML_SEQUENCES2[i3][2];
      }
      nextLine = startLine + 1;
      if (!HTML_SEQUENCES2[i3][1].test(lineText)) {
        for (; nextLine < endLine; nextLine++) {
          if (state.sCount[nextLine] < state.blkIndent) {
            break;
          }
          pos = state.bMarks[nextLine] + state.tShift[nextLine];
          max3 = state.eMarks[nextLine];
          lineText = state.src.slice(pos, max3);
          if (HTML_SEQUENCES2[i3][1].test(lineText)) {
            if (lineText.length !== 0) {
              nextLine++;
            }
            break;
          }
        }
      }
      state.line = nextLine;
      token = state.push("html_block", "", 0);
      token.map = [startLine, nextLine];
      token.content = state.getLines(startLine, nextLine, state.blkIndent, true);
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/heading.js
var require_heading = __commonJS({
  "node_modules/markdown-it/lib/rules_block/heading.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    module.exports = function heading3(state, startLine, endLine, silent) {
      var ch, level, tmp, token, pos = state.bMarks[startLine] + state.tShift[startLine], max3 = state.eMarks[startLine];
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      ch = state.src.charCodeAt(pos);
      if (ch !== 35 || pos >= max3) {
        return false;
      }
      level = 1;
      ch = state.src.charCodeAt(++pos);
      while (ch === 35 && pos < max3 && level <= 6) {
        level++;
        ch = state.src.charCodeAt(++pos);
      }
      if (level > 6 || pos < max3 && !isSpace2(ch)) {
        return false;
      }
      if (silent) {
        return true;
      }
      max3 = state.skipSpacesBack(max3, pos);
      tmp = state.skipCharsBack(max3, 35, pos);
      if (tmp > pos && isSpace2(state.src.charCodeAt(tmp - 1))) {
        max3 = tmp;
      }
      state.line = startLine + 1;
      token = state.push("heading_open", "h" + String(level), 1);
      token.markup = "########".slice(0, level);
      token.map = [startLine, state.line];
      token = state.push("inline", "", 0);
      token.content = state.src.slice(pos, max3).trim();
      token.map = [startLine, state.line];
      token.children = [];
      token = state.push("heading_close", "h" + String(level), -1);
      token.markup = "########".slice(0, level);
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/lheading.js
var require_lheading = __commonJS({
  "node_modules/markdown-it/lib/rules_block/lheading.js"(exports, module) {
    "use strict";
    module.exports = function lheading2(state, startLine, endLine) {
      var content2, terminate, i3, l3, token, pos, max3, level, marker, nextLine = startLine + 1, oldParentType, terminatorRules = state.md.block.ruler.getRules("paragraph");
      if (state.sCount[startLine] - state.blkIndent >= 4) {
        return false;
      }
      oldParentType = state.parentType;
      state.parentType = "paragraph";
      for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
        if (state.sCount[nextLine] - state.blkIndent > 3) {
          continue;
        }
        if (state.sCount[nextLine] >= state.blkIndent) {
          pos = state.bMarks[nextLine] + state.tShift[nextLine];
          max3 = state.eMarks[nextLine];
          if (pos < max3) {
            marker = state.src.charCodeAt(pos);
            if (marker === 45 || marker === 61) {
              pos = state.skipChars(pos, marker);
              pos = state.skipSpaces(pos);
              if (pos >= max3) {
                level = marker === 61 ? 1 : 2;
                break;
              }
            }
          }
        }
        if (state.sCount[nextLine] < 0) {
          continue;
        }
        terminate = false;
        for (i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
          if (terminatorRules[i3](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
      }
      if (!level) {
        return false;
      }
      content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
      state.line = nextLine + 1;
      token = state.push("heading_open", "h" + String(level), 1);
      token.markup = String.fromCharCode(marker);
      token.map = [startLine, state.line];
      token = state.push("inline", "", 0);
      token.content = content2;
      token.map = [startLine, state.line - 1];
      token.children = [];
      token = state.push("heading_close", "h" + String(level), -1);
      token.markup = String.fromCharCode(marker);
      state.parentType = oldParentType;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/paragraph.js
var require_paragraph = __commonJS({
  "node_modules/markdown-it/lib/rules_block/paragraph.js"(exports, module) {
    "use strict";
    module.exports = function paragraph2(state, startLine) {
      var content2, terminate, i3, l3, token, oldParentType, nextLine = startLine + 1, terminatorRules = state.md.block.ruler.getRules("paragraph"), endLine = state.lineMax;
      oldParentType = state.parentType;
      state.parentType = "paragraph";
      for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
        if (state.sCount[nextLine] - state.blkIndent > 3) {
          continue;
        }
        if (state.sCount[nextLine] < 0) {
          continue;
        }
        terminate = false;
        for (i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
          if (terminatorRules[i3](state, nextLine, endLine, true)) {
            terminate = true;
            break;
          }
        }
        if (terminate) {
          break;
        }
      }
      content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
      state.line = nextLine;
      token = state.push("paragraph_open", "p", 1);
      token.map = [startLine, state.line];
      token = state.push("inline", "", 0);
      token.content = content2;
      token.map = [startLine, state.line];
      token.children = [];
      token = state.push("paragraph_close", "p", -1);
      state.parentType = oldParentType;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_block/state_block.js
var require_state_block = __commonJS({
  "node_modules/markdown-it/lib/rules_block/state_block.js"(exports, module) {
    "use strict";
    var Token2 = require_token();
    var isSpace2 = require_utils().isSpace;
    function StateBlock2(src, md2, env, tokens) {
      var ch, s3, start, pos, len, indent, offset, indent_found;
      this.src = src;
      this.md = md2;
      this.env = env;
      this.tokens = tokens;
      this.bMarks = [];
      this.eMarks = [];
      this.tShift = [];
      this.sCount = [];
      this.bsCount = [];
      this.blkIndent = 0;
      this.line = 0;
      this.lineMax = 0;
      this.tight = false;
      this.ddIndent = -1;
      this.listIndent = -1;
      this.parentType = "root";
      this.level = 0;
      this.result = "";
      s3 = this.src;
      indent_found = false;
      for (start = pos = indent = offset = 0, len = s3.length; pos < len; pos++) {
        ch = s3.charCodeAt(pos);
        if (!indent_found) {
          if (isSpace2(ch)) {
            indent++;
            if (ch === 9) {
              offset += 4 - offset % 4;
            } else {
              offset++;
            }
            continue;
          } else {
            indent_found = true;
          }
        }
        if (ch === 10 || pos === len - 1) {
          if (ch !== 10) {
            pos++;
          }
          this.bMarks.push(start);
          this.eMarks.push(pos);
          this.tShift.push(indent);
          this.sCount.push(offset);
          this.bsCount.push(0);
          indent_found = false;
          indent = 0;
          offset = 0;
          start = pos + 1;
        }
      }
      this.bMarks.push(s3.length);
      this.eMarks.push(s3.length);
      this.tShift.push(0);
      this.sCount.push(0);
      this.bsCount.push(0);
      this.lineMax = this.bMarks.length - 1;
    }
    StateBlock2.prototype.push = function(type, tag, nesting) {
      var token = new Token2(type, tag, nesting);
      token.block = true;
      if (nesting < 0) this.level--;
      token.level = this.level;
      if (nesting > 0) this.level++;
      this.tokens.push(token);
      return token;
    };
    StateBlock2.prototype.isEmpty = function isEmpty5(line) {
      return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];
    };
    StateBlock2.prototype.skipEmptyLines = function skipEmptyLines2(from2) {
      for (var max3 = this.lineMax; from2 < max3; from2++) {
        if (this.bMarks[from2] + this.tShift[from2] < this.eMarks[from2]) {
          break;
        }
      }
      return from2;
    };
    StateBlock2.prototype.skipSpaces = function skipSpaces2(pos) {
      var ch;
      for (var max3 = this.src.length; pos < max3; pos++) {
        ch = this.src.charCodeAt(pos);
        if (!isSpace2(ch)) {
          break;
        }
      }
      return pos;
    };
    StateBlock2.prototype.skipSpacesBack = function skipSpacesBack2(pos, min3) {
      if (pos <= min3) {
        return pos;
      }
      while (pos > min3) {
        if (!isSpace2(this.src.charCodeAt(--pos))) {
          return pos + 1;
        }
      }
      return pos;
    };
    StateBlock2.prototype.skipChars = function skipChars2(pos, code2) {
      for (var max3 = this.src.length; pos < max3; pos++) {
        if (this.src.charCodeAt(pos) !== code2) {
          break;
        }
      }
      return pos;
    };
    StateBlock2.prototype.skipCharsBack = function skipCharsBack2(pos, code2, min3) {
      if (pos <= min3) {
        return pos;
      }
      while (pos > min3) {
        if (code2 !== this.src.charCodeAt(--pos)) {
          return pos + 1;
        }
      }
      return pos;
    };
    StateBlock2.prototype.getLines = function getLines2(begin, end, indent, keepLastLF) {
      var i3, lineIndent, ch, first2, last3, queue2, lineStart, line = begin;
      if (begin >= end) {
        return "";
      }
      queue2 = new Array(end - begin);
      for (i3 = 0; line < end; line++, i3++) {
        lineIndent = 0;
        lineStart = first2 = this.bMarks[line];
        if (line + 1 < end || keepLastLF) {
          last3 = this.eMarks[line] + 1;
        } else {
          last3 = this.eMarks[line];
        }
        while (first2 < last3 && lineIndent < indent) {
          ch = this.src.charCodeAt(first2);
          if (isSpace2(ch)) {
            if (ch === 9) {
              lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4;
            } else {
              lineIndent++;
            }
          } else if (first2 - lineStart < this.tShift[line]) {
            lineIndent++;
          } else {
            break;
          }
          first2++;
        }
        if (lineIndent > indent) {
          queue2[i3] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first2, last3);
        } else {
          queue2[i3] = this.src.slice(first2, last3);
        }
      }
      return queue2.join("");
    };
    StateBlock2.prototype.Token = Token2;
    module.exports = StateBlock2;
  }
});

// node_modules/markdown-it/lib/parser_block.js
var require_parser_block = __commonJS({
  "node_modules/markdown-it/lib/parser_block.js"(exports, module) {
    "use strict";
    var Ruler2 = require_ruler();
    var _rules4 = [
      // First 2 params - rule name & source. Secondary array - list of rules,
      // which can be terminated by this one.
      ["table", require_table(), ["paragraph", "reference"]],
      ["code", require_code()],
      ["fence", require_fence(), ["paragraph", "reference", "blockquote", "list"]],
      ["blockquote", require_blockquote(), ["paragraph", "reference", "blockquote", "list"]],
      ["hr", require_hr(), ["paragraph", "reference", "blockquote", "list"]],
      ["list", require_list(), ["paragraph", "reference", "blockquote"]],
      ["reference", require_reference()],
      ["html_block", require_html_block(), ["paragraph", "reference", "blockquote"]],
      ["heading", require_heading(), ["paragraph", "reference", "blockquote"]],
      ["lheading", require_lheading()],
      ["paragraph", require_paragraph()]
    ];
    function ParserBlock2() {
      this.ruler = new Ruler2();
      for (var i3 = 0; i3 < _rules4.length; i3++) {
        this.ruler.push(_rules4[i3][0], _rules4[i3][1], { alt: (_rules4[i3][2] || []).slice() });
      }
    }
    ParserBlock2.prototype.tokenize = function(state, startLine, endLine) {
      var ok, i3, rules = this.ruler.getRules(""), len = rules.length, line = startLine, hasEmptyLines = false, maxNesting = state.md.options.maxNesting;
      while (line < endLine) {
        state.line = line = state.skipEmptyLines(line);
        if (line >= endLine) {
          break;
        }
        if (state.sCount[line] < state.blkIndent) {
          break;
        }
        if (state.level >= maxNesting) {
          state.line = endLine;
          break;
        }
        for (i3 = 0; i3 < len; i3++) {
          ok = rules[i3](state, line, endLine, false);
          if (ok) {
            break;
          }
        }
        state.tight = !hasEmptyLines;
        if (state.isEmpty(state.line - 1)) {
          hasEmptyLines = true;
        }
        line = state.line;
        if (line < endLine && state.isEmpty(line)) {
          hasEmptyLines = true;
          line++;
          state.line = line;
        }
      }
    };
    ParserBlock2.prototype.parse = function(src, md2, env, outTokens) {
      var state;
      if (!src) {
        return;
      }
      state = new this.State(src, md2, env, outTokens);
      this.tokenize(state, state.line, state.lineMax);
    };
    ParserBlock2.prototype.State = require_state_block();
    module.exports = ParserBlock2;
  }
});

// node_modules/markdown-it/lib/rules_inline/text.js
var require_text = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/text.js"(exports, module) {
    "use strict";
    function isTerminatorChar2(ch) {
      switch (ch) {
        case 10:
        case 33:
        case 35:
        case 36:
        case 37:
        case 38:
        case 42:
        case 43:
        case 45:
        case 58:
        case 60:
        case 61:
        case 62:
        case 64:
        case 91:
        case 92:
        case 93:
        case 94:
        case 95:
        case 96:
        case 123:
        case 125:
        case 126:
          return true;
        default:
          return false;
      }
    }
    module.exports = function text3(state, silent) {
      var pos = state.pos;
      while (pos < state.posMax && !isTerminatorChar2(state.src.charCodeAt(pos))) {
        pos++;
      }
      if (pos === state.pos) {
        return false;
      }
      if (!silent) {
        state.pending += state.src.slice(state.pos, pos);
      }
      state.pos = pos;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/linkify.js
var require_linkify2 = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/linkify.js"(exports, module) {
    "use strict";
    var SCHEME_RE2 = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
    module.exports = function linkify3(state, silent) {
      var pos, max3, match2, proto, link2, url2, fullUrl, token;
      if (!state.md.options.linkify) return false;
      if (state.linkLevel > 0) return false;
      pos = state.pos;
      max3 = state.posMax;
      if (pos + 3 > max3) return false;
      if (state.src.charCodeAt(pos) !== 58) return false;
      if (state.src.charCodeAt(pos + 1) !== 47) return false;
      if (state.src.charCodeAt(pos + 2) !== 47) return false;
      match2 = state.pending.match(SCHEME_RE2);
      if (!match2) return false;
      proto = match2[1];
      link2 = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length));
      if (!link2) return false;
      url2 = link2.url;
      url2 = url2.replace(/\*+$/, "");
      fullUrl = state.md.normalizeLink(url2);
      if (!state.md.validateLink(fullUrl)) return false;
      if (!silent) {
        state.pending = state.pending.slice(0, -proto.length);
        token = state.push("link_open", "a", 1);
        token.attrs = [["href", fullUrl]];
        token.markup = "linkify";
        token.info = "auto";
        token = state.push("text", "", 0);
        token.content = state.md.normalizeLinkText(url2);
        token = state.push("link_close", "a", -1);
        token.markup = "linkify";
        token.info = "auto";
      }
      state.pos += url2.length - proto.length;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/newline.js
var require_newline = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/newline.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    module.exports = function newline2(state, silent) {
      var pmax, max3, ws, pos = state.pos;
      if (state.src.charCodeAt(pos) !== 10) {
        return false;
      }
      pmax = state.pending.length - 1;
      max3 = state.posMax;
      if (!silent) {
        if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
          if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
            ws = pmax - 1;
            while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 32) ws--;
            state.pending = state.pending.slice(0, ws);
            state.push("hardbreak", "br", 0);
          } else {
            state.pending = state.pending.slice(0, -1);
            state.push("softbreak", "br", 0);
          }
        } else {
          state.push("softbreak", "br", 0);
        }
      }
      pos++;
      while (pos < max3 && isSpace2(state.src.charCodeAt(pos))) {
        pos++;
      }
      state.pos = pos;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/escape.js
var require_escape = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/escape.js"(exports, module) {
    "use strict";
    var isSpace2 = require_utils().isSpace;
    var ESCAPED2 = [];
    for (i3 = 0; i3 < 256; i3++) {
      ESCAPED2.push(0);
    }
    var i3;
    "\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch) {
      ESCAPED2[ch.charCodeAt(0)] = 1;
    });
    module.exports = function escape4(state, silent) {
      var ch1, ch2, origStr, escapedStr, token, pos = state.pos, max3 = state.posMax;
      if (state.src.charCodeAt(pos) !== 92) return false;
      pos++;
      if (pos >= max3) return false;
      ch1 = state.src.charCodeAt(pos);
      if (ch1 === 10) {
        if (!silent) {
          state.push("hardbreak", "br", 0);
        }
        pos++;
        while (pos < max3) {
          ch1 = state.src.charCodeAt(pos);
          if (!isSpace2(ch1)) break;
          pos++;
        }
        state.pos = pos;
        return true;
      }
      escapedStr = state.src[pos];
      if (ch1 >= 55296 && ch1 <= 56319 && pos + 1 < max3) {
        ch2 = state.src.charCodeAt(pos + 1);
        if (ch2 >= 56320 && ch2 <= 57343) {
          escapedStr += state.src[pos + 1];
          pos++;
        }
      }
      origStr = "\\" + escapedStr;
      if (!silent) {
        token = state.push("text_special", "", 0);
        if (ch1 < 256 && ESCAPED2[ch1] !== 0) {
          token.content = escapedStr;
        } else {
          token.content = origStr;
        }
        token.markup = origStr;
        token.info = "escape";
      }
      state.pos = pos + 1;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/backticks.js
var require_backticks = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/backticks.js"(exports, module) {
    "use strict";
    module.exports = function backtick2(state, silent) {
      var start, max3, marker, token, matchStart, matchEnd, openerLength, closerLength, pos = state.pos, ch = state.src.charCodeAt(pos);
      if (ch !== 96) {
        return false;
      }
      start = pos;
      pos++;
      max3 = state.posMax;
      while (pos < max3 && state.src.charCodeAt(pos) === 96) {
        pos++;
      }
      marker = state.src.slice(start, pos);
      openerLength = marker.length;
      if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) {
        if (!silent) state.pending += marker;
        state.pos += openerLength;
        return true;
      }
      matchStart = matchEnd = pos;
      while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
        matchEnd = matchStart + 1;
        while (matchEnd < max3 && state.src.charCodeAt(matchEnd) === 96) {
          matchEnd++;
        }
        closerLength = matchEnd - matchStart;
        if (closerLength === openerLength) {
          if (!silent) {
            token = state.push("code_inline", "code", 0);
            token.markup = marker;
            token.content = state.src.slice(pos, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
          }
          state.pos = matchEnd;
          return true;
        }
        state.backticks[closerLength] = matchStart;
      }
      state.backticksScanned = true;
      if (!silent) state.pending += marker;
      state.pos += openerLength;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/strikethrough.js
var require_strikethrough = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/strikethrough.js"(exports, module) {
    "use strict";
    module.exports.tokenize = function strikethrough(state, silent) {
      var i3, scanned, token, len, ch, start = state.pos, marker = state.src.charCodeAt(start);
      if (silent) {
        return false;
      }
      if (marker !== 126) {
        return false;
      }
      scanned = state.scanDelims(state.pos, true);
      len = scanned.length;
      ch = String.fromCharCode(marker);
      if (len < 2) {
        return false;
      }
      if (len % 2) {
        token = state.push("text", "", 0);
        token.content = ch;
        len--;
      }
      for (i3 = 0; i3 < len; i3 += 2) {
        token = state.push("text", "", 0);
        token.content = ch + ch;
        state.delimiters.push({
          marker,
          length: 0,
          // disable "rule of 3" length checks meant for emphasis
          token: state.tokens.length - 1,
          end: -1,
          open: scanned.can_open,
          close: scanned.can_close
        });
      }
      state.pos += scanned.length;
      return true;
    };
    function postProcess3(state, delimiters) {
      var i3, j, startDelim, endDelim, token, loneMarkers = [], max3 = delimiters.length;
      for (i3 = 0; i3 < max3; i3++) {
        startDelim = delimiters[i3];
        if (startDelim.marker !== 126) {
          continue;
        }
        if (startDelim.end === -1) {
          continue;
        }
        endDelim = delimiters[startDelim.end];
        token = state.tokens[startDelim.token];
        token.type = "s_open";
        token.tag = "s";
        token.nesting = 1;
        token.markup = "~~";
        token.content = "";
        token = state.tokens[endDelim.token];
        token.type = "s_close";
        token.tag = "s";
        token.nesting = -1;
        token.markup = "~~";
        token.content = "";
        if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
          loneMarkers.push(endDelim.token - 1);
        }
      }
      while (loneMarkers.length) {
        i3 = loneMarkers.pop();
        j = i3 + 1;
        while (j < state.tokens.length && state.tokens[j].type === "s_close") {
          j++;
        }
        j--;
        if (i3 !== j) {
          token = state.tokens[j];
          state.tokens[j] = state.tokens[i3];
          state.tokens[i3] = token;
        }
      }
    }
    module.exports.postProcess = function strikethrough(state) {
      var curr, tokens_meta = state.tokens_meta, max3 = state.tokens_meta.length;
      postProcess3(state, state.delimiters);
      for (curr = 0; curr < max3; curr++) {
        if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
          postProcess3(state, tokens_meta[curr].delimiters);
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/emphasis.js
var require_emphasis = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/emphasis.js"(exports, module) {
    "use strict";
    module.exports.tokenize = function emphasis(state, silent) {
      var i3, scanned, token, start = state.pos, marker = state.src.charCodeAt(start);
      if (silent) {
        return false;
      }
      if (marker !== 95 && marker !== 42) {
        return false;
      }
      scanned = state.scanDelims(state.pos, marker === 42);
      for (i3 = 0; i3 < scanned.length; i3++) {
        token = state.push("text", "", 0);
        token.content = String.fromCharCode(marker);
        state.delimiters.push({
          // Char code of the starting marker (number).
          //
          marker,
          // Total length of these series of delimiters.
          //
          length: scanned.length,
          // A position of the token this delimiter corresponds to.
          //
          token: state.tokens.length - 1,
          // If this delimiter is matched as a valid opener, `end` will be
          // equal to its position, otherwise it's `-1`.
          //
          end: -1,
          // Boolean flags that determine if this delimiter could open or close
          // an emphasis.
          //
          open: scanned.can_open,
          close: scanned.can_close
        });
      }
      state.pos += scanned.length;
      return true;
    };
    function postProcess3(state, delimiters) {
      var i3, startDelim, endDelim, token, ch, isStrong, max3 = delimiters.length;
      for (i3 = max3 - 1; i3 >= 0; i3--) {
        startDelim = delimiters[i3];
        if (startDelim.marker !== 95 && startDelim.marker !== 42) {
          continue;
        }
        if (startDelim.end === -1) {
          continue;
        }
        endDelim = delimiters[startDelim.end];
        isStrong = i3 > 0 && delimiters[i3 - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
        delimiters[i3 - 1].marker === startDelim.marker && delimiters[i3 - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
        delimiters[startDelim.end + 1].token === endDelim.token + 1;
        ch = String.fromCharCode(startDelim.marker);
        token = state.tokens[startDelim.token];
        token.type = isStrong ? "strong_open" : "em_open";
        token.tag = isStrong ? "strong" : "em";
        token.nesting = 1;
        token.markup = isStrong ? ch + ch : ch;
        token.content = "";
        token = state.tokens[endDelim.token];
        token.type = isStrong ? "strong_close" : "em_close";
        token.tag = isStrong ? "strong" : "em";
        token.nesting = -1;
        token.markup = isStrong ? ch + ch : ch;
        token.content = "";
        if (isStrong) {
          state.tokens[delimiters[i3 - 1].token].content = "";
          state.tokens[delimiters[startDelim.end + 1].token].content = "";
          i3--;
        }
      }
    }
    module.exports.postProcess = function emphasis(state) {
      var curr, tokens_meta = state.tokens_meta, max3 = state.tokens_meta.length;
      postProcess3(state, state.delimiters);
      for (curr = 0; curr < max3; curr++) {
        if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
          postProcess3(state, tokens_meta[curr].delimiters);
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/link.js
var require_link = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/link.js"(exports, module) {
    "use strict";
    var normalizeReference2 = require_utils().normalizeReference;
    var isSpace2 = require_utils().isSpace;
    module.exports = function link2(state, silent) {
      var attrs2, code2, label, labelEnd, labelStart, pos, res, ref, token, href = "", title = "", oldPos = state.pos, max3 = state.posMax, start = state.pos, parseReference = true;
      if (state.src.charCodeAt(state.pos) !== 91) {
        return false;
      }
      labelStart = state.pos + 1;
      labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
      if (labelEnd < 0) {
        return false;
      }
      pos = labelEnd + 1;
      if (pos < max3 && state.src.charCodeAt(pos) === 40) {
        parseReference = false;
        pos++;
        for (; pos < max3; pos++) {
          code2 = state.src.charCodeAt(pos);
          if (!isSpace2(code2) && code2 !== 10) {
            break;
          }
        }
        if (pos >= max3) {
          return false;
        }
        start = pos;
        res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
        if (res.ok) {
          href = state.md.normalizeLink(res.str);
          if (state.md.validateLink(href)) {
            pos = res.pos;
          } else {
            href = "";
          }
          start = pos;
          for (; pos < max3; pos++) {
            code2 = state.src.charCodeAt(pos);
            if (!isSpace2(code2) && code2 !== 10) {
              break;
            }
          }
          res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
          if (pos < max3 && start !== pos && res.ok) {
            title = res.str;
            pos = res.pos;
            for (; pos < max3; pos++) {
              code2 = state.src.charCodeAt(pos);
              if (!isSpace2(code2) && code2 !== 10) {
                break;
              }
            }
          }
        }
        if (pos >= max3 || state.src.charCodeAt(pos) !== 41) {
          parseReference = true;
        }
        pos++;
      }
      if (parseReference) {
        if (typeof state.env.references === "undefined") {
          return false;
        }
        if (pos < max3 && state.src.charCodeAt(pos) === 91) {
          start = pos + 1;
          pos = state.md.helpers.parseLinkLabel(state, pos);
          if (pos >= 0) {
            label = state.src.slice(start, pos++);
          } else {
            pos = labelEnd + 1;
          }
        } else {
          pos = labelEnd + 1;
        }
        if (!label) {
          label = state.src.slice(labelStart, labelEnd);
        }
        ref = state.env.references[normalizeReference2(label)];
        if (!ref) {
          state.pos = oldPos;
          return false;
        }
        href = ref.href;
        title = ref.title;
      }
      if (!silent) {
        state.pos = labelStart;
        state.posMax = labelEnd;
        token = state.push("link_open", "a", 1);
        token.attrs = attrs2 = [["href", href]];
        if (title) {
          attrs2.push(["title", title]);
        }
        state.linkLevel++;
        state.md.inline.tokenize(state);
        state.linkLevel--;
        token = state.push("link_close", "a", -1);
      }
      state.pos = pos;
      state.posMax = max3;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/image.js
var require_image = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/image.js"(exports, module) {
    "use strict";
    var normalizeReference2 = require_utils().normalizeReference;
    var isSpace2 = require_utils().isSpace;
    module.exports = function image2(state, silent) {
      var attrs2, code2, content2, label, labelEnd, labelStart, pos, ref, res, title, token, tokens, start, href = "", oldPos = state.pos, max3 = state.posMax;
      if (state.src.charCodeAt(state.pos) !== 33) {
        return false;
      }
      if (state.src.charCodeAt(state.pos + 1) !== 91) {
        return false;
      }
      labelStart = state.pos + 2;
      labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
      if (labelEnd < 0) {
        return false;
      }
      pos = labelEnd + 1;
      if (pos < max3 && state.src.charCodeAt(pos) === 40) {
        pos++;
        for (; pos < max3; pos++) {
          code2 = state.src.charCodeAt(pos);
          if (!isSpace2(code2) && code2 !== 10) {
            break;
          }
        }
        if (pos >= max3) {
          return false;
        }
        start = pos;
        res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
        if (res.ok) {
          href = state.md.normalizeLink(res.str);
          if (state.md.validateLink(href)) {
            pos = res.pos;
          } else {
            href = "";
          }
        }
        start = pos;
        for (; pos < max3; pos++) {
          code2 = state.src.charCodeAt(pos);
          if (!isSpace2(code2) && code2 !== 10) {
            break;
          }
        }
        res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
        if (pos < max3 && start !== pos && res.ok) {
          title = res.str;
          pos = res.pos;
          for (; pos < max3; pos++) {
            code2 = state.src.charCodeAt(pos);
            if (!isSpace2(code2) && code2 !== 10) {
              break;
            }
          }
        } else {
          title = "";
        }
        if (pos >= max3 || state.src.charCodeAt(pos) !== 41) {
          state.pos = oldPos;
          return false;
        }
        pos++;
      } else {
        if (typeof state.env.references === "undefined") {
          return false;
        }
        if (pos < max3 && state.src.charCodeAt(pos) === 91) {
          start = pos + 1;
          pos = state.md.helpers.parseLinkLabel(state, pos);
          if (pos >= 0) {
            label = state.src.slice(start, pos++);
          } else {
            pos = labelEnd + 1;
          }
        } else {
          pos = labelEnd + 1;
        }
        if (!label) {
          label = state.src.slice(labelStart, labelEnd);
        }
        ref = state.env.references[normalizeReference2(label)];
        if (!ref) {
          state.pos = oldPos;
          return false;
        }
        href = ref.href;
        title = ref.title;
      }
      if (!silent) {
        content2 = state.src.slice(labelStart, labelEnd);
        state.md.inline.parse(
          content2,
          state.md,
          state.env,
          tokens = []
        );
        token = state.push("image", "img", 0);
        token.attrs = attrs2 = [["src", href], ["alt", ""]];
        token.children = tokens;
        token.content = content2;
        if (title) {
          attrs2.push(["title", title]);
        }
      }
      state.pos = pos;
      state.posMax = max3;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/autolink.js
var require_autolink = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/autolink.js"(exports, module) {
    "use strict";
    var EMAIL_RE2 = /^([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;
    var AUTOLINK_RE2 = /^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$/;
    module.exports = function autolink2(state, silent) {
      var url2, fullUrl, token, ch, start, max3, pos = state.pos;
      if (state.src.charCodeAt(pos) !== 60) {
        return false;
      }
      start = state.pos;
      max3 = state.posMax;
      for (; ; ) {
        if (++pos >= max3) return false;
        ch = state.src.charCodeAt(pos);
        if (ch === 60) return false;
        if (ch === 62) break;
      }
      url2 = state.src.slice(start + 1, pos);
      if (AUTOLINK_RE2.test(url2)) {
        fullUrl = state.md.normalizeLink(url2);
        if (!state.md.validateLink(fullUrl)) {
          return false;
        }
        if (!silent) {
          token = state.push("link_open", "a", 1);
          token.attrs = [["href", fullUrl]];
          token.markup = "autolink";
          token.info = "auto";
          token = state.push("text", "", 0);
          token.content = state.md.normalizeLinkText(url2);
          token = state.push("link_close", "a", -1);
          token.markup = "autolink";
          token.info = "auto";
        }
        state.pos += url2.length + 2;
        return true;
      }
      if (EMAIL_RE2.test(url2)) {
        fullUrl = state.md.normalizeLink("mailto:" + url2);
        if (!state.md.validateLink(fullUrl)) {
          return false;
        }
        if (!silent) {
          token = state.push("link_open", "a", 1);
          token.attrs = [["href", fullUrl]];
          token.markup = "autolink";
          token.info = "auto";
          token = state.push("text", "", 0);
          token.content = state.md.normalizeLinkText(url2);
          token = state.push("link_close", "a", -1);
          token.markup = "autolink";
          token.info = "auto";
        }
        state.pos += url2.length + 2;
        return true;
      }
      return false;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/html_inline.js
var require_html_inline = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/html_inline.js"(exports, module) {
    "use strict";
    var HTML_TAG_RE2 = require_html_re().HTML_TAG_RE;
    function isLinkOpen3(str) {
      return /^<a[>\s]/i.test(str);
    }
    function isLinkClose3(str) {
      return /^<\/a\s*>/i.test(str);
    }
    function isLetter2(ch) {
      var lc = ch | 32;
      return lc >= 97 && lc <= 122;
    }
    module.exports = function html_inline2(state, silent) {
      var ch, match2, max3, token, pos = state.pos;
      if (!state.md.options.html) {
        return false;
      }
      max3 = state.posMax;
      if (state.src.charCodeAt(pos) !== 60 || pos + 2 >= max3) {
        return false;
      }
      ch = state.src.charCodeAt(pos + 1);
      if (ch !== 33 && ch !== 63 && ch !== 47 && !isLetter2(ch)) {
        return false;
      }
      match2 = state.src.slice(pos).match(HTML_TAG_RE2);
      if (!match2) {
        return false;
      }
      if (!silent) {
        token = state.push("html_inline", "", 0);
        token.content = state.src.slice(pos, pos + match2[0].length);
        if (isLinkOpen3(token.content)) state.linkLevel++;
        if (isLinkClose3(token.content)) state.linkLevel--;
      }
      state.pos += match2[0].length;
      return true;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/entity.js
var require_entity = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/entity.js"(exports, module) {
    "use strict";
    var entities = require_entities2();
    var has4 = require_utils().has;
    var isValidEntityCode2 = require_utils().isValidEntityCode;
    var fromCodePoint4 = require_utils().fromCodePoint;
    var DIGITAL_RE2 = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
    var NAMED_RE2 = /^&([a-z][a-z0-9]{1,31});/i;
    module.exports = function entity2(state, silent) {
      var ch, code2, match2, token, pos = state.pos, max3 = state.posMax;
      if (state.src.charCodeAt(pos) !== 38) return false;
      if (pos + 1 >= max3) return false;
      ch = state.src.charCodeAt(pos + 1);
      if (ch === 35) {
        match2 = state.src.slice(pos).match(DIGITAL_RE2);
        if (match2) {
          if (!silent) {
            code2 = match2[1][0].toLowerCase() === "x" ? parseInt(match2[1].slice(1), 16) : parseInt(match2[1], 10);
            token = state.push("text_special", "", 0);
            token.content = isValidEntityCode2(code2) ? fromCodePoint4(code2) : fromCodePoint4(65533);
            token.markup = match2[0];
            token.info = "entity";
          }
          state.pos += match2[0].length;
          return true;
        }
      } else {
        match2 = state.src.slice(pos).match(NAMED_RE2);
        if (match2) {
          if (has4(entities, match2[1])) {
            if (!silent) {
              token = state.push("text_special", "", 0);
              token.content = entities[match2[1]];
              token.markup = match2[0];
              token.info = "entity";
            }
            state.pos += match2[0].length;
            return true;
          }
        }
      }
      return false;
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/balance_pairs.js
var require_balance_pairs = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/balance_pairs.js"(exports, module) {
    "use strict";
    function processDelimiters2(state, delimiters) {
      var closerIdx, openerIdx, closer, opener, minOpenerIdx, newMinOpenerIdx, isOddMatch, lastJump, openersBottom = {}, max3 = delimiters.length;
      if (!max3) return;
      var headerIdx = 0;
      var lastTokenIdx = -2;
      var jumps = [];
      for (closerIdx = 0; closerIdx < max3; closerIdx++) {
        closer = delimiters[closerIdx];
        jumps.push(0);
        if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
          headerIdx = closerIdx;
        }
        lastTokenIdx = closer.token;
        closer.length = closer.length || 0;
        if (!closer.close) continue;
        if (!openersBottom.hasOwnProperty(closer.marker)) {
          openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
        }
        minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
        openerIdx = headerIdx - jumps[headerIdx] - 1;
        newMinOpenerIdx = openerIdx;
        for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
          opener = delimiters[openerIdx];
          if (opener.marker !== closer.marker) continue;
          if (opener.open && opener.end < 0) {
            isOddMatch = false;
            if (opener.close || closer.open) {
              if ((opener.length + closer.length) % 3 === 0) {
                if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
                  isOddMatch = true;
                }
              }
            }
            if (!isOddMatch) {
              lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
              jumps[closerIdx] = closerIdx - openerIdx + lastJump;
              jumps[openerIdx] = lastJump;
              closer.open = false;
              opener.end = closerIdx;
              opener.close = false;
              newMinOpenerIdx = -1;
              lastTokenIdx = -2;
              break;
            }
          }
        }
        if (newMinOpenerIdx !== -1) {
          openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
        }
      }
    }
    module.exports = function link_pairs2(state) {
      var curr, tokens_meta = state.tokens_meta, max3 = state.tokens_meta.length;
      processDelimiters2(state, state.delimiters);
      for (curr = 0; curr < max3; curr++) {
        if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
          processDelimiters2(state, tokens_meta[curr].delimiters);
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/fragments_join.js
var require_fragments_join = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/fragments_join.js"(exports, module) {
    "use strict";
    module.exports = function fragments_join2(state) {
      var curr, last3, level = 0, tokens = state.tokens, max3 = state.tokens.length;
      for (curr = last3 = 0; curr < max3; curr++) {
        if (tokens[curr].nesting < 0) level--;
        tokens[curr].level = level;
        if (tokens[curr].nesting > 0) level++;
        if (tokens[curr].type === "text" && curr + 1 < max3 && tokens[curr + 1].type === "text") {
          tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
        } else {
          if (curr !== last3) {
            tokens[last3] = tokens[curr];
          }
          last3++;
        }
      }
      if (curr !== last3) {
        tokens.length = last3;
      }
    };
  }
});

// node_modules/markdown-it/lib/rules_inline/state_inline.js
var require_state_inline = __commonJS({
  "node_modules/markdown-it/lib/rules_inline/state_inline.js"(exports, module) {
    "use strict";
    var Token2 = require_token();
    var isWhiteSpace2 = require_utils().isWhiteSpace;
    var isPunctChar2 = require_utils().isPunctChar;
    var isMdAsciiPunct2 = require_utils().isMdAsciiPunct;
    function StateInline2(src, md2, env, outTokens) {
      this.src = src;
      this.env = env;
      this.md = md2;
      this.tokens = outTokens;
      this.tokens_meta = Array(outTokens.length);
      this.pos = 0;
      this.posMax = this.src.length;
      this.level = 0;
      this.pending = "";
      this.pendingLevel = 0;
      this.cache = {};
      this.delimiters = [];
      this._prev_delimiters = [];
      this.backticks = {};
      this.backticksScanned = false;
      this.linkLevel = 0;
    }
    StateInline2.prototype.pushPending = function() {
      var token = new Token2("text", "", 0);
      token.content = this.pending;
      token.level = this.pendingLevel;
      this.tokens.push(token);
      this.pending = "";
      return token;
    };
    StateInline2.prototype.push = function(type, tag, nesting) {
      if (this.pending) {
        this.pushPending();
      }
      var token = new Token2(type, tag, nesting);
      var token_meta = null;
      if (nesting < 0) {
        this.level--;
        this.delimiters = this._prev_delimiters.pop();
      }
      token.level = this.level;
      if (nesting > 0) {
        this.level++;
        this._prev_delimiters.push(this.delimiters);
        this.delimiters = [];
        token_meta = { delimiters: this.delimiters };
      }
      this.pendingLevel = this.level;
      this.tokens.push(token);
      this.tokens_meta.push(token_meta);
      return token;
    };
    StateInline2.prototype.scanDelims = function(start, canSplitWord) {
      var pos = start, lastChar, nextChar2, count, can_open, can_close, isLastWhiteSpace, isLastPunctChar, isNextWhiteSpace, isNextPunctChar, left_flanking = true, right_flanking = true, max3 = this.posMax, marker = this.src.charCodeAt(start);
      lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 32;
      while (pos < max3 && this.src.charCodeAt(pos) === marker) {
        pos++;
      }
      count = pos - start;
      nextChar2 = pos < max3 ? this.src.charCodeAt(pos) : 32;
      isLastPunctChar = isMdAsciiPunct2(lastChar) || isPunctChar2(String.fromCharCode(lastChar));
      isNextPunctChar = isMdAsciiPunct2(nextChar2) || isPunctChar2(String.fromCharCode(nextChar2));
      isLastWhiteSpace = isWhiteSpace2(lastChar);
      isNextWhiteSpace = isWhiteSpace2(nextChar2);
      if (isNextWhiteSpace) {
        left_flanking = false;
      } else if (isNextPunctChar) {
        if (!(isLastWhiteSpace || isLastPunctChar)) {
          left_flanking = false;
        }
      }
      if (isLastWhiteSpace) {
        right_flanking = false;
      } else if (isLastPunctChar) {
        if (!(isNextWhiteSpace || isNextPunctChar)) {
          right_flanking = false;
        }
      }
      if (!canSplitWord) {
        can_open = left_flanking && (!right_flanking || isLastPunctChar);
        can_close = right_flanking && (!left_flanking || isNextPunctChar);
      } else {
        can_open = left_flanking;
        can_close = right_flanking;
      }
      return {
        can_open,
        can_close,
        length: count
      };
    };
    StateInline2.prototype.Token = Token2;
    module.exports = StateInline2;
  }
});

// node_modules/markdown-it/lib/parser_inline.js
var require_parser_inline = __commonJS({
  "node_modules/markdown-it/lib/parser_inline.js"(exports, module) {
    "use strict";
    var Ruler2 = require_ruler();
    var _rules4 = [
      ["text", require_text()],
      ["linkify", require_linkify2()],
      ["newline", require_newline()],
      ["escape", require_escape()],
      ["backticks", require_backticks()],
      ["strikethrough", require_strikethrough().tokenize],
      ["emphasis", require_emphasis().tokenize],
      ["link", require_link()],
      ["image", require_image()],
      ["autolink", require_autolink()],
      ["html_inline", require_html_inline()],
      ["entity", require_entity()]
    ];
    var _rules23 = [
      ["balance_pairs", require_balance_pairs()],
      ["strikethrough", require_strikethrough().postProcess],
      ["emphasis", require_emphasis().postProcess],
      // rules for pairs separate '**' into its own text tokens, which may be left unused,
      // rule below merges unused segments back with the rest of the text
      ["fragments_join", require_fragments_join()]
    ];
    function ParserInline2() {
      var i3;
      this.ruler = new Ruler2();
      for (i3 = 0; i3 < _rules4.length; i3++) {
        this.ruler.push(_rules4[i3][0], _rules4[i3][1]);
      }
      this.ruler2 = new Ruler2();
      for (i3 = 0; i3 < _rules23.length; i3++) {
        this.ruler2.push(_rules23[i3][0], _rules23[i3][1]);
      }
    }
    ParserInline2.prototype.skipToken = function(state) {
      var ok, i3, pos = state.pos, rules = this.ruler.getRules(""), len = rules.length, maxNesting = state.md.options.maxNesting, cache5 = state.cache;
      if (typeof cache5[pos] !== "undefined") {
        state.pos = cache5[pos];
        return;
      }
      if (state.level < maxNesting) {
        for (i3 = 0; i3 < len; i3++) {
          state.level++;
          ok = rules[i3](state, true);
          state.level--;
          if (ok) {
            break;
          }
        }
      } else {
        state.pos = state.posMax;
      }
      if (!ok) {
        state.pos++;
      }
      cache5[pos] = state.pos;
    };
    ParserInline2.prototype.tokenize = function(state) {
      var ok, i3, rules = this.ruler.getRules(""), len = rules.length, end = state.posMax, maxNesting = state.md.options.maxNesting;
      while (state.pos < end) {
        if (state.level < maxNesting) {
          for (i3 = 0; i3 < len; i3++) {
            ok = rules[i3](state, false);
            if (ok) {
              break;
            }
          }
        }
        if (ok) {
          if (state.pos >= end) {
            break;
          }
          continue;
        }
        state.pending += state.src[state.pos++];
      }
      if (state.pending) {
        state.pushPending();
      }
    };
    ParserInline2.prototype.parse = function(str, md2, env, outTokens) {
      var i3, rules, len;
      var state = new this.State(str, md2, env, outTokens);
      this.tokenize(state);
      rules = this.ruler2.getRules("");
      len = rules.length;
      for (i3 = 0; i3 < len; i3++) {
        rules[i3](state);
      }
    };
    ParserInline2.prototype.State = require_state_inline();
    module.exports = ParserInline2;
  }
});

// node_modules/linkify-it/lib/re.js
var require_re = __commonJS({
  "node_modules/linkify-it/lib/re.js"(exports, module) {
    "use strict";
    module.exports = function(opts) {
      var re2 = {};
      opts = opts || {};
      re2.src_Any = require_regex2().source;
      re2.src_Cc = require_regex3().source;
      re2.src_Z = require_regex5().source;
      re2.src_P = require_regex().source;
      re2.src_ZPCc = [re2.src_Z, re2.src_P, re2.src_Cc].join("|");
      re2.src_ZCc = [re2.src_Z, re2.src_Cc].join("|");
      var text_separators = "[><\uFF5C]";
      re2.src_pseudo_letter = "(?:(?!" + text_separators + "|" + re2.src_ZPCc + ")" + re2.src_Any + ")";
      re2.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
      re2.src_auth = "(?:(?:(?!" + re2.src_ZCc + "|[@/\\[\\]()]).)+@)?";
      re2.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
      re2.src_host_terminator = "(?=$|" + text_separators + "|" + re2.src_ZPCc + ")(?!" + (opts["---"] ? "-(?!--)|" : "-|") + "_|:\\d|\\.-|\\.(?!$|" + re2.src_ZPCc + "))";
      re2.src_path = "(?:[/?#](?:(?!" + re2.src_ZCc + "|" + text_separators + `|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!` + re2.src_ZCc + "|\\]).)*\\]|\\((?:(?!" + re2.src_ZCc + "|[)]).)*\\)|\\{(?:(?!" + re2.src_ZCc + '|[}]).)*\\}|\\"(?:(?!' + re2.src_ZCc + `|["]).)+\\"|\\'(?:(?!` + re2.src_ZCc + "|[']).)+\\'|\\'(?=" + re2.src_pseudo_letter + "|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!" + re2.src_ZCc + "|[.]|$)|" + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + ",(?!" + re2.src_ZCc + "|$)|;(?!" + re2.src_ZCc + "|$)|\\!+(?!" + re2.src_ZCc + "|[!]|$)|\\?(?!" + re2.src_ZCc + "|[?]|$))+|\\/)?";
      re2.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*';
      re2.src_xn = "xn--[a-z0-9\\-]{1,59}";
      re2.src_domain_root = // Allow letters & digits (http://test1)
      "(?:" + re2.src_xn + "|" + re2.src_pseudo_letter + "{1,63})";
      re2.src_domain = "(?:" + re2.src_xn + "|(?:" + re2.src_pseudo_letter + ")|(?:" + re2.src_pseudo_letter + "(?:-|" + re2.src_pseudo_letter + "){0,61}" + re2.src_pseudo_letter + "))";
      re2.src_host = "(?:(?:(?:(?:" + re2.src_domain + ")\\.)*" + re2.src_domain + "))";
      re2.tpl_host_fuzzy = "(?:" + re2.src_ip4 + "|(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%)))";
      re2.tpl_host_no_ip_fuzzy = "(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%))";
      re2.src_host_strict = re2.src_host + re2.src_host_terminator;
      re2.tpl_host_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_host_terminator;
      re2.src_host_port_strict = re2.src_host + re2.src_port + re2.src_host_terminator;
      re2.tpl_host_port_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_port + re2.src_host_terminator;
      re2.tpl_host_port_no_ip_fuzzy_strict = re2.tpl_host_no_ip_fuzzy + re2.src_port + re2.src_host_terminator;
      re2.tpl_host_fuzzy_test = "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + re2.src_ZPCc + "|>|$))";
      re2.tpl_email_fuzzy = "(^|" + text_separators + '|"|\\(|' + re2.src_ZCc + ")(" + re2.src_email_name + "@" + re2.tpl_host_fuzzy_strict + ")";
      re2.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
      // but can start with > (markdown blockquote)
      "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uFF5C]|" + re2.src_ZPCc + "))((?![$+<=>^`|\uFF5C])" + re2.tpl_host_port_fuzzy_strict + re2.src_path + ")";
      re2.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
      // but can start with > (markdown blockquote)
      "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uFF5C]|" + re2.src_ZPCc + "))((?![$+<=>^`|\uFF5C])" + re2.tpl_host_port_no_ip_fuzzy_strict + re2.src_path + ")";
      return re2;
    };
  }
});

// node_modules/linkify-it/index.js
var require_linkify_it = __commonJS({
  "node_modules/linkify-it/index.js"(exports, module) {
    "use strict";
    function assign6(obj) {
      var sources = Array.prototype.slice.call(arguments, 1);
      sources.forEach(function(source) {
        if (!source) {
          return;
        }
        Object.keys(source).forEach(function(key2) {
          obj[key2] = source[key2];
        });
      });
      return obj;
    }
    function _class3(obj) {
      return Object.prototype.toString.call(obj);
    }
    function isString5(obj) {
      return _class3(obj) === "[object String]";
    }
    function isObject7(obj) {
      return _class3(obj) === "[object Object]";
    }
    function isRegExp2(obj) {
      return _class3(obj) === "[object RegExp]";
    }
    function isFunction4(obj) {
      return _class3(obj) === "[object Function]";
    }
    function escapeRE3(str) {
      return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
    }
    var defaultOptions4 = {
      fuzzyLink: true,
      fuzzyEmail: true,
      fuzzyIP: false
    };
    function isOptionsObj2(obj) {
      return Object.keys(obj || {}).reduce(function(acc, k2) {
        return acc || defaultOptions4.hasOwnProperty(k2);
      }, false);
    }
    var defaultSchemas2 = {
      "http:": {
        validate: function(text3, pos, self2) {
          var tail = text3.slice(pos);
          if (!self2.re.http) {
            self2.re.http = new RegExp(
              "^\\/\\/" + self2.re.src_auth + self2.re.src_host_port_strict + self2.re.src_path,
              "i"
            );
          }
          if (self2.re.http.test(tail)) {
            return tail.match(self2.re.http)[0].length;
          }
          return 0;
        }
      },
      "https:": "http:",
      "ftp:": "http:",
      "//": {
        validate: function(text3, pos, self2) {
          var tail = text3.slice(pos);
          if (!self2.re.no_http) {
            self2.re.no_http = new RegExp(
              "^" + self2.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
              // with code comments
              "(?:localhost|(?:(?:" + self2.re.src_domain + ")\\.)+" + self2.re.src_domain_root + ")" + self2.re.src_port + self2.re.src_host_terminator + self2.re.src_path,
              "i"
            );
          }
          if (self2.re.no_http.test(tail)) {
            if (pos >= 3 && text3[pos - 3] === ":") {
              return 0;
            }
            if (pos >= 3 && text3[pos - 3] === "/") {
              return 0;
            }
            return tail.match(self2.re.no_http)[0].length;
          }
          return 0;
        }
      },
      "mailto:": {
        validate: function(text3, pos, self2) {
          var tail = text3.slice(pos);
          if (!self2.re.mailto) {
            self2.re.mailto = new RegExp(
              "^" + self2.re.src_email_name + "@" + self2.re.src_host_strict,
              "i"
            );
          }
          if (self2.re.mailto.test(tail)) {
            return tail.match(self2.re.mailto)[0].length;
          }
          return 0;
        }
      }
    };
    var tlds_2ch_src_re2 = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
    var tlds_default2 = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|\u0440\u0444".split("|");
    function resetScanCache2(self2) {
      self2.__index__ = -1;
      self2.__text_cache__ = "";
    }
    function createValidator2(re2) {
      return function(text3, pos) {
        var tail = text3.slice(pos);
        if (re2.test(tail)) {
          return tail.match(re2)[0].length;
        }
        return 0;
      };
    }
    function createNormalizer2() {
      return function(match2, self2) {
        self2.normalize(match2);
      };
    }
    function compile2(self2) {
      var re2 = self2.re = require_re()(self2.__opts__);
      var tlds2 = self2.__tlds__.slice();
      self2.onCompile();
      if (!self2.__tlds_replaced__) {
        tlds2.push(tlds_2ch_src_re2);
      }
      tlds2.push(re2.src_xn);
      re2.src_tlds = tlds2.join("|");
      function untpl(tpl) {
        return tpl.replace("%TLDS%", re2.src_tlds);
      }
      re2.email_fuzzy = RegExp(untpl(re2.tpl_email_fuzzy), "i");
      re2.link_fuzzy = RegExp(untpl(re2.tpl_link_fuzzy), "i");
      re2.link_no_ip_fuzzy = RegExp(untpl(re2.tpl_link_no_ip_fuzzy), "i");
      re2.host_fuzzy_test = RegExp(untpl(re2.tpl_host_fuzzy_test), "i");
      var aliases = [];
      self2.__compiled__ = {};
      function schemaError(name2, val) {
        throw new Error('(LinkifyIt) Invalid schema "' + name2 + '": ' + val);
      }
      Object.keys(self2.__schemas__).forEach(function(name2) {
        var val = self2.__schemas__[name2];
        if (val === null) {
          return;
        }
        var compiled = { validate: null, link: null };
        self2.__compiled__[name2] = compiled;
        if (isObject7(val)) {
          if (isRegExp2(val.validate)) {
            compiled.validate = createValidator2(val.validate);
          } else if (isFunction4(val.validate)) {
            compiled.validate = val.validate;
          } else {
            schemaError(name2, val);
          }
          if (isFunction4(val.normalize)) {
            compiled.normalize = val.normalize;
          } else if (!val.normalize) {
            compiled.normalize = createNormalizer2();
          } else {
            schemaError(name2, val);
          }
          return;
        }
        if (isString5(val)) {
          aliases.push(name2);
          return;
        }
        schemaError(name2, val);
      });
      aliases.forEach(function(alias) {
        if (!self2.__compiled__[self2.__schemas__[alias]]) {
          return;
        }
        self2.__compiled__[alias].validate = self2.__compiled__[self2.__schemas__[alias]].validate;
        self2.__compiled__[alias].normalize = self2.__compiled__[self2.__schemas__[alias]].normalize;
      });
      self2.__compiled__[""] = { validate: null, normalize: createNormalizer2() };
      var slist = Object.keys(self2.__compiled__).filter(function(name2) {
        return name2.length > 0 && self2.__compiled__[name2];
      }).map(escapeRE3).join("|");
      self2.re.schema_test = RegExp("(^|(?!_)(?:[><\uFF5C]|" + re2.src_ZPCc + "))(" + slist + ")", "i");
      self2.re.schema_search = RegExp("(^|(?!_)(?:[><\uFF5C]|" + re2.src_ZPCc + "))(" + slist + ")", "ig");
      self2.re.schema_at_start = RegExp("^" + self2.re.schema_search.source, "i");
      self2.re.pretest = RegExp(
        "(" + self2.re.schema_test.source + ")|(" + self2.re.host_fuzzy_test.source + ")|@",
        "i"
      );
      resetScanCache2(self2);
    }
    function Match3(self2, shift2) {
      var start = self2.__index__, end = self2.__last_index__, text3 = self2.__text_cache__.slice(start, end);
      this.schema = self2.__schema__.toLowerCase();
      this.index = start + shift2;
      this.lastIndex = end + shift2;
      this.raw = text3;
      this.text = text3;
      this.url = text3;
    }
    function createMatch2(self2, shift2) {
      var match2 = new Match3(self2, shift2);
      self2.__compiled__[match2.schema].normalize(match2, self2);
      return match2;
    }
    function LinkifyIt2(schemas2, options2) {
      if (!(this instanceof LinkifyIt2)) {
        return new LinkifyIt2(schemas2, options2);
      }
      if (!options2) {
        if (isOptionsObj2(schemas2)) {
          options2 = schemas2;
          schemas2 = {};
        }
      }
      this.__opts__ = assign6({}, defaultOptions4, options2);
      this.__index__ = -1;
      this.__last_index__ = -1;
      this.__schema__ = "";
      this.__text_cache__ = "";
      this.__schemas__ = assign6({}, defaultSchemas2, schemas2);
      this.__compiled__ = {};
      this.__tlds__ = tlds_default2;
      this.__tlds_replaced__ = false;
      this.re = {};
      compile2(this);
    }
    LinkifyIt2.prototype.add = function add4(schema7, definition) {
      this.__schemas__[schema7] = definition;
      compile2(this);
      return this;
    };
    LinkifyIt2.prototype.set = function set4(options2) {
      this.__opts__ = assign6(this.__opts__, options2);
      return this;
    };
    LinkifyIt2.prototype.test = function test2(text3) {
      this.__text_cache__ = text3;
      this.__index__ = -1;
      if (!text3.length) {
        return false;
      }
      var m3, ml, me, len, shift2, next2, re2, tld_pos, at_pos;
      if (this.re.schema_test.test(text3)) {
        re2 = this.re.schema_search;
        re2.lastIndex = 0;
        while ((m3 = re2.exec(text3)) !== null) {
          len = this.testSchemaAt(text3, m3[2], re2.lastIndex);
          if (len) {
            this.__schema__ = m3[2];
            this.__index__ = m3.index + m3[1].length;
            this.__last_index__ = m3.index + m3[0].length + len;
            break;
          }
        }
      }
      if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
        tld_pos = text3.search(this.re.host_fuzzy_test);
        if (tld_pos >= 0) {
          if (this.__index__ < 0 || tld_pos < this.__index__) {
            if ((ml = text3.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
              shift2 = ml.index + ml[1].length;
              if (this.__index__ < 0 || shift2 < this.__index__) {
                this.__schema__ = "";
                this.__index__ = shift2;
                this.__last_index__ = ml.index + ml[0].length;
              }
            }
          }
        }
      }
      if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
        at_pos = text3.indexOf("@");
        if (at_pos >= 0) {
          if ((me = text3.match(this.re.email_fuzzy)) !== null) {
            shift2 = me.index + me[1].length;
            next2 = me.index + me[0].length;
            if (this.__index__ < 0 || shift2 < this.__index__ || shift2 === this.__index__ && next2 > this.__last_index__) {
              this.__schema__ = "mailto:";
              this.__index__ = shift2;
              this.__last_index__ = next2;
            }
          }
        }
      }
      return this.__index__ >= 0;
    };
    LinkifyIt2.prototype.pretest = function pretest2(text3) {
      return this.re.pretest.test(text3);
    };
    LinkifyIt2.prototype.testSchemaAt = function testSchemaAt2(text3, schema7, pos) {
      if (!this.__compiled__[schema7.toLowerCase()]) {
        return 0;
      }
      return this.__compiled__[schema7.toLowerCase()].validate(text3, pos, this);
    };
    LinkifyIt2.prototype.match = function match2(text3) {
      var shift2 = 0, result2 = [];
      if (this.__index__ >= 0 && this.__text_cache__ === text3) {
        result2.push(createMatch2(this, shift2));
        shift2 = this.__last_index__;
      }
      var tail = shift2 ? text3.slice(shift2) : text3;
      while (this.test(tail)) {
        result2.push(createMatch2(this, shift2));
        tail = tail.slice(this.__last_index__);
        shift2 += this.__last_index__;
      }
      if (result2.length) {
        return result2;
      }
      return null;
    };
    LinkifyIt2.prototype.matchAtStart = function matchAtStart2(text3) {
      this.__text_cache__ = text3;
      this.__index__ = -1;
      if (!text3.length) return null;
      var m3 = this.re.schema_at_start.exec(text3);
      if (!m3) return null;
      var len = this.testSchemaAt(text3, m3[2], m3[0].length);
      if (!len) return null;
      this.__schema__ = m3[2];
      this.__index__ = m3.index + m3[1].length;
      this.__last_index__ = m3.index + m3[0].length + len;
      return createMatch2(this, 0);
    };
    LinkifyIt2.prototype.tlds = function tlds2(list2, keepOld) {
      list2 = Array.isArray(list2) ? list2 : [list2];
      if (!keepOld) {
        this.__tlds__ = list2.slice();
        this.__tlds_replaced__ = true;
        compile2(this);
        return this;
      }
      this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el2, idx, arr) {
        return el2 !== arr[idx - 1];
      }).reverse();
      compile2(this);
      return this;
    };
    LinkifyIt2.prototype.normalize = function normalize5(match2) {
      if (!match2.schema) {
        match2.url = "http://" + match2.url;
      }
      if (match2.schema === "mailto:" && !/^mailto:/i.test(match2.url)) {
        match2.url = "mailto:" + match2.url;
      }
    };
    LinkifyIt2.prototype.onCompile = function onCompile2() {
    };
    module.exports = LinkifyIt2;
  }
});

// node_modules/punycode/punycode.js
var require_punycode = __commonJS({
  "node_modules/punycode/punycode.js"(exports, module) {
    "use strict";
    var maxInt2 = 2147483647;
    var base3 = 36;
    var tMin2 = 1;
    var tMax2 = 26;
    var skew2 = 38;
    var damp2 = 700;
    var initialBias2 = 72;
    var initialN2 = 128;
    var delimiter2 = "-";
    var regexPunycode2 = /^xn--/;
    var regexNonASCII2 = /[^\0-\x7E]/;
    var regexSeparators2 = /[\x2E\u3002\uFF0E\uFF61]/g;
    var errors3 = {
      "overflow": "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    };
    var baseMinusTMin2 = base3 - tMin2;
    var floor2 = Math.floor;
    var stringFromCharCode2 = String.fromCharCode;
    function error2(type) {
      throw new RangeError(errors3[type]);
    }
    function map5(array, fn) {
      const result2 = [];
      let length = array.length;
      while (length--) {
        result2[length] = fn(array[length]);
      }
      return result2;
    }
    function mapDomain2(string3, fn) {
      const parts = string3.split("@");
      let result2 = "";
      if (parts.length > 1) {
        result2 = parts[0] + "@";
        string3 = parts[1];
      }
      string3 = string3.replace(regexSeparators2, ".");
      const labels = string3.split(".");
      const encoded = map5(labels, fn).join(".");
      return result2 + encoded;
    }
    function ucs2decode3(string3) {
      const output = [];
      let counter3 = 0;
      const length = string3.length;
      while (counter3 < length) {
        const value2 = string3.charCodeAt(counter3++);
        if (value2 >= 55296 && value2 <= 56319 && counter3 < length) {
          const extra = string3.charCodeAt(counter3++);
          if ((extra & 64512) == 56320) {
            output.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
          } else {
            output.push(value2);
            counter3--;
          }
        } else {
          output.push(value2);
        }
      }
      return output;
    }
    var ucs2encode2 = (array) => String.fromCodePoint(...array);
    var basicToDigit2 = function(codePoint) {
      if (codePoint - 48 < 10) {
        return codePoint - 22;
      }
      if (codePoint - 65 < 26) {
        return codePoint - 65;
      }
      if (codePoint - 97 < 26) {
        return codePoint - 97;
      }
      return base3;
    };
    var digitToBasic2 = function(digit, flag) {
      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
    };
    var adapt2 = function(delta, numPoints, firstTime) {
      let k2 = 0;
      delta = firstTime ? floor2(delta / damp2) : delta >> 1;
      delta += floor2(delta / numPoints);
      for (; delta > baseMinusTMin2 * tMax2 >> 1; k2 += base3) {
        delta = floor2(delta / baseMinusTMin2);
      }
      return floor2(k2 + (baseMinusTMin2 + 1) * delta / (delta + skew2));
    };
    var decode3 = function(input) {
      const output = [];
      const inputLength = input.length;
      let i3 = 0;
      let n4 = initialN2;
      let bias = initialBias2;
      let basic = input.lastIndexOf(delimiter2);
      if (basic < 0) {
        basic = 0;
      }
      for (let j = 0; j < basic; ++j) {
        if (input.charCodeAt(j) >= 128) {
          error2("not-basic");
        }
        output.push(input.charCodeAt(j));
      }
      for (let index2 = basic > 0 ? basic + 1 : 0; index2 < inputLength; ) {
        let oldi = i3;
        for (let w3 = 1, k2 = base3; ; k2 += base3) {
          if (index2 >= inputLength) {
            error2("invalid-input");
          }
          const digit = basicToDigit2(input.charCodeAt(index2++));
          if (digit >= base3 || digit > floor2((maxInt2 - i3) / w3)) {
            error2("overflow");
          }
          i3 += digit * w3;
          const t3 = k2 <= bias ? tMin2 : k2 >= bias + tMax2 ? tMax2 : k2 - bias;
          if (digit < t3) {
            break;
          }
          const baseMinusT = base3 - t3;
          if (w3 > floor2(maxInt2 / baseMinusT)) {
            error2("overflow");
          }
          w3 *= baseMinusT;
        }
        const out = output.length + 1;
        bias = adapt2(i3 - oldi, out, oldi == 0);
        if (floor2(i3 / out) > maxInt2 - n4) {
          error2("overflow");
        }
        n4 += floor2(i3 / out);
        i3 %= out;
        output.splice(i3++, 0, n4);
      }
      return String.fromCodePoint(...output);
    };
    var encode3 = function(input) {
      const output = [];
      input = ucs2decode3(input);
      let inputLength = input.length;
      let n4 = initialN2;
      let delta = 0;
      let bias = initialBias2;
      for (const currentValue of input) {
        if (currentValue < 128) {
          output.push(stringFromCharCode2(currentValue));
        }
      }
      let basicLength = output.length;
      let handledCPCount = basicLength;
      if (basicLength) {
        output.push(delimiter2);
      }
      while (handledCPCount < inputLength) {
        let m3 = maxInt2;
        for (const currentValue of input) {
          if (currentValue >= n4 && currentValue < m3) {
            m3 = currentValue;
          }
        }
        const handledCPCountPlusOne = handledCPCount + 1;
        if (m3 - n4 > floor2((maxInt2 - delta) / handledCPCountPlusOne)) {
          error2("overflow");
        }
        delta += (m3 - n4) * handledCPCountPlusOne;
        n4 = m3;
        for (const currentValue of input) {
          if (currentValue < n4 && ++delta > maxInt2) {
            error2("overflow");
          }
          if (currentValue == n4) {
            let q = delta;
            for (let k2 = base3; ; k2 += base3) {
              const t3 = k2 <= bias ? tMin2 : k2 >= bias + tMax2 ? tMax2 : k2 - bias;
              if (q < t3) {
                break;
              }
              const qMinusT = q - t3;
              const baseMinusT = base3 - t3;
              output.push(
                stringFromCharCode2(digitToBasic2(t3 + qMinusT % baseMinusT, 0))
              );
              q = floor2(qMinusT / baseMinusT);
            }
            output.push(stringFromCharCode2(digitToBasic2(q, 0)));
            bias = adapt2(delta, handledCPCountPlusOne, handledCPCount == basicLength);
            delta = 0;
            ++handledCPCount;
          }
        }
        ++delta;
        ++n4;
      }
      return output.join("");
    };
    var toUnicode2 = function(input) {
      return mapDomain2(input, function(string3) {
        return regexPunycode2.test(string3) ? decode3(string3.slice(4).toLowerCase()) : string3;
      });
    };
    var toASCII2 = function(input) {
      return mapDomain2(input, function(string3) {
        return regexNonASCII2.test(string3) ? "xn--" + encode3(string3) : string3;
      });
    };
    var punycode2 = {
      /**
       * A string representing the current Punycode.js version number.
       * @memberOf punycode
       * @type String
       */
      "version": "2.1.0",
      /**
       * An object of methods to convert from JavaScript's internal character
       * representation (UCS-2) to Unicode code points, and back.
       * @see <https://mathiasbynens.be/notes/javascript-encoding>
       * @memberOf punycode
       * @type Object
       */
      "ucs2": {
        "decode": ucs2decode3,
        "encode": ucs2encode2
      },
      "decode": decode3,
      "encode": encode3,
      "toASCII": toASCII2,
      "toUnicode": toUnicode2
    };
    module.exports = punycode2;
  }
});

// node_modules/markdown-it/lib/presets/default.js
var require_default = __commonJS({
  "node_modules/markdown-it/lib/presets/default.js"(exports, module) {
    "use strict";
    module.exports = {
      options: {
        html: false,
        // Enable HTML tags in source
        xhtmlOut: false,
        // Use '/' to close single tags (<br />)
        breaks: false,
        // Convert '\n' in paragraphs into <br>
        langPrefix: "language-",
        // CSS language prefix for fenced blocks
        linkify: false,
        // autoconvert URL-like texts to links
        // Enable some language-neutral replacements + quotes beautification
        typographer: false,
        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: "\u201C\u201D\u2018\u2019",
        /* “”‘’ */
        // Highlighter function. Should return escaped HTML,
        // or '' if the source string is not changed and should be escaped externaly.
        // If result starts with <pre... internal wrapper is skipped.
        //
        // function (/*str, lang*/) { return ''; }
        //
        highlight: null,
        maxNesting: 100
        // Internal protection, recursion limit
      },
      components: {
        core: {},
        block: {},
        inline: {}
      }
    };
  }
});

// node_modules/markdown-it/lib/presets/zero.js
var require_zero = __commonJS({
  "node_modules/markdown-it/lib/presets/zero.js"(exports, module) {
    "use strict";
    module.exports = {
      options: {
        html: false,
        // Enable HTML tags in source
        xhtmlOut: false,
        // Use '/' to close single tags (<br />)
        breaks: false,
        // Convert '\n' in paragraphs into <br>
        langPrefix: "language-",
        // CSS language prefix for fenced blocks
        linkify: false,
        // autoconvert URL-like texts to links
        // Enable some language-neutral replacements + quotes beautification
        typographer: false,
        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: "\u201C\u201D\u2018\u2019",
        /* “”‘’ */
        // Highlighter function. Should return escaped HTML,
        // or '' if the source string is not changed and should be escaped externaly.
        // If result starts with <pre... internal wrapper is skipped.
        //
        // function (/*str, lang*/) { return ''; }
        //
        highlight: null,
        maxNesting: 20
        // Internal protection, recursion limit
      },
      components: {
        core: {
          rules: [
            "normalize",
            "block",
            "inline",
            "text_join"
          ]
        },
        block: {
          rules: [
            "paragraph"
          ]
        },
        inline: {
          rules: [
            "text"
          ],
          rules2: [
            "balance_pairs",
            "fragments_join"
          ]
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/presets/commonmark.js
var require_commonmark = __commonJS({
  "node_modules/markdown-it/lib/presets/commonmark.js"(exports, module) {
    "use strict";
    module.exports = {
      options: {
        html: true,
        // Enable HTML tags in source
        xhtmlOut: true,
        // Use '/' to close single tags (<br />)
        breaks: false,
        // Convert '\n' in paragraphs into <br>
        langPrefix: "language-",
        // CSS language prefix for fenced blocks
        linkify: false,
        // autoconvert URL-like texts to links
        // Enable some language-neutral replacements + quotes beautification
        typographer: false,
        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: "\u201C\u201D\u2018\u2019",
        /* “”‘’ */
        // Highlighter function. Should return escaped HTML,
        // or '' if the source string is not changed and should be escaped externaly.
        // If result starts with <pre... internal wrapper is skipped.
        //
        // function (/*str, lang*/) { return ''; }
        //
        highlight: null,
        maxNesting: 20
        // Internal protection, recursion limit
      },
      components: {
        core: {
          rules: [
            "normalize",
            "block",
            "inline",
            "text_join"
          ]
        },
        block: {
          rules: [
            "blockquote",
            "code",
            "fence",
            "heading",
            "hr",
            "html_block",
            "lheading",
            "list",
            "reference",
            "paragraph"
          ]
        },
        inline: {
          rules: [
            "autolink",
            "backticks",
            "emphasis",
            "entity",
            "escape",
            "html_inline",
            "image",
            "link",
            "newline",
            "text"
          ],
          rules2: [
            "balance_pairs",
            "emphasis",
            "fragments_join"
          ]
        }
      }
    };
  }
});

// node_modules/markdown-it/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/markdown-it/lib/index.js"(exports, module) {
    "use strict";
    var utils = require_utils();
    var helpers2 = require_helpers();
    var Renderer3 = require_renderer();
    var ParserCore = require_parser_core();
    var ParserBlock2 = require_parser_block();
    var ParserInline2 = require_parser_inline();
    var LinkifyIt2 = require_linkify_it();
    var mdurl = require_mdurl();
    var punycode2 = require_punycode();
    var config3 = {
      default: require_default(),
      zero: require_zero(),
      commonmark: require_commonmark()
    };
    var BAD_PROTO_RE2 = /^(vbscript|javascript|file|data):/;
    var GOOD_DATA_RE2 = /^data:image\/(gif|png|jpeg|webp);/;
    function validateLink2(url2) {
      var str = url2.trim().toLowerCase();
      return BAD_PROTO_RE2.test(str) ? GOOD_DATA_RE2.test(str) ? true : false : true;
    }
    var RECODE_HOSTNAME_FOR2 = ["http:", "https:", "mailto:"];
    function normalizeLink2(url2) {
      var parsed = mdurl.parse(url2, true);
      if (parsed.hostname) {
        if (!parsed.protocol || RECODE_HOSTNAME_FOR2.indexOf(parsed.protocol) >= 0) {
          try {
            parsed.hostname = punycode2.toASCII(parsed.hostname);
          } catch (er) {
          }
        }
      }
      return mdurl.encode(mdurl.format(parsed));
    }
    function normalizeLinkText2(url2) {
      var parsed = mdurl.parse(url2, true);
      if (parsed.hostname) {
        if (!parsed.protocol || RECODE_HOSTNAME_FOR2.indexOf(parsed.protocol) >= 0) {
          try {
            parsed.hostname = punycode2.toUnicode(parsed.hostname);
          } catch (er) {
          }
        }
      }
      return mdurl.decode(mdurl.format(parsed), mdurl.decode.defaultChars + "%");
    }
    function MarkdownIt2(presetName, options2) {
      if (!(this instanceof MarkdownIt2)) {
        return new MarkdownIt2(presetName, options2);
      }
      if (!options2) {
        if (!utils.isString(presetName)) {
          options2 = presetName || {};
          presetName = "default";
        }
      }
      this.inline = new ParserInline2();
      this.block = new ParserBlock2();
      this.core = new ParserCore();
      this.renderer = new Renderer3();
      this.linkify = new LinkifyIt2();
      this.validateLink = validateLink2;
      this.normalizeLink = normalizeLink2;
      this.normalizeLinkText = normalizeLinkText2;
      this.utils = utils;
      this.helpers = utils.assign({}, helpers2);
      this.options = {};
      this.configure(presetName);
      if (options2) {
        this.set(options2);
      }
    }
    MarkdownIt2.prototype.set = function(options2) {
      utils.assign(this.options, options2);
      return this;
    };
    MarkdownIt2.prototype.configure = function(presets) {
      var self2 = this, presetName;
      if (utils.isString(presets)) {
        presetName = presets;
        presets = config3[presetName];
        if (!presets) {
          throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
        }
      }
      if (!presets) {
        throw new Error("Wrong `markdown-it` preset, can't be empty");
      }
      if (presets.options) {
        self2.set(presets.options);
      }
      if (presets.components) {
        Object.keys(presets.components).forEach(function(name2) {
          if (presets.components[name2].rules) {
            self2[name2].ruler.enableOnly(presets.components[name2].rules);
          }
          if (presets.components[name2].rules2) {
            self2[name2].ruler2.enableOnly(presets.components[name2].rules2);
          }
        });
      }
      return this;
    };
    MarkdownIt2.prototype.enable = function(list2, ignoreInvalid) {
      var result2 = [];
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      ["core", "block", "inline"].forEach(function(chain3) {
        result2 = result2.concat(this[chain3].ruler.enable(list2, true));
      }, this);
      result2 = result2.concat(this.inline.ruler2.enable(list2, true));
      var missed = list2.filter(function(name2) {
        return result2.indexOf(name2) < 0;
      });
      if (missed.length && !ignoreInvalid) {
        throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
      }
      return this;
    };
    MarkdownIt2.prototype.disable = function(list2, ignoreInvalid) {
      var result2 = [];
      if (!Array.isArray(list2)) {
        list2 = [list2];
      }
      ["core", "block", "inline"].forEach(function(chain3) {
        result2 = result2.concat(this[chain3].ruler.disable(list2, true));
      }, this);
      result2 = result2.concat(this.inline.ruler2.disable(list2, true));
      var missed = list2.filter(function(name2) {
        return result2.indexOf(name2) < 0;
      });
      if (missed.length && !ignoreInvalid) {
        throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
      }
      return this;
    };
    MarkdownIt2.prototype.use = function(plugin) {
      var args = [this].concat(Array.prototype.slice.call(arguments, 1));
      plugin.apply(plugin, args);
      return this;
    };
    MarkdownIt2.prototype.parse = function(src, env) {
      if (typeof src !== "string") {
        throw new Error("Input data should be a String");
      }
      var state = new this.core.State(src, this, env);
      this.core.process(state);
      return state.tokens;
    };
    MarkdownIt2.prototype.render = function(src, env) {
      env = env || {};
      return this.renderer.render(this.parse(src, env), this.options, env);
    };
    MarkdownIt2.prototype.parseInline = function(src, env) {
      var state = new this.core.State(src, this, env);
      state.inlineMode = true;
      this.core.process(state);
      return state.tokens;
    };
    MarkdownIt2.prototype.renderInline = function(src, env) {
      env = env || {};
      return this.renderer.render(this.parseInline(src, env), this.options, env);
    };
    module.exports = MarkdownIt2;
  }
});

// node_modules/markdown-it/index.js
var require_markdown_it = __commonJS({
  "node_modules/markdown-it/index.js"(exports, module) {
    "use strict";
    module.exports = require_lib2();
  }
});

// node_modules/subscription/index.js
var require_subscription = __commonJS({
  "node_modules/subscription/index.js"(exports) {
    function Handler(f3, once, priority) {
      this.f = f3;
      this.once = once;
      this.priority = priority;
    }
    function Subscription2() {
      this.handlers = [];
    }
    exports.Subscription = Subscription2;
    function insert4(s3, handler) {
      var pos = 0;
      for (; pos < s3.handlers.length; pos++)
        if (s3.handlers[pos].priority < handler.priority) break;
      s3.handlers = s3.handlers.slice(0, pos).concat(handler).concat(s3.handlers.slice(pos));
    }
    Subscription2.prototype.handlersForDispatch = function() {
      var handlers3 = this.handlers, updated = null;
      for (var i3 = handlers3.length - 1; i3 >= 0; i3--) if (handlers3[i3].once) {
        if (!updated) updated = handlers3.slice();
        updated.splice(i3, 1);
      }
      if (updated) this.handlers = updated;
      return handlers3;
    };
    Subscription2.prototype.add = function(f3, priority) {
      insert4(this, new Handler(f3, false, priority || 0));
    };
    Subscription2.prototype.addOnce = function(f3, priority) {
      insert4(this, new Handler(f3, true, priority || 0));
    };
    Subscription2.prototype.remove = function(f3) {
      for (var i3 = 0; i3 < this.handlers.length; i3++) if (this.handlers[i3].f == f3) {
        this.handlers = this.handlers.slice(0, i3).concat(this.handlers.slice(i3 + 1));
        return;
      }
    };
    Subscription2.prototype.hasHandler = function() {
      return this.handlers.length > 0;
    };
    Subscription2.prototype.dispatch = function() {
      var handlers3 = this.handlersForDispatch();
      for (var i3 = 0; i3 < handlers3.length; i3++)
        handlers3[i3].f.apply(null, arguments);
    };
    function PipelineSubscription() {
      Subscription2.call(this);
    }
    exports.PipelineSubscription = PipelineSubscription;
    PipelineSubscription.prototype = new Subscription2();
    PipelineSubscription.prototype.dispatch = function(value2) {
      var handlers3 = this.handlersForDispatch();
      for (var i3 = 0; i3 < handlers3.length; i3++)
        value2 = handlers3[i3].f(value2);
      return value2;
    };
    function StoppableSubscription() {
      Subscription2.call(this);
    }
    exports.StoppableSubscription = StoppableSubscription;
    StoppableSubscription.prototype = new Subscription2();
    StoppableSubscription.prototype.dispatch = function() {
      var handlers3 = this.handlersForDispatch();
      for (var i3 = 0; i3 < handlers3.length; i3++) {
        var result2 = handlers3[i3].f.apply(null, arguments);
        if (result2) return result2;
      }
    };
    function DOMSubscription() {
      Subscription2.call(this);
    }
    exports.DOMSubscription = DOMSubscription;
    DOMSubscription.prototype = new Subscription2();
    DOMSubscription.prototype.dispatch = function(event2) {
      var handlers3 = this.handlersForDispatch();
      for (var i3 = 0; i3 < handlers3.length; i3++)
        if (handlers3[i3].f(event2) || event2.defaultPrevented) return true;
      return false;
    };
  }
});

// node_modules/markdown-it-flowdock/dist/unicode.js
var require_unicode = __commonJS({
  "node_modules/markdown-it-flowdock/dist/unicode.js"(exports, module) {
    module.exports = { "tagEnd": "[\\x2D0-9A-Z_a-z\\xAA\\xB2\\xB3\\xB5\\xB9\\xBA\\xBC-\\xBE\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u058A\\u0591-\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09F4-\\u09F9\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71-\\u0B77\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BF2\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C78-\\u0C7E\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D75\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F33\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1369-\\u137C\\u1380-\\u138F\\u13A0-\\u13F4\\u1400-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u17F0-\\u17F9\\u1806\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19DA\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABE\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2010-\\u2015\\u203F\\u2040\\u2054\\u2070\\u2071\\u2074-\\u2079\\u207F-\\u2089\\u2090-\\u209C\\u20D0-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2150-\\u2189\\u2460-\\u249B\\u24EA-\\u24FF\\u2776-\\u2793\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2CFD\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E17\\u2E1A\\u2E2F\\u2E3A\\u2E3B\\u2E40\\u3005-\\u3007\\u301C\\u3021-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u3192-\\u3195\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3220-\\u3229\\u3248-\\u324F\\u3251-\\u325F\\u3280-\\u3289\\u32B1-\\u32BF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA672\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA830-\\uA835\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE31-\\uFE34\\uFE4D-\\uFE4F\\uFE58\\uFE63\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF0D\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDD07-\\uDD33\\uDD40-\\uDD78\\uDD8A\\uDD8B\\uDDFD\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDEE0-\\uDEFB\\uDF00-\\uDF23\\uDF30-\\uDF4A\\uDF50-\\uDF7A\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF\\uDFD1-\\uDFD5]|\\uD801[\\uDC00-\\uDC9D\\uDCA0-\\uDCA9\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC58-\\uDC76\\uDC79-\\uDC9E\\uDCA7-\\uDCAF\\uDD00-\\uDD1B\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE33\\uDE38-\\uDE3A\\uDE3F-\\uDE47\\uDE60-\\uDE7E\\uDE80-\\uDE9F\\uDEC0-\\uDEC7\\uDEC9-\\uDEE6\\uDEEB-\\uDEEF\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF58-\\uDF72\\uDF78-\\uDF91\\uDFA9-\\uDFAF]|\\uD803[\\uDC00-\\uDC48\\uDE60-\\uDE7E]|\\uD804[\\uDC00-\\uDC46\\uDC52-\\uDC6F\\uDC7F-\\uDCBA\\uDCD0-\\uDCE8\\uDCF0-\\uDCF9\\uDD00-\\uDD34\\uDD36-\\uDD3F\\uDD50-\\uDD73\\uDD76\\uDD80-\\uDDC4\\uDDD0-\\uDDDA\\uDDE1-\\uDDF4\\uDE00-\\uDE11\\uDE13-\\uDE37\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF01-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3C-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9]|\\uD806[\\uDCA0-\\uDCF2\\uDCFF\\uDEC0-\\uDEF8]|\\uD808[\\uDC00-\\uDF98]|\\uD809[\\uDC00-\\uDC6E]|[\\uD80C\\uD840-\\uD868\\uD86A-\\uD86C][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF5B-\\uDF61\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50-\\uDF7E\\uDF8F-\\uDF9F]|\\uD82C[\\uDC00\\uDC01]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44\\uDF60-\\uDF71]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB\\uDFCE-\\uDFFF]|\\uD83A[\\uDC00-\\uDCC4\\uDCC7-\\uDCD6]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD83C[\\uDD00-\\uDD0C]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]", "tagCharacter": "[\\x2D\\.0-9A-Z_a-z\\xAA\\xB2\\xB3\\xB5\\xB9\\xBA\\xBC-\\xBE\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u058A\\u0591-\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09F4-\\u09F9\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71-\\u0B77\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BF2\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C78-\\u0C7E\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D75\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F33\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1369-\\u137C\\u1380-\\u138F\\u13A0-\\u13F4\\u1400-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u17F0-\\u17F9\\u1806\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19DA\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABE\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2010-\\u2015\\u203F\\u2040\\u2054\\u2070\\u2071\\u2074-\\u2079\\u207F-\\u2089\\u2090-\\u209C\\u20D0-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2150-\\u2189\\u2460-\\u249B\\u24EA-\\u24FF\\u2776-\\u2793\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2CFD\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E17\\u2E1A\\u2E2F\\u2E3A\\u2E3B\\u2E40\\u3005-\\u3007\\u301C\\u3021-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u3192-\\u3195\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3220-\\u3229\\u3248-\\u324F\\u3251-\\u325F\\u3280-\\u3289\\u32B1-\\u32BF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA672\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA830-\\uA835\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE31-\\uFE34\\uFE4D-\\uFE4F\\uFE58\\uFE63\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF0D\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDD07-\\uDD33\\uDD40-\\uDD78\\uDD8A\\uDD8B\\uDDFD\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDEE0-\\uDEFB\\uDF00-\\uDF23\\uDF30-\\uDF4A\\uDF50-\\uDF7A\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF\\uDFD1-\\uDFD5]|\\uD801[\\uDC00-\\uDC9D\\uDCA0-\\uDCA9\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC58-\\uDC76\\uDC79-\\uDC9E\\uDCA7-\\uDCAF\\uDD00-\\uDD1B\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE33\\uDE38-\\uDE3A\\uDE3F-\\uDE47\\uDE60-\\uDE7E\\uDE80-\\uDE9F\\uDEC0-\\uDEC7\\uDEC9-\\uDEE6\\uDEEB-\\uDEEF\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF58-\\uDF72\\uDF78-\\uDF91\\uDFA9-\\uDFAF]|\\uD803[\\uDC00-\\uDC48\\uDE60-\\uDE7E]|\\uD804[\\uDC00-\\uDC46\\uDC52-\\uDC6F\\uDC7F-\\uDCBA\\uDCD0-\\uDCE8\\uDCF0-\\uDCF9\\uDD00-\\uDD34\\uDD36-\\uDD3F\\uDD50-\\uDD73\\uDD76\\uDD80-\\uDDC4\\uDDD0-\\uDDDA\\uDDE1-\\uDDF4\\uDE00-\\uDE11\\uDE13-\\uDE37\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF01-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3C-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9]|\\uD806[\\uDCA0-\\uDCF2\\uDCFF\\uDEC0-\\uDEF8]|\\uD808[\\uDC00-\\uDF98]|\\uD809[\\uDC00-\\uDC6E]|[\\uD80C\\uD840-\\uD868\\uD86A-\\uD86C][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF5B-\\uDF61\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50-\\uDF7E\\uDF8F-\\uDF9F]|\\uD82C[\\uDC00\\uDC01]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44\\uDF60-\\uDF71]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB\\uDFCE-\\uDFFF]|\\uD83A[\\uDC00-\\uDCC4\\uDCC7-\\uDCD6]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD83C[\\uDD00-\\uDD0C]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]" };
  }
});

// node_modules/markdown-it-flowdock/dist/parser.js
var require_parser = __commonJS({
  "node_modules/markdown-it-flowdock/dist/parser.js"(exports, module) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    var _unicode = require_unicode();
    function not2(group2) {
      return "[^" + group2.slice(1);
    }
    function matcher2(boundary, body3, end) {
      return new RegExp("(?:^|$|" + not2(end) + ")((?:" + boundary + ")(?:" + body3 + ")*(?:" + end + ")+)", "g");
    }
    function split3(currentToken, boundary, regex, Token2, name2) {
      var text3 = currentToken.content;
      var level = currentToken.level;
      var matches3 = text3.match(regex);
      if (matches3 === null) {
        return;
      }
      var nodes2 = [];
      for (var m3 = 0; m3 < matches3.length; m3++) {
        var start = matches3[m3].search(boundary);
        var tagName = matches3[m3].slice(start + 1);
        var pos = text3.indexOf(matches3[m3]) + start;
        if (pos > 0) {
          var _token = new Token2("text", "", 0);
          _token.content = text3.slice(0, pos);
          _token.level = level;
          nodes2.push(_token);
        }
        var token = new Token2(name2, "", 0);
        token.content = tagName;
        token.markup = matches3[m3][start];
        token.level = level;
        nodes2.push(token);
        text3 = text3.slice(pos + 1 + tagName.length);
      }
      if (text3.length > 0) {
        var token = new Token2("text", "", 0);
        token.content = text3;
        token.level = level;
        nodes2.push(token);
      }
      return nodes2;
    }
    exports["default"] = function(md2, name2, boundary) {
      var arrayReplaceAt2 = md2.utils.arrayReplaceAt;
      var regex = matcher2(boundary.source, _unicode.tagCharacter, _unicode.tagEnd);
      return function parser4(state) {
        var blockTokens = state.tokens;
        var tokens;
        for (var j = 0; j < blockTokens.length; j++) {
          if (blockTokens[j].type !== "inline") {
            continue;
          }
          tokens = blockTokens[j].children;
          for (var i3 = tokens.length - 1; i3 >= 0; i3--) {
            var currentToken = tokens[i3];
            if (currentToken.type === "link_close") {
              i3--;
              while (tokens[i3].level !== currentToken.level && tokens[i3].type !== "link_open") {
                i3--;
              }
              continue;
            }
            if (currentToken.type !== "text") {
              continue;
            }
            var nodes2 = split3(currentToken, boundary, regex, state.Token, name2);
            if (nodes2) {
              blockTokens[j].children = tokens = arrayReplaceAt2(tokens, i3, nodes2);
            }
          }
        }
      };
    };
    module.exports = exports["default"];
  }
});

// node_modules/markdown-it-flowdock/dist/hashtag.js
var require_hashtag = __commonJS({
  "node_modules/markdown-it-flowdock/dist/hashtag.js"(exports, module) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _parser = require_parser();
    var _parser2 = _interopRequireDefault(_parser);
    function flowdockHashtag(tokens, idx) {
      var tag = tokens[idx].content;
      var markup = tokens[idx].markup;
      return '<a class="tag">' + markup + tag + "</a>";
    }
    exports["default"] = function(md2, options2) {
      var split3 = "#|\uFF03";
      var hashtag = (0, _parser2["default"])(md2, "hashtag", new RegExp(split3));
      md2.core.ruler.push("hashtag", hashtag);
      md2.renderer.rules.hashtag = flowdockHashtag;
    };
    module.exports = exports["default"];
  }
});

// node_modules/markdown-it-flowdock/dist/mention.js
var require_mention = __commonJS({
  "node_modules/markdown-it-flowdock/dist/mention.js"(exports, module) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _parser = require_parser();
    var _parser2 = _interopRequireDefault(_parser);
    function flowdockMention(tokens, idx) {
      var tag = tokens[idx].content;
      var markup = tokens[idx].markup;
      return '<a class="mention">' + markup + tag + "</a>";
    }
    exports["default"] = function(md2, options2) {
      var split3 = "@|\uFF20";
      var mention = (0, _parser2["default"])(md2, "mention", new RegExp(split3));
      md2.core.ruler.push("mention", mention);
      md2.renderer.rules.mention = flowdockMention;
    };
    module.exports = exports["default"];
  }
});

// node_modules/markdown-it-flowdock/dist/url.js
var require_url = __commonJS({
  "node_modules/markdown-it-flowdock/dist/url.js"(exports, module) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    function fixUrlsEndingInAParen(_x) {
      var _again = true;
      _function: while (_again) {
        var canidate = _x;
        _again = false;
        var matches3 = canidate.match(/(\(<[^>]+>\))|<([^>]+)>\)/);
        if (matches3 !== void 0 && matches3 !== null) {
          var brokenLink = matches3[2];
          if (brokenLink !== void 0 && brokenLink !== null) {
            var fixedCanidate = canidate.replace("<" + matches3[2] + ">)", "<" + matches3[2] + ")>");
            _x = fixedCanidate;
            _again = true;
            matches3 = brokenLink = fixedCanidate = void 0;
            continue _function;
          }
        }
        return canidate;
      }
    }
    function replaceUrlTextWithAutoLinkUrl(text3) {
      var urlMatcher = /([\x2D\.:_a-z\u017F\u212A]+:\/\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u180D\u180F-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+[0-9A-JL-RT-Z_a-z]\x2D?\/?)/ig;
      var firstPass = text3.replace(urlMatcher, "<$1>");
      return fixUrlsEndingInAParen(firstPass).replace(/(<_([^>]+)_>)/, "_[$2]($2)_").replace(/\[([^\]]+)\]\(<([^>]+)>\)/, "[$1]($2)").replace(/<(onenote:[^>]+)>/, "[$1]($1)").replace(/<<([^>]+)>>/ig, "<$1>");
    }
    function dealWithCodeBlock(text3) {
      var startOfCodeBlock = text3.indexOf("`");
      if (startOfCodeBlock === -1) {
        return replaceUrlTextWithAutoLinkUrl(text3);
      }
      var frontPart = text3.slice(0, startOfCodeBlock);
      var nextCodeBlockMarker = text3.indexOf("`", startOfCodeBlock + 1);
      var endOfCodeBlock = nextCodeBlockMarker === -1 ? text3.length : nextCodeBlockMarker + 1;
      var codeBlock = text3.slice(startOfCodeBlock, endOfCodeBlock);
      return replaceUrlTextWithAutoLinkUrl(frontPart) + codeBlock + dealWithCodeBlock(text3.slice(endOfCodeBlock));
    }
    function flowdockUrl(state) {
      var tokens = state.tokens;
      for (var i3 = 0; i3 < tokens.length; i3++) {
        var token = tokens[i3];
        if (token.type !== "inline") {
          continue;
        }
        token.content = dealWithCodeBlock(token.content);
      }
    }
    exports["default"] = function(md2, options2) {
      md2.core.ruler.after("block", "flowdock-url", flowdockUrl);
    };
    module.exports = exports["default"];
  }
});

// node_modules/markdown-it-flowdock/dist/index.js
var require_dist2 = __commonJS({
  "node_modules/markdown-it-flowdock/dist/index.js"(exports, module) {
    "use strict";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }
    var _hashtag = require_hashtag();
    var _hashtag2 = _interopRequireDefault(_hashtag);
    var _mention = require_mention();
    var _mention2 = _interopRequireDefault(_mention);
    var _url = require_url();
    var _url2 = _interopRequireDefault(_url);
    exports["default"] = function(md2, options2) {
      (0, _hashtag2["default"])(md2, options2);
      (0, _mention2["default"])(md2, options2);
      (0, _url2["default"])(md2, options2);
    };
    module.exports = exports["default"];
  }
});

// node_modules/solid-js/dist/solid.js
var sharedConfig = {
  context: void 0,
  registry: void 0
};
function setHydrateContext(context) {
  sharedConfig.context = context;
}
function nextHydrateContext() {
  return {
    ...sharedConfig.context,
    id: `${sharedConfig.context.id}${sharedConfig.context.count++}-`,
    count: 0
  };
}
var equalFn = (a3, b3) => a3 === b3;
var $PROXY = Symbol("solid-proxy");
var $TRACK = Symbol("solid-track");
var $DEVCOMP = Symbol("solid-dev-component");
var signalOptions = {
  equals: equalFn
};
var ERROR = null;
var runEffects = runQueue;
var STALE = 1;
var PENDING = 2;
var UNOWNED = {
  owned: null,
  cleanups: null,
  context: null,
  owner: null
};
var NO_INIT = {};
var Owner = null;
var Transition = null;
var Scheduler = null;
var ExternalSourceConfig = null;
var Listener = null;
var Updates = null;
var Effects = null;
var ExecCount = 0;
function createRoot(fn, detachedOwner) {
  const listener = Listener, owner = Owner, unowned = fn.length === 0, current = detachedOwner === void 0 ? owner : detachedOwner, root3 = unowned ? UNOWNED : {
    owned: null,
    cleanups: null,
    context: current ? current.context : null,
    owner: current
  }, updateFn = unowned ? fn : () => fn(() => untrack(() => cleanNode(root3)));
  Owner = root3;
  Listener = null;
  try {
    return runUpdates(updateFn, true);
  } finally {
    Listener = listener;
    Owner = owner;
  }
}
function createSignal(value2, options2) {
  options2 = options2 ? Object.assign({}, signalOptions, options2) : signalOptions;
  const s3 = {
    value: value2,
    observers: null,
    observerSlots: null,
    comparator: options2.equals || void 0
  };
  const setter = (value3) => {
    if (typeof value3 === "function") {
      if (Transition && Transition.running && Transition.sources.has(s3)) value3 = value3(s3.tValue);
      else value3 = value3(s3.value);
    }
    return writeSignal(s3, value3);
  };
  return [readSignal.bind(s3), setter];
}
function createComputed(fn, value2, options2) {
  const c3 = createComputation(fn, value2, true, STALE);
  if (Scheduler && Transition && Transition.running) Updates.push(c3);
  else updateComputation(c3);
}
function createRenderEffect(fn, value2, options2) {
  const c3 = createComputation(fn, value2, false, STALE);
  if (Scheduler && Transition && Transition.running) Updates.push(c3);
  else updateComputation(c3);
}
function createEffect(fn, value2, options2) {
  runEffects = runUserEffects;
  const c3 = createComputation(fn, value2, false, STALE), s3 = SuspenseContext && useContext(SuspenseContext);
  if (s3) c3.suspense = s3;
  if (!options2 || !options2.render) c3.user = true;
  Effects ? Effects.push(c3) : updateComputation(c3);
}
function createMemo(fn, value2, options2) {
  options2 = options2 ? Object.assign({}, signalOptions, options2) : signalOptions;
  const c3 = createComputation(fn, value2, true, 0);
  c3.observers = null;
  c3.observerSlots = null;
  c3.comparator = options2.equals || void 0;
  if (Scheduler && Transition && Transition.running) {
    c3.tState = STALE;
    Updates.push(c3);
  } else updateComputation(c3);
  return readSignal.bind(c3);
}
function isPromise(v3) {
  return v3 && typeof v3 === "object" && "then" in v3;
}
function createResource(pSource, pFetcher, pOptions) {
  let source;
  let fetcher;
  let options2;
  if (arguments.length === 2 && typeof pFetcher === "object" || arguments.length === 1) {
    source = true;
    fetcher = pSource;
    options2 = pFetcher || {};
  } else {
    source = pSource;
    fetcher = pFetcher;
    options2 = pOptions || {};
  }
  let pr = null, initP = NO_INIT, id = null, loadedUnderTransition = false, scheduled3 = false, resolved = "initialValue" in options2, dynamic = typeof source === "function" && createMemo(source);
  const contexts = /* @__PURE__ */ new Set(), [value2, setValue2] = (options2.storage || createSignal)(options2.initialValue), [error2, setError2] = createSignal(void 0), [track, trigger2] = createSignal(void 0, {
    equals: false
  }), [state, setState] = createSignal(resolved ? "ready" : "unresolved");
  if (sharedConfig.context) {
    id = `${sharedConfig.context.id}${sharedConfig.context.count++}`;
    let v3;
    if (options2.ssrLoadFrom === "initial") initP = options2.initialValue;
    else if (sharedConfig.load && (v3 = sharedConfig.load(id))) initP = v3;
  }
  function loadEnd(p4, v3, error3, key2) {
    if (pr === p4) {
      pr = null;
      key2 !== void 0 && (resolved = true);
      if ((p4 === initP || v3 === initP) && options2.onHydrated)
        queueMicrotask(
          () => options2.onHydrated(key2, {
            value: v3
          })
        );
      initP = NO_INIT;
      if (Transition && p4 && loadedUnderTransition) {
        Transition.promises.delete(p4);
        loadedUnderTransition = false;
        runUpdates(() => {
          Transition.running = true;
          completeLoad(v3, error3);
        }, false);
      } else completeLoad(v3, error3);
    }
    return v3;
  }
  function completeLoad(v3, err) {
    runUpdates(() => {
      if (err === void 0) setValue2(() => v3);
      setState(err !== void 0 ? "errored" : resolved ? "ready" : "unresolved");
      setError2(err);
      for (const c3 of contexts.keys()) c3.decrement();
      contexts.clear();
    }, false);
  }
  function read() {
    const c3 = SuspenseContext && useContext(SuspenseContext), v3 = value2(), err = error2();
    if (err !== void 0 && !pr) throw err;
    if (Listener && !Listener.user && c3) {
      createComputed(() => {
        track();
        if (pr) {
          if (c3.resolved && Transition && loadedUnderTransition) Transition.promises.add(pr);
          else if (!contexts.has(c3)) {
            c3.increment();
            contexts.add(c3);
          }
        }
      });
    }
    return v3;
  }
  function load2(refetching = true) {
    if (refetching !== false && scheduled3) return;
    scheduled3 = false;
    const lookup = dynamic ? dynamic() : source;
    loadedUnderTransition = Transition && Transition.running;
    if (lookup == null || lookup === false) {
      loadEnd(pr, untrack(value2));
      return;
    }
    if (Transition && pr) Transition.promises.delete(pr);
    const p4 = initP !== NO_INIT ? initP : untrack(
      () => fetcher(lookup, {
        value: value2(),
        refetching
      })
    );
    if (!isPromise(p4)) {
      loadEnd(pr, p4, void 0, lookup);
      return p4;
    }
    pr = p4;
    if ("value" in p4) {
      if (p4.status === "success") loadEnd(pr, p4.value, void 0, lookup);
      else loadEnd(pr, void 0, void 0, lookup);
      return p4;
    }
    scheduled3 = true;
    queueMicrotask(() => scheduled3 = false);
    runUpdates(() => {
      setState(resolved ? "refreshing" : "pending");
      trigger2();
    }, false);
    return p4.then(
      (v3) => loadEnd(p4, v3, void 0, lookup),
      (e3) => loadEnd(p4, void 0, castError(e3), lookup)
    );
  }
  Object.defineProperties(read, {
    state: {
      get: () => state()
    },
    error: {
      get: () => error2()
    },
    loading: {
      get() {
        const s3 = state();
        return s3 === "pending" || s3 === "refreshing";
      }
    },
    latest: {
      get() {
        if (!resolved) return read();
        const err = error2();
        if (err && !pr) throw err;
        return value2();
      }
    }
  });
  if (dynamic) createComputed(() => load2(false));
  else load2(false);
  return [
    read,
    {
      refetch: load2,
      mutate: setValue2
    }
  ];
}
function batch(fn) {
  return runUpdates(fn, false);
}
function untrack(fn) {
  if (!ExternalSourceConfig && Listener === null) return fn();
  const listener = Listener;
  Listener = null;
  try {
    if (ExternalSourceConfig) return ExternalSourceConfig.untrack(fn);
    return fn();
  } finally {
    Listener = listener;
  }
}
function on(deps, fn, options2) {
  const isArray3 = Array.isArray(deps);
  let prevInput;
  let defer2 = options2 && options2.defer;
  return (prevValue) => {
    let input;
    if (isArray3) {
      input = Array(deps.length);
      for (let i3 = 0; i3 < deps.length; i3++) input[i3] = deps[i3]();
    } else input = deps();
    if (defer2) {
      defer2 = false;
      return prevValue;
    }
    const result2 = untrack(() => fn(input, prevInput, prevValue));
    prevInput = input;
    return result2;
  };
}
function onMount(fn) {
  createEffect(() => untrack(fn));
}
function onCleanup(fn) {
  if (Owner === null) ;
  else if (Owner.cleanups === null) Owner.cleanups = [fn];
  else Owner.cleanups.push(fn);
  return fn;
}
function getListener() {
  return Listener;
}
function getOwner() {
  return Owner;
}
function runWithOwner(o3, fn) {
  const prev = Owner;
  const prevListener = Listener;
  Owner = o3;
  Listener = null;
  try {
    return runUpdates(fn, true);
  } catch (err) {
    handleError(err);
  } finally {
    Owner = prev;
    Listener = prevListener;
  }
}
function startTransition(fn) {
  if (Transition && Transition.running) {
    fn();
    return Transition.done;
  }
  const l3 = Listener;
  const o3 = Owner;
  return Promise.resolve().then(() => {
    Listener = l3;
    Owner = o3;
    let t3;
    if (Scheduler || SuspenseContext) {
      t3 = Transition || (Transition = {
        sources: /* @__PURE__ */ new Set(),
        effects: [],
        promises: /* @__PURE__ */ new Set(),
        disposed: /* @__PURE__ */ new Set(),
        queue: /* @__PURE__ */ new Set(),
        running: true
      });
      t3.done || (t3.done = new Promise((res) => t3.resolve = res));
      t3.running = true;
    }
    runUpdates(fn, false);
    Listener = Owner = null;
    return t3 ? t3.done : void 0;
  });
}
var [transPending, setTransPending] = /* @__PURE__ */ createSignal(false);
function useTransition() {
  return [transPending, startTransition];
}
function createContext(defaultValue, options2) {
  const id = Symbol("context");
  return {
    id,
    Provider: createProvider(id),
    defaultValue
  };
}
function useContext(context) {
  return Owner && Owner.context && Owner.context[context.id] !== void 0 ? Owner.context[context.id] : context.defaultValue;
}
function children(fn) {
  const children2 = createMemo(fn);
  const memo = createMemo(() => resolveChildren(children2()));
  memo.toArray = () => {
    const c3 = memo();
    return Array.isArray(c3) ? c3 : c3 != null ? [c3] : [];
  };
  return memo;
}
var SuspenseContext;
function readSignal() {
  const runningTransition = Transition && Transition.running;
  if (this.sources && (runningTransition ? this.tState : this.state)) {
    if ((runningTransition ? this.tState : this.state) === STALE) updateComputation(this);
    else {
      const updates = Updates;
      Updates = null;
      runUpdates(() => lookUpstream(this), false);
      Updates = updates;
    }
  }
  if (Listener) {
    const sSlot = this.observers ? this.observers.length : 0;
    if (!Listener.sources) {
      Listener.sources = [this];
      Listener.sourceSlots = [sSlot];
    } else {
      Listener.sources.push(this);
      Listener.sourceSlots.push(sSlot);
    }
    if (!this.observers) {
      this.observers = [Listener];
      this.observerSlots = [Listener.sources.length - 1];
    } else {
      this.observers.push(Listener);
      this.observerSlots.push(Listener.sources.length - 1);
    }
  }
  if (runningTransition && Transition.sources.has(this)) return this.tValue;
  return this.value;
}
function writeSignal(node, value2, isComp) {
  let current = Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value;
  if (!node.comparator || !node.comparator(current, value2)) {
    if (Transition) {
      const TransitionRunning = Transition.running;
      if (TransitionRunning || !isComp && Transition.sources.has(node)) {
        Transition.sources.add(node);
        node.tValue = value2;
      }
      if (!TransitionRunning) node.value = value2;
    } else node.value = value2;
    if (node.observers && node.observers.length) {
      runUpdates(() => {
        for (let i3 = 0; i3 < node.observers.length; i3 += 1) {
          const o3 = node.observers[i3];
          const TransitionRunning = Transition && Transition.running;
          if (TransitionRunning && Transition.disposed.has(o3)) continue;
          if (TransitionRunning ? !o3.tState : !o3.state) {
            if (o3.pure) Updates.push(o3);
            else Effects.push(o3);
            if (o3.observers) markDownstream(o3);
          }
          if (!TransitionRunning) o3.state = STALE;
          else o3.tState = STALE;
        }
        if (Updates.length > 1e6) {
          Updates = [];
          if (false) ;
          throw new Error();
        }
      }, false);
    }
  }
  return value2;
}
function updateComputation(node) {
  if (!node.fn) return;
  cleanNode(node);
  const time3 = ExecCount;
  runComputation(
    node,
    Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value,
    time3
  );
  if (Transition && !Transition.running && Transition.sources.has(node)) {
    queueMicrotask(() => {
      runUpdates(() => {
        Transition && (Transition.running = true);
        Listener = Owner = node;
        runComputation(node, node.tValue, time3);
        Listener = Owner = null;
      }, false);
    });
  }
}
function runComputation(node, value2, time3) {
  let nextValue;
  const owner = Owner, listener = Listener;
  Listener = Owner = node;
  try {
    nextValue = node.fn(value2);
  } catch (err) {
    if (node.pure) {
      if (Transition && Transition.running) {
        node.tState = STALE;
        node.tOwned && node.tOwned.forEach(cleanNode);
        node.tOwned = void 0;
      } else {
        node.state = STALE;
        node.owned && node.owned.forEach(cleanNode);
        node.owned = null;
      }
    }
    node.updatedAt = time3 + 1;
    return handleError(err);
  } finally {
    Listener = listener;
    Owner = owner;
  }
  if (!node.updatedAt || node.updatedAt <= time3) {
    if (node.updatedAt != null && "observers" in node) {
      writeSignal(node, nextValue, true);
    } else if (Transition && Transition.running && node.pure) {
      Transition.sources.add(node);
      node.tValue = nextValue;
    } else node.value = nextValue;
    node.updatedAt = time3;
  }
}
function createComputation(fn, init, pure, state = STALE, options2) {
  const c3 = {
    fn,
    state,
    updatedAt: null,
    owned: null,
    sources: null,
    sourceSlots: null,
    cleanups: null,
    value: init,
    owner: Owner,
    context: Owner ? Owner.context : null,
    pure
  };
  if (Transition && Transition.running) {
    c3.state = 0;
    c3.tState = state;
  }
  if (Owner === null) ;
  else if (Owner !== UNOWNED) {
    if (Transition && Transition.running && Owner.pure) {
      if (!Owner.tOwned) Owner.tOwned = [c3];
      else Owner.tOwned.push(c3);
    } else {
      if (!Owner.owned) Owner.owned = [c3];
      else Owner.owned.push(c3);
    }
  }
  if (ExternalSourceConfig && c3.fn) {
    const [track, trigger2] = createSignal(void 0, {
      equals: false
    });
    const ordinary = ExternalSourceConfig.factory(c3.fn, trigger2);
    onCleanup(() => ordinary.dispose());
    const triggerInTransition = () => startTransition(trigger2).then(() => inTransition.dispose());
    const inTransition = ExternalSourceConfig.factory(c3.fn, triggerInTransition);
    c3.fn = (x3) => {
      track();
      return Transition && Transition.running ? inTransition.track(x3) : ordinary.track(x3);
    };
  }
  return c3;
}
function runTop(node) {
  const runningTransition = Transition && Transition.running;
  if ((runningTransition ? node.tState : node.state) === 0) return;
  if ((runningTransition ? node.tState : node.state) === PENDING) return lookUpstream(node);
  if (node.suspense && untrack(node.suspense.inFallback)) return node.suspense.effects.push(node);
  const ancestors = [node];
  while ((node = node.owner) && (!node.updatedAt || node.updatedAt < ExecCount)) {
    if (runningTransition && Transition.disposed.has(node)) return;
    if (runningTransition ? node.tState : node.state) ancestors.push(node);
  }
  for (let i3 = ancestors.length - 1; i3 >= 0; i3--) {
    node = ancestors[i3];
    if (runningTransition) {
      let top2 = node, prev = ancestors[i3 + 1];
      while ((top2 = top2.owner) && top2 !== prev) {
        if (Transition.disposed.has(top2)) return;
      }
    }
    if ((runningTransition ? node.tState : node.state) === STALE) {
      updateComputation(node);
    } else if ((runningTransition ? node.tState : node.state) === PENDING) {
      const updates = Updates;
      Updates = null;
      runUpdates(() => lookUpstream(node, ancestors[0]), false);
      Updates = updates;
    }
  }
}
function runUpdates(fn, init) {
  if (Updates) return fn();
  let wait = false;
  if (!init) Updates = [];
  if (Effects) wait = true;
  else Effects = [];
  ExecCount++;
  try {
    const res = fn();
    completeUpdates(wait);
    return res;
  } catch (err) {
    if (!wait) Effects = null;
    Updates = null;
    handleError(err);
  }
}
function completeUpdates(wait) {
  if (Updates) {
    if (Scheduler && Transition && Transition.running) scheduleQueue(Updates);
    else runQueue(Updates);
    Updates = null;
  }
  if (wait) return;
  let res;
  if (Transition) {
    if (!Transition.promises.size && !Transition.queue.size) {
      const sources = Transition.sources;
      const disposed = Transition.disposed;
      Effects.push.apply(Effects, Transition.effects);
      res = Transition.resolve;
      for (const e4 of Effects) {
        "tState" in e4 && (e4.state = e4.tState);
        delete e4.tState;
      }
      Transition = null;
      runUpdates(() => {
        for (const d3 of disposed) cleanNode(d3);
        for (const v3 of sources) {
          v3.value = v3.tValue;
          if (v3.owned) {
            for (let i3 = 0, len = v3.owned.length; i3 < len; i3++) cleanNode(v3.owned[i3]);
          }
          if (v3.tOwned) v3.owned = v3.tOwned;
          delete v3.tValue;
          delete v3.tOwned;
          v3.tState = 0;
        }
        setTransPending(false);
      }, false);
    } else if (Transition.running) {
      Transition.running = false;
      Transition.effects.push.apply(Transition.effects, Effects);
      Effects = null;
      setTransPending(true);
      return;
    }
  }
  const e3 = Effects;
  Effects = null;
  if (e3.length) runUpdates(() => runEffects(e3), false);
  if (res) res();
}
function runQueue(queue2) {
  for (let i3 = 0; i3 < queue2.length; i3++) runTop(queue2[i3]);
}
function scheduleQueue(queue2) {
  for (let i3 = 0; i3 < queue2.length; i3++) {
    const item = queue2[i3];
    const tasks = Transition.queue;
    if (!tasks.has(item)) {
      tasks.add(item);
      Scheduler(() => {
        tasks.delete(item);
        runUpdates(() => {
          Transition.running = true;
          runTop(item);
        }, false);
        Transition && (Transition.running = false);
      });
    }
  }
}
function runUserEffects(queue2) {
  let i3, userLength = 0;
  for (i3 = 0; i3 < queue2.length; i3++) {
    const e3 = queue2[i3];
    if (!e3.user) runTop(e3);
    else queue2[userLength++] = e3;
  }
  if (sharedConfig.context) {
    if (sharedConfig.count) {
      sharedConfig.effects || (sharedConfig.effects = []);
      sharedConfig.effects.push(...queue2.slice(0, userLength));
      return;
    } else if (sharedConfig.effects) {
      queue2 = [...sharedConfig.effects, ...queue2];
      userLength += sharedConfig.effects.length;
      delete sharedConfig.effects;
    }
    setHydrateContext();
  }
  for (i3 = 0; i3 < userLength; i3++) runTop(queue2[i3]);
}
function lookUpstream(node, ignore) {
  const runningTransition = Transition && Transition.running;
  if (runningTransition) node.tState = 0;
  else node.state = 0;
  for (let i3 = 0; i3 < node.sources.length; i3 += 1) {
    const source = node.sources[i3];
    if (source.sources) {
      const state = runningTransition ? source.tState : source.state;
      if (state === STALE) {
        if (source !== ignore && (!source.updatedAt || source.updatedAt < ExecCount))
          runTop(source);
      } else if (state === PENDING) lookUpstream(source, ignore);
    }
  }
}
function markDownstream(node) {
  const runningTransition = Transition && Transition.running;
  for (let i3 = 0; i3 < node.observers.length; i3 += 1) {
    const o3 = node.observers[i3];
    if (runningTransition ? !o3.tState : !o3.state) {
      if (runningTransition) o3.tState = PENDING;
      else o3.state = PENDING;
      if (o3.pure) Updates.push(o3);
      else Effects.push(o3);
      o3.observers && markDownstream(o3);
    }
  }
}
function cleanNode(node) {
  let i3;
  if (node.sources) {
    while (node.sources.length) {
      const source = node.sources.pop(), index2 = node.sourceSlots.pop(), obs = source.observers;
      if (obs && obs.length) {
        const n4 = obs.pop(), s3 = source.observerSlots.pop();
        if (index2 < obs.length) {
          n4.sourceSlots[s3] = index2;
          obs[index2] = n4;
          source.observerSlots[index2] = s3;
        }
      }
    }
  }
  if (Transition && Transition.running && node.pure) {
    if (node.tOwned) {
      for (i3 = node.tOwned.length - 1; i3 >= 0; i3--) cleanNode(node.tOwned[i3]);
      delete node.tOwned;
    }
    reset(node, true);
  } else if (node.owned) {
    for (i3 = node.owned.length - 1; i3 >= 0; i3--) cleanNode(node.owned[i3]);
    node.owned = null;
  }
  if (node.cleanups) {
    for (i3 = node.cleanups.length - 1; i3 >= 0; i3--) node.cleanups[i3]();
    node.cleanups = null;
  }
  if (Transition && Transition.running) node.tState = 0;
  else node.state = 0;
}
function reset(node, top2) {
  if (!top2) {
    node.tState = 0;
    Transition.disposed.add(node);
  }
  if (node.owned) {
    for (let i3 = 0; i3 < node.owned.length; i3++) reset(node.owned[i3]);
  }
}
function castError(err) {
  if (err instanceof Error) return err;
  return new Error(typeof err === "string" ? err : "Unknown error", {
    cause: err
  });
}
function runErrors(err, fns, owner) {
  try {
    for (const f3 of fns) f3(err);
  } catch (e3) {
    handleError(e3, owner && owner.owner || null);
  }
}
function handleError(err, owner = Owner) {
  const fns = ERROR && owner && owner.context && owner.context[ERROR];
  const error2 = castError(err);
  if (!fns) throw error2;
  if (Effects)
    Effects.push({
      fn() {
        runErrors(error2, fns, owner);
      },
      state: STALE
    });
  else runErrors(error2, fns, owner);
}
function resolveChildren(children2) {
  if (typeof children2 === "function" && !children2.length) return resolveChildren(children2());
  if (Array.isArray(children2)) {
    const results2 = [];
    for (let i3 = 0; i3 < children2.length; i3++) {
      const result2 = resolveChildren(children2[i3]);
      Array.isArray(result2) ? results2.push.apply(results2, result2) : results2.push(result2);
    }
    return results2;
  }
  return children2;
}
function createProvider(id, options2) {
  return function provider(props2) {
    let res;
    createRenderEffect(
      () => res = untrack(() => {
        Owner.context = {
          ...Owner.context,
          [id]: props2.value
        };
        return children(() => props2.children);
      }),
      void 0
    );
    return res;
  };
}
var FALLBACK = Symbol("fallback");
function dispose(d3) {
  for (let i3 = 0; i3 < d3.length; i3++) d3[i3]();
}
function mapArray(list2, mapFn, options2 = {}) {
  let items = [], mapped = [], disposers = [], len = 0, indexes = mapFn.length > 1 ? [] : null;
  onCleanup(() => dispose(disposers));
  return () => {
    let newItems = list2() || [], i3, j;
    newItems[$TRACK];
    return untrack(() => {
      let newLen = newItems.length, newIndices, newIndicesNext, temp, tempdisposers, tempIndexes, start, end, newEnd, item;
      if (newLen === 0) {
        if (len !== 0) {
          dispose(disposers);
          disposers = [];
          items = [];
          mapped = [];
          len = 0;
          indexes && (indexes = []);
        }
        if (options2.fallback) {
          items = [FALLBACK];
          mapped[0] = createRoot((disposer) => {
            disposers[0] = disposer;
            return options2.fallback();
          });
          len = 1;
        }
      } else if (len === 0) {
        mapped = new Array(newLen);
        for (j = 0; j < newLen; j++) {
          items[j] = newItems[j];
          mapped[j] = createRoot(mapper);
        }
        len = newLen;
      } else {
        temp = new Array(newLen);
        tempdisposers = new Array(newLen);
        indexes && (tempIndexes = new Array(newLen));
        for (start = 0, end = Math.min(len, newLen); start < end && items[start] === newItems[start]; start++) ;
        for (end = len - 1, newEnd = newLen - 1; end >= start && newEnd >= start && items[end] === newItems[newEnd]; end--, newEnd--) {
          temp[newEnd] = mapped[end];
          tempdisposers[newEnd] = disposers[end];
          indexes && (tempIndexes[newEnd] = indexes[end]);
        }
        newIndices = /* @__PURE__ */ new Map();
        newIndicesNext = new Array(newEnd + 1);
        for (j = newEnd; j >= start; j--) {
          item = newItems[j];
          i3 = newIndices.get(item);
          newIndicesNext[j] = i3 === void 0 ? -1 : i3;
          newIndices.set(item, j);
        }
        for (i3 = start; i3 <= end; i3++) {
          item = items[i3];
          j = newIndices.get(item);
          if (j !== void 0 && j !== -1) {
            temp[j] = mapped[i3];
            tempdisposers[j] = disposers[i3];
            indexes && (tempIndexes[j] = indexes[i3]);
            j = newIndicesNext[j];
            newIndices.set(item, j);
          } else disposers[i3]();
        }
        for (j = start; j < newLen; j++) {
          if (j in temp) {
            mapped[j] = temp[j];
            disposers[j] = tempdisposers[j];
            if (indexes) {
              indexes[j] = tempIndexes[j];
              indexes[j](j);
            }
          } else mapped[j] = createRoot(mapper);
        }
        mapped = mapped.slice(0, len = newLen);
        items = newItems.slice(0);
      }
      return mapped;
    });
    function mapper(disposer) {
      disposers[j] = disposer;
      if (indexes) {
        const [s3, set4] = createSignal(j);
        indexes[j] = set4;
        return mapFn(newItems[j], s3);
      }
      return mapFn(newItems[j]);
    }
  };
}
function indexArray(list2, mapFn, options2 = {}) {
  let items = [], mapped = [], disposers = [], signals = [], len = 0, i3;
  onCleanup(() => dispose(disposers));
  return () => {
    const newItems = list2() || [];
    newItems[$TRACK];
    return untrack(() => {
      if (newItems.length === 0) {
        if (len !== 0) {
          dispose(disposers);
          disposers = [];
          items = [];
          mapped = [];
          len = 0;
          signals = [];
        }
        if (options2.fallback) {
          items = [FALLBACK];
          mapped[0] = createRoot((disposer) => {
            disposers[0] = disposer;
            return options2.fallback();
          });
          len = 1;
        }
        return mapped;
      }
      if (items[0] === FALLBACK) {
        disposers[0]();
        disposers = [];
        items = [];
        mapped = [];
        len = 0;
      }
      for (i3 = 0; i3 < newItems.length; i3++) {
        if (i3 < items.length && items[i3] !== newItems[i3]) {
          signals[i3](() => newItems[i3]);
        } else if (i3 >= items.length) {
          mapped[i3] = createRoot(mapper);
        }
      }
      for (; i3 < items.length; i3++) {
        disposers[i3]();
      }
      len = signals.length = disposers.length = newItems.length;
      items = newItems.slice(0);
      return mapped = mapped.slice(0, len);
    });
    function mapper(disposer) {
      disposers[i3] = disposer;
      const [s3, set4] = createSignal(newItems[i3]);
      signals[i3] = set4;
      return mapFn(s3, i3);
    }
  };
}
var hydrationEnabled = false;
function createComponent(Comp, props2) {
  if (hydrationEnabled) {
    if (sharedConfig.context) {
      const c3 = sharedConfig.context;
      setHydrateContext(nextHydrateContext());
      const r3 = untrack(() => Comp(props2 || {}));
      setHydrateContext(c3);
      return r3;
    }
  }
  return untrack(() => Comp(props2 || {}));
}
function trueFn() {
  return true;
}
var propTraps = {
  get(_5, property2, receiver) {
    if (property2 === $PROXY) return receiver;
    return _5.get(property2);
  },
  has(_5, property2) {
    if (property2 === $PROXY) return true;
    return _5.has(property2);
  },
  set: trueFn,
  deleteProperty: trueFn,
  getOwnPropertyDescriptor(_5, property2) {
    return {
      configurable: true,
      enumerable: true,
      get() {
        return _5.get(property2);
      },
      set: trueFn,
      deleteProperty: trueFn
    };
  },
  ownKeys(_5) {
    return _5.keys();
  }
};
function resolveSource(s3) {
  return !(s3 = typeof s3 === "function" ? s3() : s3) ? {} : s3;
}
function resolveSources() {
  for (let i3 = 0, length = this.length; i3 < length; ++i3) {
    const v3 = this[i3]();
    if (v3 !== void 0) return v3;
  }
}
function mergeProps(...sources) {
  let proxy = false;
  for (let i3 = 0; i3 < sources.length; i3++) {
    const s3 = sources[i3];
    proxy = proxy || !!s3 && $PROXY in s3;
    sources[i3] = typeof s3 === "function" ? (proxy = true, createMemo(s3)) : s3;
  }
  if (proxy) {
    return new Proxy(
      {
        get(property2) {
          for (let i3 = sources.length - 1; i3 >= 0; i3--) {
            const v3 = resolveSource(sources[i3])[property2];
            if (v3 !== void 0) return v3;
          }
        },
        has(property2) {
          for (let i3 = sources.length - 1; i3 >= 0; i3--) {
            if (property2 in resolveSource(sources[i3])) return true;
          }
          return false;
        },
        keys() {
          const keys5 = [];
          for (let i3 = 0; i3 < sources.length; i3++)
            keys5.push(...Object.keys(resolveSource(sources[i3])));
          return [...new Set(keys5)];
        }
      },
      propTraps
    );
  }
  const sourcesMap = {};
  const defined = /* @__PURE__ */ Object.create(null);
  for (let i3 = sources.length - 1; i3 >= 0; i3--) {
    const source = sources[i3];
    if (!source) continue;
    const sourceKeys = Object.getOwnPropertyNames(source);
    for (let i4 = sourceKeys.length - 1; i4 >= 0; i4--) {
      const key2 = sourceKeys[i4];
      if (key2 === "__proto__" || key2 === "constructor") continue;
      const desc = Object.getOwnPropertyDescriptor(source, key2);
      if (!defined[key2]) {
        defined[key2] = desc.get ? {
          enumerable: true,
          configurable: true,
          get: resolveSources.bind(sourcesMap[key2] = [desc.get.bind(source)])
        } : desc.value !== void 0 ? desc : void 0;
      } else {
        const sources2 = sourcesMap[key2];
        if (sources2) {
          if (desc.get) sources2.push(desc.get.bind(source));
          else if (desc.value !== void 0) sources2.push(() => desc.value);
        }
      }
    }
  }
  const target = {};
  const definedKeys = Object.keys(defined);
  for (let i3 = definedKeys.length - 1; i3 >= 0; i3--) {
    const key2 = definedKeys[i3], desc = defined[key2];
    if (desc && desc.get) Object.defineProperty(target, key2, desc);
    else target[key2] = desc ? desc.value : void 0;
  }
  return target;
}
function splitProps(props2, ...keys5) {
  if ($PROXY in props2) {
    const blocked = new Set(keys5.length > 1 ? keys5.flat() : keys5[0]);
    const res = keys5.map((k2) => {
      return new Proxy(
        {
          get(property2) {
            return k2.includes(property2) ? props2[property2] : void 0;
          },
          has(property2) {
            return k2.includes(property2) && property2 in props2;
          },
          keys() {
            return k2.filter((property2) => property2 in props2);
          }
        },
        propTraps
      );
    });
    res.push(
      new Proxy(
        {
          get(property2) {
            return blocked.has(property2) ? void 0 : props2[property2];
          },
          has(property2) {
            return blocked.has(property2) ? false : property2 in props2;
          },
          keys() {
            return Object.keys(props2).filter((k2) => !blocked.has(k2));
          }
        },
        propTraps
      )
    );
    return res;
  }
  const otherObject = {};
  const objects = keys5.map(() => ({}));
  for (const propName of Object.getOwnPropertyNames(props2)) {
    const desc = Object.getOwnPropertyDescriptor(props2, propName);
    const isDefaultDesc = !desc.get && !desc.set && desc.enumerable && desc.writable && desc.configurable;
    let blocked = false;
    let objectIndex = 0;
    for (const k2 of keys5) {
      if (k2.includes(propName)) {
        blocked = true;
        isDefaultDesc ? objects[objectIndex][propName] = desc.value : Object.defineProperty(objects[objectIndex], propName, desc);
      }
      ++objectIndex;
    }
    if (!blocked) {
      isDefaultDesc ? otherObject[propName] = desc.value : Object.defineProperty(otherObject, propName, desc);
    }
  }
  return [...objects, otherObject];
}
var counter = 0;
function createUniqueId() {
  const ctx = sharedConfig.context;
  return ctx ? `${ctx.id}${ctx.count++}` : `cl-${counter++}`;
}
var narrowedError = (name2) => `Stale read from <${name2}>.`;
function For(props2) {
  const fallback = "fallback" in props2 && {
    fallback: () => props2.fallback
  };
  return createMemo(mapArray(() => props2.each, props2.children, fallback || void 0));
}
function Index(props2) {
  const fallback = "fallback" in props2 && {
    fallback: () => props2.fallback
  };
  return createMemo(indexArray(() => props2.each, props2.children, fallback || void 0));
}
function Show(props2) {
  const keyed = props2.keyed;
  const condition = createMemo(() => props2.when, void 0, {
    equals: (a3, b3) => keyed ? a3 === b3 : !a3 === !b3
  });
  return createMemo(
    () => {
      const c3 = condition();
      if (c3) {
        const child = props2.children;
        const fn = typeof child === "function" && child.length > 0;
        return fn ? untrack(
          () => child(
            keyed ? c3 : () => {
              if (!untrack(condition)) throw narrowedError("Show");
              return props2.when;
            }
          )
        ) : child;
      }
      return props2.fallback;
    },
    void 0,
    void 0
  );
}
var Errors;
function resetErrorBoundaries() {
  Errors && [...Errors].forEach((fn) => fn());
}
var SuspenseListContext = createContext();
var DEV = void 0;

// node_modules/solid-js/web/dist/web.js
var booleans = [
  "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"
];
var Properties = /* @__PURE__ */ new Set([
  "className",
  "value",
  "readOnly",
  "formNoValidate",
  "isMap",
  "noModule",
  "playsInline",
  ...booleans
]);
var ChildProperties = /* @__PURE__ */ new Set([
  "innerHTML",
  "textContent",
  "innerText",
  "children"
]);
var Aliases = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(null), {
  className: "class",
  htmlFor: "for"
});
var PropAliases = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(null), {
  class: "className",
  formnovalidate: {
    $: "formNoValidate",
    BUTTON: 1,
    INPUT: 1
  },
  ismap: {
    $: "isMap",
    IMG: 1
  },
  nomodule: {
    $: "noModule",
    SCRIPT: 1
  },
  playsinline: {
    $: "playsInline",
    VIDEO: 1
  },
  readonly: {
    $: "readOnly",
    INPUT: 1,
    TEXTAREA: 1
  }
});
function getPropAlias(prop2, tagName) {
  const a3 = PropAliases[prop2];
  return typeof a3 === "object" ? a3[tagName] ? a3["$"] : void 0 : a3;
}
var DelegatedEvents = /* @__PURE__ */ new Set([
  "beforeinput",
  "click",
  "dblclick",
  "contextmenu",
  "focusin",
  "focusout",
  "input",
  "keydown",
  "keyup",
  "mousedown",
  "mousemove",
  "mouseout",
  "mouseover",
  "mouseup",
  "pointerdown",
  "pointermove",
  "pointerout",
  "pointerover",
  "pointerup",
  "touchend",
  "touchmove",
  "touchstart"
]);
var SVGElements = /* @__PURE__ */ new Set([
  "altGlyph",
  "altGlyphDef",
  "altGlyphItem",
  "animate",
  "animateColor",
  "animateMotion",
  "animateTransform",
  "circle",
  "clipPath",
  "color-profile",
  "cursor",
  "defs",
  "desc",
  "ellipse",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feDistantLight",
  "feDropShadow",
  "feFlood",
  "feFuncA",
  "feFuncB",
  "feFuncG",
  "feFuncR",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMergeNode",
  "feMorphology",
  "feOffset",
  "fePointLight",
  "feSpecularLighting",
  "feSpotLight",
  "feTile",
  "feTurbulence",
  "filter",
  "font",
  "font-face",
  "font-face-format",
  "font-face-name",
  "font-face-src",
  "font-face-uri",
  "foreignObject",
  "g",
  "glyph",
  "glyphRef",
  "hkern",
  "image",
  "line",
  "linearGradient",
  "marker",
  "mask",
  "metadata",
  "missing-glyph",
  "mpath",
  "path",
  "pattern",
  "polygon",
  "polyline",
  "radialGradient",
  "rect",
  "set",
  "stop",
  "svg",
  "switch",
  "symbol",
  "text",
  "textPath",
  "tref",
  "tspan",
  "use",
  "view",
  "vkern"
]);
var SVGNamespace = {
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace"
};
function reconcileArrays(parentNode2, a3, b3) {
  let bLength = b3.length, aEnd = a3.length, bEnd = bLength, aStart = 0, bStart = 0, after2 = a3[aEnd - 1].nextSibling, map5 = null;
  while (aStart < aEnd || bStart < bEnd) {
    if (a3[aStart] === b3[bStart]) {
      aStart++;
      bStart++;
      continue;
    }
    while (a3[aEnd - 1] === b3[bEnd - 1]) {
      aEnd--;
      bEnd--;
    }
    if (aEnd === aStart) {
      const node = bEnd < bLength ? bStart ? b3[bStart - 1].nextSibling : b3[bEnd - bStart] : after2;
      while (bStart < bEnd) parentNode2.insertBefore(b3[bStart++], node);
    } else if (bEnd === bStart) {
      while (aStart < aEnd) {
        if (!map5 || !map5.has(a3[aStart])) a3[aStart].remove();
        aStart++;
      }
    } else if (a3[aStart] === b3[bEnd - 1] && b3[bStart] === a3[aEnd - 1]) {
      const node = a3[--aEnd].nextSibling;
      parentNode2.insertBefore(b3[bStart++], a3[aStart++].nextSibling);
      parentNode2.insertBefore(b3[--bEnd], node);
      a3[aEnd] = b3[bEnd];
    } else {
      if (!map5) {
        map5 = /* @__PURE__ */ new Map();
        let i3 = bStart;
        while (i3 < bEnd) map5.set(b3[i3], i3++);
      }
      const index2 = map5.get(a3[aStart]);
      if (index2 != null) {
        if (bStart < index2 && index2 < bEnd) {
          let i3 = aStart, sequence = 1, t3;
          while (++i3 < aEnd && i3 < bEnd) {
            if ((t3 = map5.get(a3[i3])) == null || t3 !== index2 + sequence) break;
            sequence++;
          }
          if (sequence > index2 - bStart) {
            const node = a3[aStart];
            while (bStart < index2) parentNode2.insertBefore(b3[bStart++], node);
          } else parentNode2.replaceChild(b3[bStart++], a3[aStart++]);
        } else aStart++;
      } else a3[aStart++].remove();
    }
  }
}
var $$EVENTS = "_$DX_DELEGATE";
function render(code2, element2, init, options2 = {}) {
  let disposer;
  createRoot((dispose2) => {
    disposer = dispose2;
    element2 === document ? code2() : insert(element2, code2(), element2.firstChild ? null : void 0, init);
  }, options2.owner);
  return () => {
    disposer();
    element2.textContent = "";
  };
}
function template(html5, isCE, isSVG2) {
  let node;
  const create6 = () => {
    const t3 = document.createElement("template");
    t3.innerHTML = html5;
    return isSVG2 ? t3.content.firstChild.firstChild : t3.content.firstChild;
  };
  const fn = isCE ? () => untrack(() => document.importNode(node || (node = create6()), true)) : () => (node || (node = create6())).cloneNode(true);
  fn.cloneNode = fn;
  return fn;
}
function delegateEvents(eventNames, document2 = window.document) {
  const e3 = document2[$$EVENTS] || (document2[$$EVENTS] = /* @__PURE__ */ new Set());
  for (let i3 = 0, l3 = eventNames.length; i3 < l3; i3++) {
    const name2 = eventNames[i3];
    if (!e3.has(name2)) {
      e3.add(name2);
      document2.addEventListener(name2, eventHandler);
    }
  }
}
function setAttribute(node, name2, value2) {
  if (!!sharedConfig.context && node.isConnected) return;
  if (value2 == null) node.removeAttribute(name2);
  else node.setAttribute(name2, value2);
}
function setAttributeNS(node, namespace, name2, value2) {
  if (!!sharedConfig.context && node.isConnected) return;
  if (value2 == null) node.removeAttributeNS(namespace, name2);
  else node.setAttributeNS(namespace, name2, value2);
}
function className(node, value2) {
  if (!!sharedConfig.context && node.isConnected) return;
  if (value2 == null) node.removeAttribute("class");
  else node.className = value2;
}
function addEventListener(node, name2, handler, delegate) {
  if (delegate) {
    if (Array.isArray(handler)) {
      node[`$$${name2}`] = handler[0];
      node[`$$${name2}Data`] = handler[1];
    } else node[`$$${name2}`] = handler;
  } else if (Array.isArray(handler)) {
    const handlerFn = handler[0];
    node.addEventListener(name2, handler[0] = (e3) => handlerFn.call(node, handler[1], e3));
  } else node.addEventListener(name2, handler);
}
function classList(node, value2, prev = {}) {
  const classKeys = Object.keys(value2 || {}), prevKeys = Object.keys(prev);
  let i3, len;
  for (i3 = 0, len = prevKeys.length; i3 < len; i3++) {
    const key2 = prevKeys[i3];
    if (!key2 || key2 === "undefined" || value2[key2]) continue;
    toggleClassKey(node, key2, false);
    delete prev[key2];
  }
  for (i3 = 0, len = classKeys.length; i3 < len; i3++) {
    const key2 = classKeys[i3], classValue = !!value2[key2];
    if (!key2 || key2 === "undefined" || prev[key2] === classValue || !classValue) continue;
    toggleClassKey(node, key2, true);
    prev[key2] = classValue;
  }
  return prev;
}
function style(node, value2, prev) {
  if (!value2) return prev ? setAttribute(node, "style") : value2;
  const nodeStyle = node.style;
  if (typeof value2 === "string") return nodeStyle.cssText = value2;
  typeof prev === "string" && (nodeStyle.cssText = prev = void 0);
  prev || (prev = {});
  value2 || (value2 = {});
  let v3, s3;
  for (s3 in prev) {
    value2[s3] == null && nodeStyle.removeProperty(s3);
    delete prev[s3];
  }
  for (s3 in value2) {
    v3 = value2[s3];
    if (v3 !== prev[s3]) {
      nodeStyle.setProperty(s3, v3);
      prev[s3] = v3;
    }
  }
  return prev;
}
function spread(node, props2 = {}, isSVG2, skipChildren) {
  const prevProps = {};
  if (!skipChildren) {
    createRenderEffect(
      () => prevProps.children = insertExpression(node, props2.children, prevProps.children)
    );
  }
  createRenderEffect(
    () => typeof props2.ref === "function" ? use(props2.ref, node) : props2.ref = node
  );
  createRenderEffect(() => assign(node, props2, isSVG2, true, prevProps, true));
  return prevProps;
}
function use(fn, element2, arg) {
  return untrack(() => fn(element2, arg));
}
function insert(parent, accessor, marker, initial2) {
  if (marker !== void 0 && !initial2) initial2 = [];
  if (typeof accessor !== "function") return insertExpression(parent, accessor, initial2, marker);
  createRenderEffect((current) => insertExpression(parent, accessor(), current, marker), initial2);
}
function assign(node, props2, isSVG2, skipChildren, prevProps = {}, skipRef = false) {
  props2 || (props2 = {});
  for (const prop2 in prevProps) {
    if (!(prop2 in props2)) {
      if (prop2 === "children") continue;
      prevProps[prop2] = assignProp(node, prop2, null, prevProps[prop2], isSVG2, skipRef);
    }
  }
  for (const prop2 in props2) {
    if (prop2 === "children") {
      if (!skipChildren) insertExpression(node, props2.children);
      continue;
    }
    const value2 = props2[prop2];
    prevProps[prop2] = assignProp(node, prop2, value2, prevProps[prop2], isSVG2, skipRef);
  }
}
function getNextElement(template3) {
  let node, key2;
  if (!sharedConfig.context || !(node = sharedConfig.registry.get(key2 = getHydrationKey()))) {
    return template3();
  }
  if (sharedConfig.completed) sharedConfig.completed.add(node);
  sharedConfig.registry.delete(key2);
  return node;
}
function toPropertyName(name2) {
  return name2.toLowerCase().replace(/-([a-z])/g, (_5, w3) => w3.toUpperCase());
}
function toggleClassKey(node, key2, value2) {
  const classNames2 = key2.trim().split(/\s+/);
  for (let i3 = 0, nameLen = classNames2.length; i3 < nameLen; i3++)
    node.classList.toggle(classNames2[i3], value2);
}
function assignProp(node, prop2, value2, prev, isSVG2, skipRef) {
  let isCE, isProp, isChildProp, propAlias, forceProp;
  if (prop2 === "style") return style(node, value2, prev);
  if (prop2 === "classList") return classList(node, value2, prev);
  if (value2 === prev) return prev;
  if (prop2 === "ref") {
    if (!skipRef) value2(node);
  } else if (prop2.slice(0, 3) === "on:") {
    const e3 = prop2.slice(3);
    prev && node.removeEventListener(e3, prev);
    value2 && node.addEventListener(e3, value2);
  } else if (prop2.slice(0, 10) === "oncapture:") {
    const e3 = prop2.slice(10);
    prev && node.removeEventListener(e3, prev, true);
    value2 && node.addEventListener(e3, value2, true);
  } else if (prop2.slice(0, 2) === "on") {
    const name2 = prop2.slice(2).toLowerCase();
    const delegate = DelegatedEvents.has(name2);
    if (!delegate && prev) {
      const h3 = Array.isArray(prev) ? prev[0] : prev;
      node.removeEventListener(name2, h3);
    }
    if (delegate || value2) {
      addEventListener(node, name2, value2, delegate);
      delegate && delegateEvents([name2]);
    }
  } else if (prop2.slice(0, 5) === "attr:") {
    setAttribute(node, prop2.slice(5), value2);
  } else if ((forceProp = prop2.slice(0, 5) === "prop:") || (isChildProp = ChildProperties.has(prop2)) || !isSVG2 && ((propAlias = getPropAlias(prop2, node.tagName)) || (isProp = Properties.has(prop2))) || (isCE = node.nodeName.includes("-"))) {
    if (forceProp) {
      prop2 = prop2.slice(5);
      isProp = true;
    } else if (!!sharedConfig.context && node.isConnected) return value2;
    if (prop2 === "class" || prop2 === "className") className(node, value2);
    else if (isCE && !isProp && !isChildProp) node[toPropertyName(prop2)] = value2;
    else node[propAlias || prop2] = value2;
  } else {
    const ns = isSVG2 && prop2.indexOf(":") > -1 && SVGNamespace[prop2.split(":")[0]];
    if (ns) setAttributeNS(node, ns, prop2, value2);
    else setAttribute(node, Aliases[prop2] || prop2, value2);
  }
  return value2;
}
function eventHandler(e3) {
  const key2 = `$$${e3.type}`;
  let node = e3.composedPath && e3.composedPath()[0] || e3.target;
  if (e3.target !== node) {
    Object.defineProperty(e3, "target", {
      configurable: true,
      value: node
    });
  }
  Object.defineProperty(e3, "currentTarget", {
    configurable: true,
    get() {
      return node || document;
    }
  });
  if (sharedConfig.registry && !sharedConfig.done) sharedConfig.done = _$HY.done = true;
  while (node) {
    const handler = node[key2];
    if (handler && !node.disabled) {
      const data2 = node[`${key2}Data`];
      data2 !== void 0 ? handler.call(node, data2, e3) : handler.call(node, e3);
      if (e3.cancelBubble) return;
    }
    node = node._$host || node.parentNode || node.host;
  }
}
function insertExpression(parent, value2, current, marker, unwrapArray) {
  const hydrating = !!sharedConfig.context && parent.isConnected;
  if (hydrating) {
    !current && (current = [...parent.childNodes]);
    let cleaned = [];
    for (let i3 = 0; i3 < current.length; i3++) {
      const node = current[i3];
      if (node.nodeType === 8 && node.data.slice(0, 2) === "!$") node.remove();
      else cleaned.push(node);
    }
    current = cleaned;
  }
  while (typeof current === "function") current = current();
  if (value2 === current) return current;
  const t3 = typeof value2, multi = marker !== void 0;
  parent = multi && current[0] && current[0].parentNode || parent;
  if (t3 === "string" || t3 === "number") {
    if (hydrating) return current;
    if (t3 === "number") value2 = value2.toString();
    if (multi) {
      let node = current[0];
      if (node && node.nodeType === 3) {
        node.data !== value2 && (node.data = value2);
      } else node = document.createTextNode(value2);
      current = cleanChildren(parent, current, marker, node);
    } else {
      if (current !== "" && typeof current === "string") {
        current = parent.firstChild.data = value2;
      } else current = parent.textContent = value2;
    }
  } else if (value2 == null || t3 === "boolean") {
    if (hydrating) return current;
    current = cleanChildren(parent, current, marker);
  } else if (t3 === "function") {
    createRenderEffect(() => {
      let v3 = value2();
      while (typeof v3 === "function") v3 = v3();
      current = insertExpression(parent, v3, current, marker);
    });
    return () => current;
  } else if (Array.isArray(value2)) {
    const array = [];
    const currentArray = current && Array.isArray(current);
    if (normalizeIncomingArray(array, value2, current, unwrapArray)) {
      createRenderEffect(() => current = insertExpression(parent, array, current, marker, true));
      return () => current;
    }
    if (hydrating) {
      if (!array.length) return current;
      if (marker === void 0) return [...parent.childNodes];
      let node = array[0];
      let nodes2 = [node];
      while ((node = node.nextSibling) !== marker) nodes2.push(node);
      return current = nodes2;
    }
    if (array.length === 0) {
      current = cleanChildren(parent, current, marker);
      if (multi) return current;
    } else if (currentArray) {
      if (current.length === 0) {
        appendNodes(parent, array, marker);
      } else reconcileArrays(parent, current, array);
    } else {
      current && cleanChildren(parent);
      appendNodes(parent, array);
    }
    current = array;
  } else if (value2.nodeType) {
    if (hydrating && value2.parentNode) return current = multi ? [value2] : value2;
    if (Array.isArray(current)) {
      if (multi) return current = cleanChildren(parent, current, marker, value2);
      cleanChildren(parent, current, null, value2);
    } else if (current == null || current === "" || !parent.firstChild) {
      parent.appendChild(value2);
    } else parent.replaceChild(value2, parent.firstChild);
    current = value2;
  } else ;
  return current;
}
function normalizeIncomingArray(normalized, array, current, unwrap2) {
  let dynamic = false;
  for (let i3 = 0, len = array.length; i3 < len; i3++) {
    let item = array[i3], prev = current && current[normalized.length], t3;
    if (item == null || item === true || item === false) ;
    else if ((t3 = typeof item) === "object" && item.nodeType) {
      normalized.push(item);
    } else if (Array.isArray(item)) {
      dynamic = normalizeIncomingArray(normalized, item, prev) || dynamic;
    } else if (t3 === "function") {
      if (unwrap2) {
        while (typeof item === "function") item = item();
        dynamic = normalizeIncomingArray(
          normalized,
          Array.isArray(item) ? item : [item],
          Array.isArray(prev) ? prev : [prev]
        ) || dynamic;
      } else {
        normalized.push(item);
        dynamic = true;
      }
    } else {
      const value2 = String(item);
      if (prev && prev.nodeType === 3 && prev.data === value2) normalized.push(prev);
      else normalized.push(document.createTextNode(value2));
    }
  }
  return dynamic;
}
function appendNodes(parent, array, marker = null) {
  for (let i3 = 0, len = array.length; i3 < len; i3++) parent.insertBefore(array[i3], marker);
}
function cleanChildren(parent, current, marker, replacement) {
  if (marker === void 0) return parent.textContent = "";
  const node = replacement || document.createTextNode("");
  if (current.length) {
    let inserted = false;
    for (let i3 = current.length - 1; i3 >= 0; i3--) {
      const el2 = current[i3];
      if (node !== el2) {
        const isParent2 = el2.parentNode === parent;
        if (!inserted && !i3)
          isParent2 ? parent.replaceChild(node, el2) : parent.insertBefore(node, marker);
        else isParent2 && el2.remove();
      } else inserted = true;
    }
  } else parent.insertBefore(node, marker);
  return [node];
}
function getHydrationKey() {
  const hydrate = sharedConfig.context;
  return `${hydrate.id}${hydrate.count++}`;
}
var voidFn = () => void 0;
var RequestContext = Symbol();
var isServer = false;
var isDev = false;
var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
function createElement(tagName, isSVG2 = false) {
  return isSVG2 ? document.createElementNS(SVG_NAMESPACE, tagName) : document.createElement(tagName);
}
function Portal(props2) {
  const { useShadow } = props2, marker = document.createTextNode(""), mount = () => props2.mount || document.body, owner = getOwner();
  let content2;
  let hydrating = !!sharedConfig.context;
  createEffect(
    () => {
      if (hydrating) getOwner().user = hydrating = false;
      content2 || (content2 = runWithOwner(owner, () => createMemo(() => props2.children)));
      const el2 = mount();
      if (el2 instanceof HTMLHeadElement) {
        const [clean, setClean] = createSignal(false);
        const cleanup = () => setClean(true);
        createRoot((dispose2) => insert(el2, () => !clean() ? content2() : dispose2(), null));
        onCleanup(cleanup);
      } else {
        const container = createElement(props2.isSVG ? "g" : "div", props2.isSVG), renderRoot = useShadow && container.attachShadow ? container.attachShadow({
          mode: "open"
        }) : container;
        Object.defineProperty(container, "_$host", {
          get() {
            return marker.parentNode;
          },
          configurable: true
        });
        insert(renderRoot, content2);
        el2.appendChild(container);
        props2.ref && props2.ref(container);
        onCleanup(() => el2.removeChild(container));
      }
    },
    void 0,
    {
      render: !hydrating
    }
  );
  return marker;
}
function Dynamic(props2) {
  const [p4, others] = splitProps(props2, ["component"]);
  const cached = createMemo(() => p4.component);
  return createMemo(() => {
    const component = cached();
    switch (typeof component) {
      case "function":
        return untrack(() => component(others));
      case "string":
        const isSvg = SVGElements.has(component);
        const el2 = sharedConfig.context ? getNextElement() : createElement(component, isSvg);
        spread(el2, others, isSvg);
        return el2;
    }
  });
}

// public/app/utils/api.js
var Api = class {
  constructor(baseUrl2 = "", options2 = {}, errorHandlers = []) {
    this.baseUrl = baseUrl2;
    this.options = options2 || {};
    this.errorHandlers = errorHandlers;
    this.options.headers = new Headers(this.options.headers || {});
  }
  setAuthToken(token) {
    if (token) {
      this.options.headers.set("Authorization", `Bearer ${token}`);
    } else {
      this.options.headers.delete("Authorization");
    }
  }
  registerErrorHandler(fn) {
    this.errorHandlers.push(fn);
  }
  /**
   * Generate a URL for an endpoint. Params will be used to fill in the path params.
   * The baseUrl will be prepended to the endpoint.
   *
   * const [url, params] = api.url('/endpoint/:id', {id: 1, query: 'foo'}, true)
   */
  url(endpoint, params, returnLeftoverParams = false) {
    let url2 = this.baseUrl + endpoint;
    let leftovers = {};
    let urlParams = [];
    let m3;
    const urlParamsRegexp = /:([a-z0-9_]+)/ig;
    while ((m3 = urlParamsRegexp.exec(url2)) !== null) {
      urlParams.push(m3[1]);
    }
    for (let [key2, value2] of Object.entries(params || {})) {
      if (urlParams.includes(key2)) {
        url2 = url2.replace(":" + key2, value2);
      } else {
        leftovers[key2] = value2;
      }
    }
    if (url2.includes(":")) {
      throw Error("Missing parameters to build full api url");
    }
    if (returnLeftoverParams) {
      return [url2, leftovers];
    }
    return url2;
  }
  /**
   * Use fetch() to call a remote URL.
   * The baseUrl will be prepended to the endpoint.
   * Options are the same as fetch and will be merged with the instance's options.
   * GET requests will use search params, all other methods will be serialized as JSON in the body.
   *
   * Returns a promise with the JSON response (unless options.disableJsonParsing is true).
   * A tuple [data, response] can also be returned with options.resolveWithResponse
   * Rejects on error with an ApiErrorResponse
   *
   * When an error occurs, global error handlers will be triggered unless options.ignoreErrorHandlers is true.
   */
  call(endpoint, method, params, options2) {
    let url2;
    [url2, params] = this.url(endpoint, params, true);
    const headers = mergeHeaders(this.options.headers, options2?.headers);
    options2 = Object.assign({}, this.options, options2 || {}, { method, headers });
    if (Object.keys(params).length) {
      if (method === "GET") {
        const serializer = new URLSearchParams();
        for (const [key2, value2] of Object.entries(params)) {
          if (Array.isArray(value2)) {
            for (const item of value2) {
              serializer.append(key2, item);
            }
          } else if (value2 || value2 === 0 || value2 === "") {
            serializer.set(key2, value2);
          }
        }
        url2 += "?" + serializer.toString();
      } else {
        options2.headers.set("Content-Type", "application/json");
        options2.body = JSON.stringify(params);
      }
    }
    return fetch(url2, options2).then((response) => {
      if (response.ok) {
        if (options2.disableJsonParsing || !response.headers.get("Content-Type").includes("application/json")) {
          return response;
        }
        return response.json().then((data2) => options2.resolveWithResponse ? [data2, response] : data2);
      }
      if (!options2.ignoreErrorHandlers) {
        return this.triggerErrorHandlers(response, options2.ignoreErrorHandlers);
      }
      return Promise.reject(new ApiResponseError(response));
    });
  }
  triggerErrorHandlers(response, resolveWithResponse) {
    return Promise.all(this.errorHandlers.map((fn) => fn(response))).then(() => resolveWithResponse ? [null, response] : null).catch(() => Promise.reject(new ApiResponseError(response)));
  }
  endpoint(url2) {
    return new ApiEndpoint(this, url2);
  }
};
function mergeHeaders(h1, h22) {
  h1 = new Headers(h1 || {});
  h22 = new Headers(h22 || {});
  for (let [k2, v3] of h22) {
    h1.set(k2, v3);
  }
  return h1;
}
var ApiResponseError = class extends Error {
  constructor(response) {
    super();
    this.response = response;
  }
  get status() {
    return this.response.status;
  }
  json() {
    return this.response.json();
  }
};
var ApiEndpoint = class {
  constructor(api2, endpoint) {
    this.api = api2;
    this.endpoint = endpoint;
  }
  url(params) {
    return this.api.url(this.endpoint, params);
  }
  call(method, params, options2) {
    return this.api.call(this.endpoint, method, params, options2);
  }
  get(params, options2) {
    return this.call("GET", params, options2);
  }
  post(params, options2) {
    return this.call("POST", params, options2);
  }
  put(params, options2) {
    return this.call("PUT", params, options2);
  }
  patch(params, options2) {
    return this.call("PATCH", params, options2);
  }
  delete(params, options2) {
    return this.call("DELETE", params, options2);
  }
};

// public/app/api.js
var api = new Api();
api.eu_vat = {};
api.eu_vat.get_vat_rate = api.endpoint("/api/1.0/eu-vat/rates/:country_code");
api.eu_vat.validate_vat_number = api.endpoint("/api/1.0/eu-vat/validate-vat-number");
api.eu_vat.get_exchange_rate = api.endpoint("/api/1.0/eu-vat/exchange-rates/:country_code/:src_currency");
api.eu_vat.get_exchange_rate = api.endpoint("/api/1.0/eu-vat/exchange-rates/:country_code");
api.eu_vat.check = api.endpoint("/api/1.0/eu-vat/check");
api.config = {};
api.config.get_config = api.endpoint("/api/1.0/config");
api.config.get_terms = api.endpoint("/api/1.0/terms");
api.config.list_ai_providers = api.endpoint("/api/1.0/ai-providers");
api.config.get_changelog = api.endpoint("/api/1.0/changelog");
api.attr_types = {};
api.attr_types.list_attr_types = api.endpoint("/api/1.0/attribute-types");
api.attr_types.get_attr_type = api.endpoint("/api/1.0/attribute-types/:name");
api.automation_types = {};
api.automation_types.list_automation_events = api.endpoint("/api/1.0/automation-types/events");
api.automation_types.list_automation_actions = api.endpoint("/api/1.0/automation-types/actions");
api.automation_types.list_automation_queries = api.endpoint("/api/1.0/automation-types/queries");
api.integrations = {};
api.integrations.list_integrations = api.endpoint("/api/1.0/integrations");
api.integrations.get_integration = api.endpoint("/api/1.0/integrations/:name");
api.third_party_account_providers = {};
api.third_party_account_providers.list_third_party_account_providers = api.endpoint("/api/1.0/third-party-account-providers");
api.chart_types = {};
api.chart_types.list_charts = api.endpoint("/api/1.0/charts");
api.chart_types.get_chart_info = api.endpoint("/api/1.0/charts/:name");
api.async_job = {};
api.async_job.get = api.endpoint("/api/1.0/async/:id");
api.kql = {};
api.kql.parse_filter = api.endpoint("/api/1.0/kql/parse-filter");
api.kql.validate = api.endpoint("/api/1.0/kql/validate");
api.kql.list_kql_special_card_attrs = api.endpoint("/api/1.0/kql/autocomplete/special-card-attrs");
api.kql.list_kql_functions = api.endpoint("/api/1.0/kql/autocomplete/functions");
api.kql.list_kql_cond_functions = api.endpoint("/api/1.0/kql/autocomplete/cond-functions");
api.kql.kql_ask = api.endpoint("/api/1.0/kql/ask");
api.user = {};
api.user.get_user = api.endpoint("/api/1.0/users/:user_id");
api.user.get_info = api.endpoint("/api/1.0/me");
api.user.get_full_info = api.endpoint("/api/1.0/me/full");
api.user.can_be_deleted = api.endpoint("/api/1.0/me/can-delete");
api.user.update = api.endpoint("/api/1.0/me");
api.user.update_user_password = api.endpoint("/api/1.0/password");
api.user.enable_two_factor_auth = api.endpoint("/api/1.0/2fa");
api.user.disable_two_factor_auth = api.endpoint("/api/1.0/2fa");
api.user.accept_terms = api.endpoint("/api/1.0/accept-terms");
api.user.delete = api.endpoint("/api/1.0/me");
api.user.logout_all_devices = api.endpoint("/api/1.0/logout-all-devices");
api.user.mark_as_onboarded = api.endpoint("/api/1.0/mark-as-onboarded");
api.user.mark_release_version_as_read = api.endpoint("/api/1.0/mark-release-version-as-read");
api.user.dismiss_system_message = api.endpoint("/api/1.0/dismiss-system-message");
api.user.list_app_context_content = api.endpoint("/api/1.0/projects/grouped");
api.user.list_app_context_content = api.endpoint("/api/1.0/app-context");
api.user.list_favorites = api.endpoint("/api/1.0/pins");
api.user.list_favorites = api.endpoint("/api/1.0/favorites");
api.user.list_projects = api.endpoint("/api/1.0/projects");
api.user.list_shared_projects = api.endpoint("/api/1.0/projects/shared");
api.user.list_all_projects = api.endpoint("/api/1.0/projects/all");
api.user.create_project = api.endpoint("/api/1.0/projects");
api.user.get_unread_notifications = api.endpoint("/api/1.0/unread-notifications");
api.user.list_notifications = api.endpoint("/api/1.0/notifications");
api.user.clear_notifications = api.endpoint("/api/1.0/notifications");
api.user.get_inbox_feed = api.endpoint("/api/1.0/inbox");
api.user.list_requests = api.endpoint("/api/1.0/requests");
api.user.list_templates = api.endpoint("/api/1.0/templates");
api.user.list_models = api.endpoint("/api/1.0/models");
api.user.list_group_types = api.endpoint("/api/1.0/group-types");
api.user.list_request_forms = api.endpoint("/api/1.0/request-forms");
api.user.list_roles = api.endpoint("/api/1.0/roles");
api.user.list_reminders = api.endpoint("/api/1.0/reminders");
api.user.ping = api.endpoint("/api/1.0/ping");
api.user.update_dashboard = api.endpoint("/api/1.0/dashboard");
api.user.update_app_params = api.endpoint("/api/1.0/app-params");
api.user.list_api_keys = api.endpoint("/api/1.0/api-keys");
api.user.create_api_key = api.endpoint("/api/1.0/api-keys");
api.user.revoke_api_key = api.endpoint("/api/1.0/api-keys");
api.user.get_calendar_url = api.endpoint("/api/1.0/calendar-url");
api.user.list_third_party_accounts = api.endpoint("/api/1.0/third-party-accounts");
api.user.remove_third_party_account = api.endpoint("/api/1.0/third-party-accounts/:provider");
api.user.autocomplete_invites = api.endpoint("/api/1.0/autocomplete-invites");
api.user.contact_support = api.endpoint("/api/1.0/support");
api.user.send_email_validation = api.endpoint("/api/1.0/send-email-validation");
api.user_calendar = {};
api.user_calendar.get = api.endpoint("/api/1.0/ical/users/:token/events.ics");
api.user_calendar.get_query = api.endpoint("/api/1.0/ical/users/:token/query.ics");
api.user_calendar.get_org = api.endpoint("/api/1.0/ical/users/:token/org.ics");
api.assistant = {};
api.assistant.ask_assistant = api.endpoint("/api/1.0/assistant");
api.assistant.confirm_assistant = api.endpoint("/api/1.0/assistant/confirm");
api.search = {};
api.search.search = api.endpoint("/api/1.0/search");
api.search.get_calendar_url = api.endpoint("/api/1.0/search/ical-url");
api.search.list_group_by_possibilities = api.endpoint("/api/1.0/search/group-by-list");
api.search.list_group_by_groups = api.endpoint("/api/1.0/search/group-by-groups");
api.search.list_filterable_fields = api.endpoint("/api/1.0/search/filterable-fields");
api.search.list_groups = api.endpoint("/api/1.0/search/groups");
api.views = {};
api.views.list_global_views = api.endpoint("/api/1.0/views");
api.views.list_my_work_views = api.endpoint("/api/1.0/views/my-work");
api.views.get_view = api.endpoint("/api/1.0/views/:view_id");
api.views.create_view = api.endpoint("/api/1.0/views");
api.views.update_view = api.endpoint("/api/1.0/views/:view_id");
api.views.reorder_view = api.endpoint("/api/1.0/views/:view_id/reorder");
api.views.favorite_view = api.endpoint("/api/1.0/views/:view_id/favorite");
api.views.unfavorite_view = api.endpoint("/api/1.0/views/:view_id/favorite");
api.views.delete_view = api.endpoint("/api/1.0/views/:view_id");
api.roles = {};
api.roles.create = api.endpoint("/api/1.0/roles");
api.roles.get = api.endpoint("/api/1.0/roles/:role_id");
api.roles.update = api.endpoint("/api/1.0/roles/:role_id");
api.roles.update_project_permissions = api.endpoint("/api/1.0/roles/:role_id/project-permissions");
api.roles.duplicate = api.endpoint("/api/1.0/roles/:role_id/duplicate");
api.roles.get_available_actions = api.endpoint("/api/1.0/roles/available-actions");
api.roles.add_permission = api.endpoint("/api/1.0/roles/:role_id/permissions");
api.roles.update_permission = api.endpoint("/api/1.0/roles/:role_id/permissions/:permission_id");
api.roles.upsert_permission = api.endpoint("/api/1.0/roles/:role_id/permissions");
api.roles.delete_permission = api.endpoint("/api/1.0/roles/:role_id/permissions/:permission_id");
api.roles.reset = api.endpoint("/api/1.0/roles/:role_id/reset");
api.roles.delete = api.endpoint("/api/1.0/roles/:role_id");
api.card_group_types = {};
api.card_group_types.create = api.endpoint("/api/1.0/group-types");
api.card_group_types.get = api.endpoint("/api/1.0/group-types/:type_id");
api.card_group_types.get_groups = api.endpoint("/api/1.0/group-types/:type_id/groups");
api.card_group_types.update = api.endpoint("/api/1.0/group-types/:type_id");
api.card_group_types.delete = api.endpoint("/api/1.0/group-types/:type_id");
api.card_group_types.list_enabled_in_projects = api.endpoint("/api/1.0/group-types/:type_id/projects");
api.log_types = {};
api.log_types.list_attributes = api.endpoint("/api/1.0/log-types/:type_id/attributes");
api.log_types.create_attributes = api.endpoint("/api/1.0/log-types/:type_id/attributes");
api.log_types.update_attributes = api.endpoint("/api/1.0/log-types/:type_id/attributes");
api.log_types.update_attribute_containers = api.endpoint("/api/1.0/log-types/:type_id/attributes/containers");
api.log_types.clear_attributes = api.endpoint("/api/1.0/log-types/:type_id/attributes");
api.log_types.get_attribute = api.endpoint("/api/1.0/log-types/:type_id/attributes/:attr_id");
api.log_types.update_attribute = api.endpoint("/api/1.0/log-types/:type_id/attributes/:attr_id");
api.log_types.move_attribute = api.endpoint("/api/1.0/log-types/:type_id/attributes/:attr_id/move");
api.log_types.get_attribute_choices = api.endpoint("/api/1.0/log-types/:type_id/attributes/:attr_id/choices");
api.log_types.change_owner = api.endpoint("/api/1.0/log-types/:type_id/attributes/:attr_id/change-owner");
api.log_types.delete_attribute = api.endpoint("/api/1.0/log-types/:type_id/attributes/:attr_id");
api.log_types.create_log_type = api.endpoint("/api/1.0/log-types");
api.log_types.update_log_type = api.endpoint("/api/1.0/log-types/:type_id");
api.log_types.delete_log_type = api.endpoint("/api/1.0/log-types/:type_id");
api.log_types.get_log_type = api.endpoint("/api/1.0/log-types/:type_id");
api.log_types.list_logs = api.endpoint("/api/1.0/log-types/:type_id/logs");
api.log_types.export_logs = api.endpoint("/api/1.0/log-types/:type_id/export");
api.card_models = {};
api.card_models.list_attributes = api.endpoint("/api/1.0/models/:model_id/attributes");
api.card_models.create_attributes = api.endpoint("/api/1.0/models/:model_id/attributes");
api.card_models.update_attributes = api.endpoint("/api/1.0/models/:model_id/attributes");
api.card_models.update_attribute_containers = api.endpoint("/api/1.0/models/:model_id/attributes/containers");
api.card_models.clear_attributes = api.endpoint("/api/1.0/models/:model_id/attributes");
api.card_models.get_attribute = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id");
api.card_models.update_attribute = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id");
api.card_models.move_attribute = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id/move");
api.card_models.get_attribute_choices = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id/choices");
api.card_models.change_owner = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id/change-owner");
api.card_models.delete_attribute = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id");
api.card_models.create_model = api.endpoint("/api/1.0/models");
api.card_models.get_model = api.endpoint("/api/1.0/models/:model_id");
api.card_models.update_model = api.endpoint("/api/1.0/models/:model_id");
api.card_models.share_model = api.endpoint("/api/1.0/models/:model_id/share");
api.card_models.make_model_private = api.endpoint("/api/1.0/models/:model_id/make-private");
api.card_models.copy_model = api.endpoint("/api/1.0/models/:model_id/copy");
api.card_models.delete_model = api.endpoint("/api/1.0/models/:model_id");
api.card_models.list_enabled_model_in_projects = api.endpoint("/api/1.0/models/:model_id/projects");
api.card_models.update_attribute_containers = api.endpoint("/api/1.0/models/:model_id/attribute-containers/:project_id");
api.card_models.update_attribute_containers = api.endpoint("/api/1.0/models/:model_id/attributes/containers/:project_id");
api.card_models.move_attribute = api.endpoint("/api/1.0/models/:model_id/attributes/:attr_id/move/:project_id");
api.request_form = {};
api.request_form.get_request_form = api.endpoint("/api/1.0/request-forms/:request_form_id");
api.request_form.post_request = api.endpoint("/api/1.0/request-forms/:request_form_id");
api.request_form.list_field_choices = api.endpoint("/api/1.0/request-forms/:request_form_id/field-choices/:field_id");
api.request = {};
api.request.get_request = api.endpoint("/api/1.0/requests/:request_token");
api.request.post_comment = api.endpoint("/api/1.0/requests/:request_token/comments");
api.request.update_request_fields = api.endpoint("/api/1.0/requests/:request_token");
api.projects = {};
api.projects.list_attributes = api.endpoint("/api/1.0/projects/:project_id/attributes");
api.projects.create_attributes = api.endpoint("/api/1.0/projects/:project_id/attributes");
api.projects.update_attributes = api.endpoint("/api/1.0/projects/:project_id/attributes");
api.projects.update_attribute_containers = api.endpoint("/api/1.0/projects/:project_id/attributes/containers");
api.projects.clear_attributes = api.endpoint("/api/1.0/projects/:project_id/attributes");
api.projects.get_attribute = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id");
api.projects.update_attribute = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id");
api.projects.move_attribute = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id/move");
api.projects.get_attribute_choices = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id/choices");
api.projects.change_owner = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id/change-owner");
api.projects.delete_attribute = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id");
api.projects.get_project = api.endpoint("/api/1.0/projects/:project_id");
api.projects.update_project = api.endpoint("/api/1.0/projects/:project_id");
api.projects.update_project_access = api.endpoint("/api/1.0/projects/:project_id/access");
api.projects.get_project_guide = api.endpoint("/api/1.0/projects/:project_id/guide");
api.projects.update_project_guide = api.endpoint("/api/1.0/projects/:project_id/guide");
api.projects.archive_project = api.endpoint("/api/1.0/projects/:project_id/archive");
api.projects.restore_project = api.endpoint("/api/1.0/projects/:project_id/archive");
api.projects.delete_project = api.endpoint("/api/1.0/projects/:project_id");
api.projects.copy_project = api.endpoint("/api/1.0/projects/:project_id/copy");
api.projects.relocate_project_to_other_org = api.endpoint("/api/1.0/projects/:project_id/relocate-to-other-org");
api.projects.convert_project_to_card = api.endpoint("/api/1.0/projects/:project_id/convert-to-card");
api.projects.list_cards = api.endpoint("/api/1.0/projects/:project_id/cards");
api.projects.query_project = api.endpoint("/api/1.0/projects/:project_id/query");
api.projects.get_card_by_ref = api.endpoint("/api/1.0/projects/:project_id/cards/:ref");
api.projects.get_board = api.endpoint("/api/1.0/projects/:project_id/board/:ref");
api.projects.get_board = api.endpoint("/api/1.0/projects/:project_id/board");
api.projects.list_activities = api.endpoint("/api/1.0/projects/:project_id/activities");
api.projects.list_roles = api.endpoint("/api/1.0/projects/:project_id/roles");
api.projects.list_reminders_for_user = api.endpoint("/api/1.0/projects/:project_id/reminders");
api.projects.export_project = api.endpoint("/api/1.0/projects/:project_id/export");
api.projects.export_project_stream = api.endpoint("/api/1.0/projects/:project_id/export/stream");
api.projects.export_project_json = api.endpoint("/api/1.0/projects/:project_id/export/json");
api.projects.export_activities = api.endpoint("/api/1.0/projects/:project_id/activities/export");
api.projects.export_pii_report = api.endpoint("/api/1.0/projects/:project_id/pii-report");
api.projects.batch_card_actions = api.endpoint("/api/1.0/projects/:project_id/batch");
api.projects.batch_dates = api.endpoint("/api/1.0/projects/:project_id/batch/dates");
api.projects.get_attribute_choices = api.endpoint("/api/1.0/projects/:project_id/attributes/:attr_id/choices");
api.projects.get_ai_config = api.endpoint("/api/1.0/projects/:project_id/ai");
api.projects.update_ai_config = api.endpoint("/api/1.0/projects/:project_id/ai");
api.share_objects = {};
api.share_objects.get = api.endpoint("/api/1.0/share/:token");
api.share_objects.create = api.endpoint("/api/1.0/share");
api.share_objects.update = api.endpoint("/api/1.0/share/:token");
api.share_objects.add_form = api.endpoint("/api/1.0/share/:token/forms");
api.share_objects.remove_form = api.endpoint("/api/1.0/share/:token/forms");
api.share_objects.delete = api.endpoint("/api/1.0/share/:token");
api.share_objects.list_cards = api.endpoint("/api/1.0/share/:token/cards");
api.reporting = {};
api.reporting.get_project_chart_data = api.endpoint("/api/1.0/projects/:project_id/charts/:name");
api.reporting.get_portfolio_chart_data = api.endpoint("/api/1.0/projects/:project_id/portfolio/charts/:name");
api.reporting.get_chart_data = api.endpoint("/api/1.0/charts/:name");
api.importers = {};
api.importers.list_available = api.endpoint("/api/1.0/importers");
api.importers.authorize = api.endpoint("/api/1.0/importers/:name/authorize");
api.importers.list_projects = api.endpoint("/api/1.0/importers/:name/projects");
api.importers.discover = api.endpoint("/api/1.0/importers/:name/discover");
api.importers.import_project = api.endpoint("/api/1.0/importers/:name/import");
api.template_library = {};
api.template_library.list_templates = api.endpoint("/api/1.0/template-library");
api.template_library.list_used = api.endpoint("/api/1.0/template-library/used");
api.template_library.list_from_user = api.endpoint("/api/1.0/template-library/user");
api.template_library.list_from_org = api.endpoint("/api/1.0/template-library/organizations/:org_id");
api.template_library.list_featured = api.endpoint("/api/1.0/template-library/featured");
api.template_library.list_tags = api.endpoint("/api/1.0/template-library/tags");
api.billing = {};
api.billing.create_setup_intent = api.endpoint("/api/1.0/billing/setup-intent");
api.billing.get_account = api.endpoint("/api/1.0/billing/:account_id");
api.billing.update_account = api.endpoint("/api/1.0/billing/:account_id");
api.billing.cancel_account = api.endpoint("/api/1.0/billing/:account_id/cancel");
api.billing.revert_cancel_account = api.endpoint("/api/1.0/billing/:account_id/cancel");
api.billing.list_invoices = api.endpoint("/api/1.0/billing/:account_id/invoices");
api.billing.get_next_invoice_amount = api.endpoint("/api/1.0/billing/:account_id/next-invoice-amount");
api.billing.get_seat_price = api.endpoint("/api/1.0/billing/:account_id/seat-price");
api.pricing = {};
api.pricing.get_pricing = api.endpoint("/api/1.0/pricing/:country");
api.pricing.get_pricing = api.endpoint("/api/1.0/pricing");
api.organizations = {};
api.organizations.list_attributes = api.endpoint("/api/1.0/organizations/:org_id/attributes");
api.organizations.create_attributes = api.endpoint("/api/1.0/organizations/:org_id/attributes");
api.organizations.update_attributes = api.endpoint("/api/1.0/organizations/:org_id/attributes");
api.organizations.update_attribute_containers = api.endpoint("/api/1.0/organizations/:org_id/attributes/containers");
api.organizations.clear_attributes = api.endpoint("/api/1.0/organizations/:org_id/attributes");
api.organizations.get_attribute = api.endpoint("/api/1.0/organizations/:org_id/attributes/:attr_id");
api.organizations.update_attribute = api.endpoint("/api/1.0/organizations/:org_id/attributes/:attr_id");
api.organizations.move_attribute = api.endpoint("/api/1.0/organizations/:org_id/attributes/:attr_id/move");
api.organizations.get_attribute_choices = api.endpoint("/api/1.0/organizations/:org_id/attributes/:attr_id/choices");
api.organizations.change_owner = api.endpoint("/api/1.0/organizations/:org_id/attributes/:attr_id/change-owner");
api.organizations.delete_attribute = api.endpoint("/api/1.0/organizations/:org_id/attributes/:attr_id");
api.organizations.list_orgs = api.endpoint("/api/1.0/organizations");
api.organizations.create_org = api.endpoint("/api/1.0/organizations");
api.organizations.get_org = api.endpoint("/api/1.0/organizations/:org_id");
api.organizations.update_org = api.endpoint("/api/1.0/organizations/:org_id");
api.organizations.enable_org_invite_link = api.endpoint("/api/1.0/organizations/:org_id/invite-link");
api.organizations.disable_org_invite_link = api.endpoint("/api/1.0/organizations/:org_id/invite-link");
api.organizations.delete_org = api.endpoint("/api/1.0/organizations/:org_id");
api.organizations.list_featured_items = api.endpoint("/api/1.0/organizations/:org_id/featured-items");
api.organizations.add_featured_item = api.endpoint("/api/1.0/organizations/:org_id/featured-items");
api.organizations.remove_featured_item = api.endpoint("/api/1.0/organizations/:org_id/featured-items/:item_id");
api.organizations.list_models = api.endpoint("/api/1.0/organizations/:org_id/models");
api.organizations.list_group_types = api.endpoint("/api/1.0/organizations/:org_id/group-types");
api.organizations.list_log_types = api.endpoint("/api/1.0/organizations/:org_id/log-types");
api.organizations.list_request_forms = api.endpoint("/api/1.0/organizations/:org_id/request-forms");
api.organizations.search = api.endpoint("/api/1.0/organizations/:org_id/search");
api.organizations.list_roles = api.endpoint("/api/1.0/organizations/:org_id/roles");
api.organizations.get_calendar_url = api.endpoint("/api/1.0/organizations/:org_id/calendar-url");
api.organizations.get_pii_data = api.endpoint("/api/1.0/organizations/:org_id/pii/data");
api.organizations.export_pii_report = api.endpoint("/api/1.0/organizations/:org_id/pii/report");
api.organizations.export = api.endpoint("/api/1.0/organizations/:org_id/export");
api.organizations.list_updates = api.endpoint("/api/1.0/organizations/:org_id/updates");
api.organizations.post_update = api.endpoint("/api/1.0/organizations/:org_id/updates");
api.organizations.get_ai_config = api.endpoint("/api/1.0/organizations/:org_id/ai");
api.organizations.update_ai_config = api.endpoint("/api/1.0/organizations/:org_id/ai");
api.organizations.list_projects = api.endpoint("/api/1.0/organizations/:org_id/projects");
api.organizations.list_all_projects = api.endpoint("/api/1.0/organizations/:org_id/projects/all");
api.organizations.list_archived_projects = api.endpoint("/api/1.0/organizations/:org_id/projects/archived");
api.organizations.create_project = api.endpoint("/api/1.0/organizations/:org_id/projects");
api.organizations.list_templates = api.endpoint("/api/1.0/organizations/:org_id/templates");
api.organizations.create_template = api.endpoint("/api/1.0/organizations/:org_id/templates");
api.organizations.list_portfolios = api.endpoint("/api/1.0/organizations/:org_id/portfolios");
api.organizations.create_portfolio = api.endpoint("/api/1.0/organizations/:org_id/portfolios");
api.organization_top_level_card_attrs = {};
api.organization_top_level_card_attrs.list_attributes = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes");
api.organization_top_level_card_attrs.create_attributes = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes");
api.organization_top_level_card_attrs.update_attributes = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes");
api.organization_top_level_card_attrs.update_attribute_containers = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/containers");
api.organization_top_level_card_attrs.clear_attributes = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes");
api.organization_top_level_card_attrs.get_attribute = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/:attr_id");
api.organization_top_level_card_attrs.update_attribute = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/:attr_id");
api.organization_top_level_card_attrs.move_attribute = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/:attr_id/move");
api.organization_top_level_card_attrs.get_attribute_choices = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/:attr_id/choices");
api.organization_top_level_card_attrs.change_owner = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/:attr_id/change-owner");
api.organization_top_level_card_attrs.delete_attribute = api.endpoint("/api/1.0/organizations/:org_id/top-level-card-attributes/:attr_id");
api.org_integrations = {};
api.org_integrations.list_integrations = api.endpoint("/api/1.0/organizations/:org_id/integrations");
api.org_integrations.create_integration = api.endpoint("/api/1.0/organizations/:org_id/integrations");
api.org_integrations.authorize_integration = api.endpoint("/api/1.0/organizations/:org_id/integrations/authorize/:name");
api.org_integrations.authorize_integration_callback = api.endpoint("/api/1.0/organizations/:org_id/integrations/authorize/:name/callback");
api.org_integrations.get_integration = api.endpoint("/api/1.0/organizations/:org_id/integrations/:instance_id");
api.org_integrations.reauthorize_integration = api.endpoint("/api/1.0/organizations/:org_id/integrations/:instance_id/authorize");
api.org_integrations.reauthorize_integration_callback = api.endpoint("/api/1.0/organizations/:org_id/integrations/:instance_id/authorize-callback");
api.org_integrations.clear_integration_error = api.endpoint("/api/1.0/organizations/:org_id/integrations/:instance_id/error");
api.org_integrations.remove_integration = api.endpoint("/api/1.0/organizations/:org_id/integrations/:instance_id");
api.org_members = {};
api.org_members.invite = api.endpoint("/api/1.0/organizations/:org_id/invites");
api.org_members.list_invites = api.endpoint("/api/1.0/organizations/:org_id/invites");
api.org_members.add_user = api.endpoint("/api/1.0/organizations/:org_id/members");
api.org_members.list_members = api.endpoint("/api/1.0/organizations/:org_id/members");
api.org_members.update_member_permission = api.endpoint("/api/1.0/organizations/:org_id/members/:member_id");
api.org_members.remove_member = api.endpoint("/api/1.0/organizations/:org_id/members/:member_id");
api.teams = {};
api.teams.list_teams = api.endpoint("/api/1.0/organizations/:org_id/teams");
api.teams.create_team = api.endpoint("/api/1.0/organizations/:org_id/teams");
api.teams.get_team = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id");
api.teams.update_team = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id");
api.teams.delete_team = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id");
api.teams.list_team_members = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id/members");
api.teams.add_team_member = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id/members");
api.teams.update_team_member = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id/members/:org_member_id");
api.teams.remove_team_member = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id/members/:org_member_id");
api.teams.list_projects = api.endpoint("/api/1.0/organizations/:org_id/teams/:team_id/projects");
api.project_export_templates = {};
api.project_export_templates.list_templates = api.endpoint("/api/1.0/projects/:project_id/export-templates");
api.project_export_templates.create_template = api.endpoint("/api/1.0/projects/:project_id/export-templates");
api.project_export_templates.update_template = api.endpoint("/api/1.0/projects/:project_id/export-templates/:template_id");
api.project_export_templates.delete_template = api.endpoint("/api/1.0/projects/:project_id/export-templates/:template_id");
api.project_group_types = {};
api.project_group_types.list_group_types_in_project = api.endpoint("/api/1.0/projects/:project_id/group-types");
api.project_group_types.create_group_type_in_project = api.endpoint("/api/1.0/projects/:project_id/group-types");
api.project_group_types.enable_group_type = api.endpoint("/api/1.0/projects/:project_id/group-types");
api.project_group_types.get_group_type = api.endpoint("/api/1.0/projects/:project_id/group-types/:type_id");
api.project_group_types.disable_or_delete_group_type = api.endpoint("/api/1.0/projects/:project_id/group-types/:type_id");
api.project_integrations = {};
api.project_integrations.list_available_integrations = api.endpoint("/api/1.0/projects/:project_id/available-integrations");
api.project_integrations.list_integrations = api.endpoint("/api/1.0/projects/:project_id/integrations");
api.project_integrations.activate_integration = api.endpoint("/api/1.0/projects/:project_id/integrations");
api.project_integrations.update_integration = api.endpoint("/api/1.0/projects/:project_id/integrations/:instance_id");
api.project_integrations.remove_integration = api.endpoint("/api/1.0/projects/:project_id/integrations/:instance_id");
api.project_log_types = {};
api.project_log_types.list_enabled_log_types = api.endpoint("/api/1.0/projects/:project_id/log-types");
api.project_log_types.enable_log_type = api.endpoint("/api/1.0/projects/:project_id/log-types");
api.project_log_types.get_log_type = api.endpoint("/api/1.0/projects/:project_id/log-types/:type_id");
api.project_log_types.disable_or_delete_log_type = api.endpoint("/api/1.0/projects/:project_id/log-types/:type_id");
api.project_log_types.list_logs = api.endpoint("/api/1.0/projects/:project_id/log-types/:type_id/logs");
api.project_log_types.list_attribute_choices = api.endpoint("/api/1.0/projects/:project_id/log-types/:type_id/attribute-choices/:type_name");
api.project_members = {};
api.project_members.join_project = api.endpoint("/api/1.0/projects/:project_id/join");
api.project_members.leave_project = api.endpoint("/api/1.0/projects/:project_id/leave");
api.project_members.invite = api.endpoint("/api/1.0/projects/:project_id/invites");
api.project_members.add_user = api.endpoint("/api/1.0/projects/:project_id/members");
api.project_members.update_member = api.endpoint("/api/1.0/projects/:project_id/members/:member_id");
api.project_members.remove_member = api.endpoint("/api/1.0/projects/:project_id/members/:member_id");
api.project_members.list_invites = api.endpoint("/api/1.0/projects/:project_id/invites");
api.project_members.list_members = api.endpoint("/api/1.0/projects/:project_id/members");
api.project_models = {};
api.project_models.list_enabled_models = api.endpoint("/api/1.0/projects/:project_id/models");
api.project_models.enable_model = api.endpoint("/api/1.0/projects/:project_id/models");
api.project_models.get_model = api.endpoint("/api/1.0/projects/:project_id/models/:model_id");
api.project_models.disable_or_delete_model = api.endpoint("/api/1.0/projects/:project_id/models/:model_id");
api.project_models.copy_model = api.endpoint("/api/1.0/projects/:project_id/models/:model_id/copy");
api.project_recurring_cards = {};
api.project_recurring_cards.list_recurring_cards = api.endpoint("/api/1.0/projects/:project_id/recurring_cards");
api.project_recurring_cards.create_recurring_card = api.endpoint("/api/1.0/projects/:project_id/recurring_cards");
api.project_recurring_cards.update_recurring_card = api.endpoint("/api/1.0/projects/:project_id/recurring_cards/:recurring_id");
api.project_recurring_cards.remove_recurring_card = api.endpoint("/api/1.0/projects/:project_id/recurring_cards/:recurring_id");
api.project_request_forms = {};
api.project_request_forms.list_request_forms = api.endpoint("/api/1.0/projects/:project_id/request-forms");
api.project_request_forms.get_request_form = api.endpoint("/api/1.0/projects/:project_id/request-forms/:request_form_id");
api.project_request_forms.get_request_form_requests = api.endpoint("/api/1.0/projects/:project_id/request-forms/:request_form_id/requests");
api.project_request_forms.create_request_form = api.endpoint("/api/1.0/projects/:project_id/request-forms");
api.project_request_forms.update_request_form = api.endpoint("/api/1.0/projects/:project_id/request-forms/:request_form_id");
api.project_request_forms.copy_request_form = api.endpoint("/api/1.0/projects/:project_id/request-forms/:request_form_id/copy");
api.project_request_forms.delete_request_form = api.endpoint("/api/1.0/projects/:project_id/request-forms/:request_form_id");
api.project_views = {};
api.project_views.list_views = api.endpoint("/api/1.0/projects/:project_id/views");
api.project_views.get_view = api.endpoint("/api/1.0/projects/:project_id/views/:view_id");
api.project_views.create_view = api.endpoint("/api/1.0/projects/:project_id/views");
api.project_views.update_view = api.endpoint("/api/1.0/projects/:project_id/views/:view_id");
api.project_views.reorder_view = api.endpoint("/api/1.0/projects/:project_id/views/:view_id/reorder");
api.project_views.delete_view = api.endpoint("/api/1.0/projects/:project_id/views/:view_id");
api.project_views.list_view_categories = api.endpoint("/api/1.0/projects/:project_id/views/categories");
api.project_views.create_view_category = api.endpoint("/api/1.0/projects/:project_id/views/categories");
api.project_views.update_view_category = api.endpoint("/api/1.0/projects/:project_id/views/categories/:category_id");
api.project_views.reorder_view_category = api.endpoint("/api/1.0/projects/:project_id/views/categories/:category_id/reorder");
api.project_views.delete_view_category = api.endpoint("/api/1.0/projects/:project_id/views/categories/:category_id");
api.project_webhooks = {};
api.project_webhooks.list_webhooks = api.endpoint("/api/1.0/projects/:project_id/webhooks");
api.project_webhooks.get_webhook = api.endpoint("/api/1.0/projects/:project_id/webhooks/:webhook_id");
api.project_webhooks.create_webhook = api.endpoint("/api/1.0/projects/:project_id/webhooks");
api.project_webhooks.update_webhook = api.endpoint("/api/1.0/projects/:project_id/webhooks/:webhook_id");
api.project_webhooks.delete_webhook = api.endpoint("/api/1.0/projects/:project_id/webhooks/:webhook_id");
api.project_automations = {};
api.project_automations.list_automation_rules = api.endpoint("/api/1.0/projects/:project_id/automations");
api.project_automations.create_automation_rule = api.endpoint("/api/1.0/projects/:project_id/automations");
api.project_automations.get_automation_rule = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id");
api.project_automations.create_automation_rule_run_token = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/run-token");
api.project_automations.invalidate_all_automation_rule_run_tokens = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/invalidate-all-run-tokens");
api.project_automations.get_automation_states = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/states");
api.project_automations.get_automation_error_states = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/states/errors");
api.project_automations.clear_all_automation_error_states = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/states/errors");
api.project_automations.get_automation_activities = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/activities");
api.project_automations.trigger_automation_rule = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/trigger");
api.project_automations.update_automation_rule = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id");
api.project_automations.delete_automation_rule = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id");
api.project_automations.copy_automation_rule = api.endpoint("/api/1.0/projects/:project_id/automations/:rule_id/copy");
api.project_automations.add_toolbar_action = api.endpoint("/api/1.0/projects/:project_id/automations/toolbars");
api.project_automations.remove_toolbar_action = api.endpoint("/api/1.0/projects/:project_id/automations/toolbars/actions/:rule_id");
api.project_automations.remove_toolbar = api.endpoint("/api/1.0/projects/:project_id/automations/toolbars");
api.project_automations.list_toolbar_actions = api.endpoint("/api/1.0/projects/:project_id/automations/toolbars/actions");
api.project_files = {};
api.project_files.list_files = api.endpoint("/api/1.0/projects/:project_id/files");
api.project_files.get_file = api.endpoint("/api/1.0/projects/:project_id/files/:file_id");
api.project_files.upload_file = api.endpoint("/api/1.0/projects/:project_id/files");
api.project_portfolio = {};
api.project_portfolio.list_portfolio_projects = api.endpoint("/api/1.0/projects/:project_id/portfolio/projects");
api.project_portfolio.add_project_to_portfolio = api.endpoint("/api/1.0/projects/:project_id/portfolio/projects");
api.project_portfolio.set_portfolio_projects = api.endpoint("/api/1.0/projects/:project_id/portfolio/projects");
api.project_portfolio.remove_project_from_portfolio = api.endpoint("/api/1.0/projects/:project_id/portfolio/projects/:portfolio_project_id");
api.project_portfolio.search = api.endpoint("/api/1.0/projects/:project_id/portfolio/search");
api.project_portfolio.list_group_by_possibilities = api.endpoint("/api/1.0/projects/:project_id/portfolio/group-by-list");
api.project_portfolio.list_group_by_groups = api.endpoint("/api/1.0/projects/:project_id/portfolio/group-by-groups");
api.project_portfolio.list_filterable_fields = api.endpoint("/api/1.0/projects/:project_id/portfolio/filterable-fields");
api.cards = {};
api.cards.get_attributes = api.endpoint("/api/1.0/cards/:card_id/attributes");
api.cards.get_attribute = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id");
api.cards.get_attribute_value = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id/value");
api.cards.list_attribute_choices = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id/choices");
api.cards.set_attributes = api.endpoint("/api/1.0/cards/:card_id/attributes");
api.cards.clear_attributes = api.endpoint("/api/1.0/cards/:card_id/attributes");
api.cards.set_attribute = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id");
api.cards.append_attribute = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id/append");
api.cards.pop_attribute = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id/pop");
api.cards.clear_attribute = api.endpoint("/api/1.0/cards/:card_id/attributes/:attr_id");
api.cards.get_card = api.endpoint("/api/1.0/cards/:card_id");
api.cards.remove_board = api.endpoint("/api/1.0/cards/:card_id/board");
api.cards.get_change_history = api.endpoint("/api/1.0/cards/:card_id/history");
api.cards.update = api.endpoint("/api/1.0/cards/:card_id");
api.cards.set_state = api.endpoint("/api/1.0/cards/:card_id/state");
api.cards.list_states = api.endpoint("/api/1.0/cards/:card_id/states");
api.cards.delete = api.endpoint("/api/1.0/cards/:card_id");
api.cards.get_self_attributes = api.endpoint("/api/1.0/cards/:card_id/self-attributes");
api.cards.update_self_attributes = api.endpoint("/api/1.0/cards/:card_id/self-attributes");
api.cards.switch_model = api.endpoint("/api/1.0/cards/:card_id/model");
api.cards.relocate = api.endpoint("/api/1.0/cards/:card_id/relocate");
api.cards.copy = api.endpoint("/api/1.0/cards/:card_id/copy");
api.cards.convert_to_project = api.endpoint("/api/1.0/cards/:card_id/convert-to-project");
api.cards.add_to_group = api.endpoint("/api/1.0/cards/:card_id/add-to-group");
api.cards.remove_from_group = api.endpoint("/api/1.0/cards/:card_id/remove-from-group");
api.cards.switch_group = api.endpoint("/api/1.0/cards/:card_id/switch-group");
api.cards.remove_from_group_type = api.endpoint("/api/1.0/cards/:card_id/remove-from-group-type");
api.cards.archive = api.endpoint("/api/1.0/cards/:card_id/archive");
api.cards.restore = api.endpoint("/api/1.0/cards/:card_id/archive");
api.cards.get_subscription = api.endpoint("/api/1.0/cards/:card_id/subscription");
api.cards.subscribe = api.endpoint("/api/1.0/cards/:card_id/subscription");
api.cards.unsubscribe = api.endpoint("/api/1.0/cards/:card_id/subscription");
api.cards.favorite = api.endpoint("/api/1.0/cards/:card_id/pin");
api.cards.favorite = api.endpoint("/api/1.0/cards/:card_id/favorite");
api.cards.unfavorite = api.endpoint("/api/1.0/cards/:card_id/pin");
api.cards.unfavorite = api.endpoint("/api/1.0/cards/:card_id/favorite");
api.cards.create_child = api.endpoint("/api/1.0/cards/:card_id/children");
api.cards.list_children = api.endpoint("/api/1.0/cards/:card_id/children");
api.cards.list_archived_children = api.endpoint("/api/1.0/cards/:card_id/children/archived");
api.cards.list_descendants = api.endpoint("/api/1.0/cards/:card_id/descendants");
api.cards.list_archived_descendants = api.endpoint("/api/1.0/cards/:card_id/descendants/archived");
api.cards.get_hierarchy = api.endpoint("/api/1.0/cards/:card_id/hierarchy");
api.cards.list_reminders = api.endpoint("/api/1.0/cards/:card_id/reminders");
api.cards.matches = api.endpoint("/api/1.0/cards/:card_id/matches");
api.cards.check_valid_groups = api.endpoint("/api/1.0/cards/:card_id/valid-in-groups");
api.cards.get_card_request = api.endpoint("/api/1.0/cards/:card_id/request");
api.cards.create_card_request = api.endpoint("/api/1.0/cards/:card_id/request");
api.cards.delete_card_request = api.endpoint("/api/1.0/cards/:card_id/request");
api.cards.query_card = api.endpoint("/api/1.0/cards/:card_id/query");
api.cards.list_card_automation_states = api.endpoint("/api/1.0/cards/:card_id/automation-states");
api.cards.cancel_card_automation_state = api.endpoint("/api/1.0/cards/:card_id/automation-states/:state_id");
api.calendar = {};
api.calendar.get_url = api.endpoint("/api/1.0/cards/:card_id/calendar/url");
api.calendar.get_calendar = api.endpoint("/api/1.0/ical/:token/events.ics");
api.card_groups = {};
api.card_groups.list_all = api.endpoint("/api/1.0/cards/:card_id/groups");
api.card_groups.list_archived = api.endpoint("/api/1.0/cards/:card_id/groups/archived");
api.card_groups.create_group = api.endpoint("/api/1.0/cards/:card_id/groups");
api.card_groups.toggle_all_flow_indicators = api.endpoint("/api/1.0/cards/:card_id/groups/toggle-flow-indicators");
api.card_groups.get = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id");
api.card_groups.update = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id");
api.card_groups.list_cards = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/cards");
api.card_groups.list_archived_cards = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/archives");
api.card_groups.relocate = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/relocate");
api.card_groups.archive = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/archive");
api.card_groups.restore = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/archive");
api.card_groups.get_subscription = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/subscription");
api.card_groups.subscribe = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/subscription");
api.card_groups.unsubscribe = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/subscription");
api.card_groups.delete = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id");
api.card_groups.set_cards_state = api.endpoint("/api/1.0/cards/:card_id/groups/:group_id/set-cards-state");
api.card_reminders = {};
api.card_reminders.create_reminder = api.endpoint("/api/1.0/cards/:card_id/reminders");
api.card_reminders.delete_reminder = api.endpoint("/api/1.0/cards/:card_id/reminders/:reminder_id");
api.card_stream = {};
api.card_stream.list_stream = api.endpoint("/api/1.0/cards/:card_id/stream");
api.card_stream.list_activities = api.endpoint("/api/1.0/cards/:card_id/activities");
api.card_stream.create_activity = api.endpoint("/api/1.0/cards/:card_id/activities");
api.card_stream.list_comments = api.endpoint("/api/1.0/cards/:card_id/comments");
api.card_stream.post_comment = api.endpoint("/api/1.0/cards/:card_id/comments");
api.card_stream.get_comment = api.endpoint("/api/1.0/cards/:card_id/comments/:comment_id");
api.card_stream.edit_comment = api.endpoint("/api/1.0/cards/:card_id/comments/:comment_id");
api.card_stream.delete_comment = api.endpoint("/api/1.0/cards/:card_id/comments/:comment_id");
api.card_stream.pin_comment = api.endpoint("/api/1.0/cards/:card_id/comments/:comment_id/pin");
api.card_stream.get_pinned_comment = api.endpoint("/api/1.0/cards/:card_id/comments/pinned");
api.card_stream.unpin_comment = api.endpoint("/api/1.0/cards/:card_id/comments/pinned");
api.card_stream.upload_file = api.endpoint("/api/1.0/cards/:card_id/comments/upload_file");
api.card_stream.list_logs = api.endpoint("/api/1.0/cards/:card_id/logs");
api.card_stream.add_log = api.endpoint("/api/1.0/cards/:card_id/logs");
api.card_stream.get_log = api.endpoint("/api/1.0/cards/:card_id/logs/:log_id");
api.card_stream.edit_log = api.endpoint("/api/1.0/cards/:card_id/logs/:log_id");
api.card_stream.delete_log = api.endpoint("/api/1.0/cards/:card_id/logs/:log_id");
api.admin = {};
api.admin.get_admin_config = api.endpoint("/api/1.0/admin/config");
api.admin.get_stats = api.endpoint("/api/1.0/admin/stats");
api.admin.list_organizations = api.endpoint("/api/1.0/admin/organizations");
api.admin.export_organizations = api.endpoint("/api/1.0/admin/organizations.xlsx");
api.admin.export_organizations_memberships = api.endpoint("/api/1.0/admin/organizations-memberships.xlsx");
api.admin.create_org = api.endpoint("/api/1.0/admin/organizations");
api.admin.update_org = api.endpoint("/api/1.0/admin/organizations/:org_id");
api.admin.bulk_delete_orgs = api.endpoint("/api/1.0/admin/organizations");
api.admin.list_users = api.endpoint("/api/1.0/admin/users");
api.admin.export_users = api.endpoint("/api/1.0/admin/users.xlsx");
api.admin.get_user = api.endpoint("/api/1.0/admin/users/:user_id");
api.admin.list_user_projects = api.endpoint("/api/1.0/admin/users/:user_id/projects");
api.admin.list_user_org_memberships = api.endpoint("/api/1.0/admin/users/:user_id/org-memberships");
api.admin.create_user = api.endpoint("/api/1.0/admin/users");
api.admin.update_user = api.endpoint("/api/1.0/admin/users/:user_id");
api.admin.bulk_update_users = api.endpoint("/api/1.0/admin/users");
api.admin.delete_user = api.endpoint("/api/1.0/admin/users/:user_id");
api.admin.bulk_delete_users = api.endpoint("/api/1.0/admin/users");
api.admin.bulk_import_users_csv = api.endpoint("/api/1.0/admin/bulk/users/import");
api.admin.bulk_delete_users_csv = api.endpoint("/api/1.0/admin/bulk/users/delete");
api.admin.reset_password = api.endpoint("/api/1.0/admin/users/:user_id/reset-password");
api.admin.logout_user = api.endpoint("/api/1.0/admin/users/:user_id/logout");
api.admin.disable_2fa = api.endpoint("/api/1.0/admin/users/:user_id/disable-2fa");
api.admin.delete_project = api.endpoint("/api/1.0/admin/users/:user_id/projects/:project_id");
api.admin.import_org_from_file = api.endpoint("/api/1.0/admin/import-org-from-file");
api.admin.import_org_from_url = api.endpoint("/api/1.0/admin/import-org-from-url");
api.admin.create_org_billing_account = api.endpoint("/api/1.0/admin/organizations/:org_id/billing");
api.admin.update_billing_account = api.endpoint("/api/1.0/admin/billing/:account_id");
api.admin.delete_billing_account = api.endpoint("/api/1.0/admin/billing/:account_id");
api.admin.create_stripe_customer = api.endpoint("/api/1.0/admin/billing/:account_id/stripe-customer");
api.admin.force_update_stripe = api.endpoint("/api/1.0/admin/billing/:account_id/force-update-stripe");
api.admin.force_update_from_stripe = api.endpoint("/api/1.0/admin/billing/:account_id/force-update-from-stripe");
api.admin.charge_stripe_invoice_items = api.endpoint("/api/1.0/admin/billing/:account_id/charge-stripe-invoice-items");
api.admin.get_logs = api.endpoint("/api/1.0/admin/logs");
api.oauth = {};
api.oauth.list_apps = api.endpoint("/api/1.0/oauth-apps");
api.oauth.create_app = api.endpoint("/api/1.0/oauth-apps");
api.oauth.update_app = api.endpoint("/api/1.0/oauth-apps/:app_id");
api.oauth.delete_app = api.endpoint("/api/1.0/oauth-apps/:app_id");
api.emailing_templates = {};
api.emailing_templates.list_email_templates = api.endpoint("/api/1.0/projects/:project_id/email-templates");
api.emailing_templates.get_email_template = api.endpoint("/api/1.0/projects/:project_id/email-templates/:email_template_id");
api.emailing_templates.create_email_template = api.endpoint("/api/1.0/projects/:project_id/email-templates");
api.emailing_templates.update_email_template = api.endpoint("/api/1.0/projects/:project_id/email-templates/:email_template_id");
api.emailing_templates.delete_email_template = api.endpoint("/api/1.0/projects/:project_id/email-templates/:email_template_id");
api.emailing_templates.send_test_email = api.endpoint("/api/1.0/projects/:project_id/email-templates/:email_template_id/test");
api.emailing_templates.list_template_markers = api.endpoint("/api/1.0/projects/:project_id/email-templates/template-markers");
api.emailing_templates.get_smtp_connection = api.endpoint("/api/1.0/projects/:project_id/email-templates/smtp-connection");
api.emailing_templates.configure_smtp_connection = api.endpoint("/api/1.0/projects/:project_id/email-templates/smtp-connection");
api.sso = {};
api.sso.update_sso_config = api.endpoint("/api/1.0/organizations/:org_id/sso");
api.sso.setup_sso_provider = api.endpoint("/api/1.0/organizations/:org_id/sso/setup");
api.sso.clear_sso_config = api.endpoint("/api/1.0/organizations/:org_id/sso");
api.sso.get_sso_config = api.endpoint("/api/1.0/organizations/:org_id/sso");
api.sso.get_available_providers = api.endpoint("/api/1.0/organizations/:org_id/sso/providers");
api.google_integration = {};
api.google_integration.get_tokens = api.endpoint("/api/1.0/google-integration/tokens");
var api_default = api;

// virtual-ns:angular
var angular_default = angular;

// node_modules/@solid-primitives/utils/dist/chunk/R5675YMU.js
var isClient = !isServer;
var isDev2 = isClient && !!DEV;
var noop = () => void 0;
function isObject(value2) {
  return value2 !== null && (typeof value2 === "object" || typeof value2 === "function");
}
var isNonNullable = (i3) => i3 != null;
var filterNonNullable = (arr) => arr.filter(isNonNullable);
var arrayEquals = (a3, b3) => a3 === b3 || a3.length === b3.length && a3.every((e3, i3) => e3 === b3[i3]);
var access = (v3) => typeof v3 === "function" && !v3.length ? v3() : v3;
var asArray = (value2) => Array.isArray(value2) ? value2 : value2 ? [value2] : [];
function accessWith(valueOrFn, ...args) {
  return typeof valueOrFn === "function" ? valueOrFn(...args) : valueOrFn;
}
var tryOnCleanup = isDev2 ? (fn) => getOwner() ? onCleanup(fn) : fn : onCleanup;
function createHydratableSignal(serverValue, update2, options2) {
  if (isServer) {
    return createSignal(serverValue, options2);
  }
  if (sharedConfig.context) {
    const [state, setState] = createSignal(serverValue, options2);
    onMount(() => setState(() => update2()));
    return [state, setState];
  }
  return createSignal(update2(), options2);
}
function handleDiffArray(current, prev, handleAdded, handleRemoved) {
  const currLength = current.length;
  const prevLength = prev.length;
  let i3 = 0;
  if (!prevLength) {
    for (; i3 < currLength; i3++)
      handleAdded(current[i3]);
    return;
  }
  if (!currLength) {
    for (; i3 < prevLength; i3++)
      handleRemoved(prev[i3]);
    return;
  }
  for (; i3 < prevLength; i3++) {
    if (prev[i3] !== current[i3])
      break;
  }
  let prevEl;
  let currEl;
  prev = prev.slice(i3);
  current = current.slice(i3);
  for (prevEl of prev) {
    if (!current.includes(prevEl))
      handleRemoved(prevEl);
  }
  for (currEl of current) {
    if (!prev.includes(currEl))
      handleAdded(currEl);
  }
}

// node_modules/@solid-primitives/event-listener/dist/index.js
function makeEventListener(target, type, handler, options2) {
  target.addEventListener(type, handler, options2);
  return tryOnCleanup(target.removeEventListener.bind(target, type, handler, options2));
}
function createEventListener(targets, type, handler, options2) {
  if (isServer)
    return;
  const attachListeners = () => {
    asArray(access(targets)).forEach((el2) => {
      if (el2)
        asArray(access(type)).forEach((type2) => makeEventListener(el2, type2, handler, options2));
    });
  };
  if (typeof targets === "function")
    createEffect(attachListeners);
  else
    createRenderEffect(attachListeners);
}

// node_modules/@solid-primitives/rootless/dist/index.js
function createSubRoot(fn, ...owners) {
  if (owners.length === 0)
    owners = [getOwner()];
  return createRoot((dispose2) => {
    asArray(access(owners)).forEach(
      (owner) => owner && runWithOwner(owner, onCleanup.bind(void 0, dispose2))
    );
    return fn(dispose2);
  }, owners[0]);
}
function createDisposable(fn, ...owners) {
  return createSubRoot(
    (dispose2) => {
      fn(dispose2);
      return dispose2;
    },
    ...owners
  );
}
function createSingletonRoot(factory, detachedOwner = getOwner()) {
  let listeners = 0, value2, disposeRoot;
  return () => {
    listeners++;
    onCleanup(() => {
      listeners--;
      queueMicrotask(() => {
        if (!listeners && disposeRoot) {
          disposeRoot();
          disposeRoot = value2 = void 0;
        }
      });
    });
    if (!disposeRoot) {
      createRoot((dispose2) => value2 = factory(disposeRoot = dispose2), detachedOwner);
    }
    return value2;
  };
}
function createHydratableSingletonRoot(factory) {
  const owner = getOwner();
  const singleton2 = createSingletonRoot(factory, owner);
  return () => isServer || sharedConfig.context ? createRoot(factory, owner) : singleton2();
}

// node_modules/@solid-primitives/static-store/dist/index.js
function createStaticStore(init) {
  const copy2 = { ...init }, store2 = { ...init }, cache5 = {};
  const getValue2 = (key2) => {
    let signal = cache5[key2];
    if (!signal) {
      if (!getListener())
        return copy2[key2];
      cache5[key2] = signal = createSignal(copy2[key2], { internal: true });
      delete copy2[key2];
    }
    return signal[0]();
  };
  for (const key2 in init) {
    Object.defineProperty(store2, key2, { get: () => getValue2(key2), enumerable: true });
  }
  const setValue2 = (key2, value2) => {
    const signal = cache5[key2];
    if (signal)
      return signal[1](value2);
    if (key2 in copy2)
      copy2[key2] = accessWith(value2, [copy2[key2]]);
  };
  return [
    store2,
    (a3, b3) => {
      if (isObject(a3)) {
        const entries2 = untrack(
          () => Object.entries(accessWith(a3, store2))
        );
        batch(() => {
          for (const [key2, value2] of entries2)
            setValue2(key2, () => value2);
        });
      } else
        setValue2(a3, b3);
      return store2;
    }
  ];
}
function createHydratableStaticStore(serverValue, update2) {
  if (isServer)
    return createStaticStore(serverValue);
  if (sharedConfig.context) {
    const [state, setState] = createStaticStore(serverValue);
    onMount(() => setState(update2()));
    return [state, setState];
  }
  return createStaticStore(update2());
}

// node_modules/@solid-primitives/resize-observer/dist/index.js
function makeResizeObserver(callback, options2) {
  if (isServer) {
    return { observe: noop, unobserve: noop };
  }
  const observer = new ResizeObserver(callback);
  onCleanup(observer.disconnect.bind(observer));
  return {
    observe: (ref) => observer.observe(ref, options2),
    unobserve: observer.unobserve.bind(observer)
  };
}
function createResizeObserver(targets, onResize, options2) {
  if (isServer)
    return;
  const previousMap = /* @__PURE__ */ new WeakMap(), { observe: observe2, unobserve } = makeResizeObserver((entries2) => {
    for (const entry of entries2) {
      const { contentRect, target } = entry, width = Math.round(contentRect.width), height = Math.round(contentRect.height), previous = previousMap.get(target);
      if (!previous || previous.width !== width || previous.height !== height) {
        onResize(contentRect, target, entry);
        previousMap.set(target, { width, height });
      }
    }
  }, options2);
  createEffect((prev) => {
    const refs = filterNonNullable(asArray(access(targets)));
    handleDiffArray(refs, prev, observe2, unobserve);
    return refs;
  }, []);
}
var WINDOW_SIZE_FALLBACK = { width: 0, height: 0 };
function getWindowSize() {
  if (isServer)
    return { ...WINDOW_SIZE_FALLBACK };
  return {
    width: window.innerWidth,
    height: window.innerHeight
  };
}
function createWindowSize() {
  if (isServer) {
    return WINDOW_SIZE_FALLBACK;
  }
  const [size4, setSize] = createHydratableStaticStore(WINDOW_SIZE_FALLBACK, getWindowSize);
  makeEventListener(window, "resize", () => setSize(getWindowSize()));
  return size4;
}
var useWindowSize = /* @__PURE__ */ createHydratableSingletonRoot(createWindowSize);

// public/app/ui/base/screensize.js
var breakpoints = {
  xs: 0,
  sm: 768,
  md: 992,
  lg: 1200
};
var size = useWindowSize();
var screensize = createMemo(() => {
  const sortedBreakpoints = Object.entries(breakpoints).sort((a3, b3) => b3[1] - a3[1]);
  for (let [name2, breakpointSize] of sortedBreakpoints) {
    if (size.width >= breakpointSize) {
      return name2;
    }
  }
});
function getScreensize() {
  return screensize();
}
function isScreensizeXS() {
  return getScreensize() === "xs";
}

// public/app/utils/events.js
function createEvent() {
  let subscribers = [];
  const dispatch = function(...args) {
    for (let fn of subscribers) {
      fn(...args);
    }
  };
  dispatch.subscribe = function(fn) {
    subscribers.push(fn);
    return () => {
      subscribers = subscribers.filter((f3) => f3 !== fn);
    };
  };
  return dispatch;
}
function onEvent(event2, fn) {
  onMount(() => onCleanup(event2.subscribe(fn)));
}
var EventedMixin = {
  initEventedMixin() {
    this.listeners = {};
  },
  _getListeners(eventName) {
    if (typeof this.listeners[eventName] === "undefined") {
      this.listeners[eventName] = [];
    }
    return this.listeners[eventName];
  },
  trigger(eventName, ...args) {
    this._getListeners(eventName).slice(0).forEach((listener) => listener(...args));
  },
  on(eventName, callback) {
    const listeners = this._getListeners(eventName);
    listeners.push(callback);
    const off = function() {
      const i3 = listeners.indexOf(callback);
      if (i3 >= 0) {
        listeners.splice(i3, 1);
      }
    };
    off.callback = callback;
    return off;
  },
  $on(scope, eventName, callback) {
    const cb2 = (...args) => {
      scope.$applyAsync(() => {
        callback && callback(...args);
      });
    };
    const off = this.on(eventName, cb2);
    scope.$on("$destroy", off);
    return off;
  },
  watch(propName, callback, immediate) {
    if (immediate === void 0 || immediate) {
      callback(this[propName]);
    }
    return this.on(propName + "Changed", callback);
  },
  $watch(scope, propName, callback, immediate) {
    if (immediate === void 0 || immediate) {
      callback(this[propName]);
    }
    return this.$on(scope, propName + "Changed", callback);
  },
  clearListeners(eventName) {
    if (eventName) {
      if (typeof this.listeners[eventName] !== "undefined") {
        this.listeners[eventName] = [];
      }
    } else {
      this.listeners = {};
    }
  }
};

// public/app/services/connectivity.js
var [isConnectionManagerDisabled, setConnectionManagerDisabled] = createSignal(false);
var [isOnline, setOnline] = createSignal(true);
var [isConnected, setConnected] = createSignal(true);
var onConnectivityRecovered = createEvent();
function disableConnectionManager() {
  setConnectionManagerDisabled(true);
  setConnected(true);
}
function notifyConnectionLost() {
  if (isConnectionManagerDisabled()) return;
  setConnected(false);
}
function notifyConnectionRecovered() {
  if (!isConnected()) {
    setConnected(true);
    onConnectivityRecovered();
  }
}
function ensureConnectivity(fn) {
  if (isConnected()) {
    fn();
  } else {
    const off = onConnectivityRecovered(() => {
      fn();
      off();
    });
  }
}
var connectionLostTimeout;
makeEventListener(window, "online", () => {
  setOnline(true);
  if (connectionLostTimeout) {
    clearTimeout(connectionLostTimeout);
  }
  notifyConnectionRecovered();
});
makeEventListener(window, "offline", () => {
  setOnline(false);
  connectionLostTimeout = setTimeout(() => notifyConnectionLost(), 3e3);
});

// virtual-ns:jquery
var jquery_default = $;

// node_modules/solid-js/store/dist/store.js
var $RAW = Symbol("store-raw");
var $NODE = Symbol("store-node");
var $HAS = Symbol("store-has");
var $SELF = Symbol("store-self");
function wrap$1(value2) {
  let p4 = value2[$PROXY];
  if (!p4) {
    Object.defineProperty(value2, $PROXY, {
      value: p4 = new Proxy(value2, proxyTraps$1)
    });
    if (!Array.isArray(value2)) {
      const keys5 = Object.keys(value2), desc = Object.getOwnPropertyDescriptors(value2);
      for (let i3 = 0, l3 = keys5.length; i3 < l3; i3++) {
        const prop2 = keys5[i3];
        if (desc[prop2].get) {
          Object.defineProperty(value2, prop2, {
            enumerable: desc[prop2].enumerable,
            get: desc[prop2].get.bind(p4)
          });
        }
      }
    }
  }
  return p4;
}
function isWrappable(obj) {
  let proto;
  return obj != null && typeof obj === "object" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));
}
function unwrap(item, set4 = /* @__PURE__ */ new Set()) {
  let result2, unwrapped, v3, prop2;
  if (result2 = item != null && item[$RAW]) return result2;
  if (!isWrappable(item) || set4.has(item)) return item;
  if (Array.isArray(item)) {
    if (Object.isFrozen(item)) item = item.slice(0);
    else set4.add(item);
    for (let i3 = 0, l3 = item.length; i3 < l3; i3++) {
      v3 = item[i3];
      if ((unwrapped = unwrap(v3, set4)) !== v3) item[i3] = unwrapped;
    }
  } else {
    if (Object.isFrozen(item)) item = Object.assign({}, item);
    else set4.add(item);
    const keys5 = Object.keys(item), desc = Object.getOwnPropertyDescriptors(item);
    for (let i3 = 0, l3 = keys5.length; i3 < l3; i3++) {
      prop2 = keys5[i3];
      if (desc[prop2].get) continue;
      v3 = item[prop2];
      if ((unwrapped = unwrap(v3, set4)) !== v3) item[prop2] = unwrapped;
    }
  }
  return item;
}
function getNodes(target, symbol) {
  let nodes2 = target[symbol];
  if (!nodes2)
    Object.defineProperty(target, symbol, {
      value: nodes2 = /* @__PURE__ */ Object.create(null)
    });
  return nodes2;
}
function getNode(nodes2, property2, value2) {
  if (nodes2[property2]) return nodes2[property2];
  const [s3, set4] = createSignal(value2, {
    equals: false,
    internal: true
  });
  s3.$ = set4;
  return nodes2[property2] = s3;
}
function proxyDescriptor$1(target, property2) {
  const desc = Reflect.getOwnPropertyDescriptor(target, property2);
  if (!desc || desc.get || !desc.configurable || property2 === $PROXY || property2 === $NODE)
    return desc;
  delete desc.value;
  delete desc.writable;
  desc.get = () => target[$PROXY][property2];
  return desc;
}
function trackSelf(target) {
  getListener() && getNode(getNodes(target, $NODE), $SELF)();
}
function ownKeys(target) {
  trackSelf(target);
  return Reflect.ownKeys(target);
}
var proxyTraps$1 = {
  get(target, property2, receiver) {
    if (property2 === $RAW) return target;
    if (property2 === $PROXY) return receiver;
    if (property2 === $TRACK) {
      trackSelf(target);
      return receiver;
    }
    const nodes2 = getNodes(target, $NODE);
    const tracked = nodes2[property2];
    let value2 = tracked ? tracked() : target[property2];
    if (property2 === $NODE || property2 === $HAS || property2 === "__proto__") return value2;
    if (!tracked) {
      const desc = Object.getOwnPropertyDescriptor(target, property2);
      if (getListener() && (typeof value2 !== "function" || target.hasOwnProperty(property2)) && !(desc && desc.get))
        value2 = getNode(nodes2, property2, value2)();
    }
    return isWrappable(value2) ? wrap$1(value2) : value2;
  },
  has(target, property2) {
    if (property2 === $RAW || property2 === $PROXY || property2 === $TRACK || property2 === $NODE || property2 === $HAS || property2 === "__proto__")
      return true;
    getListener() && getNode(getNodes(target, $HAS), property2)();
    return property2 in target;
  },
  set() {
    return true;
  },
  deleteProperty() {
    return true;
  },
  ownKeys,
  getOwnPropertyDescriptor: proxyDescriptor$1
};
function setProperty(state, property2, value2, deleting = false) {
  if (!deleting && state[property2] === value2) return;
  const prev = state[property2], len = state.length;
  if (value2 === void 0) {
    delete state[property2];
    if (state[$HAS] && state[$HAS][property2] && prev !== void 0) state[$HAS][property2].$();
  } else {
    state[property2] = value2;
    if (state[$HAS] && state[$HAS][property2] && prev === void 0) state[$HAS][property2].$();
  }
  let nodes2 = getNodes(state, $NODE), node;
  if (node = getNode(nodes2, property2, prev)) node.$(() => value2);
  if (Array.isArray(state) && state.length !== len) {
    for (let i3 = state.length; i3 < len; i3++) (node = nodes2[i3]) && node.$();
    (node = getNode(nodes2, "length", len)) && node.$(state.length);
  }
  (node = nodes2[$SELF]) && node.$();
}
function mergeStoreNode(state, value2) {
  const keys5 = Object.keys(value2);
  for (let i3 = 0; i3 < keys5.length; i3 += 1) {
    const key2 = keys5[i3];
    setProperty(state, key2, value2[key2]);
  }
}
function updateArray(current, next2) {
  if (typeof next2 === "function") next2 = next2(current);
  next2 = unwrap(next2);
  if (Array.isArray(next2)) {
    if (current === next2) return;
    let i3 = 0, len = next2.length;
    for (; i3 < len; i3++) {
      const value2 = next2[i3];
      if (current[i3] !== value2) setProperty(current, i3, value2);
    }
    setProperty(current, "length", len);
  } else mergeStoreNode(current, next2);
}
function updatePath(current, path, traversed = []) {
  let part, prev = current;
  if (path.length > 1) {
    part = path.shift();
    const partType = typeof part, isArray3 = Array.isArray(current);
    if (Array.isArray(part)) {
      for (let i3 = 0; i3 < part.length; i3++) {
        updatePath(current, [part[i3]].concat(path), traversed);
      }
      return;
    } else if (isArray3 && partType === "function") {
      for (let i3 = 0; i3 < current.length; i3++) {
        if (part(current[i3], i3)) updatePath(current, [i3].concat(path), traversed);
      }
      return;
    } else if (isArray3 && partType === "object") {
      const { from: from2 = 0, to = current.length - 1, by = 1 } = part;
      for (let i3 = from2; i3 <= to; i3 += by) {
        updatePath(current, [i3].concat(path), traversed);
      }
      return;
    } else if (path.length > 1) {
      updatePath(current[part], path, [part].concat(traversed));
      return;
    }
    prev = current[part];
    traversed = [part].concat(traversed);
  }
  let value2 = path[0];
  if (typeof value2 === "function") {
    value2 = value2(prev, traversed);
    if (value2 === prev) return;
  }
  if (part === void 0 && value2 == void 0) return;
  value2 = unwrap(value2);
  if (part === void 0 || isWrappable(prev) && isWrappable(value2) && !Array.isArray(value2)) {
    mergeStoreNode(prev, value2);
  } else setProperty(current, part, value2);
}
function createStore(...[store2, options2]) {
  const unwrappedStore = unwrap(store2 || {});
  const isArray3 = Array.isArray(unwrappedStore);
  const wrappedStore = wrap$1(unwrappedStore);
  function setStore(...args) {
    batch(() => {
      isArray3 && args.length === 1 ? updateArray(unwrappedStore, args[0]) : updatePath(unwrappedStore, args);
    });
  }
  return [wrappedStore, setStore];
}
var $ROOT = Symbol("store-root");
function applyState(target, parent, property2, merge4, key2) {
  const previous = parent[property2];
  if (target === previous) return;
  const isArray3 = Array.isArray(target);
  if (property2 !== $ROOT && (!isWrappable(target) || !isWrappable(previous) || isArray3 !== Array.isArray(previous) || key2 && target[key2] !== previous[key2])) {
    setProperty(parent, property2, target);
    return;
  }
  if (isArray3) {
    if (target.length && previous.length && (!merge4 || key2 && target[0] && target[0][key2] != null)) {
      let i3, j, start, end, newEnd, item, newIndicesNext, keyVal;
      for (start = 0, end = Math.min(previous.length, target.length); start < end && (previous[start] === target[start] || key2 && previous[start] && target[start] && previous[start][key2] === target[start][key2]); start++) {
        applyState(target[start], previous, start, merge4, key2);
      }
      const temp = new Array(target.length), newIndices = /* @__PURE__ */ new Map();
      for (end = previous.length - 1, newEnd = target.length - 1; end >= start && newEnd >= start && (previous[end] === target[newEnd] || key2 && previous[start] && target[start] && previous[end][key2] === target[newEnd][key2]); end--, newEnd--) {
        temp[newEnd] = previous[end];
      }
      if (start > newEnd || start > end) {
        for (j = start; j <= newEnd; j++) setProperty(previous, j, target[j]);
        for (; j < target.length; j++) {
          setProperty(previous, j, temp[j]);
          applyState(target[j], previous, j, merge4, key2);
        }
        if (previous.length > target.length) setProperty(previous, "length", target.length);
        return;
      }
      newIndicesNext = new Array(newEnd + 1);
      for (j = newEnd; j >= start; j--) {
        item = target[j];
        keyVal = key2 && item ? item[key2] : item;
        i3 = newIndices.get(keyVal);
        newIndicesNext[j] = i3 === void 0 ? -1 : i3;
        newIndices.set(keyVal, j);
      }
      for (i3 = start; i3 <= end; i3++) {
        item = previous[i3];
        keyVal = key2 && item ? item[key2] : item;
        j = newIndices.get(keyVal);
        if (j !== void 0 && j !== -1) {
          temp[j] = previous[i3];
          j = newIndicesNext[j];
          newIndices.set(keyVal, j);
        }
      }
      for (j = start; j < target.length; j++) {
        if (j in temp) {
          setProperty(previous, j, temp[j]);
          applyState(target[j], previous, j, merge4, key2);
        } else setProperty(previous, j, target[j]);
      }
    } else {
      for (let i3 = 0, len = target.length; i3 < len; i3++) {
        applyState(target[i3], previous, i3, merge4, key2);
      }
    }
    if (previous.length > target.length) setProperty(previous, "length", target.length);
    return;
  }
  const targetKeys = Object.keys(target);
  for (let i3 = 0, len = targetKeys.length; i3 < len; i3++) {
    applyState(target[targetKeys[i3]], previous, targetKeys[i3], merge4, key2);
  }
  const previousKeys = Object.keys(previous);
  for (let i3 = 0, len = previousKeys.length; i3 < len; i3++) {
    if (target[previousKeys[i3]] === void 0) setProperty(previous, previousKeys[i3], void 0);
  }
}
function reconcile(value2, options2 = {}) {
  const { merge: merge4, key: key2 = "id" } = options2, v3 = unwrap(value2);
  return (state) => {
    if (!isWrappable(state) || !isWrappable(v3)) return v3;
    const res = applyState(
      v3,
      {
        [$ROOT]: state
      },
      $ROOT,
      merge4,
      key2
    );
    return res === void 0 ? state : res;
  };
}
var producers = /* @__PURE__ */ new WeakMap();
var setterTraps = {
  get(target, property2) {
    if (property2 === $RAW) return target;
    const value2 = target[property2];
    let proxy;
    return isWrappable(value2) ? producers.get(value2) || (producers.set(value2, proxy = new Proxy(value2, setterTraps)), proxy) : value2;
  },
  set(target, property2, value2) {
    setProperty(target, property2, unwrap(value2));
    return true;
  },
  deleteProperty(target, property2) {
    setProperty(target, property2, void 0, true);
    return true;
  }
};
function produce(fn) {
  return (state) => {
    if (isWrappable(state)) {
      let proxy;
      if (!(proxy = producers.get(state))) {
        producers.set(state, proxy = new Proxy(state, setterTraps));
      }
      fn(proxy);
    }
    return state;
  };
}

// public/app/ui/system/theme.js
var import_tinycolor22 = __toESM(require_tinycolor());

// node_modules/underscore/modules/index.js
var modules_exports = {};
__export(modules_exports, {
  VERSION: () => VERSION,
  after: () => after,
  all: () => every,
  allKeys: () => allKeys,
  any: () => some,
  assign: () => extendOwn_default,
  before: () => before,
  bind: () => bind_default,
  bindAll: () => bindAll_default,
  chain: () => chain2,
  chunk: () => chunk,
  clone: () => clone,
  collect: () => map,
  compact: () => compact,
  compose: () => compose,
  constant: () => constant,
  contains: () => contains,
  countBy: () => countBy_default,
  create: () => create,
  debounce: () => debounce,
  default: () => underscore_array_methods_default,
  defaults: () => defaults_default,
  defer: () => defer_default,
  delay: () => delay_default,
  detect: () => find,
  difference: () => difference_default,
  drop: () => rest,
  each: () => each,
  escape: () => escape_default,
  every: () => every,
  extend: () => extend_default,
  extendOwn: () => extendOwn_default,
  filter: () => filter2,
  find: () => find,
  findIndex: () => findIndex_default,
  findKey: () => findKey,
  findLastIndex: () => findLastIndex_default,
  findWhere: () => findWhere,
  first: () => first,
  flatten: () => flatten2,
  foldl: () => reduce_default,
  foldr: () => reduceRight_default,
  forEach: () => each,
  functions: () => functions,
  get: () => get,
  groupBy: () => groupBy_default,
  has: () => has2,
  head: () => first,
  identity: () => identity,
  include: () => contains,
  includes: () => contains,
  indexBy: () => indexBy_default,
  indexOf: () => indexOf_default,
  initial: () => initial,
  inject: () => reduce_default,
  intersection: () => intersection,
  invert: () => invert,
  invoke: () => invoke_default,
  isArguments: () => isArguments_default,
  isArray: () => isArray_default,
  isArrayBuffer: () => isArrayBuffer_default,
  isBoolean: () => isBoolean,
  isDataView: () => isDataView_default,
  isDate: () => isDate_default,
  isElement: () => isElement,
  isEmpty: () => isEmpty,
  isEqual: () => isEqual,
  isError: () => isError_default,
  isFinite: () => isFinite2,
  isFunction: () => isFunction_default,
  isMap: () => isMap_default,
  isMatch: () => isMatch,
  isNaN: () => isNaN2,
  isNull: () => isNull,
  isNumber: () => isNumber_default,
  isObject: () => isObject2,
  isRegExp: () => isRegExp_default,
  isSet: () => isSet_default,
  isString: () => isString_default,
  isSymbol: () => isSymbol_default,
  isTypedArray: () => isTypedArray_default,
  isUndefined: () => isUndefined,
  isWeakMap: () => isWeakMap_default,
  isWeakSet: () => isWeakSet_default,
  iteratee: () => iteratee,
  keys: () => keys2,
  last: () => last2,
  lastIndexOf: () => lastIndexOf_default,
  map: () => map,
  mapObject: () => mapObject,
  matcher: () => matcher,
  matches: () => matcher,
  max: () => max,
  memoize: () => memoize,
  methods: () => functions,
  min: () => min,
  mixin: () => mixin,
  negate: () => negate,
  noop: () => noop2,
  now: () => now_default,
  object: () => object,
  omit: () => omit_default,
  once: () => once_default,
  pairs: () => pairs,
  partial: () => partial_default,
  partition: () => partition_default,
  pick: () => pick_default,
  pluck: () => pluck,
  property: () => property,
  propertyOf: () => propertyOf,
  random: () => random,
  range: () => range,
  reduce: () => reduce_default,
  reduceRight: () => reduceRight_default,
  reject: () => reject,
  rest: () => rest,
  restArguments: () => restArguments,
  result: () => result,
  sample: () => sample,
  select: () => filter2,
  shuffle: () => shuffle,
  size: () => size2,
  some: () => some,
  sortBy: () => sortBy,
  sortedIndex: () => sortedIndex,
  tail: () => rest,
  take: () => first,
  tap: () => tap,
  template: () => template2,
  templateSettings: () => templateSettings_default,
  throttle: () => throttle,
  times: () => times,
  toArray: () => toArray,
  toPath: () => toPath,
  transpose: () => unzip,
  unescape: () => unescape_default,
  union: () => union_default,
  uniq: () => uniq,
  unique: () => uniq,
  uniqueId: () => uniqueId,
  unzip: () => unzip,
  values: () => values,
  where: () => where,
  without: () => without_default,
  wrap: () => wrap,
  zip: () => zip_default
});

// node_modules/underscore/modules/_setup.js
var VERSION = "1.13.4";
var root = typeof self == "object" && self.self === self && self || typeof global == "object" && global.global === global && global || Function("return this")() || {};
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var SymbolProto = typeof Symbol !== "undefined" ? Symbol.prototype : null;
var push = ArrayProto.push;
var slice = ArrayProto.slice;
var toString = ObjProto.toString;
var hasOwnProperty = ObjProto.hasOwnProperty;
var supportsArrayBuffer = typeof ArrayBuffer !== "undefined";
var supportsDataView = typeof DataView !== "undefined";
var nativeIsArray = Array.isArray;
var nativeKeys = Object.keys;
var nativeCreate = Object.create;
var nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
var _isNaN = isNaN;
var _isFinite = isFinite;
var hasEnumBug = !{ toString: null }.propertyIsEnumerable("toString");
var nonEnumerableProps = [
  "valueOf",
  "isPrototypeOf",
  "toString",
  "propertyIsEnumerable",
  "hasOwnProperty",
  "toLocaleString"
];
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;

// node_modules/underscore/modules/restArguments.js
function restArguments(func, startIndex) {
  startIndex = startIndex == null ? func.length - 1 : +startIndex;
  return function() {
    var length = Math.max(arguments.length - startIndex, 0), rest2 = Array(length), index2 = 0;
    for (; index2 < length; index2++) {
      rest2[index2] = arguments[index2 + startIndex];
    }
    switch (startIndex) {
      case 0:
        return func.call(this, rest2);
      case 1:
        return func.call(this, arguments[0], rest2);
      case 2:
        return func.call(this, arguments[0], arguments[1], rest2);
    }
    var args = Array(startIndex + 1);
    for (index2 = 0; index2 < startIndex; index2++) {
      args[index2] = arguments[index2];
    }
    args[startIndex] = rest2;
    return func.apply(this, args);
  };
}

// node_modules/underscore/modules/isObject.js
function isObject2(obj) {
  var type = typeof obj;
  return type === "function" || type === "object" && !!obj;
}

// node_modules/underscore/modules/isNull.js
function isNull(obj) {
  return obj === null;
}

// node_modules/underscore/modules/isUndefined.js
function isUndefined(obj) {
  return obj === void 0;
}

// node_modules/underscore/modules/isBoolean.js
function isBoolean(obj) {
  return obj === true || obj === false || toString.call(obj) === "[object Boolean]";
}

// node_modules/underscore/modules/isElement.js
function isElement(obj) {
  return !!(obj && obj.nodeType === 1);
}

// node_modules/underscore/modules/_tagTester.js
function tagTester(name2) {
  var tag = "[object " + name2 + "]";
  return function(obj) {
    return toString.call(obj) === tag;
  };
}

// node_modules/underscore/modules/isString.js
var isString_default = tagTester("String");

// node_modules/underscore/modules/isNumber.js
var isNumber_default = tagTester("Number");

// node_modules/underscore/modules/isDate.js
var isDate_default = tagTester("Date");

// node_modules/underscore/modules/isRegExp.js
var isRegExp_default = tagTester("RegExp");

// node_modules/underscore/modules/isError.js
var isError_default = tagTester("Error");

// node_modules/underscore/modules/isSymbol.js
var isSymbol_default = tagTester("Symbol");

// node_modules/underscore/modules/isArrayBuffer.js
var isArrayBuffer_default = tagTester("ArrayBuffer");

// node_modules/underscore/modules/isFunction.js
var isFunction = tagTester("Function");
var nodelist = root.document && root.document.childNodes;
if (typeof /./ != "function" && typeof Int8Array != "object" && typeof nodelist != "function") {
  isFunction = function(obj) {
    return typeof obj == "function" || false;
  };
}
var isFunction_default = isFunction;

// node_modules/underscore/modules/_hasObjectTag.js
var hasObjectTag_default = tagTester("Object");

// node_modules/underscore/modules/_stringTagBug.js
var hasStringTagBug = supportsDataView && hasObjectTag_default(new DataView(new ArrayBuffer(8)));
var isIE11 = typeof Map !== "undefined" && hasObjectTag_default(/* @__PURE__ */ new Map());

// node_modules/underscore/modules/isDataView.js
var isDataView = tagTester("DataView");
function ie10IsDataView(obj) {
  return obj != null && isFunction_default(obj.getInt8) && isArrayBuffer_default(obj.buffer);
}
var isDataView_default = hasStringTagBug ? ie10IsDataView : isDataView;

// node_modules/underscore/modules/isArray.js
var isArray_default = nativeIsArray || tagTester("Array");

// node_modules/underscore/modules/_has.js
function has(obj, key2) {
  return obj != null && hasOwnProperty.call(obj, key2);
}

// node_modules/underscore/modules/isArguments.js
var isArguments = tagTester("Arguments");
(function() {
  if (!isArguments(arguments)) {
    isArguments = function(obj) {
      return has(obj, "callee");
    };
  }
})();
var isArguments_default = isArguments;

// node_modules/underscore/modules/isFinite.js
function isFinite2(obj) {
  return !isSymbol_default(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
}

// node_modules/underscore/modules/isNaN.js
function isNaN2(obj) {
  return isNumber_default(obj) && _isNaN(obj);
}

// node_modules/underscore/modules/constant.js
function constant(value2) {
  return function() {
    return value2;
  };
}

// node_modules/underscore/modules/_createSizePropertyCheck.js
function createSizePropertyCheck(getSizeProperty) {
  return function(collection) {
    var sizeProperty = getSizeProperty(collection);
    return typeof sizeProperty == "number" && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
  };
}

// node_modules/underscore/modules/_shallowProperty.js
function shallowProperty(key2) {
  return function(obj) {
    return obj == null ? void 0 : obj[key2];
  };
}

// node_modules/underscore/modules/_getByteLength.js
var getByteLength_default = shallowProperty("byteLength");

// node_modules/underscore/modules/_isBufferLike.js
var isBufferLike_default = createSizePropertyCheck(getByteLength_default);

// node_modules/underscore/modules/isTypedArray.js
var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
function isTypedArray(obj) {
  return nativeIsView ? nativeIsView(obj) && !isDataView_default(obj) : isBufferLike_default(obj) && typedArrayPattern.test(toString.call(obj));
}
var isTypedArray_default = supportsArrayBuffer ? isTypedArray : constant(false);

// node_modules/underscore/modules/_getLength.js
var getLength_default = shallowProperty("length");

// node_modules/underscore/modules/_collectNonEnumProps.js
function emulatedSet(keys5) {
  var hash = {};
  for (var l3 = keys5.length, i3 = 0; i3 < l3; ++i3) hash[keys5[i3]] = true;
  return {
    contains: function(key2) {
      return hash[key2] === true;
    },
    push: function(key2) {
      hash[key2] = true;
      return keys5.push(key2);
    }
  };
}
function collectNonEnumProps(obj, keys5) {
  keys5 = emulatedSet(keys5);
  var nonEnumIdx = nonEnumerableProps.length;
  var constructor = obj.constructor;
  var proto = isFunction_default(constructor) && constructor.prototype || ObjProto;
  var prop2 = "constructor";
  if (has(obj, prop2) && !keys5.contains(prop2)) keys5.push(prop2);
  while (nonEnumIdx--) {
    prop2 = nonEnumerableProps[nonEnumIdx];
    if (prop2 in obj && obj[prop2] !== proto[prop2] && !keys5.contains(prop2)) {
      keys5.push(prop2);
    }
  }
}

// node_modules/underscore/modules/keys.js
function keys2(obj) {
  if (!isObject2(obj)) return [];
  if (nativeKeys) return nativeKeys(obj);
  var keys5 = [];
  for (var key2 in obj) if (has(obj, key2)) keys5.push(key2);
  if (hasEnumBug) collectNonEnumProps(obj, keys5);
  return keys5;
}

// node_modules/underscore/modules/isEmpty.js
function isEmpty(obj) {
  if (obj == null) return true;
  var length = getLength_default(obj);
  if (typeof length == "number" && (isArray_default(obj) || isString_default(obj) || isArguments_default(obj))) return length === 0;
  return getLength_default(keys2(obj)) === 0;
}

// node_modules/underscore/modules/isMatch.js
function isMatch(object2, attrs2) {
  var _keys = keys2(attrs2), length = _keys.length;
  if (object2 == null) return !length;
  var obj = Object(object2);
  for (var i3 = 0; i3 < length; i3++) {
    var key2 = _keys[i3];
    if (attrs2[key2] !== obj[key2] || !(key2 in obj)) return false;
  }
  return true;
}

// node_modules/underscore/modules/underscore.js
function _2(obj) {
  if (obj instanceof _2) return obj;
  if (!(this instanceof _2)) return new _2(obj);
  this._wrapped = obj;
}
_2.VERSION = VERSION;
_2.prototype.value = function() {
  return this._wrapped;
};
_2.prototype.valueOf = _2.prototype.toJSON = _2.prototype.value;
_2.prototype.toString = function() {
  return String(this._wrapped);
};

// node_modules/underscore/modules/_toBufferView.js
function toBufferView(bufferSource) {
  return new Uint8Array(
    bufferSource.buffer || bufferSource,
    bufferSource.byteOffset || 0,
    getByteLength_default(bufferSource)
  );
}

// node_modules/underscore/modules/isEqual.js
var tagDataView = "[object DataView]";
function eq(a3, b3, aStack, bStack) {
  if (a3 === b3) return a3 !== 0 || 1 / a3 === 1 / b3;
  if (a3 == null || b3 == null) return false;
  if (a3 !== a3) return b3 !== b3;
  var type = typeof a3;
  if (type !== "function" && type !== "object" && typeof b3 != "object") return false;
  return deepEq(a3, b3, aStack, bStack);
}
function deepEq(a3, b3, aStack, bStack) {
  if (a3 instanceof _2) a3 = a3._wrapped;
  if (b3 instanceof _2) b3 = b3._wrapped;
  var className2 = toString.call(a3);
  if (className2 !== toString.call(b3)) return false;
  if (hasStringTagBug && className2 == "[object Object]" && isDataView_default(a3)) {
    if (!isDataView_default(b3)) return false;
    className2 = tagDataView;
  }
  switch (className2) {
    // These types are compared by value.
    case "[object RegExp]":
    // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
    case "[object String]":
      return "" + a3 === "" + b3;
    case "[object Number]":
      if (+a3 !== +a3) return +b3 !== +b3;
      return +a3 === 0 ? 1 / +a3 === 1 / b3 : +a3 === +b3;
    case "[object Date]":
    case "[object Boolean]":
      return +a3 === +b3;
    case "[object Symbol]":
      return SymbolProto.valueOf.call(a3) === SymbolProto.valueOf.call(b3);
    case "[object ArrayBuffer]":
    case tagDataView:
      return deepEq(toBufferView(a3), toBufferView(b3), aStack, bStack);
  }
  var areArrays = className2 === "[object Array]";
  if (!areArrays && isTypedArray_default(a3)) {
    var byteLength = getByteLength_default(a3);
    if (byteLength !== getByteLength_default(b3)) return false;
    if (a3.buffer === b3.buffer && a3.byteOffset === b3.byteOffset) return true;
    areArrays = true;
  }
  if (!areArrays) {
    if (typeof a3 != "object" || typeof b3 != "object") return false;
    var aCtor = a3.constructor, bCtor = b3.constructor;
    if (aCtor !== bCtor && !(isFunction_default(aCtor) && aCtor instanceof aCtor && isFunction_default(bCtor) && bCtor instanceof bCtor) && ("constructor" in a3 && "constructor" in b3)) {
      return false;
    }
  }
  aStack = aStack || [];
  bStack = bStack || [];
  var length = aStack.length;
  while (length--) {
    if (aStack[length] === a3) return bStack[length] === b3;
  }
  aStack.push(a3);
  bStack.push(b3);
  if (areArrays) {
    length = a3.length;
    if (length !== b3.length) return false;
    while (length--) {
      if (!eq(a3[length], b3[length], aStack, bStack)) return false;
    }
  } else {
    var _keys = keys2(a3), key2;
    length = _keys.length;
    if (keys2(b3).length !== length) return false;
    while (length--) {
      key2 = _keys[length];
      if (!(has(b3, key2) && eq(a3[key2], b3[key2], aStack, bStack))) return false;
    }
  }
  aStack.pop();
  bStack.pop();
  return true;
}
function isEqual(a3, b3) {
  return eq(a3, b3);
}

// node_modules/underscore/modules/allKeys.js
function allKeys(obj) {
  if (!isObject2(obj)) return [];
  var keys5 = [];
  for (var key2 in obj) keys5.push(key2);
  if (hasEnumBug) collectNonEnumProps(obj, keys5);
  return keys5;
}

// node_modules/underscore/modules/_methodFingerprint.js
function ie11fingerprint(methods) {
  var length = getLength_default(methods);
  return function(obj) {
    if (obj == null) return false;
    var keys5 = allKeys(obj);
    if (getLength_default(keys5)) return false;
    for (var i3 = 0; i3 < length; i3++) {
      if (!isFunction_default(obj[methods[i3]])) return false;
    }
    return methods !== weakMapMethods || !isFunction_default(obj[forEachName]);
  };
}
var forEachName = "forEach";
var hasName = "has";
var commonInit = ["clear", "delete"];
var mapTail = ["get", hasName, "set"];
var mapMethods = commonInit.concat(forEachName, mapTail);
var weakMapMethods = commonInit.concat(mapTail);
var setMethods = ["add"].concat(commonInit, forEachName, hasName);

// node_modules/underscore/modules/isMap.js
var isMap_default = isIE11 ? ie11fingerprint(mapMethods) : tagTester("Map");

// node_modules/underscore/modules/isWeakMap.js
var isWeakMap_default = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester("WeakMap");

// node_modules/underscore/modules/isSet.js
var isSet_default = isIE11 ? ie11fingerprint(setMethods) : tagTester("Set");

// node_modules/underscore/modules/isWeakSet.js
var isWeakSet_default = tagTester("WeakSet");

// node_modules/underscore/modules/values.js
function values(obj) {
  var _keys = keys2(obj);
  var length = _keys.length;
  var values2 = Array(length);
  for (var i3 = 0; i3 < length; i3++) {
    values2[i3] = obj[_keys[i3]];
  }
  return values2;
}

// node_modules/underscore/modules/pairs.js
function pairs(obj) {
  var _keys = keys2(obj);
  var length = _keys.length;
  var pairs3 = Array(length);
  for (var i3 = 0; i3 < length; i3++) {
    pairs3[i3] = [_keys[i3], obj[_keys[i3]]];
  }
  return pairs3;
}

// node_modules/underscore/modules/invert.js
function invert(obj) {
  var result2 = {};
  var _keys = keys2(obj);
  for (var i3 = 0, length = _keys.length; i3 < length; i3++) {
    result2[obj[_keys[i3]]] = _keys[i3];
  }
  return result2;
}

// node_modules/underscore/modules/functions.js
function functions(obj) {
  var names = [];
  for (var key2 in obj) {
    if (isFunction_default(obj[key2])) names.push(key2);
  }
  return names.sort();
}

// node_modules/underscore/modules/_createAssigner.js
function createAssigner(keysFunc, defaults5) {
  return function(obj) {
    var length = arguments.length;
    if (defaults5) obj = Object(obj);
    if (length < 2 || obj == null) return obj;
    for (var index2 = 1; index2 < length; index2++) {
      var source = arguments[index2], keys5 = keysFunc(source), l3 = keys5.length;
      for (var i3 = 0; i3 < l3; i3++) {
        var key2 = keys5[i3];
        if (!defaults5 || obj[key2] === void 0) obj[key2] = source[key2];
      }
    }
    return obj;
  };
}

// node_modules/underscore/modules/extend.js
var extend_default = createAssigner(allKeys);

// node_modules/underscore/modules/extendOwn.js
var extendOwn_default = createAssigner(keys2);

// node_modules/underscore/modules/defaults.js
var defaults_default = createAssigner(allKeys, true);

// node_modules/underscore/modules/_baseCreate.js
function ctor() {
  return function() {
  };
}
function baseCreate(prototype) {
  if (!isObject2(prototype)) return {};
  if (nativeCreate) return nativeCreate(prototype);
  var Ctor = ctor();
  Ctor.prototype = prototype;
  var result2 = new Ctor();
  Ctor.prototype = null;
  return result2;
}

// node_modules/underscore/modules/create.js
function create(prototype, props2) {
  var result2 = baseCreate(prototype);
  if (props2) extendOwn_default(result2, props2);
  return result2;
}

// node_modules/underscore/modules/clone.js
function clone(obj) {
  if (!isObject2(obj)) return obj;
  return isArray_default(obj) ? obj.slice() : extend_default({}, obj);
}

// node_modules/underscore/modules/tap.js
function tap(obj, interceptor) {
  interceptor(obj);
  return obj;
}

// node_modules/underscore/modules/toPath.js
function toPath(path) {
  return isArray_default(path) ? path : [path];
}
_2.toPath = toPath;

// node_modules/underscore/modules/_toPath.js
function toPath2(path) {
  return _2.toPath(path);
}

// node_modules/underscore/modules/_deepGet.js
function deepGet(obj, path) {
  var length = path.length;
  for (var i3 = 0; i3 < length; i3++) {
    if (obj == null) return void 0;
    obj = obj[path[i3]];
  }
  return length ? obj : void 0;
}

// node_modules/underscore/modules/get.js
function get(object2, path, defaultValue) {
  var value2 = deepGet(object2, toPath2(path));
  return isUndefined(value2) ? defaultValue : value2;
}

// node_modules/underscore/modules/has.js
function has2(obj, path) {
  path = toPath2(path);
  var length = path.length;
  for (var i3 = 0; i3 < length; i3++) {
    var key2 = path[i3];
    if (!has(obj, key2)) return false;
    obj = obj[key2];
  }
  return !!length;
}

// node_modules/underscore/modules/identity.js
function identity(value2) {
  return value2;
}

// node_modules/underscore/modules/matcher.js
function matcher(attrs2) {
  attrs2 = extendOwn_default({}, attrs2);
  return function(obj) {
    return isMatch(obj, attrs2);
  };
}

// node_modules/underscore/modules/property.js
function property(path) {
  path = toPath2(path);
  return function(obj) {
    return deepGet(obj, path);
  };
}

// node_modules/underscore/modules/_optimizeCb.js
function optimizeCb(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1:
      return function(value2) {
        return func.call(context, value2);
      };
    // The 2-argument case is omitted because we’re not using it.
    case 3:
      return function(value2, index2, collection) {
        return func.call(context, value2, index2, collection);
      };
    case 4:
      return function(accumulator, value2, index2, collection) {
        return func.call(context, accumulator, value2, index2, collection);
      };
  }
  return function() {
    return func.apply(context, arguments);
  };
}

// node_modules/underscore/modules/_baseIteratee.js
function baseIteratee(value2, context, argCount) {
  if (value2 == null) return identity;
  if (isFunction_default(value2)) return optimizeCb(value2, context, argCount);
  if (isObject2(value2) && !isArray_default(value2)) return matcher(value2);
  return property(value2);
}

// node_modules/underscore/modules/iteratee.js
function iteratee(value2, context) {
  return baseIteratee(value2, context, Infinity);
}
_2.iteratee = iteratee;

// node_modules/underscore/modules/_cb.js
function cb(value2, context, argCount) {
  if (_2.iteratee !== iteratee) return _2.iteratee(value2, context);
  return baseIteratee(value2, context, argCount);
}

// node_modules/underscore/modules/mapObject.js
function mapObject(obj, iteratee2, context) {
  iteratee2 = cb(iteratee2, context);
  var _keys = keys2(obj), length = _keys.length, results2 = {};
  for (var index2 = 0; index2 < length; index2++) {
    var currentKey = _keys[index2];
    results2[currentKey] = iteratee2(obj[currentKey], currentKey, obj);
  }
  return results2;
}

// node_modules/underscore/modules/noop.js
function noop2() {
}

// node_modules/underscore/modules/propertyOf.js
function propertyOf(obj) {
  if (obj == null) return noop2;
  return function(path) {
    return get(obj, path);
  };
}

// node_modules/underscore/modules/times.js
function times(n4, iteratee2, context) {
  var accum = Array(Math.max(0, n4));
  iteratee2 = optimizeCb(iteratee2, context, 1);
  for (var i3 = 0; i3 < n4; i3++) accum[i3] = iteratee2(i3);
  return accum;
}

// node_modules/underscore/modules/random.js
function random(min3, max3) {
  if (max3 == null) {
    max3 = min3;
    min3 = 0;
  }
  return min3 + Math.floor(Math.random() * (max3 - min3 + 1));
}

// node_modules/underscore/modules/now.js
var now_default = Date.now || function() {
  return (/* @__PURE__ */ new Date()).getTime();
};

// node_modules/underscore/modules/_createEscaper.js
function createEscaper(map5) {
  var escaper = function(match2) {
    return map5[match2];
  };
  var source = "(?:" + keys2(map5).join("|") + ")";
  var testRegexp = RegExp(source);
  var replaceRegexp = RegExp(source, "g");
  return function(string3) {
    string3 = string3 == null ? "" : "" + string3;
    return testRegexp.test(string3) ? string3.replace(replaceRegexp, escaper) : string3;
  };
}

// node_modules/underscore/modules/_escapeMap.js
var escapeMap_default = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#x27;",
  "`": "&#x60;"
};

// node_modules/underscore/modules/escape.js
var escape_default = createEscaper(escapeMap_default);

// node_modules/underscore/modules/_unescapeMap.js
var unescapeMap_default = invert(escapeMap_default);

// node_modules/underscore/modules/unescape.js
var unescape_default = createEscaper(unescapeMap_default);

// node_modules/underscore/modules/templateSettings.js
var templateSettings_default = _2.templateSettings = {
  evaluate: /<%([\s\S]+?)%>/g,
  interpolate: /<%=([\s\S]+?)%>/g,
  escape: /<%-([\s\S]+?)%>/g
};

// node_modules/underscore/modules/template.js
var noMatch = /(.)^/;
var escapes = {
  "'": "'",
  "\\": "\\",
  "\r": "r",
  "\n": "n",
  "\u2028": "u2028",
  "\u2029": "u2029"
};
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
function escapeChar(match2) {
  return "\\" + escapes[match2];
}
var bareIdentifier = /^\s*(\w|\$)+\s*$/;
function template2(text3, settings, oldSettings) {
  if (!settings && oldSettings) settings = oldSettings;
  settings = defaults_default({}, settings, _2.templateSettings);
  var matcher2 = RegExp([
    (settings.escape || noMatch).source,
    (settings.interpolate || noMatch).source,
    (settings.evaluate || noMatch).source
  ].join("|") + "|$", "g");
  var index2 = 0;
  var source = "__p+='";
  text3.replace(matcher2, function(match2, escape4, interpolate2, evaluate, offset) {
    source += text3.slice(index2, offset).replace(escapeRegExp, escapeChar);
    index2 = offset + match2.length;
    if (escape4) {
      source += "'+\n((__t=(" + escape4 + "))==null?'':_.escape(__t))+\n'";
    } else if (interpolate2) {
      source += "'+\n((__t=(" + interpolate2 + "))==null?'':__t)+\n'";
    } else if (evaluate) {
      source += "';\n" + evaluate + "\n__p+='";
    }
    return match2;
  });
  source += "';\n";
  var argument = settings.variable;
  if (argument) {
    if (!bareIdentifier.test(argument)) throw new Error(
      "variable is not a bare identifier: " + argument
    );
  } else {
    source = "with(obj||{}){\n" + source + "}\n";
    argument = "obj";
  }
  source = "var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n";
  var render3;
  try {
    render3 = new Function(argument, "_", source);
  } catch (e3) {
    e3.source = source;
    throw e3;
  }
  var template3 = function(data2) {
    return render3.call(this, data2, _2);
  };
  template3.source = "function(" + argument + "){\n" + source + "}";
  return template3;
}

// node_modules/underscore/modules/result.js
function result(obj, path, fallback) {
  path = toPath2(path);
  var length = path.length;
  if (!length) {
    return isFunction_default(fallback) ? fallback.call(obj) : fallback;
  }
  for (var i3 = 0; i3 < length; i3++) {
    var prop2 = obj == null ? void 0 : obj[path[i3]];
    if (prop2 === void 0) {
      prop2 = fallback;
      i3 = length;
    }
    obj = isFunction_default(prop2) ? prop2.call(obj) : prop2;
  }
  return obj;
}

// node_modules/underscore/modules/uniqueId.js
var idCounter = 0;
function uniqueId(prefix5) {
  var id = ++idCounter + "";
  return prefix5 ? prefix5 + id : id;
}

// node_modules/underscore/modules/chain.js
function chain2(obj) {
  var instance = _2(obj);
  instance._chain = true;
  return instance;
}

// node_modules/underscore/modules/_executeBound.js
function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
  if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  var self2 = baseCreate(sourceFunc.prototype);
  var result2 = sourceFunc.apply(self2, args);
  if (isObject2(result2)) return result2;
  return self2;
}

// node_modules/underscore/modules/partial.js
var partial = restArguments(function(func, boundArgs) {
  var placeholder = partial.placeholder;
  var bound = function() {
    var position = 0, length = boundArgs.length;
    var args = Array(length);
    for (var i3 = 0; i3 < length; i3++) {
      args[i3] = boundArgs[i3] === placeholder ? arguments[position++] : boundArgs[i3];
    }
    while (position < arguments.length) args.push(arguments[position++]);
    return executeBound(func, bound, this, this, args);
  };
  return bound;
});
partial.placeholder = _2;
var partial_default = partial;

// node_modules/underscore/modules/bind.js
var bind_default = restArguments(function(func, context, args) {
  if (!isFunction_default(func)) throw new TypeError("Bind must be called on a function");
  var bound = restArguments(function(callArgs) {
    return executeBound(func, bound, context, this, args.concat(callArgs));
  });
  return bound;
});

// node_modules/underscore/modules/_isArrayLike.js
var isArrayLike_default = createSizePropertyCheck(getLength_default);

// node_modules/underscore/modules/_flatten.js
function flatten(input, depth2, strict, output) {
  output = output || [];
  if (!depth2 && depth2 !== 0) {
    depth2 = Infinity;
  } else if (depth2 <= 0) {
    return output.concat(input);
  }
  var idx = output.length;
  for (var i3 = 0, length = getLength_default(input); i3 < length; i3++) {
    var value2 = input[i3];
    if (isArrayLike_default(value2) && (isArray_default(value2) || isArguments_default(value2))) {
      if (depth2 > 1) {
        flatten(value2, depth2 - 1, strict, output);
        idx = output.length;
      } else {
        var j = 0, len = value2.length;
        while (j < len) output[idx++] = value2[j++];
      }
    } else if (!strict) {
      output[idx++] = value2;
    }
  }
  return output;
}

// node_modules/underscore/modules/bindAll.js
var bindAll_default = restArguments(function(obj, keys5) {
  keys5 = flatten(keys5, false, false);
  var index2 = keys5.length;
  if (index2 < 1) throw new Error("bindAll must be passed function names");
  while (index2--) {
    var key2 = keys5[index2];
    obj[key2] = bind_default(obj[key2], obj);
  }
  return obj;
});

// node_modules/underscore/modules/memoize.js
function memoize(func, hasher) {
  var memoize4 = function(key2) {
    var cache5 = memoize4.cache;
    var address = "" + (hasher ? hasher.apply(this, arguments) : key2);
    if (!has(cache5, address)) cache5[address] = func.apply(this, arguments);
    return cache5[address];
  };
  memoize4.cache = {};
  return memoize4;
}

// node_modules/underscore/modules/delay.js
var delay_default = restArguments(function(func, wait, args) {
  return setTimeout(function() {
    return func.apply(null, args);
  }, wait);
});

// node_modules/underscore/modules/defer.js
var defer_default = partial_default(delay_default, _2, 1);

// node_modules/underscore/modules/throttle.js
function throttle(func, wait, options2) {
  var timeout, context, args, result2;
  var previous = 0;
  if (!options2) options2 = {};
  var later = function() {
    previous = options2.leading === false ? 0 : now_default();
    timeout = null;
    result2 = func.apply(context, args);
    if (!timeout) context = args = null;
  };
  var throttled = function() {
    var _now = now_default();
    if (!previous && options2.leading === false) previous = _now;
    var remaining = wait - (_now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = _now;
      result2 = func.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options2.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result2;
  };
  throttled.cancel = function() {
    clearTimeout(timeout);
    previous = 0;
    timeout = context = args = null;
  };
  return throttled;
}

// node_modules/underscore/modules/debounce.js
function debounce(func, wait, immediate) {
  var timeout, previous, args, result2, context;
  var later = function() {
    var passed = now_default() - previous;
    if (wait > passed) {
      timeout = setTimeout(later, wait - passed);
    } else {
      timeout = null;
      if (!immediate) result2 = func.apply(context, args);
      if (!timeout) args = context = null;
    }
  };
  var debounced = restArguments(function(_args) {
    context = this;
    args = _args;
    previous = now_default();
    if (!timeout) {
      timeout = setTimeout(later, wait);
      if (immediate) result2 = func.apply(context, args);
    }
    return result2;
  });
  debounced.cancel = function() {
    clearTimeout(timeout);
    timeout = args = context = null;
  };
  return debounced;
}

// node_modules/underscore/modules/wrap.js
function wrap(func, wrapper) {
  return partial_default(wrapper, func);
}

// node_modules/underscore/modules/negate.js
function negate(predicate) {
  return function() {
    return !predicate.apply(this, arguments);
  };
}

// node_modules/underscore/modules/compose.js
function compose() {
  var args = arguments;
  var start = args.length - 1;
  return function() {
    var i3 = start;
    var result2 = args[start].apply(this, arguments);
    while (i3--) result2 = args[i3].call(this, result2);
    return result2;
  };
}

// node_modules/underscore/modules/after.js
function after(times2, func) {
  return function() {
    if (--times2 < 1) {
      return func.apply(this, arguments);
    }
  };
}

// node_modules/underscore/modules/before.js
function before(times2, func) {
  var memo;
  return function() {
    if (--times2 > 0) {
      memo = func.apply(this, arguments);
    }
    if (times2 <= 1) func = null;
    return memo;
  };
}

// node_modules/underscore/modules/once.js
var once_default = partial_default(before, 2);

// node_modules/underscore/modules/findKey.js
function findKey(obj, predicate, context) {
  predicate = cb(predicate, context);
  var _keys = keys2(obj), key2;
  for (var i3 = 0, length = _keys.length; i3 < length; i3++) {
    key2 = _keys[i3];
    if (predicate(obj[key2], key2, obj)) return key2;
  }
}

// node_modules/underscore/modules/_createPredicateIndexFinder.js
function createPredicateIndexFinder(dir) {
  return function(array, predicate, context) {
    predicate = cb(predicate, context);
    var length = getLength_default(array);
    var index2 = dir > 0 ? 0 : length - 1;
    for (; index2 >= 0 && index2 < length; index2 += dir) {
      if (predicate(array[index2], index2, array)) return index2;
    }
    return -1;
  };
}

// node_modules/underscore/modules/findIndex.js
var findIndex_default = createPredicateIndexFinder(1);

// node_modules/underscore/modules/findLastIndex.js
var findLastIndex_default = createPredicateIndexFinder(-1);

// node_modules/underscore/modules/sortedIndex.js
function sortedIndex(array, obj, iteratee2, context) {
  iteratee2 = cb(iteratee2, context, 1);
  var value2 = iteratee2(obj);
  var low = 0, high = getLength_default(array);
  while (low < high) {
    var mid = Math.floor((low + high) / 2);
    if (iteratee2(array[mid]) < value2) low = mid + 1;
    else high = mid;
  }
  return low;
}

// node_modules/underscore/modules/_createIndexFinder.js
function createIndexFinder(dir, predicateFind, sortedIndex2) {
  return function(array, item, idx) {
    var i3 = 0, length = getLength_default(array);
    if (typeof idx == "number") {
      if (dir > 0) {
        i3 = idx >= 0 ? idx : Math.max(idx + length, i3);
      } else {
        length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
      }
    } else if (sortedIndex2 && idx && length) {
      idx = sortedIndex2(array, item);
      return array[idx] === item ? idx : -1;
    }
    if (item !== item) {
      idx = predicateFind(slice.call(array, i3, length), isNaN2);
      return idx >= 0 ? idx + i3 : -1;
    }
    for (idx = dir > 0 ? i3 : length - 1; idx >= 0 && idx < length; idx += dir) {
      if (array[idx] === item) return idx;
    }
    return -1;
  };
}

// node_modules/underscore/modules/indexOf.js
var indexOf_default = createIndexFinder(1, findIndex_default, sortedIndex);

// node_modules/underscore/modules/lastIndexOf.js
var lastIndexOf_default = createIndexFinder(-1, findLastIndex_default);

// node_modules/underscore/modules/find.js
function find(obj, predicate, context) {
  var keyFinder = isArrayLike_default(obj) ? findIndex_default : findKey;
  var key2 = keyFinder(obj, predicate, context);
  if (key2 !== void 0 && key2 !== -1) return obj[key2];
}

// node_modules/underscore/modules/findWhere.js
function findWhere(obj, attrs2) {
  return find(obj, matcher(attrs2));
}

// node_modules/underscore/modules/each.js
function each(obj, iteratee2, context) {
  iteratee2 = optimizeCb(iteratee2, context);
  var i3, length;
  if (isArrayLike_default(obj)) {
    for (i3 = 0, length = obj.length; i3 < length; i3++) {
      iteratee2(obj[i3], i3, obj);
    }
  } else {
    var _keys = keys2(obj);
    for (i3 = 0, length = _keys.length; i3 < length; i3++) {
      iteratee2(obj[_keys[i3]], _keys[i3], obj);
    }
  }
  return obj;
}

// node_modules/underscore/modules/map.js
function map(obj, iteratee2, context) {
  iteratee2 = cb(iteratee2, context);
  var _keys = !isArrayLike_default(obj) && keys2(obj), length = (_keys || obj).length, results2 = Array(length);
  for (var index2 = 0; index2 < length; index2++) {
    var currentKey = _keys ? _keys[index2] : index2;
    results2[index2] = iteratee2(obj[currentKey], currentKey, obj);
  }
  return results2;
}

// node_modules/underscore/modules/_createReduce.js
function createReduce(dir) {
  var reducer = function(obj, iteratee2, memo, initial2) {
    var _keys = !isArrayLike_default(obj) && keys2(obj), length = (_keys || obj).length, index2 = dir > 0 ? 0 : length - 1;
    if (!initial2) {
      memo = obj[_keys ? _keys[index2] : index2];
      index2 += dir;
    }
    for (; index2 >= 0 && index2 < length; index2 += dir) {
      var currentKey = _keys ? _keys[index2] : index2;
      memo = iteratee2(memo, obj[currentKey], currentKey, obj);
    }
    return memo;
  };
  return function(obj, iteratee2, memo, context) {
    var initial2 = arguments.length >= 3;
    return reducer(obj, optimizeCb(iteratee2, context, 4), memo, initial2);
  };
}

// node_modules/underscore/modules/reduce.js
var reduce_default = createReduce(1);

// node_modules/underscore/modules/reduceRight.js
var reduceRight_default = createReduce(-1);

// node_modules/underscore/modules/filter.js
function filter2(obj, predicate, context) {
  var results2 = [];
  predicate = cb(predicate, context);
  each(obj, function(value2, index2, list2) {
    if (predicate(value2, index2, list2)) results2.push(value2);
  });
  return results2;
}

// node_modules/underscore/modules/reject.js
function reject(obj, predicate, context) {
  return filter2(obj, negate(cb(predicate)), context);
}

// node_modules/underscore/modules/every.js
function every(obj, predicate, context) {
  predicate = cb(predicate, context);
  var _keys = !isArrayLike_default(obj) && keys2(obj), length = (_keys || obj).length;
  for (var index2 = 0; index2 < length; index2++) {
    var currentKey = _keys ? _keys[index2] : index2;
    if (!predicate(obj[currentKey], currentKey, obj)) return false;
  }
  return true;
}

// node_modules/underscore/modules/some.js
function some(obj, predicate, context) {
  predicate = cb(predicate, context);
  var _keys = !isArrayLike_default(obj) && keys2(obj), length = (_keys || obj).length;
  for (var index2 = 0; index2 < length; index2++) {
    var currentKey = _keys ? _keys[index2] : index2;
    if (predicate(obj[currentKey], currentKey, obj)) return true;
  }
  return false;
}

// node_modules/underscore/modules/contains.js
function contains(obj, item, fromIndex, guard) {
  if (!isArrayLike_default(obj)) obj = values(obj);
  if (typeof fromIndex != "number" || guard) fromIndex = 0;
  return indexOf_default(obj, item, fromIndex) >= 0;
}

// node_modules/underscore/modules/invoke.js
var invoke_default = restArguments(function(obj, path, args) {
  var contextPath, func;
  if (isFunction_default(path)) {
    func = path;
  } else {
    path = toPath2(path);
    contextPath = path.slice(0, -1);
    path = path[path.length - 1];
  }
  return map(obj, function(context) {
    var method = func;
    if (!method) {
      if (contextPath && contextPath.length) {
        context = deepGet(context, contextPath);
      }
      if (context == null) return void 0;
      method = context[path];
    }
    return method == null ? method : method.apply(context, args);
  });
});

// node_modules/underscore/modules/pluck.js
function pluck(obj, key2) {
  return map(obj, property(key2));
}

// node_modules/underscore/modules/where.js
function where(obj, attrs2) {
  return filter2(obj, matcher(attrs2));
}

// node_modules/underscore/modules/max.js
function max(obj, iteratee2, context) {
  var result2 = -Infinity, lastComputed = -Infinity, value2, computed;
  if (iteratee2 == null || typeof iteratee2 == "number" && typeof obj[0] != "object" && obj != null) {
    obj = isArrayLike_default(obj) ? obj : values(obj);
    for (var i3 = 0, length = obj.length; i3 < length; i3++) {
      value2 = obj[i3];
      if (value2 != null && value2 > result2) {
        result2 = value2;
      }
    }
  } else {
    iteratee2 = cb(iteratee2, context);
    each(obj, function(v3, index2, list2) {
      computed = iteratee2(v3, index2, list2);
      if (computed > lastComputed || computed === -Infinity && result2 === -Infinity) {
        result2 = v3;
        lastComputed = computed;
      }
    });
  }
  return result2;
}

// node_modules/underscore/modules/min.js
function min(obj, iteratee2, context) {
  var result2 = Infinity, lastComputed = Infinity, value2, computed;
  if (iteratee2 == null || typeof iteratee2 == "number" && typeof obj[0] != "object" && obj != null) {
    obj = isArrayLike_default(obj) ? obj : values(obj);
    for (var i3 = 0, length = obj.length; i3 < length; i3++) {
      value2 = obj[i3];
      if (value2 != null && value2 < result2) {
        result2 = value2;
      }
    }
  } else {
    iteratee2 = cb(iteratee2, context);
    each(obj, function(v3, index2, list2) {
      computed = iteratee2(v3, index2, list2);
      if (computed < lastComputed || computed === Infinity && result2 === Infinity) {
        result2 = v3;
        lastComputed = computed;
      }
    });
  }
  return result2;
}

// node_modules/underscore/modules/toArray.js
var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
function toArray(obj) {
  if (!obj) return [];
  if (isArray_default(obj)) return slice.call(obj);
  if (isString_default(obj)) {
    return obj.match(reStrSymbol);
  }
  if (isArrayLike_default(obj)) return map(obj, identity);
  return values(obj);
}

// node_modules/underscore/modules/sample.js
function sample(obj, n4, guard) {
  if (n4 == null || guard) {
    if (!isArrayLike_default(obj)) obj = values(obj);
    return obj[random(obj.length - 1)];
  }
  var sample2 = toArray(obj);
  var length = getLength_default(sample2);
  n4 = Math.max(Math.min(n4, length), 0);
  var last3 = length - 1;
  for (var index2 = 0; index2 < n4; index2++) {
    var rand = random(index2, last3);
    var temp = sample2[index2];
    sample2[index2] = sample2[rand];
    sample2[rand] = temp;
  }
  return sample2.slice(0, n4);
}

// node_modules/underscore/modules/shuffle.js
function shuffle(obj) {
  return sample(obj, Infinity);
}

// node_modules/underscore/modules/sortBy.js
function sortBy(obj, iteratee2, context) {
  var index2 = 0;
  iteratee2 = cb(iteratee2, context);
  return pluck(map(obj, function(value2, key2, list2) {
    return {
      value: value2,
      index: index2++,
      criteria: iteratee2(value2, key2, list2)
    };
  }).sort(function(left, right) {
    var a3 = left.criteria;
    var b3 = right.criteria;
    if (a3 !== b3) {
      if (a3 > b3 || a3 === void 0) return 1;
      if (a3 < b3 || b3 === void 0) return -1;
    }
    return left.index - right.index;
  }), "value");
}

// node_modules/underscore/modules/_group.js
function group(behavior, partition) {
  return function(obj, iteratee2, context) {
    var result2 = partition ? [[], []] : {};
    iteratee2 = cb(iteratee2, context);
    each(obj, function(value2, index2) {
      var key2 = iteratee2(value2, index2, obj);
      behavior(result2, value2, key2);
    });
    return result2;
  };
}

// node_modules/underscore/modules/groupBy.js
var groupBy_default = group(function(result2, value2, key2) {
  if (has(result2, key2)) result2[key2].push(value2);
  else result2[key2] = [value2];
});

// node_modules/underscore/modules/indexBy.js
var indexBy_default = group(function(result2, value2, key2) {
  result2[key2] = value2;
});

// node_modules/underscore/modules/countBy.js
var countBy_default = group(function(result2, value2, key2) {
  if (has(result2, key2)) result2[key2]++;
  else result2[key2] = 1;
});

// node_modules/underscore/modules/partition.js
var partition_default = group(function(result2, value2, pass) {
  result2[pass ? 0 : 1].push(value2);
}, true);

// node_modules/underscore/modules/size.js
function size2(obj) {
  if (obj == null) return 0;
  return isArrayLike_default(obj) ? obj.length : keys2(obj).length;
}

// node_modules/underscore/modules/_keyInObj.js
function keyInObj(value2, key2, obj) {
  return key2 in obj;
}

// node_modules/underscore/modules/pick.js
var pick_default = restArguments(function(obj, keys5) {
  var result2 = {}, iteratee2 = keys5[0];
  if (obj == null) return result2;
  if (isFunction_default(iteratee2)) {
    if (keys5.length > 1) iteratee2 = optimizeCb(iteratee2, keys5[1]);
    keys5 = allKeys(obj);
  } else {
    iteratee2 = keyInObj;
    keys5 = flatten(keys5, false, false);
    obj = Object(obj);
  }
  for (var i3 = 0, length = keys5.length; i3 < length; i3++) {
    var key2 = keys5[i3];
    var value2 = obj[key2];
    if (iteratee2(value2, key2, obj)) result2[key2] = value2;
  }
  return result2;
});

// node_modules/underscore/modules/omit.js
var omit_default = restArguments(function(obj, keys5) {
  var iteratee2 = keys5[0], context;
  if (isFunction_default(iteratee2)) {
    iteratee2 = negate(iteratee2);
    if (keys5.length > 1) context = keys5[1];
  } else {
    keys5 = map(flatten(keys5, false, false), String);
    iteratee2 = function(value2, key2) {
      return !contains(keys5, key2);
    };
  }
  return pick_default(obj, iteratee2, context);
});

// node_modules/underscore/modules/initial.js
function initial(array, n4, guard) {
  return slice.call(array, 0, Math.max(0, array.length - (n4 == null || guard ? 1 : n4)));
}

// node_modules/underscore/modules/first.js
function first(array, n4, guard) {
  if (array == null || array.length < 1) return n4 == null || guard ? void 0 : [];
  if (n4 == null || guard) return array[0];
  return initial(array, array.length - n4);
}

// node_modules/underscore/modules/rest.js
function rest(array, n4, guard) {
  return slice.call(array, n4 == null || guard ? 1 : n4);
}

// node_modules/underscore/modules/last.js
function last2(array, n4, guard) {
  if (array == null || array.length < 1) return n4 == null || guard ? void 0 : [];
  if (n4 == null || guard) return array[array.length - 1];
  return rest(array, Math.max(0, array.length - n4));
}

// node_modules/underscore/modules/compact.js
function compact(array) {
  return filter2(array, Boolean);
}

// node_modules/underscore/modules/flatten.js
function flatten2(array, depth2) {
  return flatten(array, depth2, false);
}

// node_modules/underscore/modules/difference.js
var difference_default = restArguments(function(array, rest2) {
  rest2 = flatten(rest2, true, true);
  return filter2(array, function(value2) {
    return !contains(rest2, value2);
  });
});

// node_modules/underscore/modules/without.js
var without_default = restArguments(function(array, otherArrays) {
  return difference_default(array, otherArrays);
});

// node_modules/underscore/modules/uniq.js
function uniq(array, isSorted, iteratee2, context) {
  if (!isBoolean(isSorted)) {
    context = iteratee2;
    iteratee2 = isSorted;
    isSorted = false;
  }
  if (iteratee2 != null) iteratee2 = cb(iteratee2, context);
  var result2 = [];
  var seen = [];
  for (var i3 = 0, length = getLength_default(array); i3 < length; i3++) {
    var value2 = array[i3], computed = iteratee2 ? iteratee2(value2, i3, array) : value2;
    if (isSorted && !iteratee2) {
      if (!i3 || seen !== computed) result2.push(value2);
      seen = computed;
    } else if (iteratee2) {
      if (!contains(seen, computed)) {
        seen.push(computed);
        result2.push(value2);
      }
    } else if (!contains(result2, value2)) {
      result2.push(value2);
    }
  }
  return result2;
}

// node_modules/underscore/modules/union.js
var union_default = restArguments(function(arrays) {
  return uniq(flatten(arrays, true, true));
});

// node_modules/underscore/modules/intersection.js
function intersection(array) {
  var result2 = [];
  var argsLength = arguments.length;
  for (var i3 = 0, length = getLength_default(array); i3 < length; i3++) {
    var item = array[i3];
    if (contains(result2, item)) continue;
    var j;
    for (j = 1; j < argsLength; j++) {
      if (!contains(arguments[j], item)) break;
    }
    if (j === argsLength) result2.push(item);
  }
  return result2;
}

// node_modules/underscore/modules/unzip.js
function unzip(array) {
  var length = array && max(array, getLength_default).length || 0;
  var result2 = Array(length);
  for (var index2 = 0; index2 < length; index2++) {
    result2[index2] = pluck(array, index2);
  }
  return result2;
}

// node_modules/underscore/modules/zip.js
var zip_default = restArguments(unzip);

// node_modules/underscore/modules/object.js
function object(list2, values2) {
  var result2 = {};
  for (var i3 = 0, length = getLength_default(list2); i3 < length; i3++) {
    if (values2) {
      result2[list2[i3]] = values2[i3];
    } else {
      result2[list2[i3][0]] = list2[i3][1];
    }
  }
  return result2;
}

// node_modules/underscore/modules/range.js
function range(start, stop, step2) {
  if (stop == null) {
    stop = start || 0;
    start = 0;
  }
  if (!step2) {
    step2 = stop < start ? -1 : 1;
  }
  var length = Math.max(Math.ceil((stop - start) / step2), 0);
  var range2 = Array(length);
  for (var idx = 0; idx < length; idx++, start += step2) {
    range2[idx] = start;
  }
  return range2;
}

// node_modules/underscore/modules/chunk.js
function chunk(array, count) {
  if (count == null || count < 1) return [];
  var result2 = [];
  var i3 = 0, length = array.length;
  while (i3 < length) {
    result2.push(slice.call(array, i3, i3 += count));
  }
  return result2;
}

// node_modules/underscore/modules/_chainResult.js
function chainResult(instance, obj) {
  return instance._chain ? _2(obj).chain() : obj;
}

// node_modules/underscore/modules/mixin.js
function mixin(obj) {
  each(functions(obj), function(name2) {
    var func = _2[name2] = obj[name2];
    _2.prototype[name2] = function() {
      var args = [this._wrapped];
      push.apply(args, arguments);
      return chainResult(this, func.apply(_2, args));
    };
  });
  return _2;
}

// node_modules/underscore/modules/underscore-array-methods.js
each(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function(name2) {
  var method = ArrayProto[name2];
  _2.prototype[name2] = function() {
    var obj = this._wrapped;
    if (obj != null) {
      method.apply(obj, arguments);
      if ((name2 === "shift" || name2 === "splice") && obj.length === 0) {
        delete obj[0];
      }
    }
    return chainResult(this, obj);
  };
});
each(["concat", "join", "slice"], function(name2) {
  var method = ArrayProto[name2];
  _2.prototype[name2] = function() {
    var obj = this._wrapped;
    if (obj != null) obj = method.apply(obj, arguments);
    return chainResult(this, obj);
  };
});
var underscore_array_methods_default = _2;

// node_modules/underscore/modules/index-default.js
var _3 = mixin(modules_exports);
_3._ = _3;
var index_default_default = _3;

// public/app/utils/debounce.ts
function debounce2(func, wait, thisArg) {
  var timeoutId;
  var debounced = function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      timeoutId = null;
      func.apply(thisArg || this, args);
    }, wait || 0);
  };
  debounced.immediate = function(...args) {
    clearTimeout(timeoutId);
    timeoutId = null;
    return func.apply(thisArg, args);
  };
  debounced.isRunning = () => timeoutId !== null;
  debounced.clear = function() {
    clearTimeout(timeoutId);
    timeoutId = null;
  };
  return debounced;
}
function createDebounce(func, wait, thisArg) {
  const debounced = debounce2(func, wait, thisArg);
  onCleanup(() => {
    debounced.clear?.();
  });
  return debounced;
}

// public/app/utils/misc.ts
var import_tinycolor2 = __toESM(require_tinycolor());
var NotImplementedError = class extends Error {
  constructor() {
    super("Not implemented");
  }
};
function convertReferencesToLinks(text3) {
  return text3.replace(/\B(#(\d+))(\s|$|\<)/g, '<a href class="card-ref" rel="$2">$1</a>$3').replace(/\B(@[a-z0-9._-]+[a-z0-9_-])/g, "<em>$1</em>");
}
function capitalize(text3) {
  return text3 ? text3.charAt(0).toUpperCase() + text3.slice(1) : "";
}
function deferredPromise() {
  const defer2 = {};
  defer2.promise = new Promise((resolve2, reject2) => {
    defer2.resolve = resolve2;
    defer2.reject = reject2;
  });
  return defer2;
}
function extractColorFromText2(value2) {
  if (!value2) {
    return null;
  }
  var r3 = value2.toString().match(/ \[(#[a-z0-9]{6})\]$/i);
  if (r3) {
    return [value2.replace(r3[0], ""), r3[1], import_tinycolor2.default.mostReadable(r3[1], ["#FFFFFF", "#000000"]).toHexString()];
  }
  return null;
}
function singleton(func) {
  const decorator = function(...args) {
    if (decorator.instance) {
      return decorator.instance;
    }
    decorator.instance = func(...args);
    if (decorator.instance instanceof Promise) {
      decorator.instance.catch((e3) => {
        decorator.instance = null;
        return Promise.reject(e3);
      });
    }
    return decorator.instance;
  };
  return decorator;
}
function oncePromise(func) {
  let promise;
  return function(...args) {
    if (promise) {
      return promise;
    }
    promise = func(...args);
    promise.finally(() => {
      promise = null;
    });
    return promise;
  };
}
function memoize2(fn) {
  const memoize4 = function() {
    if (typeof memoize4.cache !== "undefined") {
      return memoize4.cache;
    }
    const res = fn();
    memoize4.cache = res;
    return res;
  };
  return memoize4;
}
function _mixin(cls, mixins) {
  for (const mixin3 of mixins) {
    const mixinPropKeys = Object.getOwnPropertyNames(mixin3);
    for (const propKey of mixinPropKeys) {
      if (propKey !== "constructor") {
        const desc = Object.getOwnPropertyDescriptor(mixin3, propKey);
        Object.defineProperty(cls.prototype, propKey, desc);
      }
    }
  }
}
function mixin2(...mixins) {
  const cls = class {
  };
  _mixin(cls, mixins);
  return cls;
}
function extendWithMixin(baseCls, ...mixins) {
  const cls = class extends baseCls {
  };
  _mixin(cls, mixins);
  return cls;
}
var documentSearchParams = new URL(document.location.href).searchParams;
function getUrlSearchParam(name2) {
  return documentSearchParams.get(name2);
}
var LazyString = class {
  constructor(fn) {
    this.fn = fn;
  }
  toString() {
    return this.fn();
  }
  valueOf() {
    return this.fn();
  }
  toJSON() {
    return this.fn();
  }
};
["toUpperCase", "toLowerCase", "charAt", "slice"].forEach((prop2) => {
  LazyString.prototype[prop2] = function(...args) {
    return this.fn()[prop2](...args);
  };
});
function isFullscreen() {
  return !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement);
}
function toggleFullscreen(element2) {
  if (isFullscreen()) {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  } else {
    if (element2.requestFullscreen) {
      element2.requestFullscreen();
    } else if (element2.webkitRequestFullscreen) {
      element2.webkitRequestFullscreen();
    } else if (element2.mozRequestFullScreen) {
      element2.mozRequestFullScreen();
    } else if (element2.msRequestFullscreen) {
      element2.msRequestFullscreen();
    }
  }
}

// public/app/utils/stdlib.ts
function compare2(a3, b3, castToInt = false, reverse = false) {
  const r3 = reverse ? -1 : 1;
  if (a3 === void 0 || a3 === false) {
    return 1;
  } else if (b3 === void 0 || b3 === false) {
    return -1;
  } else if (typeof a3 === "number" && typeof b3 === "number") {
    return (a3 - b3) * r3;
  } else if (castToInt) {
    return (parseInt(a3, 10) - parseInt(b3, 10)) * r3;
  } else if (a3 && b3) {
    return a3.toString().localeCompare(b3.toString()) * r3;
  } else {
    return 0;
  }
}
function isWindow(obj) {
  return obj && obj.window === obj;
}
function isScope(obj) {
  return obj && obj.$evalAsync && obj.$watch;
}
function equals(o1, o22) {
  if (o1 === o22) return true;
  if (o1 === null || o22 === null) return false;
  if (o1 !== o1 && o22 !== o22) return true;
  var t1 = typeof o1, t22 = typeof o22, length, key2, keySet;
  if (t1 == t22) {
    if (t1 == "object") {
      if (isArray_default(o1)) {
        if (!isArray_default(o22)) return false;
        if ((length = o1.length) == o22.length) {
          for (key2 = 0; key2 < length; key2++) {
            if (!equals(o1[key2], o22[key2])) return false;
          }
          return true;
        }
      } else if (isDate_default(o1)) {
        if (!isDate_default(o22)) return false;
        return equals(o1.getTime(), o22.getTime());
      } else if (isRegExp_default(o1)) {
        return isRegExp_default(o22) ? o1.toString() == o22.toString() : false;
      } else {
        if (isScope(o1) || isScope(o22) || isWindow(o1) || isWindow(o22) || isArray_default(o22) || isDate_default(o22) || isRegExp_default(o22))
          return false;
        keySet = /* @__PURE__ */ Object.create(null);
        for (key2 in o1) {
          if (key2.charAt(0) === "$" || isFunction_default(o1[key2])) continue;
          if (!equals(o1[key2], o22[key2])) return false;
          keySet[key2] = true;
        }
        for (key2 in o22) {
          if (!(key2 in keySet) && key2.charAt(0) !== "$" && typeof o22[key2] !== "undefined" && !isFunction_default(o22[key2]))
            return false;
        }
        return true;
      }
    }
  }
  return false;
}
function filterMap(inputMap, filter4) {
  const filteredMap = /* @__PURE__ */ new Map();
  for (const [key2, value2] of inputMap) {
    if (filter4(value2, key2)) {
      filteredMap.set(key2, value2);
    }
  }
  return filteredMap;
}
function reorderMap(map5, order2) {
  const orderedMap = /* @__PURE__ */ new Map();
  for (const orderKey of order2) {
    if (map5.has(orderKey)) {
      orderedMap.set(orderKey, map5.get(orderKey));
    }
  }
  for (const [mapKey, mapValue] of map5) {
    if (!orderedMap.has(mapKey)) {
      orderedMap.set(mapKey, mapValue);
    }
  }
  return orderedMap;
}
function localeSort(strA, strB, locale) {
  return strA.localeCompare(strB, locale, {
    sensitivity: "base",
    ignorePunctuation: true,
    numeric: true
  });
}
function toInt(n4) {
  if (typeof n4 === "number") {
    return Math.floor(n4);
  }
  return parseInt(n4, 10);
}

// public/app/services/embed.js
var _isEmbedded;
function isEmbedded() {
  if (_isEmbedded === void 0) {
    _isEmbedded = window.location !== window.parent.location || window.self !== window.top || getUrlSearchParam("embed");
  }
  return _isEmbedded;
}

// public/app/utils/storage.js
var StorageWrapper = class {
  constructor(storage, prefix5 = "") {
    this.storage = storage;
    this.prefix = prefix5;
  }
  get length() {
    return this.storage.length;
  }
  key(index2) {
    return this.storage.key(index2);
  }
  getItem(key2) {
    return JSON.parse(this.storage.getItem(this.prefix + key2));
  }
  setItem(key2, value2) {
    return this.storage.setItem(this.prefix + key2, JSON.stringify(value2));
  }
  removeItem(key2) {
    return this.storage.removeItem(this.prefix + key2);
  }
  clear() {
    return this.storage.clear();
  }
};
var IndexedDBStorage = class {
  constructor(name2, version = 1) {
    this.name = name2;
    this.version = version;
    this.kvVersion = version <= 1 ? "kv" : `kv${version}`;
    this.open = singleton(() => new Promise((resolve2, reject2) => {
      let req = indexedDB.open(this.name, this.version);
      req.onupgradeneeded = (event2) => {
        const db = req.result;
        if (event2.oldVersion < this.version) {
          for (let version2 = 0; version2 < this.version; version2++) {
            const kvVersion = version2 <= 1 ? "kv" : `kv${version2}`;
            if (db.objectStoreNames.contains(kvVersion)) {
              db.deleteObjectStore(kvVersion);
            }
          }
          db.createObjectStore(this.kvVersion);
        }
      };
      req.onerror = () => reject2(req.error);
      req.onsuccess = () => {
        this.db = req.result;
        this.db.onversionchange = () => {
          this.reset();
        };
        resolve2(this.db);
      };
    }));
    this.open();
  }
  async transaction(mode, requestCallback) {
    await this.open();
    return new Promise(async (resolve2, reject2) => {
      try {
        const tx = this.db.transaction(this.kvVersion, mode);
        const store2 = tx.objectStore(this.kvVersion);
        const req = requestCallback(store2);
        tx.oncomplete = () => resolve2(req.result);
        tx.onsuccess = () => resolve2(req.result);
        tx.onabort = () => reject2(req.error ?? req.transaction.error);
      } catch (e3) {
        this.reset();
        return this.transaction(mode, requestCallback);
      }
    });
  }
  getItem(key2) {
    return this.transaction("readonly", (store2) => store2.get(key2)).then((v3) => v3 === void 0 ? null : v3);
  }
  setItem(key2, data2) {
    return this.transaction("readwrite", (store2) => store2.put(data2, key2));
  }
  removeItem(key2) {
    return this.transaction("readwrite", (store2) => store2.delete(key2));
  }
  clear() {
    return this.transaction("readwrite", (store2) => store2.clear());
  }
  reset() {
    this.db.close();
    this.open.instance = null;
    this.open();
  }
};
var StorageKey = class {
  constructor(storage, key2) {
    this.storage = storage;
    this.key = key2;
  }
  get() {
    return this.storage.getItem(this.key);
  }
  set(value2) {
    this.storage.setItem(this.key, value2);
  }
  remove() {
    this.storage.removeItem(this.key);
  }
};

// public/app/services/storage.ts
var jsonLocalStorage = new StorageWrapper(localStorage);
var idbLocalStorage = new IndexedDBStorage("kantree-stores", 2);

// public/app/services/config.ts
var [serverConfig, setServerConfig] = createStore(window.KANTREE_CONFIG || {});
var loadServerConfig = singleton(async () => {
  if (serverConfig.version) {
    return serverConfig;
  }
  if (isOnline()) {
    try {
      setServerConfig(await api_default.config.get_config.get());
      notifyConnectionRecovered();
      return serverConfig;
    } catch {
      notifyConnectionLost();
    }
  }
  const localConfig = jsonLocalStorage.getItem("config");
  if (localConfig) {
    setServerConfig(localConfig);
    return serverConfig;
  }
  alert("Kantree cannot be loaded");
  document.location.reload();
});

// public/app/services/base-url.js
var [baseUrl, setBaseUrl] = createSignal("");
function joinUrl(base3, url2) {
  if (!url2 || url2.match(/^[a-z]+:\/\//i)) {
    return url2;
  }
  if (url2.match(/^\/\//)) {
    if (window.location.protocol === "file:") {
      return "https:" + url2;
    }
    return url2;
  }
  if (url2.match(/^#!/)) {
    url2 = url2.slice(2);
  }
  return base3 + url2;
}
function prependBaseUrl(url2) {
  return joinUrl(baseUrl(), url2);
}
function makeUrlAbsolute(url2) {
  if (!baseUrl()) {
    return joinUrl(window.location.origin, url2);
  }
  return prependBaseUrl(url2);
}

// public/app/services/auth.js
var guestAvatarUrl = createMemo(() => prependBaseUrl("/static/assets/guest-avatar.png"));
var guestUserData = {
  id: null,
  username: "Guest",
  display_name: "Guest",
  avatar: guestAvatarUrl(),
  app_params: {}
};
var [currentUser2, setCurrentUser] = createStore(guestUserData);
function isAuthenticated() {
  return currentUser2.id !== null;
}
var cachedUser = new StorageKey(jsonLocalStorage, "user");
var currentUserRefreshInterval;
function saveCurrentUser(userData) {
  Object.assign(userData, { avatar: userData.avatar ? prependBaseUrl(userData.avatar) : null });
  setCurrentUser(userData);
  cachedUser.set(userData);
}
var loadCurrentUser = singleton(async function() {
  let userData;
  if (isConnected()) {
    try {
      userData = await api_default.user.get_info.get({}, { ignoreErrorHandlers: true });
    } catch (r3) {
      if (r3.status === 401) {
        clearCurrentUser();
        return;
      }
    }
  }
  if (!userData) {
    userData = cachedUser.get();
  }
  if (userData) {
    saveCurrentUser(userData);
  }
  currentUserRefreshInterval = setInterval(fetchCurrentUserData, 3600 * 1e3);
});
async function fetchCurrentUserData(full = false) {
  if (isConnected()) {
    const userData = await api_default.user[full ? "get_full_info" : "get_info"].get({}, { ignoreErrorHandlers: true });
    saveCurrentUser(userData);
  }
}
function clearCurrentUser() {
  cachedUser.set(null);
  setCurrentUser(guestUserData);
  clearInterval(currentUserRefreshInterval);
}

// public/app/actions/user.ts
function saveUserAppParams(params, reset3) {
  if (reset3) {
    setCurrentUser("app_params", params);
  } else {
    setCurrentUser("app_params", Object.assign({}, currentUser2.app_params, params));
  }
  return api_default.user.update_app_params.put({ params, merge: !reset3 }, { ignoreErrorHandlers: true });
}
async function markAsOnboarded(step2) {
  if ((currentUser2.onboarded || []).includes(step2)) {
    return;
  }
  try {
    const user = await api_default.user.mark_as_onboarded.post({ step: step2 }, { ignoreErrorHandlers: true });
    setCurrentUser(user);
  } catch {
  }
}

// public/app/ui/system/theme.js
var [themeState, setThemeState] = createStore({
  defaultPageColor: null,
  pageColor: null,
  backgroungImageUrl: null
});
var themeName = createMemo(() => {
  if (isEmbedded() && isScreensizeXS() && themeState.name === "sidebar") {
    return "topbar";
  }
  if (isEmbedded()) {
    return "sidebar";
  }
  return themeState.name;
});
var themeColor = createMemo(() => {
  if (themeState.color !== "") {
    return themeState.color;
  }
  return serverConfig.theme_color;
});
var pageColor = createMemo(() => {
  if (themeState.pageColor) {
    return themeState.pageColor;
  }
  if (themeState.color !== "") {
    return themeState.color;
  }
  if (themeState.defaultPageColor) {
    return themeState.defaultPageColor;
  }
  return serverConfig.theme_color;
});
function ThemeContext(props2) {
  loadCurrentUser().then(() => {
    setThemeState({
      name: get(currentUser2.app_params, "theme", "sidebar"),
      color: get(currentUser2.app_params, "theme_color", "")
    });
  });
  return props2.children;
}
createEffect(() => {
  if (!document.body.classList.contains(`user-theme-${themeName()}`)) {
    jquery_default("body").removeClassRegex("user-theme-");
    document.body.classList.add(`user-theme-${themeName()}`);
  }
  const root3 = document.documentElement;
  if (pageColor()) {
    const color = (0, import_tinycolor22.default)(pageColor());
    const hslColor = color.toHsl();
    root3.style.setProperty("--theme-base-hue", hslColor.h);
    root3.style.setProperty("--theme-base-saturation", Math.round(hslColor.s * 100) + "%");
    root3.style.setProperty("--theme-base-lightness", Math.round(hslColor.l * 100) + "%");
    root3.style.setProperty("--theme-base-luma-sign", color.isLight() ? "1" : "-1");
    if (themeName() === "topbar") {
      root3.style.setProperty("--theme-base-logo", color.isLight() ? "var(--topbar-logo-black)" : "var(--topbar-logo-white)");
    }
    root3.style.setProperty("--theme-sidebar-logo", color.isLight() ? "var(--sidebar-logo-black)" : "var(--sidebar-logo-white)");
    root3.style.setProperty("--theme-sidebar-luma-sign", color.darken(Math.round(hslColor.l * 100) * 0.25).saturate(2).isLight() ? "1" : "-1");
  } else {
    root3.style.setProperty("--theme-base-hue", "176");
    root3.style.setProperty("--theme-base-saturation", "55%");
    root3.style.setProperty("--theme-base-lightness", "22%");
    root3.style.setProperty("--theme-base-luma-sign", "-1");
    root3.style.setProperty("--theme-base-logo", "var(--topbar-logo-white)");
    root3.style.setProperty("--theme-sidebar-logo", "var(--sidebar-logo-white)");
    root3.style.setProperty("--theme-sidebar-luma-sign", "-1");
  }
  const bgImgEl = document.getElementById("app-main");
  if (bgImgEl) {
    bgImgEl.style.setProperty("background-image", themeState.backgroungImageUrl ? `url(${themeState.backgroungImageUrl})` : "");
    bgImgEl.classList.toggle("with-app-background-image", !!themeState.backgroungImageUrl);
  }
});
function setPageColor(color, force = true) {
  if (!color) {
    setThemeState({ pageColor: null, defaultPageColor: null });
  } else if (force) {
    setThemeState({ pageColor: color });
  } else {
    setThemeState({ defaultPageColor: color });
  }
  return () => setPageColor();
}
function setPageBackgroundImage(url2) {
  setThemeState({ backgroungImageUrl: url2 });
  return () => setThemeState({ backgroungImageUrl: null });
}
function saveTheme(name2, color) {
  const state = { name: name2 };
  const params = { theme: name2 };
  if (color !== void 0) {
    state.color = color;
    params.theme_color = color;
  }
  setThemeState(state);
  saveUserAppParams(params);
}

// virtual-ns:moment
var moment_default = moment;

// virtual-ns:script.js
var script_default = $script;

// public/app/utils/proxy-handler.js
function createProxyHandler(defaultValue) {
  let handler = defaultValue;
  return new Proxy({}, {
    get(obj, prop2) {
      if (prop2 === "setHandler") {
        return function(handler_) {
          handler = handler_;
        };
      }
      return handler[prop2].bind(handler);
    }
  });
}

// public/app/services/i18n.js
var currentLocale = "en";
var catalog = {};
function getCurrentLocale() {
  return currentLocale;
}
var localeLoader = createProxyHandler({
  load(locale) {
    return new Promise((resolve2, reject2) => {
      script_default([prependBaseUrl(`/static/locales/${locale}/all.js`)], () => resolve2());
    });
  }
});
function _4(text3, ...args) {
  return formatTranslationString(getCatalogValue(text3)[1] || text3, ...args);
}
function _p(context, text3, ...args) {
  return formatTranslationString(getCatalogValue(text3, context)[1] || text3, ...args);
}
function _n(singular, plural, count, args, context) {
  args = args || {};
  args["count"] = count;
  const value2 = getCatalogValue(singular, context);
  if (value2) {
    if (value2[1]) {
      singular = value2[1];
    }
    if (value2[2]) {
      plural = value2[2];
    }
  }
  if (count > 1) {
    return formatTranslationString(plural, args);
  }
  return formatTranslationString(singular, args);
}
function _np(context, singular, plural, count, args) {
  return _n(singular, plural, count, args, context);
}
function _lazy(...args) {
  return new LazyString(() => _4(...args));
}
var setLocaleFromUser = singleton(async function() {
  await loadCurrentUser();
  await setLocale(currentUser2.locale);
});
async function setLocale(locale) {
  if (!locale) {
    locale = getUrlSearchParam("locale") || (window.navigator?.language || "").substring(0, 2) || "en";
  }
  if (currentLocale === locale) {
    updateMomentLocaleWithUserSettings();
    return;
  }
  activateLocale(locale);
  if (locale !== "en" && !isCatalogAvailable(locale)) {
    await localeLoader.load(locale);
  }
  if (isCatalogAvailable(locale)) {
    catalog = window[`LOCALE_${locale.toUpperCase()}_CATALOG`];
  } else {
    activateLocale("en");
    catalog = {};
  }
}
function activateLocale(locale) {
  currentLocale = locale;
  moment_default.locale(locale);
  updateMomentLocaleWithUserSettings();
}
function updateMomentLocaleWithUserSettings() {
  if (!isAuthenticated()) return;
  if (currentUser2.time_format) {
    const longDateFormat = moment_default.localeData()._longDateFormat;
    for (let [key2, value2] of Object.entries(longDateFormat)) {
      if (!["LT", "LTS"].includes(key2)) {
        longDateFormat[key2] = value2.replace(longDateFormat["LTS"], "LTS").replace(longDateFormat["LT"], "LT");
      }
    }
    longDateFormat["LT"] = currentUser2.time_format === "am_pm" ? "h:mm A" : "HH:mm";
    longDateFormat["LTS"] = currentUser2.time_format === "am_pm" ? "h:mm:ss A" : "HH:mm:ss";
    moment_default.updateLocale(moment_default.locale(), { longDateFormat });
  }
  if (currentUser2.dow_start !== null) {
    moment_default.updateLocale(moment_default.locale(), { week: { dow: currentUser2.dow_start } });
  }
}
function getCatalogValue(text3, context) {
  const messageId = context ? context + "::" + text3 : text3;
  if (typeof catalog[messageId] !== "undefined" && catalog[messageId][1]) {
    return catalog[messageId];
  }
  return [null, null];
}
function isCatalogAvailable(locale) {
  if (!locale) return false;
  return typeof window[`LOCALE_${locale.toUpperCase()}_CATALOG`] !== "undefined";
}
function formatTranslationString(text3, ...data2) {
  if (data2.length) {
    if (data2.length === 1 && $.isPlainObject(data2[0])) {
      data2 = data2[0];
    }
    for (let [key2, value2] of Object.entries(data2)) {
      text3 = text3.replace(new RegExp("\\{" + key2 + "\\}", "gi"), value2);
    }
  }
  return text3;
}

// public/app/utils/angular/locationProvider.js
var $customLocationProviderGet = [
  "$rootScope",
  "$browser",
  "$sniffer",
  "$rootElement",
  "$injector",
  function($rootScope, $browser, $sniffer, $rootElement, $injector) {
    var $location, initialUrl = $browser.url();
    const appBase = document.location.protocol + "//" + document.location.host + "/";
    $location = new LocationHtml5Url(appBase, appBase, "#!");
    $location.$$parseLinkUrl(initialUrl, initialUrl);
    $location.$$state = $browser.state();
    var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
    function urlsEqual(a3, b3) {
      return a3 === b3 || urlResolve(a3).href === urlResolve(b3).href;
    }
    function setBrowserUrlWithFallback(url2, replace4, state) {
      var oldUrl = $location.url();
      var oldState = $location.$$state;
      try {
        $location.$$state = $browser.state();
      } catch (e3) {
        $location.url(oldUrl);
        $location.$$state = oldState;
        throw e3;
      }
    }
    var initializing = true;
    $browser.onUrlChange(function(newUrl, newState) {
      $rootScope.$evalAsync(function() {
        var oldUrl = $location.absUrl();
        var oldState = $location.$$state;
        var defaultPrevented;
        $location.$$parse(newUrl);
        $location.$$state = newState;
        defaultPrevented = $rootScope.$broadcast(
          "$locationChangeStart",
          newUrl,
          oldUrl,
          newState,
          oldState
        ).defaultPrevented;
        if ($location.absUrl() !== newUrl) return;
        if (defaultPrevented) {
          $location.$$parse(oldUrl);
          $location.$$state = oldState;
          setBrowserUrlWithFallback(oldUrl, false, oldState);
        } else {
          initializing = false;
          afterLocationChange(oldUrl, oldState);
        }
      });
      if (!$rootScope.$$phase) $rootScope.$digest();
    });
    $rootScope.$watch(function $locationWatch() {
      if (initializing || $location.$$urlUpdatedByLocation) {
        $location.$$urlUpdatedByLocation = false;
        var oldUrl = $browser.url();
        var newUrl = $location.absUrl();
        var oldState = $browser.state();
        var currentReplace = $location.$$replace;
        var urlOrStateChanged = !urlsEqual(oldUrl, newUrl) || $location.$$html5 && $sniffer.history && oldState !== $location.$$state;
        if (initializing || urlOrStateChanged) {
          initializing = false;
          $rootScope.$evalAsync(function() {
            var newUrl2 = $location.absUrl();
            var defaultPrevented = $rootScope.$broadcast(
              "$locationChangeStart",
              newUrl2,
              oldUrl,
              $location.$$state,
              oldState
            ).defaultPrevented;
            if ($location.absUrl() !== newUrl2) return;
            if (defaultPrevented) {
              $location.$$parse(oldUrl);
              $location.$$state = oldState;
            } else {
              if (urlOrStateChanged) {
                setBrowserUrlWithFallback(
                  newUrl2,
                  currentReplace,
                  oldState === $location.$$state ? null : $location.$$state
                );
              }
              afterLocationChange(oldUrl, oldState);
            }
          });
        }
      }
      $location.$$replace = false;
    });
    return $location;
    function afterLocationChange(oldUrl, oldState) {
      $rootScope.$broadcast(
        "$locationChangeSuccess",
        $location.absUrl(),
        oldUrl,
        $location.$$state,
        oldState
      );
    }
  }
];
var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/;
var DEFAULT_PORTS = { "http": 80, "https": 443, "ftp": 21 };
var locationPrototype = {
  /**
   * Ensure absolute URL is initialized.
   * @private
   */
  $$absUrl: "",
  /**
   * Are we in html5 mode?
   * @private
   */
  $$html5: false,
  /**
   * Has any change been replacing?
   * @private
   */
  $$replace: false,
  /**
   * Compose url and update `url` and `absUrl` property
   * @private
   */
  $$compose: function() {
    this.$$url = normalizePath(this.$$path, this.$$search, this.$$hash);
    this.$$absUrl = this.$$normalizeUrl(this.$$url);
    this.$$urlUpdatedByLocation = true;
  },
  /**
   * @ngdoc method
   * @name $location#absUrl
   *
   * @description
   * This method is getter only.
   *
   * Return full URL representation with all segments encoded according to rules specified in
   * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var absUrl = $location.absUrl();
   * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
   * ```
   *
   * @return {string} full URL
   */
  absUrl: locationGetter("$$absUrl"),
  /**
   * @ngdoc method
   * @name $location#url
   *
   * @description
   * This method is getter / setter.
   *
   * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
   *
   * Change path, search and hash, when called with parameter and return `$location`.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var url = $location.url();
   * // => "/some/path?foo=bar&baz=xoxo"
   * ```
   *
   * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
   * @return {string} url
   */
  url: function(url2) {
    if (isUndefined2(url2)) {
      return this.$$url;
    }
    var match2 = PATH_MATCH.exec(url2);
    if (match2[1] || url2 === "") this.path(decodeURIComponent(match2[1]));
    if (match2[2] || match2[1] || url2 === "") this.search(match2[3] || "");
    this.hash(match2[5] || "");
    return this;
  },
  /**
   * @ngdoc method
   * @name $location#protocol
   *
   * @description
   * This method is getter only.
   *
   * Return protocol of current URL.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var protocol = $location.protocol();
   * // => "http"
   * ```
   *
   * @return {string} protocol of current URL
   */
  protocol: locationGetter("$$protocol"),
  /**
   * @ngdoc method
   * @name $location#host
   *
   * @description
   * This method is getter only.
   *
   * Return host of current URL.
   *
   * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var host = $location.host();
   * // => "example.com"
   *
   * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
   * host = $location.host();
   * // => "example.com"
   * host = location.host;
   * // => "example.com:8080"
   * ```
   *
   * @return {string} host of current URL.
   */
  host: locationGetter("$$host"),
  /**
   * @ngdoc method
   * @name $location#port
   *
   * @description
   * This method is getter only.
   *
   * Return port of current URL.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var port = $location.port();
   * // => 80
   * ```
   *
   * @return {Number} port
   */
  port: locationGetter("$$port"),
  /**
   * @ngdoc method
   * @name $location#path
   *
   * @description
   * This method is getter / setter.
   *
   * Return path of current URL when called without any parameter.
   *
   * Change path when called with parameter and return `$location`.
   *
   * Note: Path should always begin with forward slash (/), this method will add the forward slash
   * if it is missing.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var path = $location.path();
   * // => "/some/path"
   * ```
   *
   * @param {(string|number)=} path New path
   * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
   */
  path: locationGetterSetter("$$path", function(path) {
    path = path !== null ? path.toString() : "";
    return path.charAt(0) === "/" ? path : "/" + path;
  }),
  /**
   * @ngdoc method
   * @name $location#search
   *
   * @description
   * This method is getter / setter.
   *
   * Return search part (as object) of current URL when called without any parameter.
   *
   * Change search part when called with parameter and return `$location`.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
   * var searchObject = $location.search();
   * // => {foo: 'bar', baz: 'xoxo'}
   *
   * // set foo to 'yipee'
   * $location.search('foo', 'yipee');
   * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
   * ```
   *
   * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
   * hash object.
   *
   * When called with a single argument the method acts as a setter, setting the `search` component
   * of `$location` to the specified value.
   *
   * If the argument is a hash object containing an array of values, these values will be encoded
   * as duplicate search parameters in the URL.
   *
   * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
   * will override only a single search property.
   *
   * If `paramValue` is an array, it will override the property of the `search` component of
   * `$location` specified via the first argument.
   *
   * If `paramValue` is `null`, the property specified via the first argument will be deleted.
   *
   * If `paramValue` is `true`, the property specified via the first argument will be added with no
   * value nor trailing equal sign.
   *
   * @return {Object} If called with no arguments returns the parsed `search` object. If called with
   * one or more arguments returns `$location` object itself.
   */
  search: function(search, paramValue) {
    switch (arguments.length) {
      case 0:
        return this.$$search;
      case 1:
        if (isString(search) || isNumber(search)) {
          search = search.toString();
          this.$$search = parseKeyValue(search);
        } else if (isObject3(search)) {
          search = angular.copy(search, {});
          angular.forEach(search, function(value2, key2) {
            if (value2 == null) delete search[key2];
          });
          this.$$search = search;
        } else {
          throw Error(
            "isrcharg",
            "The first argument of the `$location#search()` call must be a string or an object."
          );
        }
        break;
      default:
        if (isUndefined2(paramValue) || paramValue === null) {
          delete this.$$search[search];
        } else {
          this.$$search[search] = paramValue;
        }
    }
    this.$$compose();
    return this;
  },
  /**
   * @ngdoc method
   * @name $location#hash
   *
   * @description
   * This method is getter / setter.
   *
   * Returns the hash fragment when called without any parameters.
   *
   * Changes the hash fragment when called with a parameter and returns `$location`.
   *
   *
   * ```js
   * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
   * var hash = $location.hash();
   * // => "hashValue"
   * ```
   *
   * @param {(string|number)=} hash New hash fragment
   * @return {string} hash
   */
  hash: locationGetterSetter("$$hash", function(hash) {
    return hash !== null ? hash.toString() : "";
  }),
  /**
   * @ngdoc method
   * @name $location#replace
   *
   * @description
   * If called, all changes to $location during the current `$digest` will replace the current history
   * record, instead of adding a new one.
   */
  replace: function() {
    this.$$replace = true;
    return this;
  }
};
function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  this.$$html5 = true;
  basePrefix = basePrefix || "";
  parseAbsoluteUrl(appBase, this);
  this.$$parse = function(url2) {
    var pathUrl = stripBaseUrl(appBaseNoFile, url2);
    if (!isString(pathUrl)) {
      throw Error(
        "ipthprfx",
        'Invalid url "{0}", missing path prefix "{1}".',
        url2,
        appBaseNoFile
      );
    }
    parseAppUrl(pathUrl, this, true);
    if (!this.$$path) {
      this.$$path = "/";
    }
    this.$$compose();
  };
  this.$$normalizeUrl = function(url2) {
    return appBaseNoFile + url2.substr(1);
  };
  this.$$parseLinkUrl = function(url2, relHref) {
    if (relHref && relHref[0] === "#") {
      this.hash(relHref.slice(1));
      return true;
    }
    var appUrl, prevAppUrl;
    var rewrittenUrl;
    if (isDefined(appUrl = stripBaseUrl(appBase, url2))) {
      prevAppUrl = appUrl;
      if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
        rewrittenUrl = appBaseNoFile + (stripBaseUrl("/", appUrl) || appUrl);
      } else {
        rewrittenUrl = appBase + prevAppUrl;
      }
    } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url2))) {
      rewrittenUrl = appBaseNoFile + appUrl;
    } else if (appBaseNoFile === url2 + "/") {
      rewrittenUrl = appBaseNoFile;
    }
    if (rewrittenUrl) {
      this.$$parse(rewrittenUrl);
    }
    return !!rewrittenUrl;
  };
}
LocationHtml5Url.prototype = Object.create(locationPrototype);
var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
function parseAppUrl(url2, locationObj, html5Mode) {
  if (DOUBLE_SLASH_REGEX.test(url2)) {
    throw Error("badpath", 'Invalid url "{0}".', url2);
  }
  var prefixed = url2.charAt(0) !== "/";
  if (prefixed) {
    url2 = "/" + url2;
  }
  var match2 = urlResolve(url2);
  var path = prefixed && match2.pathname.charAt(0) === "/" ? match2.pathname.substring(1) : match2.pathname;
  locationObj.$$path = decodePath(path, html5Mode);
  locationObj.$$search = parseKeyValue(match2.search);
  locationObj.$$hash = decodeURIComponent(match2.hash);
  if (locationObj.$$path && locationObj.$$path.charAt(0) !== "/") {
    locationObj.$$path = "/" + locationObj.$$path;
  }
}
function urlResolve(url2) {
  const urlParsingNode = new URL(url2, document.location.href);
  var hostname = urlParsingNode.hostname;
  return {
    href: urlParsingNode.href,
    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "",
    host: urlParsingNode.host,
    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "",
    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "",
    hostname,
    port: urlParsingNode.port,
    pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname
  };
}
function parseKeyValue(keyValue) {
  const params = new URLSearchParams(keyValue);
  return Object.fromEntries(params.entries());
}
function decodePath(path, html5Mode) {
  var segments = path.split("/"), i3 = segments.length;
  while (i3--) {
    segments[i3] = decodeURIComponent(segments[i3]);
    if (html5Mode) {
      segments[i3] = segments[i3].replace(/\//g, "%2F");
    }
  }
  return segments.join("/");
}
function parseAbsoluteUrl(absoluteUrl, locationObj) {
  var parsedUrl = urlResolve(absoluteUrl);
  locationObj.$$protocol = parsedUrl.protocol;
  locationObj.$$host = parsedUrl.hostname;
  locationObj.$$port = toInt2(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}
function startsWith(str, search) {
  return str.slice(0, search.length) === search;
}
function stripBaseUrl(base3, url2) {
  if (startsWith(url2, base3)) {
    return url2.substr(base3.length);
  }
}
function normalizePath(pathValue, searchValue, hashValue) {
  var search = toKeyValue(searchValue), hash = hashValue ? "#" + encodeUriSegment(hashValue) : "", path = encodePath(pathValue);
  return path + (search ? "?" + search : "") + hash;
}
function locationGetter(property2) {
  return (
    /** @this */
    function() {
      return this[property2];
    }
  );
}
function locationGetterSetter(property2, preprocess) {
  return (
    /** @this */
    function(value2) {
      if (isUndefined2(value2)) {
        return this[property2];
      }
      this[property2] = preprocess(value2);
      this.$$compose();
      return this;
    }
  );
}
function isUndefined2(value2) {
  return typeof value2 === "undefined";
}
function isDefined(value2) {
  return typeof value2 !== "undefined";
}
function isObject3(value2) {
  return value2 !== null && typeof value2 === "object";
}
function isString(value2) {
  return typeof value2 === "string";
}
function isNumber(value2) {
  return typeof value2 === "number";
}
function toKeyValue(obj) {
  var parts = [];
  angular.forEach(obj, function(value2, key2) {
    if (angular.isArray(value2)) {
      angular.forEach(value2, function(arrayValue) {
        parts.push(encodeUriQuery(key2, true) + (arrayValue === true ? "" : "=" + encodeUriQuery(arrayValue, true)));
      });
    } else {
      parts.push(encodeUriQuery(key2, true) + (value2 === true ? "" : "=" + encodeUriQuery(value2, true)));
    }
  });
  return parts.length ? parts.join("&") : "";
}
function encodeUriQuery(val, pctEncodeSpaces) {
  return encodeURIComponent(val).replace(/%40/gi, "@").replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%3B/gi, ";").replace(/%20/g, pctEncodeSpaces ? "%20" : "+");
}
function encodeUriSegment(val) {
  return encodeUriQuery(val, true).replace(/%26/gi, "&").replace(/%3D/gi, "=").replace(/%2B/gi, "+");
}
function encodePath(path) {
  var segments = path.split("/"), i3 = segments.length;
  while (i3--) {
    segments[i3] = encodeUriSegment(segments[i3].replace(/%2F/g, "/"));
  }
  return segments.join("/");
}
function toInt2(str) {
  return parseInt(str, 10);
}

// public/app/ng-app.js
var ngApp = angular_default.module("kantree", [
  "ngSanitize",
  //'ui.router',
  "ui.bootstrap",
  "ui.sortable",
  "ui.select",
  "ngFileUpload",
  "bootstrapLightbox",
  "cfp.hotkeys",
  "puigcerber.countryPicker",
  "widgetGrid",
  "com.2fdevs.videogular",
  "ngFitText"
]);
var [isBootstraped, setBootstraped] = createSignal(false);
ngApp.bootstrap = function(el2) {
  ngApp.$injector = angular_default.bootstrap(el2, ["kantree"]);
  setBootstraped(true);
};
function $digest(fn) {
  const r3 = ngApp.$injector.invoke(fn);
  ngApp.$injector.get("$rootScope").$applyAsync();
  return r3;
}
function $broadcast(...args) {
  ngApp.$injector.get("$rootScope").$broadcast(...args);
}
function $invoke(fn, locals) {
  return ngApp.$injector.invoke(fn, null, locals);
}
function $invokeDecorator(fn, annotations, thisArg) {
  return function(...args) {
    let locals = {};
    if (annotations === true) {
      annotations = ngApp.$injector.annotate(fn);
    }
    if (annotations) {
      for (let i3 = 0; i3 < annotations.length; i3++) {
        locals[annotations[i3]] = args[i3];
      }
    } else {
      locals = { $args: args };
    }
    return $invoke(fn, locals);
  };
}
function $createEffect(scope, fn) {
  const dispose2 = createDisposable(() => {
    createEffect(() => $digest(fn));
  });
  const disposeOn = scope.$on("$destroy", dispose2);
  return () => {
    dispose2();
    disposeOn();
  };
}
function _injectI18nHelpersIntoScope(scope, $sce, $filter2) {
  scope._ = _4;
  scope._p = _p;
  scope._trust = (...args) => $sce.trustAsHtml(_4(...args));
  scope._ptrust = (...args) => $sce.trustAsHtml(_p(...args));
  scope._ntrust = (...args) => $sce.trustAsHtml(_n(...args));
  scope._n = _n;
  scope._np = _np;
}
function injectI18nHelpersIntoScope(scope) {
  $invoke([
    "$sce",
    "$filter",
    ($sce, $filter2) => {
      _injectI18nHelpersIntoScope(scope, $sce, $filter2);
    }
  ]);
}
angular_default.module("kantree").config([
  "$uibTooltipProvider",
  "hotkeysProvider",
  "LightboxProvider",
  "uiSelectConfig",
  "$compileProvider",
  "$locationProvider",
  function($uibTooltipProvider, hotkeysProvider, LightboxProvider, uiSelectConfig, $compileProvider, $locationProvider) {
    if (typeof window.KANTREE_DEBUG === "undefined") {
      $compileProvider.debugInfoEnabled(false);
      $compileProvider.commentDirectivesEnabled(false);
      $compileProvider.cssClassDirectivesEnabled(false);
    }
    $locationProvider.$get = $customLocationProviderGet;
    $uibTooltipProvider.options({
      appendToBody: true,
      popupDelay: 200
    });
    uiSelectConfig.theme = "bootstrap";
    LightboxProvider.templateUrl = "/static/app/ui/utils/ng-components/templates/lightbox.html";
    LightboxProvider.calculateModalDimensions = function(dimensions) {
      var width = Math.max(200, dimensions.imageDisplayWidth);
      var height = Math.max(200, dimensions.imageDisplayHeight);
      if (width >= dimensions.windowWidth - 20 || dimensions.windowWidth < 768) {
        width = "auto";
      }
      if (height >= dimensions.windowHeight) {
        height = "auto";
      }
      return {
        "width": width,
        "height": height
      };
    };
    hotkeysProvider.template = `
      <div class="cfp-hotkeys-container fade in" ng-if="helpVisible"><div class="cfp-hotkeys">
        <h4 class="cfp-hotkeys-title">{{ title }}</h4>
        <ul>
          <li ng-repeat="hotkey in hotkeys | filter:{ description: '!$$undefined$$' }">
            <span class="cfp-hotkeys-keys">
              <span ng-repeat="key in hotkey.format() track by $index" class="cfp-hotkeys-key">{{ key }}</span>
            </span>
            <span class="cfp-hotkeys-text">{{ hotkey.description }}</span>
          </li>
        </ul>
        <div class="cfp-hotkeys-close" ng-click="toggleCheatSheet()">\xD7</div>
      </div></div>`;
  }
]);
angular_default.module("kantree").run([
  "$rootScope",
  "$q",
  "hotkeys",
  "$sce",
  "$filter",
  "termsValidationModal",
  function($rootScope, $q, hotkeys, $sce, $filter2, termsValidationModal) {
    $q.digest = function(promise) {
      return $q.when(promise, (r3) => r3);
    };
    createEffect(() => {
      $rootScope.$broadcast("connectivityChanged", isConnected());
    });
    createEffect(on(
      () => {
        themeState.name;
        themeState.color;
        themeState.pageColor;
        themeState.defaultPageColor;
      },
      () => $rootScope.$broadcast("interfaceThemeUpdated"),
      { defer: true }
    ));
    createEffect(on(
      () => currentUser2.email_validated,
      () => currentUser2.email_validated && $rootScope.$broadcast("userEmailValidated"),
      { defer: true }
    ));
    createEffect(() => {
      if (isAuthenticated() && currentUser2.needs_terms_validation) {
        termsValidationModal.open();
      }
    });
    _injectI18nHelpersIntoScope($rootScope, $sce, $filter2);
    hotkeys.cheatSheetDescription = _4("Show / hide this help menu");
    hotkeys.templateTitle = _4("Keyboard Shortcuts:");
    createEffect(on(
      screensize,
      () => $rootScope.$broadcast("screensize:changed"),
      { defer: true }
    ));
  }
]);

// public/app/utils/device.js
function isFirefox() {
  return window.navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
}
function isIE() {
  return window.navigator.userAgent.indexOf("MSIE ") > -1 || navigator.userAgent.indexOf("Trident/") > -1;
}
function isMacOS() {
  return typeof window.navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(window.navigator.platform) : false;
}

// public/app/ui/base/alerts.jsx
var _tmpl$ = /* @__PURE__ */ template(`<div class="alert"></div>`, 2);
function Alert(props2) {
  return (() => {
    const _el$ = _tmpl$.cloneNode(true);
    insert(_el$, () => props2.children);
    createRenderEffect((_$p) => classList(_el$, {
      [props2.style]: true,
      "alert-actionnable": props2.actionnable
    }, _$p));
    return _el$;
  })();
}

// public/app/ui/base/loader.jsx
var _tmpl$2 = /* @__PURE__ */ template(`<i class="fa fa-spin fa-spinner"></i>`, 2);
function LoadingIndicator(props2) {
  const [local, others] = splitProps(props2, ["class"]);
  return (() => {
    const _el$ = _tmpl$2.cloneNode(true);
    spread(_el$, mergeProps({
      get classList() {
        return {
          [local.class]: local.class
        };
      }
    }, others), false, false);
    return _el$;
  })();
}

// public/app/ui/utils/colors.js
var colors_exports = {};
__export(colors_exports, {
  ColorizeElement: () => ColorizeElement,
  ReadableTextColor: () => ReadableTextColor,
  colorizeElement: () => colorizeElement,
  darkenColor: () => darkenColor,
  lightenColor: () => lightenColor,
  slightlyDifferentColor: () => slightlyDifferentColor,
  textColor: () => textColor,
  useColorizeElement: () => useColorizeElement,
  useReadableTextColor: () => useReadableTextColor
});
var import_tinycolor23 = __toESM(require_tinycolor());
__reExport(colors_exports, __toESM(require_tinycolor()));
function textColor(color, light, dark, undefinedColor) {
  if (!color) {
    return undefinedColor || dark || null;
  }
  return import_tinycolor23.default.mostReadable(color, [light || "#FFFFFF", dark || "#000000"]).toString();
}
function darkenColor(color, value2) {
  return (0, import_tinycolor23.default)(color).darken(value2).toString();
}
function lightenColor(color, value2) {
  return (0, import_tinycolor23.default)(color).lighten(value2).toString();
}
function slightlyDifferentColor(color, value2) {
  if (!color || color === "") return null;
  if (import_tinycolor23.default.mostReadable(color, ["#000000", "#ffffff"]).toString() === "#000000") {
    return (0, import_tinycolor23.default)("#000").setAlpha(value2 || 0.1).toRgbString();
  } else {
    return (0, import_tinycolor23.default)("#fff").setAlpha(value2 || 0.1).toRgbString();
  }
}
function colorizeElement(el2, bgColor, fgColor = null, highlightOnOver = false) {
  const origColors = { "background-color": el2.style.backgroundColor, color: el2.style.color };
  if (!fgColor) {
    fgColor = import_tinycolor23.default.mostReadable(bgColor, ["#FFFFFF", "#000000"]).toHexString();
  }
  const setColor = (bgColor2, fgColor2) => {
    el2.style.backgroundColor = bgColor2;
    el2.style.color = fgColor2;
  };
  setColor(bgColor, fgColor);
  const setColorFunction = () => setColor((0, import_tinycolor23.default)(bgColor).darken(10).toString(), fgColor);
  const setBgFgColorFunction = () => setColor(bgColor, fgColor);
  if (highlightOnOver) {
    el2.addEventListener("mouseenter", setColorFunction);
    el2.addEventListener("mouseleave", setBgFgColorFunction);
  }
  return () => {
    if (highlightOnOver) {
      el2.removeEventListener("mouseenter", setColorFunction);
      el2.removeEventListener("mouseleave", setBgFgColorFunction);
    }
    setColor(origColors["background-color"], origColors["color"]);
  };
}
function useColorizeElement(elementAccessor, bgColor, fgColor, highlightOnOver = false) {
  let dispose2;
  createEffect(() => {
    const ref = elementAccessor();
    dispose2 = colorizeElement(ref, bgColor(), fgColor(), highlightOnOver);
  });
  onCleanup(() => dispose2 && dispose2());
}
function useReadableTextColor(elementAccessor, bgColor = null) {
  let origColor;
  createEffect(() => {
    const ref = elementAccessor();
    if (origColor === void 0) {
      origColor = ref.style.color;
    }
    const _bgColor = (bgColor ? bgColor() : ref.style.backgroundColor) || "#FFFFFF";
    ref.style.color = import_tinycolor23.default.mostReadable(_bgColor, ["#FFFFFF", "#000000"]);
    onCleanup(() => {
      ref.style.color = origColor;
    });
  });
}
function ColorizeElement(props2) {
  const resolved = children(() => props2.children);
  useColorizeElement(resolved, () => props2.bgColor, () => props2.fgColor, props2.highlightOnOver);
  return resolved();
}
function ReadableTextColor(props2) {
  const resolved = children(() => props2.children);
  useReadableTextColor(resolved, () => props2.bgColor);
  return resolved();
}

// public/app/ui/utils/avatars.ts
var AVATAR_COLORS = ["#0E7C7B", "#17BEBB", "#D4F4DD", "#D62246", "#4B1D3F", "#C0DA74", "#BEEDAA", "#B2DDF7", "#FFFF82", "#13315C", "#6761A8", "#407887", "#0CCE6B", "#F1AB86", "#EAD94C", "#23B5D3", "#324376"];
function avatarUrl(src, name2 = null) {
  if (!src) {
    return "data:image/svg+xml," + encodeURIComponent(createLetterAvatarSVG(name2 || "?"));
  }
  return src;
}
function userAvatarUrl(user) {
  let url2;
  if (user?.avatar && !user.avatar.includes("/avatar/")) {
    url2 = prependBaseUrl(user.avatar);
  }
  return avatarUrl(url2, user?.display_name || user?.username || "?");
}
function createLetterAvatarSVG(name2) {
  const text3 = name2[0].toLowerCase();
  const bgColor = AVATAR_COLORS[[...name2].map((c3) => c3.charCodeAt(0)).reduce((p4, c3) => p4 + c3, 0) % AVATAR_COLORS.length];
  const fgColor = textColor(bgColor);
  return `
  <svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" viewBox="0 0 100 100" width="80" height="80" style="background-color: ${bgColor};">
    <text text-anchor="middle" y="50%" x="50%" dy="20%"
      pointer-events="auto" fill="${fgColor}" font-family="Helvetica Neue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif"
      style="font-weight: 400; font-size: 70px">
        ${text3}
    </text>
  </svg>`;
}

// public/app/ui/base/avatar.tsx
var _tmpl$22 = /* @__PURE__ */ template(`<span class="user-online-dot"><span></span></span>`, 4);
var _tmpl$3 = /* @__PURE__ */ template(`<div class="user-avatar"></div>`, 2);
var _tmpl$4 = /* @__PURE__ */ template(`<span class="mb-1 rounded-circle" style="background-size: cover; width: 100px; height: 100px"></span>`, 2);
function UserAvatar(props2) {
  return (() => {
    const _el$2 = _tmpl$3.cloneNode(true);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props2.showPresence && props2.connected;
      },
      get children() {
        return _tmpl$22.cloneNode(true);
      }
    }));
    createRenderEffect(() => _el$2.style.setProperty("background-image", `url(${userAvatarUrl(props2.user)})`));
    return _el$2;
  })();
}
function ProfileAvatar(props2) {
  let imageContainer;
  const image2 = new Image();
  image2.src = props2.src;
  const retryInterval = 1e3;
  const retryDecay = 1.5;
  let retryAttempts = -1;
  const maxAttempts = 5;
  const load2 = () => {
    if (++retryAttempts >= maxAttempts) {
      imageContainer.innerText = _4("Error while loading");
      return;
    }
    image2.src = props2.src + "?" + retryAttempts;
  };
  image2.onload = function() {
    imageContainer.innerHTML = "";
    imageContainer.style.backgroundImage = `url(${image2.src})`;
  };
  image2.onerror = function() {
    setTimeout(load2, retryInterval * Math.pow(retryDecay, retryAttempts));
  };
  return (() => {
    const _el$4 = _tmpl$4.cloneNode(true);
    const _ref$ = imageContainer;
    typeof _ref$ === "function" ? use(_ref$, _el$4) : imageContainer = _el$4;
    insert(_el$4, createComponent(LoadingIndicator, {}));
    return _el$4;
  })();
}

// node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs
function t(t3) {
  return t3.split("-")[1];
}
function e2(t3) {
  return "y" === t3 ? "height" : "width";
}
function n2(t3) {
  return t3.split("-")[0];
}
function o(t3) {
  return ["top", "bottom"].includes(n2(t3)) ? "x" : "y";
}
function i(i3, r3, a3) {
  let { reference: l3, floating: s3 } = i3;
  const c3 = l3.x + l3.width / 2 - s3.width / 2, f3 = l3.y + l3.height / 2 - s3.height / 2, u3 = o(r3), m3 = e2(u3), g3 = l3[m3] / 2 - s3[m3] / 2, d3 = "x" === u3;
  let p4;
  switch (n2(r3)) {
    case "top":
      p4 = { x: c3, y: l3.y - s3.height };
      break;
    case "bottom":
      p4 = { x: c3, y: l3.y + l3.height };
      break;
    case "right":
      p4 = { x: l3.x + l3.width, y: f3 };
      break;
    case "left":
      p4 = { x: l3.x - s3.width, y: f3 };
      break;
    default:
      p4 = { x: l3.x, y: l3.y };
  }
  switch (t(r3)) {
    case "start":
      p4[u3] -= g3 * (a3 && d3 ? -1 : 1);
      break;
    case "end":
      p4[u3] += g3 * (a3 && d3 ? -1 : 1);
  }
  return p4;
}
var r = async (t3, e3, n4) => {
  const { placement: o3 = "bottom", strategy: r3 = "absolute", middleware: a3 = [], platform: l3 } = n4, s3 = a3.filter(Boolean), c3 = await (null == l3.isRTL ? void 0 : l3.isRTL(e3));
  let f3 = await l3.getElementRects({ reference: t3, floating: e3, strategy: r3 }), { x: u3, y: m3 } = i(f3, o3, c3), g3 = o3, d3 = {}, p4 = 0;
  for (let n5 = 0; n5 < s3.length; n5++) {
    const { name: a4, fn: h3 } = s3[n5], { x: y3, y: x3, data: w3, reset: v3 } = await h3({ x: u3, y: m3, initialPlacement: o3, placement: g3, strategy: r3, middlewareData: d3, rects: f3, platform: l3, elements: { reference: t3, floating: e3 } });
    u3 = null != y3 ? y3 : u3, m3 = null != x3 ? x3 : m3, d3 = { ...d3, [a4]: { ...d3[a4], ...w3 } }, v3 && p4 <= 50 && (p4++, "object" == typeof v3 && (v3.placement && (g3 = v3.placement), v3.rects && (f3 = true === v3.rects ? await l3.getElementRects({ reference: t3, floating: e3, strategy: r3 }) : v3.rects), { x: u3, y: m3 } = i(f3, g3, c3)), n5 = -1);
  }
  return { x: u3, y: m3, placement: g3, strategy: r3, middlewareData: d3 };
};
function a(t3) {
  return "number" != typeof t3 ? function(t4) {
    return { top: 0, right: 0, bottom: 0, left: 0, ...t4 };
  }(t3) : { top: t3, right: t3, bottom: t3, left: t3 };
}
function l(t3) {
  return { ...t3, top: t3.y, left: t3.x, right: t3.x + t3.width, bottom: t3.y + t3.height };
}
async function s(t3, e3) {
  var n4;
  void 0 === e3 && (e3 = {});
  const { x: o3, y: i3, platform: r3, rects: s3, elements: c3, strategy: f3 } = t3, { boundary: u3 = "clippingAncestors", rootBoundary: m3 = "viewport", elementContext: g3 = "floating", altBoundary: d3 = false, padding: p4 = 0 } = e3, h3 = a(p4), y3 = c3[d3 ? "floating" === g3 ? "reference" : "floating" : g3], x3 = l(await r3.getClippingRect({ element: null == (n4 = await (null == r3.isElement ? void 0 : r3.isElement(y3))) || n4 ? y3 : y3.contextElement || await (null == r3.getDocumentElement ? void 0 : r3.getDocumentElement(c3.floating)), boundary: u3, rootBoundary: m3, strategy: f3 })), w3 = "floating" === g3 ? { ...s3.floating, x: o3, y: i3 } : s3.reference, v3 = await (null == r3.getOffsetParent ? void 0 : r3.getOffsetParent(c3.floating)), b3 = await (null == r3.isElement ? void 0 : r3.isElement(v3)) && await (null == r3.getScale ? void 0 : r3.getScale(v3)) || { x: 1, y: 1 }, R2 = l(r3.convertOffsetParentRelativeRectToViewportRelativeRect ? await r3.convertOffsetParentRelativeRectToViewportRelativeRect({ rect: w3, offsetParent: v3, strategy: f3 }) : w3);
  return { top: (x3.top - R2.top + h3.top) / b3.y, bottom: (R2.bottom - x3.bottom + h3.bottom) / b3.y, left: (x3.left - R2.left + h3.left) / b3.x, right: (R2.right - x3.right + h3.right) / b3.x };
}
var c = Math.min;
var f = Math.max;
function u(t3, e3, n4) {
  return f(t3, c(e3, n4));
}
var m = (n4) => ({ name: "arrow", options: n4, async fn(i3) {
  const { element: r3, padding: l3 = 0 } = n4 || {}, { x: s3, y: c3, placement: f3, rects: m3, platform: g3 } = i3;
  if (null == r3) return {};
  const d3 = a(l3), p4 = { x: s3, y: c3 }, h3 = o(f3), y3 = e2(h3), x3 = await g3.getDimensions(r3), w3 = "y" === h3 ? "top" : "left", v3 = "y" === h3 ? "bottom" : "right", b3 = m3.reference[y3] + m3.reference[h3] - p4[h3] - m3.floating[y3], R2 = p4[h3] - m3.reference[h3], A4 = await (null == g3.getOffsetParent ? void 0 : g3.getOffsetParent(r3));
  let P3 = A4 ? "y" === h3 ? A4.clientHeight || 0 : A4.clientWidth || 0 : 0;
  0 === P3 && (P3 = m3.floating[y3]);
  const T3 = b3 / 2 - R2 / 2, O4 = d3[w3], D3 = P3 - x3[y3] - d3[v3], E3 = P3 / 2 - x3[y3] / 2 + T3, L5 = u(O4, E3, D3), k2 = null != t(f3) && E3 != L5 && m3.reference[y3] / 2 - (E3 < O4 ? d3[w3] : d3[v3]) - x3[y3] / 2 < 0;
  return { [h3]: p4[h3] - (k2 ? E3 < O4 ? O4 - E3 : D3 - E3 : 0), data: { [h3]: L5, centerOffset: E3 - L5 } };
} });
var g = ["top", "right", "bottom", "left"];
var d = g.reduce((t3, e3) => t3.concat(e3, e3 + "-start", e3 + "-end"), []);
var p = { left: "right", right: "left", bottom: "top", top: "bottom" };
function h(t3) {
  return t3.replace(/left|right|bottom|top/g, (t4) => p[t4]);
}
function y(n4, i3, r3) {
  void 0 === r3 && (r3 = false);
  const a3 = t(n4), l3 = o(n4), s3 = e2(l3);
  let c3 = "x" === l3 ? a3 === (r3 ? "end" : "start") ? "right" : "left" : "start" === a3 ? "bottom" : "top";
  return i3.reference[s3] > i3.floating[s3] && (c3 = h(c3)), { main: c3, cross: h(c3) };
}
var x = { start: "end", end: "start" };
function w(t3) {
  return t3.replace(/start|end/g, (t4) => x[t4]);
}
var b = function(e3) {
  return void 0 === e3 && (e3 = {}), { name: "flip", options: e3, async fn(o3) {
    var i3;
    const { placement: r3, middlewareData: a3, rects: l3, initialPlacement: c3, platform: f3, elements: u3 } = o3, { mainAxis: m3 = true, crossAxis: g3 = true, fallbackPlacements: d3, fallbackStrategy: p4 = "bestFit", fallbackAxisSideDirection: x3 = "none", flipAlignment: v3 = true, ...b3 } = e3, R2 = n2(r3), A4 = n2(c3) === c3, P3 = await (null == f3.isRTL ? void 0 : f3.isRTL(u3.floating)), T3 = d3 || (A4 || !v3 ? [h(c3)] : function(t3) {
      const e4 = h(t3);
      return [w(t3), e4, w(e4)];
    }(c3));
    d3 || "none" === x3 || T3.push(...function(e4, o4, i4, r4) {
      const a4 = t(e4);
      let l4 = function(t3, e5, n4) {
        const o5 = ["left", "right"], i5 = ["right", "left"], r5 = ["top", "bottom"], a5 = ["bottom", "top"];
        switch (t3) {
          case "top":
          case "bottom":
            return n4 ? e5 ? i5 : o5 : e5 ? o5 : i5;
          case "left":
          case "right":
            return e5 ? r5 : a5;
          default:
            return [];
        }
      }(n2(e4), "start" === i4, r4);
      return a4 && (l4 = l4.map((t3) => t3 + "-" + a4), o4 && (l4 = l4.concat(l4.map(w)))), l4;
    }(c3, v3, x3, P3));
    const O4 = [c3, ...T3], D3 = await s(o3, b3), E3 = [];
    let L5 = (null == (i3 = a3.flip) ? void 0 : i3.overflows) || [];
    if (m3 && E3.push(D3[R2]), g3) {
      const { main: t3, cross: e4 } = y(r3, l3, P3);
      E3.push(D3[t3], D3[e4]);
    }
    if (L5 = [...L5, { placement: r3, overflows: E3 }], !E3.every((t3) => t3 <= 0)) {
      var k2;
      const t3 = ((null == (k2 = a3.flip) ? void 0 : k2.index) || 0) + 1, e4 = O4[t3];
      if (e4) return { data: { index: t3, overflows: L5 }, reset: { placement: e4 } };
      let n4 = "bottom";
      switch (p4) {
        case "bestFit": {
          var B;
          const t4 = null == (B = L5.map((t5) => [t5, t5.overflows.filter((t6) => t6 > 0).reduce((t6, e5) => t6 + e5, 0)]).sort((t5, e5) => t5[1] - e5[1])[0]) ? void 0 : B[0].placement;
          t4 && (n4 = t4);
          break;
        }
        case "initialPlacement":
          n4 = c3;
      }
      if (r3 !== n4) return { reset: { placement: n4 } };
    }
    return {};
  } };
};
var O2 = function(e3) {
  return void 0 === e3 && (e3 = 0), { name: "offset", options: e3, async fn(i3) {
    const { x: r3, y: a3 } = i3, l3 = await async function(e4, i4) {
      const { placement: r4, platform: a4, elements: l4 } = e4, s3 = await (null == a4.isRTL ? void 0 : a4.isRTL(l4.floating)), c3 = n2(r4), f3 = t(r4), u3 = "x" === o(r4), m3 = ["left", "top"].includes(c3) ? -1 : 1, g3 = s3 && u3 ? -1 : 1, d3 = "function" == typeof i4 ? i4(e4) : i4;
      let { mainAxis: p4, crossAxis: h3, alignmentAxis: y3 } = "number" == typeof d3 ? { mainAxis: d3, crossAxis: 0, alignmentAxis: null } : { mainAxis: 0, crossAxis: 0, alignmentAxis: null, ...d3 };
      return f3 && "number" == typeof y3 && (h3 = "end" === f3 ? -1 * y3 : y3), u3 ? { x: h3 * g3, y: p4 * m3 } : { x: p4 * m3, y: h3 * g3 };
    }(i3, e3);
    return { x: r3 + l3.x, y: a3 + l3.y, data: l3 };
  } };
};
function D(t3) {
  return "x" === t3 ? "y" : "x";
}
var E = function(t3) {
  return void 0 === t3 && (t3 = {}), { name: "shift", options: t3, async fn(e3) {
    const { x: i3, y: r3, placement: a3 } = e3, { mainAxis: l3 = true, crossAxis: c3 = false, limiter: f3 = { fn: (t4) => {
      let { x: e4, y: n4 } = t4;
      return { x: e4, y: n4 };
    } }, ...m3 } = t3, g3 = { x: i3, y: r3 }, d3 = await s(e3, m3), p4 = o(n2(a3)), h3 = D(p4);
    let y3 = g3[p4], x3 = g3[h3];
    if (l3) {
      const t4 = "y" === p4 ? "bottom" : "right";
      y3 = u(y3 + d3["y" === p4 ? "top" : "left"], y3, y3 - d3[t4]);
    }
    if (c3) {
      const t4 = "y" === h3 ? "bottom" : "right";
      x3 = u(x3 + d3["y" === h3 ? "top" : "left"], x3, x3 - d3[t4]);
    }
    const w3 = f3.fn({ ...e3, [p4]: y3, [h3]: x3 });
    return { ...w3, data: { x: w3.x - i3, y: w3.y - r3 } };
  } };
};
var k = function(e3) {
  return void 0 === e3 && (e3 = {}), { name: "size", options: e3, async fn(o3) {
    const { placement: i3, rects: r3, platform: a3, elements: l3 } = o3, { apply: c3 = () => {
    }, ...u3 } = e3, m3 = await s(o3, u3), g3 = n2(i3), d3 = t(i3);
    let p4, h3;
    "top" === g3 || "bottom" === g3 ? (p4 = g3, h3 = d3 === (await (null == a3.isRTL ? void 0 : a3.isRTL(l3.floating)) ? "start" : "end") ? "left" : "right") : (h3 = g3, p4 = "end" === d3 ? "top" : "bottom");
    const y3 = f(m3.left, 0), x3 = f(m3.right, 0), w3 = f(m3.top, 0), v3 = f(m3.bottom, 0), b3 = { availableHeight: r3.floating.height - (["left", "right"].includes(i3) ? 2 * (0 !== w3 || 0 !== v3 ? w3 + v3 : f(m3.top, m3.bottom)) : m3[p4]), availableWidth: r3.floating.width - (["top", "bottom"].includes(i3) ? 2 * (0 !== y3 || 0 !== x3 ? y3 + x3 : f(m3.left, m3.right)) : m3[h3]) };
    await c3({ ...o3, ...b3 });
    const R2 = await a3.getDimensions(l3.floating);
    return r3.floating.width !== R2.width || r3.floating.height !== R2.height ? { reset: { rects: true } } : {};
  } };
};

// node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs
function n3(t3) {
  var e3;
  return (null == (e3 = t3.ownerDocument) ? void 0 : e3.defaultView) || window;
}
function o2(t3) {
  return n3(t3).getComputedStyle(t3);
}
function i2(t3) {
  return f2(t3) ? (t3.nodeName || "").toLowerCase() : "";
}
var r2;
function l2() {
  if (r2) return r2;
  const t3 = navigator.userAgentData;
  return t3 && Array.isArray(t3.brands) ? (r2 = t3.brands.map((t4) => t4.brand + "/" + t4.version).join(" "), r2) : navigator.userAgent;
}
function c2(t3) {
  return t3 instanceof n3(t3).HTMLElement;
}
function s2(t3) {
  return t3 instanceof n3(t3).Element;
}
function f2(t3) {
  return t3 instanceof n3(t3).Node;
}
function u2(t3) {
  if ("undefined" == typeof ShadowRoot) return false;
  return t3 instanceof n3(t3).ShadowRoot || t3 instanceof ShadowRoot;
}
function a2(t3) {
  const { overflow: e3, overflowX: n4, overflowY: i3, display: r3 } = o2(t3);
  return /auto|scroll|overlay|hidden|clip/.test(e3 + i3 + n4) && !["inline", "contents"].includes(r3);
}
function d2(t3) {
  return ["table", "td", "th"].includes(i2(t3));
}
function h2(t3) {
  const e3 = /firefox/i.test(l2()), n4 = o2(t3), i3 = n4.backdropFilter || n4.WebkitBackdropFilter;
  return "none" !== n4.transform || "none" !== n4.perspective || !!i3 && "none" !== i3 || e3 && "filter" === n4.willChange || e3 && !!n4.filter && "none" !== n4.filter || ["transform", "perspective"].some((t4) => n4.willChange.includes(t4)) || ["paint", "layout", "strict", "content"].some((t4) => {
    const e4 = n4.contain;
    return null != e4 && e4.includes(t4);
  });
}
function p2() {
  return !/^((?!chrome|android).)*safari/i.test(l2());
}
function g2(t3) {
  return ["html", "body", "#document"].includes(i2(t3));
}
var m2 = Math.min;
var y2 = Math.max;
var x2 = Math.round;
function w2(t3) {
  const e3 = o2(t3);
  let n4 = parseFloat(e3.width), i3 = parseFloat(e3.height);
  const r3 = t3.offsetWidth, l3 = t3.offsetHeight, c3 = x2(n4) !== r3 || x2(i3) !== l3;
  return c3 && (n4 = r3, i3 = l3), { width: n4, height: i3, fallback: c3 };
}
function v2(t3) {
  return s2(t3) ? t3 : t3.contextElement;
}
var b2 = { x: 1, y: 1 };
function L3(t3) {
  const e3 = v2(t3);
  if (!c2(e3)) return b2;
  const n4 = e3.getBoundingClientRect(), { width: o3, height: i3, fallback: r3 } = w2(e3);
  let l3 = (r3 ? x2(n4.width) : n4.width) / o3, s3 = (r3 ? x2(n4.height) : n4.height) / i3;
  return l3 && Number.isFinite(l3) || (l3 = 1), s3 && Number.isFinite(s3) || (s3 = 1), { x: l3, y: s3 };
}
function E2(t3, e3, o3, i3) {
  var r3, l3;
  void 0 === e3 && (e3 = false), void 0 === o3 && (o3 = false);
  const c3 = t3.getBoundingClientRect(), f3 = v2(t3);
  let u3 = b2;
  e3 && (i3 ? s2(i3) && (u3 = L3(i3)) : u3 = L3(t3));
  const a3 = f3 ? n3(f3) : window, d3 = !p2() && o3;
  let h3 = (c3.left + (d3 && (null == (r3 = a3.visualViewport) ? void 0 : r3.offsetLeft) || 0)) / u3.x, g3 = (c3.top + (d3 && (null == (l3 = a3.visualViewport) ? void 0 : l3.offsetTop) || 0)) / u3.y, m3 = c3.width / u3.x, y3 = c3.height / u3.y;
  if (f3) {
    const t4 = n3(f3), e4 = i3 && s2(i3) ? n3(i3) : i3;
    let o4 = t4.frameElement;
    for (; o4 && i3 && e4 !== t4; ) {
      const t5 = L3(o4), e5 = o4.getBoundingClientRect(), i4 = getComputedStyle(o4);
      e5.x += (o4.clientLeft + parseFloat(i4.paddingLeft)) * t5.x, e5.y += (o4.clientTop + parseFloat(i4.paddingTop)) * t5.y, h3 *= t5.x, g3 *= t5.y, m3 *= t5.x, y3 *= t5.y, h3 += e5.x, g3 += e5.y, o4 = n3(o4).frameElement;
    }
  }
  return { width: m3, height: y3, top: g3, right: h3 + m3, bottom: g3 + y3, left: h3, x: h3, y: g3 };
}
function R(t3) {
  return ((f2(t3) ? t3.ownerDocument : t3.document) || window.document).documentElement;
}
function T2(t3) {
  return s2(t3) ? { scrollLeft: t3.scrollLeft, scrollTop: t3.scrollTop } : { scrollLeft: t3.pageXOffset, scrollTop: t3.pageYOffset };
}
function C(t3) {
  return E2(R(t3)).left + T2(t3).scrollLeft;
}
function F(t3, e3, n4) {
  const o3 = c2(e3), r3 = R(e3), l3 = E2(t3, true, "fixed" === n4, e3);
  let s3 = { scrollLeft: 0, scrollTop: 0 };
  const f3 = { x: 0, y: 0 };
  if (o3 || !o3 && "fixed" !== n4) if (("body" !== i2(e3) || a2(r3)) && (s3 = T2(e3)), c2(e3)) {
    const t4 = E2(e3, true);
    f3.x = t4.x + e3.clientLeft, f3.y = t4.y + e3.clientTop;
  } else r3 && (f3.x = C(r3));
  return { x: l3.left + s3.scrollLeft - f3.x, y: l3.top + s3.scrollTop - f3.y, width: l3.width, height: l3.height };
}
function W(t3) {
  if ("html" === i2(t3)) return t3;
  const e3 = t3.assignedSlot || t3.parentNode || (u2(t3) ? t3.host : null) || R(t3);
  return u2(e3) ? e3.host : e3;
}
function D2(t3) {
  return c2(t3) && "fixed" !== o2(t3).position ? t3.offsetParent : null;
}
function S(t3) {
  const e3 = n3(t3);
  let r3 = D2(t3);
  for (; r3 && d2(r3) && "static" === o2(r3).position; ) r3 = D2(r3);
  return r3 && ("html" === i2(r3) || "body" === i2(r3) && "static" === o2(r3).position && !h2(r3)) ? e3 : r3 || function(t4) {
    let e4 = W(t4);
    for (; c2(e4) && !g2(e4); ) {
      if (h2(e4)) return e4;
      e4 = W(e4);
    }
    return null;
  }(t3) || e3;
}
function A(t3) {
  const e3 = W(t3);
  return g2(e3) ? t3.ownerDocument.body : c2(e3) && a2(e3) ? e3 : A(e3);
}
function H(t3, e3) {
  var o3;
  void 0 === e3 && (e3 = []);
  const i3 = A(t3), r3 = i3 === (null == (o3 = t3.ownerDocument) ? void 0 : o3.body), l3 = n3(i3);
  return r3 ? e3.concat(l3, l3.visualViewport || [], a2(i3) ? i3 : []) : e3.concat(i3, H(i3));
}
function O3(e3, i3, r3) {
  return "viewport" === i3 ? l(function(t3, e4) {
    const o3 = n3(t3), i4 = R(t3), r4 = o3.visualViewport;
    let l3 = i4.clientWidth, c3 = i4.clientHeight, s3 = 0, f3 = 0;
    if (r4) {
      l3 = r4.width, c3 = r4.height;
      const t4 = p2();
      (t4 || !t4 && "fixed" === e4) && (s3 = r4.offsetLeft, f3 = r4.offsetTop);
    }
    return { width: l3, height: c3, x: s3, y: f3 };
  }(e3, r3)) : s2(i3) ? function(t3, e4) {
    const n4 = E2(t3, true, "fixed" === e4), o3 = n4.top + t3.clientTop, i4 = n4.left + t3.clientLeft, r4 = c2(t3) ? L3(t3) : { x: 1, y: 1 }, l3 = t3.clientWidth * r4.x, s3 = t3.clientHeight * r4.y, f3 = i4 * r4.x, u3 = o3 * r4.y;
    return { top: u3, left: f3, right: f3 + l3, bottom: u3 + s3, x: f3, y: u3, width: l3, height: s3 };
  }(i3, r3) : l(function(t3) {
    var e4;
    const n4 = R(t3), i4 = T2(t3), r4 = null == (e4 = t3.ownerDocument) ? void 0 : e4.body, l3 = y2(n4.scrollWidth, n4.clientWidth, r4 ? r4.scrollWidth : 0, r4 ? r4.clientWidth : 0), c3 = y2(n4.scrollHeight, n4.clientHeight, r4 ? r4.scrollHeight : 0, r4 ? r4.clientHeight : 0);
    let s3 = -i4.scrollLeft + C(t3);
    const f3 = -i4.scrollTop;
    return "rtl" === o2(r4 || n4).direction && (s3 += y2(n4.clientWidth, r4 ? r4.clientWidth : 0) - l3), { width: l3, height: c3, x: s3, y: f3 };
  }(R(e3)));
}
var P2 = { getClippingRect: function(t3) {
  let { element: e3, boundary: n4, rootBoundary: r3, strategy: l3 } = t3;
  const c3 = "clippingAncestors" === n4 ? function(t4, e4) {
    const n5 = e4.get(t4);
    if (n5) return n5;
    let r4 = H(t4).filter((t5) => s2(t5) && "body" !== i2(t5)), l4 = null;
    const c4 = "fixed" === o2(t4).position;
    let f4 = c4 ? W(t4) : t4;
    for (; s2(f4) && !g2(f4); ) {
      const t5 = o2(f4), e5 = h2(f4);
      (c4 ? e5 || l4 : e5 || "static" !== t5.position || !l4 || !["absolute", "fixed"].includes(l4.position)) ? l4 = t5 : r4 = r4.filter((t6) => t6 !== f4), f4 = W(f4);
    }
    return e4.set(t4, r4), r4;
  }(e3, this._c) : [].concat(n4), f3 = [...c3, r3], u3 = f3[0], a3 = f3.reduce((t4, n5) => {
    const o3 = O3(e3, n5, l3);
    return t4.top = y2(o3.top, t4.top), t4.right = m2(o3.right, t4.right), t4.bottom = m2(o3.bottom, t4.bottom), t4.left = y2(o3.left, t4.left), t4;
  }, O3(e3, u3, l3));
  return { width: a3.right - a3.left, height: a3.bottom - a3.top, x: a3.left, y: a3.top };
}, convertOffsetParentRelativeRectToViewportRelativeRect: function(t3) {
  let { rect: e3, offsetParent: n4, strategy: o3 } = t3;
  const r3 = c2(n4), l3 = R(n4);
  if (n4 === l3) return e3;
  let s3 = { scrollLeft: 0, scrollTop: 0 }, f3 = { x: 1, y: 1 };
  const u3 = { x: 0, y: 0 };
  if ((r3 || !r3 && "fixed" !== o3) && (("body" !== i2(n4) || a2(l3)) && (s3 = T2(n4)), c2(n4))) {
    const t4 = E2(n4);
    f3 = L3(n4), u3.x = t4.x + n4.clientLeft, u3.y = t4.y + n4.clientTop;
  }
  return { width: e3.width * f3.x, height: e3.height * f3.y, x: e3.x * f3.x - s3.scrollLeft * f3.x + u3.x, y: e3.y * f3.y - s3.scrollTop * f3.y + u3.y };
}, isElement: s2, getDimensions: function(t3) {
  return w2(t3);
}, getOffsetParent: S, getDocumentElement: R, getScale: L3, async getElementRects(t3) {
  let { reference: e3, floating: n4, strategy: o3 } = t3;
  const i3 = this.getOffsetParent || S, r3 = this.getDimensions;
  return { reference: F(e3, await i3(n4), o3), floating: { x: 0, y: 0, ...await r3(n4) } };
}, getClientRects: (t3) => Array.from(t3.getClientRects()), isRTL: (t3) => "rtl" === o2(t3).direction };
function z(t3, e3, n4, o3) {
  void 0 === o3 && (o3 = {});
  const { ancestorScroll: i3 = true, ancestorResize: r3 = true, elementResize: l3 = true, animationFrame: c3 = false } = o3, f3 = i3 && !c3, u3 = f3 || r3 ? [...s2(t3) ? H(t3) : t3.contextElement ? H(t3.contextElement) : [], ...H(e3)] : [];
  u3.forEach((t4) => {
    f3 && t4.addEventListener("scroll", n4, { passive: true }), r3 && t4.addEventListener("resize", n4);
  });
  let a3, d3 = null;
  if (l3) {
    let o4 = true;
    d3 = new ResizeObserver(() => {
      o4 || n4(), o4 = false;
    }), s2(t3) && !c3 && d3.observe(t3), s2(t3) || !t3.contextElement || c3 || d3.observe(t3.contextElement), d3.observe(e3);
  }
  let h3 = c3 ? E2(t3) : null;
  return c3 && function e4() {
    const o4 = E2(t3);
    !h3 || o4.x === h3.x && o4.y === h3.y && o4.width === h3.width && o4.height === h3.height || n4();
    h3 = o4, a3 = requestAnimationFrame(e4);
  }(), n4(), () => {
    var t4;
    u3.forEach((t5) => {
      f3 && t5.removeEventListener("scroll", n4), r3 && t5.removeEventListener("resize", n4);
    }), null == (t4 = d3) || t4.disconnect(), d3 = null, c3 && cancelAnimationFrame(a3);
  };
}
var V = (t3, n4, o3) => {
  const i3 = /* @__PURE__ */ new Map(), r3 = { platform: P2, ...o3 }, l3 = { ...r3.platform, _c: i3 };
  return r(t3, n4, { ...r3, platform: l3 });
};

// public/app/ui/utils/click-outside.tsx
function useClickOutside(props2) {
  const [state, setState] = createStore({
    isPointerDown: false,
    ignoreEmulatedMouseEvents: false
  });
  const onPointerDown = (e3) => {
    if (isValidEvent(e3, props2.element())) {
      setState("isPointerDown", true);
    }
  };
  const onMouseUp = (event2) => {
    if (state.ignoreEmulatedMouseEvents) {
      setState("ignoreEmulatedMouseEvents", false);
      return;
    }
    if (state.isPointerDown && props2.handler && isValidEvent(event2, props2.element())) {
      setState("isPointerDown", false);
      props2.handler(event2);
    }
  };
  const onTouchEnd = (event2) => {
    setState("ignoreEmulatedMouseEvents", true);
    if (props2.handler && state.isPointerDown && isValidEvent(event2, props2.element())) {
      setState("isPointerDown", false);
      props2.handler(event2);
    }
  };
  onMount(() => {
    const doc4 = getOwnerDocument(props2.element());
    doc4.addEventListener("mousedown", onPointerDown, true);
    doc4.addEventListener("mouseup", onMouseUp, true);
    doc4.addEventListener("touchstart", onPointerDown, true);
    doc4.addEventListener("touchend", onTouchEnd, true);
  });
  onCleanup(() => {
    const doc4 = getOwnerDocument(props2.element());
    doc4.removeEventListener("mousedown", onPointerDown, true);
    doc4.removeEventListener("mouseup", onMouseUp, true);
    doc4.removeEventListener("touchstart", onPointerDown, true);
    doc4.removeEventListener("touchend", onTouchEnd, true);
  });
}
function isValidEvent(event2, element2) {
  const target = event2.target;
  if (event2.button > 0) {
    return false;
  }
  if (target) {
    const doc4 = getOwnerDocument(target);
    if (!doc4.body.contains(target)) return false;
  }
  return !element2?.contains(target);
}
function getOwnerDocument(node) {
  return node.ownerDocument ?? document;
}
function ClickOutside(props2) {
  const resolvedChildren = children(() => props2.children);
  useClickOutside({
    element: () => resolvedChildren(),
    handler: (event2) => props2.onClickOutside(event2)
  });
  return resolvedChildren;
}

// public/app/ui/utils/styles.js
function classNames(...classes) {
  return classes.flat().filter(Boolean).join(" ");
}

// public/app/utils/uuid.js
function uuid4() {
  function s4() {
    return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1);
  }
  return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
}

// node_modules/@solid-primitives/props/dist/index.js
var extractCSSregex = /((?:--)?(?:\w+-?)+)\s*:\s*([^;]*)/g;
function stringStyleToObject(style3) {
  const object2 = {};
  let match2;
  while (match2 = extractCSSregex.exec(style3)) {
    object2[match2[1]] = match2[2];
  }
  return object2;
}
function combineStyle(a3, b3) {
  if (typeof a3 === "string") {
    if (typeof b3 === "string")
      return `${a3};${b3}`;
    a3 = stringStyleToObject(a3);
  } else if (typeof b3 === "string") {
    b3 = stringStyleToObject(b3);
  }
  return { ...a3, ...b3 };
}

// node_modules/@motionone/utils/dist/array.es.js
function addUniqueItem(array, item) {
  array.indexOf(item) === -1 && array.push(item);
}
function removeItem(arr, item) {
  const index2 = arr.indexOf(item);
  index2 > -1 && arr.splice(index2, 1);
}

// node_modules/@motionone/utils/dist/clamp.es.js
var clamp2 = (min3, max3, v3) => Math.min(Math.max(v3, min3), max3);

// node_modules/@motionone/utils/dist/defaults.es.js
var defaults = {
  duration: 0.3,
  delay: 0,
  endDelay: 0,
  repeat: 0,
  easing: "ease"
};

// node_modules/@motionone/utils/dist/is-number.es.js
var isNumber2 = (value2) => typeof value2 === "number";

// node_modules/@motionone/utils/dist/is-easing-list.es.js
var isEasingList = (easing) => Array.isArray(easing) && !isNumber2(easing[0]);

// node_modules/@motionone/utils/dist/wrap.es.js
var wrap2 = (min3, max3, v3) => {
  const rangeSize = max3 - min3;
  return ((v3 - min3) % rangeSize + rangeSize) % rangeSize + min3;
};

// node_modules/@motionone/utils/dist/easing.es.js
function getEasingForSegment(easing, i3) {
  return isEasingList(easing) ? easing[wrap2(0, easing.length, i3)] : easing;
}

// node_modules/@motionone/utils/dist/mix.es.js
var mix = (min3, max3, progress2) => -progress2 * min3 + progress2 * max3 + min3;

// node_modules/@motionone/utils/dist/noop.es.js
var noop3 = () => {
};
var noopReturn = (v3) => v3;

// node_modules/@motionone/utils/dist/progress.es.js
var progress = (min3, max3, value2) => max3 - min3 === 0 ? 1 : (value2 - min3) / (max3 - min3);

// node_modules/@motionone/utils/dist/offset.es.js
function fillOffset(offset, remaining) {
  const min3 = offset[offset.length - 1];
  for (let i3 = 1; i3 <= remaining; i3++) {
    const offsetProgress = progress(0, remaining, i3);
    offset.push(mix(min3, 1, offsetProgress));
  }
}
function defaultOffset(length) {
  const offset = [0];
  fillOffset(offset, length - 1);
  return offset;
}

// node_modules/@motionone/utils/dist/interpolate.es.js
function interpolate(output, input = defaultOffset(output.length), easing = noopReturn) {
  const length = output.length;
  const remainder = length - input.length;
  remainder > 0 && fillOffset(input, remainder);
  return (t3) => {
    let i3 = 0;
    for (; i3 < length - 2; i3++) {
      if (t3 < input[i3 + 1])
        break;
    }
    let progressInRange = clamp2(0, 1, progress(input[i3], input[i3 + 1], t3));
    const segmentEasing = getEasingForSegment(easing, i3);
    progressInRange = segmentEasing(progressInRange);
    return mix(output[i3], output[i3 + 1], progressInRange);
  };
}

// node_modules/@motionone/utils/dist/is-cubic-bezier.es.js
var isCubicBezier = (easing) => Array.isArray(easing) && isNumber2(easing[0]);

// node_modules/@motionone/utils/dist/is-easing-generator.es.js
var isEasingGenerator = (easing) => typeof easing === "object" && Boolean(easing.createAnimation);

// node_modules/@motionone/utils/dist/is-function.es.js
var isFunction2 = (value2) => typeof value2 === "function";

// node_modules/@motionone/utils/dist/is-string.es.js
var isString2 = (value2) => typeof value2 === "string";

// node_modules/@motionone/utils/dist/time.es.js
var time = {
  ms: (seconds) => seconds * 1e3,
  s: (milliseconds) => milliseconds / 1e3
};

// node_modules/@motionone/easing/dist/cubic-bezier.es.js
var calcBezier = (t3, a1, a22) => (((1 - 3 * a22 + 3 * a1) * t3 + (3 * a22 - 6 * a1)) * t3 + 3 * a1) * t3;
var subdivisionPrecision = 1e-7;
var subdivisionMaxIterations = 12;
function binarySubdivide(x3, lowerBound, upperBound, mX1, mX2) {
  let currentX;
  let currentT;
  let i3 = 0;
  do {
    currentT = lowerBound + (upperBound - lowerBound) / 2;
    currentX = calcBezier(currentT, mX1, mX2) - x3;
    if (currentX > 0) {
      upperBound = currentT;
    } else {
      lowerBound = currentT;
    }
  } while (Math.abs(currentX) > subdivisionPrecision && ++i3 < subdivisionMaxIterations);
  return currentT;
}
function cubicBezier(mX1, mY1, mX2, mY2) {
  if (mX1 === mY1 && mX2 === mY2)
    return noopReturn;
  const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
  return (t3) => t3 === 0 || t3 === 1 ? t3 : calcBezier(getTForX(t3), mY1, mY2);
}

// node_modules/@motionone/easing/dist/steps.es.js
var steps = (steps2, direction = "end") => (progress2) => {
  progress2 = direction === "end" ? Math.min(progress2, 0.999) : Math.max(progress2, 1e-3);
  const expanded = progress2 * steps2;
  const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
  return clamp2(0, 1, rounded / steps2);
};

// node_modules/@motionone/animation/dist/utils/easing.es.js
var namedEasings = {
  ease: cubicBezier(0.25, 0.1, 0.25, 1),
  "ease-in": cubicBezier(0.42, 0, 1, 1),
  "ease-in-out": cubicBezier(0.42, 0, 0.58, 1),
  "ease-out": cubicBezier(0, 0, 0.58, 1)
};
var functionArgsRegex = /\((.*?)\)/;
function getEasingFunction(definition) {
  if (isFunction2(definition))
    return definition;
  if (isCubicBezier(definition))
    return cubicBezier(...definition);
  if (namedEasings[definition])
    return namedEasings[definition];
  if (definition.startsWith("steps")) {
    const args = functionArgsRegex.exec(definition);
    if (args) {
      const argsArray = args[1].split(",");
      return steps(parseFloat(argsArray[0]), argsArray[1].trim());
    }
  }
  return noopReturn;
}

// node_modules/@motionone/animation/dist/Animation.es.js
var Animation = class {
  constructor(output, keyframes = [0, 1], { easing, duration: initialDuration = defaults.duration, delay = defaults.delay, endDelay = defaults.endDelay, repeat = defaults.repeat, offset, direction = "normal", autoplay = true } = {}) {
    this.startTime = null;
    this.rate = 1;
    this.t = 0;
    this.cancelTimestamp = null;
    this.easing = noopReturn;
    this.duration = 0;
    this.totalDuration = 0;
    this.repeat = 0;
    this.playState = "idle";
    this.finished = new Promise((resolve2, reject2) => {
      this.resolve = resolve2;
      this.reject = reject2;
    });
    easing = easing || defaults.easing;
    if (isEasingGenerator(easing)) {
      const custom = easing.createAnimation(keyframes);
      easing = custom.easing;
      keyframes = custom.keyframes || keyframes;
      initialDuration = custom.duration || initialDuration;
    }
    this.repeat = repeat;
    this.easing = isEasingList(easing) ? noopReturn : getEasingFunction(easing);
    this.updateDuration(initialDuration);
    const interpolate$1 = interpolate(keyframes, offset, isEasingList(easing) ? easing.map(getEasingFunction) : noopReturn);
    this.tick = (timestamp2) => {
      var _a4;
      delay = delay;
      let t3 = 0;
      if (this.pauseTime !== void 0) {
        t3 = this.pauseTime;
      } else {
        t3 = (timestamp2 - this.startTime) * this.rate;
      }
      this.t = t3;
      t3 /= 1e3;
      t3 = Math.max(t3 - delay, 0);
      if (this.playState === "finished" && this.pauseTime === void 0) {
        t3 = this.totalDuration;
      }
      const progress2 = t3 / this.duration;
      let currentIteration = Math.floor(progress2);
      let iterationProgress = progress2 % 1;
      if (!iterationProgress && progress2 >= 1) {
        iterationProgress = 1;
      }
      iterationProgress === 1 && currentIteration--;
      const iterationIsOdd = currentIteration % 2;
      if (direction === "reverse" || direction === "alternate" && iterationIsOdd || direction === "alternate-reverse" && !iterationIsOdd) {
        iterationProgress = 1 - iterationProgress;
      }
      const p4 = t3 >= this.totalDuration ? 1 : Math.min(iterationProgress, 1);
      const latest = interpolate$1(this.easing(p4));
      output(latest);
      const isAnimationFinished = this.pauseTime === void 0 && (this.playState === "finished" || t3 >= this.totalDuration + endDelay);
      if (isAnimationFinished) {
        this.playState = "finished";
        (_a4 = this.resolve) === null || _a4 === void 0 ? void 0 : _a4.call(this, latest);
      } else if (this.playState !== "idle") {
        this.frameRequestId = requestAnimationFrame(this.tick);
      }
    };
    if (autoplay)
      this.play();
  }
  play() {
    const now = performance.now();
    this.playState = "running";
    if (this.pauseTime !== void 0) {
      this.startTime = now - this.pauseTime;
    } else if (!this.startTime) {
      this.startTime = now;
    }
    this.cancelTimestamp = this.startTime;
    this.pauseTime = void 0;
    this.frameRequestId = requestAnimationFrame(this.tick);
  }
  pause() {
    this.playState = "paused";
    this.pauseTime = this.t;
  }
  finish() {
    this.playState = "finished";
    this.tick(0);
  }
  stop() {
    var _a4;
    this.playState = "idle";
    if (this.frameRequestId !== void 0) {
      cancelAnimationFrame(this.frameRequestId);
    }
    (_a4 = this.reject) === null || _a4 === void 0 ? void 0 : _a4.call(this, false);
  }
  cancel() {
    this.stop();
    this.tick(this.cancelTimestamp);
  }
  reverse() {
    this.rate *= -1;
  }
  commitStyles() {
  }
  updateDuration(duration) {
    this.duration = duration;
    this.totalDuration = duration * (this.repeat + 1);
  }
  get currentTime() {
    return this.t;
  }
  set currentTime(t3) {
    if (this.pauseTime !== void 0 || this.rate === 0) {
      this.pauseTime = t3;
    } else {
      this.startTime = performance.now() - t3 / this.rate;
    }
  }
  get playbackRate() {
    return this.rate;
  }
  set playbackRate(rate) {
    this.rate = rate;
  }
};

// node_modules/hey-listen/dist/hey-listen.es.js
var warning = function() {
};
var invariant = function() {
};
if (true) {
  warning = function(check, message) {
    if (!check && typeof console !== "undefined") {
      console.warn(message);
    }
  };
  invariant = function(check, message) {
    if (!check) {
      throw new Error(message);
    }
  };
}

// node_modules/@motionone/types/dist/MotionValue.es.js
var MotionValue = class {
  setAnimation(animation) {
    this.animation = animation;
    animation === null || animation === void 0 ? void 0 : animation.finished.then(() => this.clearAnimation()).catch(() => {
    });
  }
  clearAnimation() {
    this.animation = this.generator = void 0;
  }
};

// node_modules/@motionone/dom/dist/animate/data.es.js
var data = /* @__PURE__ */ new WeakMap();
function getAnimationData(element2) {
  if (!data.has(element2)) {
    data.set(element2, {
      transforms: [],
      values: /* @__PURE__ */ new Map()
    });
  }
  return data.get(element2);
}
function getMotionValue(motionValues, name2) {
  if (!motionValues.has(name2)) {
    motionValues.set(name2, new MotionValue());
  }
  return motionValues.get(name2);
}

// node_modules/@motionone/dom/dist/animate/utils/transforms.es.js
var axes = ["", "X", "Y", "Z"];
var order = ["translate", "scale", "rotate", "skew"];
var transformAlias = {
  x: "translateX",
  y: "translateY",
  z: "translateZ"
};
var rotation = {
  syntax: "<angle>",
  initialValue: "0deg",
  toDefaultUnit: (v3) => v3 + "deg"
};
var baseTransformProperties = {
  translate: {
    syntax: "<length-percentage>",
    initialValue: "0px",
    toDefaultUnit: (v3) => v3 + "px"
  },
  rotate: rotation,
  scale: {
    syntax: "<number>",
    initialValue: 1,
    toDefaultUnit: noopReturn
  },
  skew: rotation
};
var transformDefinitions = /* @__PURE__ */ new Map();
var asTransformCssVar = (name2) => `--motion-${name2}`;
var transforms = ["x", "y", "z"];
order.forEach((name2) => {
  axes.forEach((axis) => {
    transforms.push(name2 + axis);
    transformDefinitions.set(asTransformCssVar(name2 + axis), baseTransformProperties[name2]);
  });
});
var compareTransformOrder = (a3, b3) => transforms.indexOf(a3) - transforms.indexOf(b3);
var transformLookup = new Set(transforms);
var isTransform = (name2) => transformLookup.has(name2);
var addTransformToElement = (element2, name2) => {
  if (transformAlias[name2])
    name2 = transformAlias[name2];
  const { transforms: transforms2 } = getAnimationData(element2);
  addUniqueItem(transforms2, name2);
  element2.style.transform = buildTransformTemplate(transforms2);
};
var buildTransformTemplate = (transforms2) => transforms2.sort(compareTransformOrder).reduce(transformListToString, "").trim();
var transformListToString = (template3, name2) => `${template3} ${name2}(var(${asTransformCssVar(name2)}))`;

// node_modules/@motionone/dom/dist/animate/utils/css-var.es.js
var isCssVar = (name2) => name2.startsWith("--");
var registeredProperties = /* @__PURE__ */ new Set();
function registerCssVariable(name2) {
  if (registeredProperties.has(name2))
    return;
  registeredProperties.add(name2);
  try {
    const { syntax, initialValue } = transformDefinitions.has(name2) ? transformDefinitions.get(name2) : {};
    CSS.registerProperty({
      name: name2,
      inherits: false,
      syntax,
      initialValue
    });
  } catch (e3) {
  }
}

// node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js
var testAnimation = (keyframes, options2) => document.createElement("div").animate(keyframes, options2);
var featureTests = {
  cssRegisterProperty: () => typeof CSS !== "undefined" && Object.hasOwnProperty.call(CSS, "registerProperty"),
  waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"),
  partialKeyframes: () => {
    try {
      testAnimation({ opacity: [1] });
    } catch (e3) {
      return false;
    }
    return true;
  },
  finished: () => Boolean(testAnimation({ opacity: [0, 1] }, { duration: 1e-3 }).finished),
  linearEasing: () => {
    try {
      testAnimation({ opacity: 0 }, { easing: "linear(0, 1)" });
    } catch (e3) {
      return false;
    }
    return true;
  }
};
var results = {};
var supports = {};
for (const key2 in featureTests) {
  supports[key2] = () => {
    if (results[key2] === void 0)
      results[key2] = featureTests[key2]();
    return results[key2];
  };
}

// node_modules/@motionone/dom/dist/animate/utils/easing.es.js
var resolution = 0.015;
var generateLinearEasingPoints = (easing, duration) => {
  let points = "";
  const numPoints = Math.round(duration / resolution);
  for (let i3 = 0; i3 < numPoints; i3++) {
    points += easing(progress(0, numPoints - 1, i3)) + ", ";
  }
  return points.substring(0, points.length - 2);
};
var convertEasing = (easing, duration) => {
  if (isFunction2(easing)) {
    return supports.linearEasing() ? `linear(${generateLinearEasingPoints(easing, duration)})` : defaults.easing;
  } else {
    return isCubicBezier(easing) ? cubicBezierAsString(easing) : easing;
  }
};
var cubicBezierAsString = ([a3, b3, c3, d3]) => `cubic-bezier(${a3}, ${b3}, ${c3}, ${d3})`;

// node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js
function hydrateKeyframes(keyframes, readInitialValue) {
  for (let i3 = 0; i3 < keyframes.length; i3++) {
    if (keyframes[i3] === null) {
      keyframes[i3] = i3 ? keyframes[i3 - 1] : readInitialValue();
    }
  }
  return keyframes;
}
var keyframesList = (keyframes) => Array.isArray(keyframes) ? keyframes : [keyframes];

// node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js
function getStyleName(key2) {
  if (transformAlias[key2])
    key2 = transformAlias[key2];
  return isTransform(key2) ? asTransformCssVar(key2) : key2;
}

// node_modules/@motionone/dom/dist/animate/style.es.js
var style2 = {
  get: (element2, name2) => {
    name2 = getStyleName(name2);
    let value2 = isCssVar(name2) ? element2.style.getPropertyValue(name2) : getComputedStyle(element2)[name2];
    if (!value2 && value2 !== 0) {
      const definition = transformDefinitions.get(name2);
      if (definition)
        value2 = definition.initialValue;
    }
    return value2;
  },
  set: (element2, name2, value2) => {
    name2 = getStyleName(name2);
    if (isCssVar(name2)) {
      element2.style.setProperty(name2, value2);
    } else {
      element2.style[name2] = value2;
    }
  }
};

// node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js
function stopAnimation(animation, needsCommit = true) {
  if (!animation || animation.playState === "finished")
    return;
  try {
    if (animation.stop) {
      animation.stop();
    } else {
      needsCommit && animation.commitStyles();
      animation.cancel();
    }
  } catch (e3) {
  }
}

// node_modules/@motionone/dom/dist/animate/utils/get-unit.es.js
function getUnitConverter(keyframes, definition) {
  var _a4;
  let toUnit = (definition === null || definition === void 0 ? void 0 : definition.toDefaultUnit) || noopReturn;
  const finalKeyframe = keyframes[keyframes.length - 1];
  if (isString2(finalKeyframe)) {
    const unit = ((_a4 = finalKeyframe.match(/(-?[\d.]+)([a-z%]*)/)) === null || _a4 === void 0 ? void 0 : _a4[2]) || "";
    if (unit)
      toUnit = (value2) => value2 + unit;
  }
  return toUnit;
}

// node_modules/@motionone/dom/dist/animate/animate-style.es.js
function getDevToolsRecord() {
  return window.__MOTION_DEV_TOOLS_RECORD;
}
function animateStyle(element2, key2, keyframesDefinition, options2 = {}, AnimationPolyfill) {
  const record = getDevToolsRecord();
  const isRecording = options2.record !== false && record;
  let animation;
  let { duration = defaults.duration, delay = defaults.delay, endDelay = defaults.endDelay, repeat = defaults.repeat, easing = defaults.easing, persist = false, direction, offset, allowWebkitAcceleration = false, autoplay = true } = options2;
  const data2 = getAnimationData(element2);
  const valueIsTransform = isTransform(key2);
  let canAnimateNatively = supports.waapi();
  valueIsTransform && addTransformToElement(element2, key2);
  const name2 = getStyleName(key2);
  const motionValue = getMotionValue(data2.values, name2);
  const definition = transformDefinitions.get(name2);
  stopAnimation(motionValue.animation, !(isEasingGenerator(easing) && motionValue.generator) && options2.record !== false);
  return () => {
    const readInitialValue = () => {
      var _a4, _b;
      return (_b = (_a4 = style2.get(element2, name2)) !== null && _a4 !== void 0 ? _a4 : definition === null || definition === void 0 ? void 0 : definition.initialValue) !== null && _b !== void 0 ? _b : 0;
    };
    let keyframes = hydrateKeyframes(keyframesList(keyframesDefinition), readInitialValue);
    const toUnit = getUnitConverter(keyframes, definition);
    if (isEasingGenerator(easing)) {
      const custom = easing.createAnimation(keyframes, key2 !== "opacity", readInitialValue, name2, motionValue);
      easing = custom.easing;
      keyframes = custom.keyframes || keyframes;
      duration = custom.duration || duration;
    }
    if (isCssVar(name2)) {
      if (supports.cssRegisterProperty()) {
        registerCssVariable(name2);
      } else {
        canAnimateNatively = false;
      }
    }
    if (valueIsTransform && !supports.linearEasing() && (isFunction2(easing) || isEasingList(easing) && easing.some(isFunction2))) {
      canAnimateNatively = false;
    }
    if (canAnimateNatively) {
      if (definition) {
        keyframes = keyframes.map((value2) => isNumber2(value2) ? definition.toDefaultUnit(value2) : value2);
      }
      if (keyframes.length === 1 && (!supports.partialKeyframes() || isRecording)) {
        keyframes.unshift(readInitialValue());
      }
      const animationOptions = {
        delay: time.ms(delay),
        duration: time.ms(duration),
        endDelay: time.ms(endDelay),
        easing: !isEasingList(easing) ? convertEasing(easing, duration) : void 0,
        direction,
        iterations: repeat + 1,
        fill: "both"
      };
      animation = element2.animate({
        [name2]: keyframes,
        offset,
        easing: isEasingList(easing) ? easing.map((thisEasing) => convertEasing(thisEasing, duration)) : void 0
      }, animationOptions);
      if (!animation.finished) {
        animation.finished = new Promise((resolve2, reject2) => {
          animation.onfinish = resolve2;
          animation.oncancel = reject2;
        });
      }
      const target = keyframes[keyframes.length - 1];
      animation.finished.then(() => {
        if (persist)
          return;
        style2.set(element2, name2, target);
        animation.cancel();
      }).catch(noop3);
      if (!allowWebkitAcceleration)
        animation.playbackRate = 1.000001;
    } else if (AnimationPolyfill && valueIsTransform) {
      keyframes = keyframes.map((value2) => typeof value2 === "string" ? parseFloat(value2) : value2);
      if (keyframes.length === 1) {
        keyframes.unshift(parseFloat(readInitialValue()));
      }
      animation = new AnimationPolyfill((latest) => {
        style2.set(element2, name2, toUnit ? toUnit(latest) : latest);
      }, keyframes, Object.assign(Object.assign({}, options2), {
        duration,
        easing
      }));
    } else {
      const target = keyframes[keyframes.length - 1];
      style2.set(element2, name2, definition && isNumber2(target) ? definition.toDefaultUnit(target) : target);
    }
    if (isRecording) {
      record(element2, key2, keyframes, {
        duration,
        delay,
        easing,
        repeat,
        offset
      }, "motion-one");
    }
    motionValue.setAnimation(animation);
    if (animation && !autoplay)
      animation.pause();
    return animation;
  };
}

// node_modules/@motionone/dom/dist/animate/utils/options.es.js
var getOptions = (options2, key2) => (
  /**
   * TODO: Make test for this
   * Always return a new object otherwise delay is overwritten by results of stagger
   * and this results in no stagger
   */
  options2[key2] ? Object.assign(Object.assign({}, options2), options2[key2]) : Object.assign({}, options2)
);

// node_modules/@motionone/dom/dist/utils/resolve-elements.es.js
function resolveElements(elements, selectorCache) {
  var _a4;
  if (typeof elements === "string") {
    if (selectorCache) {
      (_a4 = selectorCache[elements]) !== null && _a4 !== void 0 ? _a4 : selectorCache[elements] = document.querySelectorAll(elements);
      elements = selectorCache[elements];
    } else {
      elements = document.querySelectorAll(elements);
    }
  } else if (elements instanceof Element) {
    elements = [elements];
  }
  return Array.from(elements || []);
}

// node_modules/@motionone/dom/node_modules/tslib/tslib.es6.mjs
function __rest(s3, e3) {
  var t3 = {};
  for (var p4 in s3) if (Object.prototype.hasOwnProperty.call(s3, p4) && e3.indexOf(p4) < 0)
    t3[p4] = s3[p4];
  if (s3 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p4 = Object.getOwnPropertySymbols(s3); i3 < p4.length; i3++) {
      if (e3.indexOf(p4[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p4[i3]))
        t3[p4[i3]] = s3[p4[i3]];
    }
  return t3;
}

// node_modules/@motionone/dom/dist/gestures/in-view.es.js
var thresholds = {
  any: 0,
  all: 1
};
function inView(elementOrSelector, onStart, { root: root3, margin: rootMargin, amount = "any" } = {}) {
  if (typeof IntersectionObserver === "undefined") {
    return () => {
    };
  }
  const elements = resolveElements(elementOrSelector);
  const activeIntersections = /* @__PURE__ */ new WeakMap();
  const onIntersectionChange = (entries2) => {
    entries2.forEach((entry) => {
      const onEnd = activeIntersections.get(entry.target);
      if (entry.isIntersecting === Boolean(onEnd))
        return;
      if (entry.isIntersecting) {
        const newOnEnd = onStart(entry);
        if (isFunction2(newOnEnd)) {
          activeIntersections.set(entry.target, newOnEnd);
        } else {
          observer.unobserve(entry.target);
        }
      } else if (onEnd) {
        onEnd(entry);
        activeIntersections.delete(entry.target);
      }
    });
  };
  const observer = new IntersectionObserver(onIntersectionChange, {
    root: root3,
    rootMargin,
    threshold: typeof amount === "number" ? amount : thresholds[amount]
  });
  elements.forEach((element2) => observer.observe(element2));
  return () => observer.disconnect();
}

// node_modules/@motionone/dom/dist/state/utils/has-changed.es.js
function hasChanged(a3, b3) {
  if (typeof a3 !== typeof b3)
    return true;
  if (Array.isArray(a3) && Array.isArray(b3))
    return !shallowCompare(a3, b3);
  return a3 !== b3;
}
function shallowCompare(next2, prev) {
  const prevLength = prev.length;
  if (prevLength !== next2.length)
    return false;
  for (let i3 = 0; i3 < prevLength; i3++) {
    if (prev[i3] !== next2[i3])
      return false;
  }
  return true;
}

// node_modules/@motionone/dom/dist/state/utils/is-variant.es.js
function isVariant(definition) {
  return typeof definition === "object";
}

// node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js
function resolveVariant(definition, variants) {
  if (isVariant(definition)) {
    return definition;
  } else if (definition && variants) {
    return variants[definition];
  }
}

// node_modules/@motionone/dom/dist/state/utils/schedule.es.js
var scheduled = void 0;
function processScheduledAnimations() {
  if (!scheduled)
    return;
  const generators = scheduled.sort(compareByDepth).map(fireAnimateUpdates);
  generators.forEach(fireNext);
  generators.forEach(fireNext);
  scheduled = void 0;
}
function scheduleAnimation(state) {
  if (!scheduled) {
    scheduled = [state];
    requestAnimationFrame(processScheduledAnimations);
  } else {
    addUniqueItem(scheduled, state);
  }
}
function unscheduleAnimation(state) {
  scheduled && removeItem(scheduled, state);
}
var compareByDepth = (a3, b3) => a3.getDepth() - b3.getDepth();
var fireAnimateUpdates = (state) => state.animateUpdates();
var fireNext = (iterator) => iterator.next();

// node_modules/@motionone/dom/dist/state/utils/events.es.js
var motionEvent = (name2, target) => new CustomEvent(name2, { detail: { target } });
function dispatchPointerEvent(element2, name2, event2) {
  element2.dispatchEvent(new CustomEvent(name2, { detail: { originalEvent: event2 } }));
}
function dispatchViewEvent(element2, name2, entry) {
  element2.dispatchEvent(new CustomEvent(name2, { detail: { originalEntry: entry } }));
}

// node_modules/@motionone/dom/dist/state/gestures/in-view.es.js
var inView2 = {
  isActive: (options2) => Boolean(options2.inView),
  subscribe: (element2, { enable, disable }, { inViewOptions = {} }) => {
    const { once } = inViewOptions, viewOptions = __rest(inViewOptions, ["once"]);
    return inView(element2, (enterEntry) => {
      enable();
      dispatchViewEvent(element2, "viewenter", enterEntry);
      if (!once) {
        return (leaveEntry) => {
          disable();
          dispatchViewEvent(element2, "viewleave", leaveEntry);
        };
      }
    }, viewOptions);
  }
};

// node_modules/@motionone/dom/dist/state/gestures/hover.es.js
var mouseEvent = (element2, name2, action) => (event2) => {
  if (event2.pointerType && event2.pointerType !== "mouse")
    return;
  action();
  dispatchPointerEvent(element2, name2, event2);
};
var hover = {
  isActive: (options2) => Boolean(options2.hover),
  subscribe: (element2, { enable, disable }) => {
    const onEnter = mouseEvent(element2, "hoverstart", enable);
    const onLeave = mouseEvent(element2, "hoverend", disable);
    element2.addEventListener("pointerenter", onEnter);
    element2.addEventListener("pointerleave", onLeave);
    return () => {
      element2.removeEventListener("pointerenter", onEnter);
      element2.removeEventListener("pointerleave", onLeave);
    };
  }
};

// node_modules/@motionone/dom/dist/state/gestures/press.es.js
var press = {
  isActive: (options2) => Boolean(options2.press),
  subscribe: (element2, { enable, disable }) => {
    const onPointerUp = (event2) => {
      disable();
      dispatchPointerEvent(element2, "pressend", event2);
      window.removeEventListener("pointerup", onPointerUp);
    };
    const onPointerDown = (event2) => {
      enable();
      dispatchPointerEvent(element2, "pressstart", event2);
      window.addEventListener("pointerup", onPointerUp);
    };
    element2.addEventListener("pointerdown", onPointerDown);
    return () => {
      element2.removeEventListener("pointerdown", onPointerDown);
      window.removeEventListener("pointerup", onPointerUp);
    };
  }
};

// node_modules/@motionone/dom/dist/state/index.es.js
var gestures = { inView: inView2, hover, press };
var stateTypes = ["initial", "animate", ...Object.keys(gestures), "exit"];
var mountedStates = /* @__PURE__ */ new WeakMap();
function createMotionState(options2 = {}, parent) {
  let element2;
  let depth2 = parent ? parent.getDepth() + 1 : 0;
  const activeStates = { initial: true, animate: true };
  const gestureSubscriptions = {};
  const context = {};
  for (const name2 of stateTypes) {
    context[name2] = typeof options2[name2] === "string" ? options2[name2] : parent === null || parent === void 0 ? void 0 : parent.getContext()[name2];
  }
  const initialVariantSource = options2.initial === false ? "animate" : "initial";
  let _a4 = resolveVariant(options2[initialVariantSource] || context[initialVariantSource], options2.variants) || {}, target = __rest(_a4, ["transition"]);
  const baseTarget = Object.assign({}, target);
  function* animateUpdates() {
    var _a5, _b;
    const prevTarget = target;
    target = {};
    const animationOptions = {};
    for (const name2 of stateTypes) {
      if (!activeStates[name2])
        continue;
      const variant = resolveVariant(options2[name2]);
      if (!variant)
        continue;
      for (const key2 in variant) {
        if (key2 === "transition")
          continue;
        target[key2] = variant[key2];
        animationOptions[key2] = getOptions((_b = (_a5 = variant.transition) !== null && _a5 !== void 0 ? _a5 : options2.transition) !== null && _b !== void 0 ? _b : {}, key2);
      }
    }
    const allTargetKeys = /* @__PURE__ */ new Set([
      ...Object.keys(target),
      ...Object.keys(prevTarget)
    ]);
    const animationFactories = [];
    allTargetKeys.forEach((key2) => {
      var _a6;
      if (target[key2] === void 0) {
        target[key2] = baseTarget[key2];
      }
      if (hasChanged(prevTarget[key2], target[key2])) {
        (_a6 = baseTarget[key2]) !== null && _a6 !== void 0 ? _a6 : baseTarget[key2] = style2.get(element2, key2);
        animationFactories.push(animateStyle(element2, key2, target[key2], animationOptions[key2], Animation));
      }
    });
    yield;
    const animations = animationFactories.map((factory) => factory()).filter(Boolean);
    if (!animations.length)
      return;
    const animationTarget = target;
    element2.dispatchEvent(motionEvent("motionstart", animationTarget));
    Promise.all(animations.map((animation) => animation.finished)).then(() => {
      element2.dispatchEvent(motionEvent("motioncomplete", animationTarget));
    }).catch(noop3);
  }
  const setGesture = (name2, isActive) => () => {
    activeStates[name2] = isActive;
    scheduleAnimation(state);
  };
  const updateGestureSubscriptions = () => {
    for (const name2 in gestures) {
      const isGestureActive = gestures[name2].isActive(options2);
      const remove3 = gestureSubscriptions[name2];
      if (isGestureActive && !remove3) {
        gestureSubscriptions[name2] = gestures[name2].subscribe(element2, {
          enable: setGesture(name2, true),
          disable: setGesture(name2, false)
        }, options2);
      } else if (!isGestureActive && remove3) {
        remove3();
        delete gestureSubscriptions[name2];
      }
    }
  };
  const state = {
    update: (newOptions) => {
      if (!element2)
        return;
      options2 = newOptions;
      updateGestureSubscriptions();
      scheduleAnimation(state);
    },
    setActive: (name2, isActive) => {
      if (!element2)
        return;
      activeStates[name2] = isActive;
      scheduleAnimation(state);
    },
    animateUpdates,
    getDepth: () => depth2,
    getTarget: () => target,
    getOptions: () => options2,
    getContext: () => context,
    mount: (newElement) => {
      invariant(Boolean(newElement), "Animation state must be mounted with valid Element");
      element2 = newElement;
      mountedStates.set(element2, state);
      updateGestureSubscriptions();
      return () => {
        mountedStates.delete(element2);
        unscheduleAnimation(state);
        for (const key2 in gestureSubscriptions) {
          gestureSubscriptions[key2]();
        }
      };
    },
    isMounted: () => Boolean(element2)
  };
  return state;
}

// node_modules/@motionone/dom/dist/animate/utils/style-object.es.js
function createStyles(keyframes) {
  const initialKeyframes = {};
  const transformKeys = [];
  for (let key2 in keyframes) {
    const value2 = keyframes[key2];
    if (isTransform(key2)) {
      if (transformAlias[key2])
        key2 = transformAlias[key2];
      transformKeys.push(key2);
      key2 = asTransformCssVar(key2);
    }
    let initialKeyframe = Array.isArray(value2) ? value2[0] : value2;
    const definition = transformDefinitions.get(key2);
    if (definition) {
      initialKeyframe = isNumber2(value2) ? definition.toDefaultUnit(value2) : value2;
    }
    initialKeyframes[key2] = initialKeyframe;
  }
  if (transformKeys.length) {
    initialKeyframes.transform = buildTransformTemplate(transformKeys);
  }
  return initialKeyframes;
}

// node_modules/@solid-primitives/refs/dist/index.js
var defaultElementPredicate = isServer ? (item) => item != null && typeof item === "object" && "t" in item : (item) => item instanceof Element;
function getFirstChild(value2, predicate) {
  if (predicate(value2))
    return value2;
  if (typeof value2 === "function" && !value2.length)
    return getFirstChild(value2(), predicate);
  if (Array.isArray(value2)) {
    for (const item of value2) {
      const result2 = getFirstChild(item, predicate);
      if (result2)
        return result2;
    }
  }
  return null;
}
function resolveFirst(fn, predicate = defaultElementPredicate, serverPredicate = defaultElementPredicate) {
  const children2 = createMemo(fn);
  return createMemo(() => getFirstChild(children2(), isServer ? serverPredicate : predicate));
}

// node_modules/@solid-primitives/transition-group/dist/index.js
var noop4 = () => {
};
var noopTransition = (el2, done) => done();
function createSwitchTransition(source, options2) {
  const initSource = untrack(source);
  const initReturned = initSource ? [initSource] : [];
  if (isServer) {
    return () => initReturned;
  }
  const { onEnter = noopTransition, onExit = noopTransition } = options2;
  const [returned, setReturned] = createSignal(
    options2.appear ? [] : initReturned
  );
  const [isTransitionPending] = useTransition();
  let next2;
  let isExiting = false;
  function exitTransition(el2, after2) {
    if (!el2)
      return after2 && after2();
    isExiting = true;
    onExit(el2, () => {
      batch(() => {
        isExiting = false;
        setReturned((p4) => p4.filter((e3) => e3 !== el2));
        after2 && after2();
      });
    });
  }
  function enterTransition(after2) {
    const el2 = next2;
    if (!el2)
      return after2 && after2();
    next2 = void 0;
    setReturned((p4) => [el2, ...p4]);
    onEnter(el2, after2 ?? noop4);
  }
  const triggerTransitions = options2.mode === "out-in" ? (
    // exit -> enter
    (prev) => isExiting || exitTransition(prev, enterTransition)
  ) : options2.mode === "in-out" ? (
    // enter -> exit
    (prev) => enterTransition(() => exitTransition(prev))
  ) : (
    // exit & enter
    (prev) => {
      exitTransition(prev);
      enterTransition();
    }
  );
  createComputed(
    (prev) => {
      const el2 = source();
      if (untrack(isTransitionPending)) {
        isTransitionPending();
        return prev;
      }
      if (el2 !== prev) {
        next2 = el2;
        batch(() => untrack(() => triggerTransitions(prev)));
      }
      return el2;
    },
    options2.appear ? void 0 : initSource
  );
  return returned;
}

// node_modules/solid-motionone/dist/index.js
var PresenceContext = createContext();
var Presence = (props2) => {
  const [mount, setMount] = createSignal(true), state = {
    initial: props2.initial ?? true,
    mount
  }, render3 = createComponent(PresenceContext.Provider, {
    value: state,
    get children() {
      return createSwitchTransition(resolveFirst(() => props2.children), {
        appear: state.initial,
        mode: props2.exitBeforeEnter ? "out-in" : "parallel",
        onExit(el2, done) {
          batch(() => {
            setMount(false);
            mountedStates.get(el2)?.getOptions().exit ? el2.addEventListener("motioncomplete", done) : done();
          });
        },
        onEnter(_5, done) {
          batch(() => {
            setMount(true);
            done();
          });
        }
      });
    }
  });
  state.initial = true;
  return render3;
};
function createAndBindMotionState(el2, options2, presence_state, parent_state) {
  const state = createMotionState(
    presence_state?.initial === false ? { ...options2(), initial: false } : options2(),
    parent_state
  );
  createEffect(() => {
    if (presence_state && !presence_state.mount())
      return;
    const el_ref = el2(), unmount = state.mount(el_ref);
    createEffect(() => state.update(options2()));
    onCleanup(() => {
      if (presence_state && options2().exit) {
        state.setActive("exit", true);
        el_ref.addEventListener("motioncomplete", unmount);
      } else
        unmount();
    });
  });
  return [state, createStyles(state.getTarget())];
}
var OPTION_KEYS = ["initial", "animate", "inView", "inViewOptions", "hover", "press", "variants", "transition", "exit"];
var ATTR_KEYS = ["tag"];
var ParentContext = createContext();
var MotionComponent = (props2) => {
  const [options2, , attrs2] = splitProps(props2, OPTION_KEYS, ATTR_KEYS);
  const [state, style22] = createAndBindMotionState(() => root3, () => ({
    ...options2
  }), useContext(PresenceContext), useContext(ParentContext));
  let root3;
  return createComponent(ParentContext.Provider, {
    value: state,
    get children() {
      return createComponent(Dynamic, mergeProps(attrs2, {
        ref: (el2) => {
          root3 = el2;
          props2.ref?.(el2);
        },
        get component() {
          return props2.tag || "div";
        },
        get style() {
          return combineStyle(props2.style, style22);
        }
      }));
    }
  });
};
var Motion = new Proxy(MotionComponent, {
  get: (_5, tag) => (props2) => createComponent(MotionComponent, mergeProps(props2, {
    tag
  }))
});

// public/app/ui/base/dropdown.tsx
var _tmpl$5 = /* @__PURE__ */ template(`<div class="solid-dropdown-arrow"></div>`, 2);
var DropdownState = class {
  constructor(opened = false, id) {
    [this.state, this.setState] = createStore({
      opened,
      ready: false,
      id: id ?? `dropdown-${uuid4()}`
    });
  }
  setTriggerRef(ref) {
    this.triggerRef = ref;
  }
  setContentRef(ref) {
    this.contentRef = ref;
  }
  isOpened() {
    return this.state.opened;
  }
  open() {
    this.setState("opened", true);
  }
  close() {
    this.setState("opened", false);
  }
  toggleOpen() {
    this.setState("opened", !this.state.opened);
  }
  isReady() {
    return this.state.ready;
  }
  setIsReady(ready) {
    this.setState("ready", ready);
  }
};
var DropdownContext = createContext();
function useDropdownContext() {
  return useContext(DropdownContext);
}
function Dropdown(props2) {
  const state = () => props2.state ?? new DropdownState();
  return createComponent(DropdownContext.Provider, {
    get value() {
      return state();
    },
    get children() {
      return props2.children;
    }
  });
}
function DropdownTrigger(props2) {
  const ctx = useDropdownContext();
  const trigger2 = children(() => props2.children);
  const handler = () => {
    ctx.open();
  };
  createEffect(on(() => trigger2(), (elt) => {
    ctx.setTriggerRef(elt);
    elt.setAttribute("aria-controls", ctx.state.id);
    elt.setAttribute("aria-expanded", String(ctx.isOpened()));
    elt.addEventListener("click", handler);
  }));
  createEffect(on(() => ctx.isOpened(), (opened) => {
    if (!ctx.triggerRef) return;
    if (opened) {
      ctx.triggerRef.setAttribute("aria-expanded", "true");
      ctx.triggerRef.removeEventListener("click", handler);
    } else {
      ctx.triggerRef.setAttribute("aria-expanded", "false");
      setTimeout(() => {
        ctx.triggerRef.addEventListener("click", handler);
      });
    }
  }));
  return createMemo(trigger2);
}
function DropdownContent(props2) {
  const ctx = useDropdownContext();
  let ref;
  let arrowRef;
  const [placement, setPlacement] = createSignal("bottom");
  onMount(() => {
    ctx.setContentRef(ref);
  });
  const updatePosition = async () => {
    const middleware = [b(), E({
      padding: 8
    }), k({
      apply({
        availableWidth,
        availableHeight,
        elements
      }) {
        Object.assign(elements.floating.style, {
          maxWidth: `${availableWidth}px`,
          maxHeight: `${availableHeight}px`
        });
      }
    })];
    if (!props2.disableArrow) {
      middleware.push(O2(10));
      middleware.push(m({
        element: arrowRef
      }));
    }
    const {
      x: x3,
      y: y3,
      placement: placement2,
      middlewareData
    } = await V(ctx.triggerRef, ref, {
      placement: props2.placement ?? "bottom",
      middleware
    });
    setPlacement(placement2);
    const staticSide = {
      top: "bottom",
      right: "left",
      bottom: "top",
      left: "right"
    }[placement2.split("-")[0]];
    Object.assign(ref.style, {
      left: `${Math.round(x3)}px`,
      top: `${Math.round(y3)}px`
    });
    if (props2.disableArrow) return;
    const {
      x: arrowX,
      y: arrowY
    } = middlewareData.arrow;
    Object.assign(arrowRef.style, {
      left: arrowX != null ? `${arrowX}px` : "",
      top: arrowY != null ? `${arrowY}px` : "",
      right: "",
      bottom: "",
      [staticSide]: "-5px"
    });
  };
  let cleanupAutoUpdate;
  createEffect(on(() => ctx.isOpened(), async (opened, wasOpened) => {
    if (opened) {
      cleanupAutoUpdate = z(ctx.triggerRef, ref, updatePosition);
    } else {
      if (wasOpened) {
        props2.onClose?.();
      }
      if (cleanupAutoUpdate) {
        cleanupAutoUpdate();
        cleanupAutoUpdate = void 0;
      }
    }
  }), {
    defer: true
  });
  const animateTranslate = () => {
    const p4 = placement().split("-")[0];
    const axe = p4 === "bottom" || p4 === "top" ? "translateY" : "translateX";
    const keyFrames = p4 === "bottom" || p4 === "right" ? [-30, 0] : [30, 0];
    return {
      [axe]: keyFrames
    };
  };
  const focusFirstAutofocusable = () => {
    if (!ref) return;
    const autofocusElement = ref.querySelector("[autofocus]");
    if (autofocusElement) {
      autofocusElement.focus();
      return;
    }
    const focusable = ref.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    focusable?.focus();
  };
  const onKeyUp = (e3) => {
    if (e3.key === "Escape") {
      e3.preventDefault();
      ctx.close();
    }
  };
  return createComponent(Portal, {
    get mount() {
      return props2.mount;
    },
    get children() {
      return createComponent(Presence, {
        get children() {
          return createComponent(Show, {
            get when() {
              return ctx.isOpened();
            },
            get children() {
              return createComponent(ClickOutside, {
                onClickOutside: (e3) => {
                  ctx.close();
                  props2.onClickOutside?.(e3);
                },
                get children() {
                  return createComponent(Motion.div, {
                    get animate() {
                      return {
                        opacity: [0, 1],
                        ...animateTranslate()
                      };
                    },
                    exit: {
                      opacity: [1, 0],
                      scale: [1, 0.9]
                    },
                    onMotionStart: () => ctx.setIsReady(false),
                    onMotionComplete: () => {
                      ctx.setIsReady(true);
                      focusFirstAutofocusable();
                    },
                    onKeyUp,
                    get transition() {
                      return {
                        duration: props2.duration ?? 0.2
                      };
                    },
                    get ["class"]() {
                      return classNames("solid-dropdown", props2.class);
                    },
                    get inert() {
                      return createMemo(() => !!ctx.isOpened())() && !ctx.isReady();
                    },
                    ref(r$) {
                      const _ref$ = ref;
                      typeof _ref$ === "function" ? _ref$(r$) : ref = r$;
                    },
                    get id() {
                      return ctx.state.id;
                    },
                    get children() {
                      return [createComponent(Show, {
                        get when() {
                          return !props2.disableArrow;
                        },
                        get children() {
                          const _el$ = _tmpl$5.cloneNode(true);
                          const _ref$2 = arrowRef;
                          typeof _ref$2 === "function" ? use(_ref$2, _el$) : arrowRef = _el$;
                          return _el$;
                        }
                      }), createMemo(() => props2.children)];
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
  });
}

// public/app/ui/base/icon.tsx
init_icons();
var _tmpl$6 = /* @__PURE__ */ template(`<i></i>`, 2);
function iconClass2(input) {
  if (!input) {
    return "";
  }
  if (availableIconAliases[input]) {
    input = availableIconAliases[input];
  }
  if (input.substr(0, 3) === "bi-") {
    return input;
  }
  if (input.substr(0, 4) === "kfi-") {
    return "kfi " + input;
  }
  if (input.substr(0, 3) === "fa-") {
    return "fa " + input;
  }
  return "fa fa-" + input;
}
function Icon(props2) {
  const [local, others] = splitProps(props2, ["name", "class", "classList"]);
  return (() => {
    const _el$ = _tmpl$6.cloneNode(true);
    spread(_el$, mergeProps({
      get ["class"]() {
        return iconClass2(local.name);
      },
      get classList() {
        return {
          ...local.classList,
          [local.class]: !!local.class
        };
      }
    }, others), false, false);
    return _el$;
  })();
}

// public/app/ui/base/tooltip.jsx
var _tmpl$7 = /* @__PURE__ */ template(`<div class="solid-tooltip-arrow"></div>`, 2);
var _tmpl$23 = /* @__PURE__ */ template(`<div class="solid-tooltip"><div class="solid-tooltip-inner"></div></div>`, 4);
function Tooltip(props2) {
  props2 = mergeProps({
    label: "placeholder",
    showArrow: true,
    placement: "top",
    enable: true,
    delay: false,
    showDelay: false
  }, props2);
  const [local, others] = splitProps(props2, ["label", "showArrow", "placement", "enable", "delay", "showDelay", "mount", "show"], ["children"]);
  const [showTooltip2, setShowTooltip] = createSignal(false);
  const resolved = children(() => others.children);
  const displayTooltip = () => {
    if (!local.enable) return;
    setShowTooltip(true);
  };
  const hideTooltip2 = () => {
    setShowTooltip(false);
  };
  onMount(() => {
    [["mouseenter", displayTooltip], ["mousemove", displayTooltip], ["mouseleave", hideTooltip2]].forEach(([event2, listener]) => {
      resolved.toArray()[0].addEventListener(event2, listener);
    });
  });
  createEffect(on(() => local.show, (show) => {
    if (show) {
      displayTooltip();
    } else {
      hideTooltip2();
    }
  }));
  return [createMemo(resolved), createComponent(Show, {
    get when() {
      return local.label;
    },
    get children() {
      return createComponent(Portal, {
        get mount() {
          return local.mount;
        },
        get children() {
          return createComponent(_Tooltip, mergeProps(local, {
            get open() {
              return local.enable && showTooltip2() && resolved;
            },
            get target() {
              return resolved.toArray()[0];
            }
          }));
        }
      });
    }
  })];
}
function _Tooltip(local) {
  let tooltip, arrowContainer, cleanup;
  const [open, setOpen] = createSignal(false);
  const updatePosition = () => {
    if (!local.target && !tooltip) return;
    V(local.target, tooltip, {
      placement: local.placement,
      middleware: [b(), E({
        padding: 5
      }), O2(10), m({
        element: arrowContainer
      })]
    }).then(({
      x: x3,
      y: y3,
      placement,
      middlewareData
    }) => {
      Object.assign(tooltip?.style, {
        left: `${x3}px`,
        top: `${y3}px`
      });
      if (local.showArrow) {
        const {
          x: arrowX,
          y: arrowY
        } = middlewareData.arrow;
        const staticSide = {
          top: "bottom",
          right: "left",
          bottom: "top",
          left: "right"
        }[placement.split("-")[0]];
        Object.assign(arrowContainer.style, {
          left: arrowX != null ? `${arrowX}px` : "",
          top: arrowY != null ? `${arrowY}px` : "",
          right: "",
          bottom: "",
          [staticSide]: "-4px"
        });
      }
    });
  };
  onMount(() => {
    updatePosition();
    cleanup = z(tooltip, local.target, updatePosition);
  });
  let delayTimeout;
  function openHandler() {
    const delay = local.showDelay ?? local.delay;
    if (delay) {
      if (delayTimeout) {
        clearTimeout(delayTimeout);
      }
      delayTimeout = setTimeout(() => setOpen(true), delay);
    } else {
      setOpen(true);
    }
  }
  function closeHandler() {
    if (delayTimeout) {
      clearTimeout(delayTimeout);
    }
    setOpen(false);
  }
  createEffect(() => {
    if (local.open) {
      openHandler();
    } else {
      closeHandler();
    }
  });
  onCleanup(() => {
    cleanup && cleanup();
    if (delayTimeout) {
      clearTimeout(delayTimeout);
    }
  });
  return (() => {
    const _el$ = _tmpl$23.cloneNode(true), _el$2 = _el$.firstChild;
    const _ref$ = tooltip;
    typeof _ref$ === "function" ? use(_ref$, _el$) : tooltip = _el$;
    insert(_el$2, () => local.label);
    insert(_el$, createComponent(Show, {
      get when() {
        return local.showArrow;
      },
      get children() {
        const _el$3 = _tmpl$7.cloneNode(true);
        const _ref$2 = arrowContainer;
        typeof _ref$2 === "function" ? use(_ref$2, _el$3) : arrowContainer = _el$3;
        return _el$3;
      }
    }), null);
    createRenderEffect(() => _el$.classList.toggle("open", !!open()));
    return _el$;
  })();
}

// public/app/ui/base/buttons.jsx
var _tmpl$8 = /* @__PURE__ */ template(`<button></button>`, 2);
function Button(props2) {
  props2 = mergeProps({
    tooltip: false,
    hideoffline: false,
    type: "button"
  }, props2);
  const [local, others] = splitProps(props2, ["class", "classList", "disabled", "disableoffline", "label", "hideoffline", "tooltip", "size", "style"]);
  const btn = (() => {
    const _el$ = _tmpl$8.cloneNode(true);
    spread(_el$, mergeProps({
      get ["class"]() {
        return ["btn", local.size ? `btn-${local.size}` : "", `btn-${local.style || "default"}`].join(" ");
      },
      get classList() {
        return {
          [local.class]: local.class,
          ...local.classList
        };
      },
      get disabled() {
        return local.disabled || local.disableoffline === !isOnline();
      }
    }, others), false, true);
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.icon;
      },
      get children() {
        return createComponent(Icon, {
          get name() {
            return props2.icon;
          }
        });
      }
    }), null);
    insert(_el$, () => local.label || props2.children, null);
    return _el$;
  })();
  return createComponent(Show, {
    get when() {
      return !(local.hideoffline && !isOnline());
    },
    get children() {
      return createMemo(() => !!local.tooltip)() ? createComponent(Tooltip, mergeProps(() => local.tooltip, {
        children: btn
      })) : btn;
    }
  });
}
function IconButton(props2) {
  const [local, others] = splitProps(props2, ["icon", "class"]);
  return createComponent(Button, mergeProps({
    get ["class"]() {
      return "btn-icon " + (local.class || "");
    }
  }, others, {
    get children() {
      return createComponent(Icon, {
        get name() {
          return local.icon;
        }
      });
    }
  }));
}

// node_modules/@solid-primitives/storage/dist/index.js
function createStorageSignal(key2, initialValue, props2) {
  const [error2, setError2] = createSignal();
  const apis = props2?.api ? Array.isArray(props2.api) ? props2.api : [props2.api] : [globalThis.localStorage].filter(Boolean);
  const prefix5 = props2?.prefix ? `${props2.prefix}.` : "";
  const read = () => apis.reduce((result2, api2) => {
    if (result2 !== null || !api2) {
      return result2;
    }
    let value2 = null;
    try {
      value2 = api2.getItem(`${prefix5}${key2}`);
    } catch (err) {
      setError2(
        err instanceof Error ? err : new Error(`Error reading ${prefix5}${key2} from ${api2.name}`)
      );
      if (props2?.throw) {
        throw err;
      }
    }
    if (value2 !== null && props2?.deserializer) {
      return props2.deserializer(value2 + "", key2, props2.options);
    }
    return value2;
  }, null);
  const [accessor, setter] = createHydratableSignal(
    initialValue,
    () => read() ?? initialValue,
    props2
  );
  createEffect(() => {
    const value2 = accessor();
    const filteredValue = props2?.serializer ? props2.serializer(value2, key2, props2.options) : value2 + "";
    const apiKey = `${prefix5}${key2}`;
    try {
      if (value2 === null) {
        apis.forEach((api2) => api2.getItem(apiKey) !== null && api2.removeItem(apiKey));
      } else {
        apis.forEach(
          (api2) => api2.getItem(apiKey) !== filteredValue && api2.setItem(apiKey, filteredValue, props2?.options)
        );
      }
    } catch (err) {
      setError2(
        err instanceof Error ? err : new Error(`Error ${value2 === null ? "removing" : "writing"} value`)
      );
      if (props2?.throw) {
        throw err;
      }
    }
  });
  const refetch = () => {
    const value2 = read();
    setter(value2);
  };
  props2?.sync !== false && onMount(() => {
    const listener = (ev) => {
      let changed = false;
      try {
        apis.forEach((api2) => {
          if (api2 !== ev.storageArea && ev.key && ev.newValue !== api2.getItem(ev.key)) {
            ev.newValue ? api2.setItem(ev.key, ev.newValue) : api2.removeItem(ev.key);
            changed = true;
          }
        });
      } catch (err) {
        setError2(err instanceof Error ? err : new Error("Error synching api after event"));
        if (props2?.throw) {
          throw err;
        }
      }
      changed && refetch();
    };
    if ("addEventListener" in globalThis) {
      globalThis.addEventListener("storage", listener);
      onCleanup(() => globalThis.removeEventListener("storage", listener));
    } else {
      apis.forEach((api2) => api2.addEventListener?.("storage", listener));
      onCleanup(() => apis.forEach((api2) => api2.removeEventListener?.("storage", listener)));
    }
  });
  return [Object.assign(accessor, { error: error2 }), setter, refetch];
}
var addClearMethod = (storage) => {
  if (typeof storage.clear === "function") {
    return storage;
  }
  storage.clear = () => {
    let key2;
    while (key2 = storage.key(0)) {
      storage.removeItem(key2);
    }
  };
  return storage;
};
var methodKeys = ["clear", "getItem", "getAll", "setItem", "removeItem", "key", "getLength"];
var addWithOptionsMethod = (storage) => {
  storage.withOptions = (options2) => methodKeys.reduce(
    (wrapped, key2) => {
      if (typeof storage[key2] === "function") {
        wrapped[key2] = (...args) => {
          args[storage[key2].length - 1] = options2;
          return storage[key2](...args);
        };
      }
      return wrapped;
    },
    {
      get length() {
        return storage.length;
      },
      withOptions: (options22) => storage.withOptions(options22)
    }
  );
  return storage;
};
var cookiePropertyKeys = [
  "domain",
  "expires",
  "path",
  "secure",
  "httpOnly",
  "maxAge",
  "sameSite"
];
function serializeCookieOptions(options2) {
  if (!options2) {
    return "";
  }
  let memo = "";
  for (const key2 in options2) {
    if (!cookiePropertyKeys.includes(key2))
      continue;
    const value2 = options2[key2];
    memo += value2 instanceof Date ? `; ${key2}=${value2.toUTCString()}` : typeof value2 === "boolean" ? `; ${key2}` : `; ${key2}=${value2}`;
  }
  return memo;
}
function deserializeCookieOptions(cookie, key2) {
  return cookie.match(`(^|;)\\s*${key2}\\s*=\\s*([^;]+)`)?.pop() ?? null;
}
var getRequestHeaders = isServer ? () => voidFn()?.request?.headers || new Headers() : () => new Headers();
var getResponseHeaders = isServer ? () => voidFn()?.response?.headers || new Headers() : () => new Headers();
var cookieStorage = addWithOptionsMethod(
  addClearMethod({
    _read: isServer ? (options2) => {
      const requestCookies = (options2?.getRequestHeaders?.() || getRequestHeaders()).get(
        "Cookie"
      );
      const responseCookies = (options2?.getResponseHeaders?.() || getResponseHeaders()).get(
        "Set-Cookie"
      );
      const cookies = {};
      const addCookie = (_5, key2, val) => cookies[key2] = val;
      requestCookies?.replace(/(?:^|;)([^=]+)=([^;]+)/g, addCookie);
      responseCookies?.replace(/(?:^|, )([^=]+)=([^;]+)/g, addCookie);
      return Object.entries(cookies).map((keyval) => keyval.join("=")).join("; ");
    } : () => document.cookie,
    _write: isServer ? (key2, value2, options2) => {
      const responseHeaders = getResponseHeaders();
      responseHeaders.set(
        "Set-Cookie",
        (responseHeaders.get("Set-Cookie") || "").replace(
          new RegExp(`(?:^|, )${key2}=[^,]+`, "g"),
          ""
        )
      );
      responseHeaders.append("Set-Cookie", `${key2}=${value2}${serializeCookieOptions(options2)}`);
    } : (key2, value2, options2) => {
      document.cookie = `${key2}=${value2}${serializeCookieOptions(options2)}`;
    },
    getItem: (key2, options2) => deserializeCookieOptions(cookieStorage._read(options2), key2),
    setItem: (key2, value2, options2) => {
      cookieStorage._write(key2, value2, options2);
    },
    removeItem: (key2, options2) => {
      cookieStorage._write(key2, "deleted", { ...options2, expires: /* @__PURE__ */ new Date(0) });
    },
    key: (index2, options2) => {
      let key2 = null;
      let count = 0;
      cookieStorage._read(options2).replace(/(?:^|;)\s*(.+?)\s*=\s*[^;]+/g, (_5, found2) => {
        if (!key2 && found2 && count++ === index2) {
          key2 = found2;
        }
        return "";
      });
      return key2;
    },
    getLength: (options2) => {
      let length = 0;
      cookieStorage._read(options2).replace(/(?:^|;)\s*.+?\s*=\s*[^;]+/g, (found2) => {
        length += found2 ? 1 : 0;
        return "";
      });
      return length;
    },
    get length() {
      return this.getLength();
    }
  })
);
function makePersisted(signal, options2 = {}) {
  const storage = options2.storage || globalThis.localStorage;
  if (!storage) {
    return signal;
  }
  const storageOptions = options2.storageOptions;
  const name2 = options2.name || `storage-${createUniqueId()}`;
  const serialize = options2.serialize || JSON.stringify.bind(JSON);
  const deserialize = options2.deserialize || JSON.parse.bind(JSON);
  const init = storage.getItem(name2, storageOptions);
  const set4 = typeof signal[0] === "function" ? (data2) => {
    try {
      const value2 = deserialize(data2);
      signal[1](() => value2);
    } catch (e3) {
      if (isDev)
        console.warn(e3);
    }
  } : (data2) => {
    try {
      const value2 = deserialize(data2);
      signal[1](reconcile(value2));
    } catch (e3) {
      if (isDev)
        console.warn(e3);
    }
  };
  let unchanged = true;
  if (init instanceof Promise)
    init.then((data2) => unchanged && data2 && set4(data2));
  else if (init)
    set4(init);
  if (typeof options2.sync?.[0] === "function") {
    const get7 = typeof signal[0] === "function" ? signal[0] : () => signal[0];
    options2.sync[0]((data2) => {
      if (data2.key !== name2 || !isServer && (data2.url || globalThis.location.href) !== globalThis.location.href || data2.newValue === serialize(untrack(get7))) {
        return;
      }
      set4(data2.newValue);
    });
  }
  return [
    signal[0],
    typeof signal[0] === "function" ? (value2) => {
      const output = signal[1](value2);
      const serialized = value2 != null ? serialize(output) : value2;
      options2.sync?.[1](name2, serialized);
      if (value2 != null)
        storage.setItem(name2, serialized, storageOptions);
      else
        storage.removeItem(name2, storageOptions);
      unchanged = false;
      return output;
    } : (...args) => {
      signal[1](...args);
      const value2 = serialize(untrack(() => signal[0]));
      options2.sync?.[1](name2, value2);
      storage.setItem(name2, value2, storageOptions);
      unchanged = false;
    }
  ];
}

// public/app/ui/base/color-picker.tsx
var import_tinycolor24 = __toESM(require_tinycolor());

// node_modules/@solid-primitives/keyboard/dist/index.js
function equalsKeyHoldSequence(sequence, model) {
  for (let i3 = sequence.length - 1; i3 >= 0; i3--) {
    const _model = model.slice(0, i3 + 1);
    if (!arrayEquals(sequence[i3], _model))
      return false;
  }
  return true;
}
var useKeyDownEvent = /* @__PURE__ */ createSingletonRoot(
  () => {
    if (isServer) {
      return () => null;
    }
    const [event2, setEvent] = createSignal(null);
    makeEventListener(window, "keydown", (e3) => {
      setEvent(e3);
      setTimeout(() => setEvent(null));
    });
    return event2;
  }
);
var useKeyDownList = /* @__PURE__ */ createSingletonRoot(() => {
  if (isServer) {
    const keys5 = () => [];
    keys5[0] = keys5;
    keys5[1] = { event: () => null };
    keys5[Symbol.iterator] = function* () {
      yield keys5[0];
      yield keys5[1];
    };
    return keys5;
  }
  const [pressedKeys, setPressedKeys] = createSignal([]), reset3 = () => setPressedKeys([]), event2 = useKeyDownEvent();
  makeEventListener(window, "keydown", (e3) => {
    if (e3.repeat || typeof e3.key !== "string")
      return;
    const key2 = e3.key.toUpperCase(), currentKeys = pressedKeys();
    if (currentKeys.includes(key2))
      return;
    const keys5 = [...currentKeys, key2];
    if (currentKeys.length === 0 && key2 !== "ALT" && key2 !== "CONTROL" && key2 !== "META" && key2 !== "SHIFT") {
      if (e3.shiftKey)
        keys5.unshift("SHIFT");
      if (e3.altKey)
        keys5.unshift("ALT");
      if (e3.ctrlKey)
        keys5.unshift("CONTROL");
      if (e3.metaKey)
        keys5.unshift("META");
    }
    setPressedKeys(keys5);
  });
  makeEventListener(window, "keyup", (e3) => {
    if (typeof e3.key !== "string")
      return;
    const key2 = e3.key.toUpperCase();
    setPressedKeys((prev) => prev.filter((_key) => _key !== key2));
  });
  makeEventListener(window, "blur", reset3);
  makeEventListener(window, "contextmenu", (e3) => {
    e3.defaultPrevented || reset3();
  });
  pressedKeys[0] = pressedKeys;
  pressedKeys[1] = { event: event2 };
  pressedKeys[Symbol.iterator] = function* () {
    yield pressedKeys[0];
    yield pressedKeys[1];
  };
  return pressedKeys;
});
var useCurrentlyHeldKey = /* @__PURE__ */ createSingletonRoot(
  () => {
    if (isServer) {
      return () => null;
    }
    const keys5 = useKeyDownList();
    let prevKeys = untrack(keys5);
    return createMemo(() => {
      const _keys = keys5();
      const prev = prevKeys;
      prevKeys = _keys;
      if (prev.length === 0 && _keys.length === 1)
        return _keys[0];
      return null;
    });
  }
);
var useKeyDownSequence = /* @__PURE__ */ createSingletonRoot(() => {
  if (isServer) {
    return () => [];
  }
  const keys5 = useKeyDownList();
  return createMemo((prev) => {
    if (keys5().length === 0)
      return [];
    return [...prev, keys5()];
  }, []);
});
function createKeyHold(key2, options2 = {}) {
  if (isServer) {
    return () => false;
  }
  key2 = key2.toUpperCase();
  const { preventDefault = true } = options2, event2 = useKeyDownEvent(), heldKey = useCurrentlyHeldKey();
  return createMemo(() => heldKey() === key2 && (preventDefault && event2()?.preventDefault(), true));
}
function createShortcut(keys5, callback, options2 = {}) {
  if (isServer || !keys5.length) {
    return;
  }
  keys5 = keys5.map((key2) => key2.toUpperCase());
  const { preventDefault = true } = options2, event2 = useKeyDownEvent(), sequence = useKeyDownSequence();
  let reset3 = false;
  const handleSequenceWithReset = (sequence2) => {
    if (!sequence2.length)
      return reset3 = false;
    if (reset3)
      return;
    const e3 = event2();
    if (sequence2.length < keys5.length) {
      if (equalsKeyHoldSequence(sequence2, keys5.slice(0, sequence2.length))) {
        preventDefault && e3 && e3.preventDefault();
      } else {
        reset3 = true;
      }
    } else {
      reset3 = true;
      if (equalsKeyHoldSequence(sequence2, keys5)) {
        preventDefault && e3 && e3.preventDefault();
        callback(e3);
      }
    }
  };
  const handleSequenceWithoutReset = (sequence2) => {
    const last3 = sequence2.at(-1);
    if (!last3)
      return;
    const e3 = event2();
    if (preventDefault && last3.length < keys5.length) {
      if (arrayEquals(last3, keys5.slice(0, keys5.length - 1))) {
        e3 && e3.preventDefault();
      }
      return;
    }
    if (arrayEquals(last3, keys5)) {
      const prev = sequence2.at(-2);
      if (!prev || arrayEquals(prev, keys5.slice(0, keys5.length - 1))) {
        preventDefault && e3 && e3.preventDefault();
        callback(e3);
      }
    }
  };
  createEffect(
    on(sequence, options2.requireReset ? handleSequenceWithReset : handleSequenceWithoutReset)
  );
}

// public/app/ui/base/keyboard/state.ts
var [keyboardState, setKeyboardState] = createStore({
  Alt: false,
  Control: false,
  Shift: false,
  Meta: false
});

// public/app/ui/base/keyboard/types.ts
var modifiers = [
  "Alt",
  "Control",
  "Shift",
  "Meta"
];
var sequenceModifiers = {
  Alt: "ALT",
  Control: "CONTROL",
  Shift: "SHIFT",
  Meta: "META"
};

// public/app/ui/base/keyboard/context.tsx
var KeyboardContext = createContext();
function useKeyboard() {
  return useContext(KeyboardContext);
}
function KeyboardProvider(props2) {
  const sequence = useKeyDownSequence();
  createEffect(() => {
    const sequences = sequence();
    setKeyboardState(produce((s3) => {
      modifiers.forEach((modifier) => {
        const lastSequence = sequences[sequences.length - 1] ?? [];
        s3[modifier] = lastSequence.includes(sequenceModifiers[modifier]);
      });
    }));
  });
  return createComponent(KeyboardContext.Provider, {
    value: keyboardState,
    get children() {
      return props2.children;
    }
  });
}

// public/app/ui/base/keyboard/spacebar.ts
function useSpacebar(options2) {
  const spaceBarHold = createKeyHold(" ", options2);
  return spaceBarHold;
}

// public/app/ui/base/drag/draggable.ts
function draggable(elt, options2) {
  const [state, setState] = createStore({
    dragging: false,
    sx: void 0,
    sy: void 0,
    px: void 0,
    py: void 0,
    x: void 0,
    y: void 0,
    autoScrolling: { x: false, y: false },
    autoScrollVelocity: { x: 0, y: 0 },
    autoScrollOffset: { x: 0, y: 0 }
  });
  const container = () => options2().container?.();
  const target = () => options2().disable?.() ? void 0 : typeof elt === "function" ? elt() : elt;
  let autoScrollFrameId = null;
  let cachedScrollContainerBounds = null;
  const getAutoScrollConfig = () => {
    const autoScroll = options2().autoScroll;
    if (!autoScroll) return { x: false, y: false };
    if (typeof autoScroll === "boolean")
      return { x: autoScroll, y: autoScroll };
    return { x: autoScroll.x ?? true, y: autoScroll.y ?? true };
  };
  const getScrollContainer = () => {
    return options2().autoScrollContainer?.() || container() || window;
  };
  const detectAutoScrollZone = (mouseX, mouseY, containerBounds, zone, offset) => {
    const intensity = { x: 0, y: 0 };
    const leftBound = containerBounds.left + (offset?.left ?? 0);
    const rightBound = containerBounds.right - (offset?.right ?? 0);
    const topBound = containerBounds.top + (offset?.top ?? 0);
    const bottomBound = containerBounds.bottom - (offset?.bottom ?? 0);
    if (mouseX < leftBound + zone && mouseX >= leftBound) {
      intensity.x = -(1 - (mouseX - leftBound) / zone);
    } else if (mouseX > rightBound - zone && mouseX <= rightBound) {
      intensity.x = 1 - (rightBound - mouseX) / zone;
    }
    if (mouseY < topBound + zone && mouseY >= topBound) {
      intensity.y = -(1 - (mouseY - topBound) / zone);
    } else if (mouseY > bottomBound - zone && mouseY <= bottomBound) {
      intensity.y = 1 - (bottomBound - mouseY) / zone;
    }
    intensity.x = Math.max(-1, Math.min(1, intensity.x));
    intensity.y = Math.max(-1, Math.min(1, intensity.y));
    return intensity;
  };
  const performAutoScroll = () => {
    if (!state.dragging) {
      autoScrollFrameId = null;
      return;
    }
    const scrollContainer = getScrollContainer();
    const velocity = state.autoScrollVelocity;
    if (scrollContainer instanceof Window) {
      window.scrollBy(velocity.x, velocity.y);
    } else {
      scrollContainer.scrollLeft += velocity.x;
      scrollContainer.scrollTop += velocity.y;
    }
    setState(
      produce((s3) => {
        s3.autoScrollOffset.x += velocity.x;
        s3.autoScrollOffset.y += velocity.y;
        s3.sx = (s3.sx ?? 0) - velocity.x;
        s3.sy = (s3.sy ?? 0) - velocity.y;
      })
    );
    if (options2().onDrag) {
      const syntheticEvent = new MouseEvent("mousemove", {
        clientX: state.x,
        clientY: state.y,
        bubbles: true,
        cancelable: true
      });
      options2().onDrag(syntheticEvent, state);
    }
    options2().onAutoScroll?.(velocity);
    autoScrollFrameId = requestAnimationFrame(performAutoScroll);
  };
  const updateAutoScroll = (mouseX, mouseY) => {
    const config3 = getAutoScrollConfig();
    if (!config3.x && !config3.y) return;
    const scrollContainer = getScrollContainer();
    const zone = options2().autoScrollZone ?? 50;
    const speed = options2().autoScrollSpeed ?? 10;
    const acceleration = options2().autoScrollAcceleration ?? true;
    const zoneOffset = options2().autoScrollZoneOffset;
    let bounds;
    if (scrollContainer instanceof Window) {
      bounds = new DOMRect(0, 0, window.innerWidth, window.innerHeight);
    } else {
      if (!cachedScrollContainerBounds) {
        cachedScrollContainerBounds = scrollContainer.getBoundingClientRect();
      }
      bounds = cachedScrollContainerBounds;
    }
    const intensity = detectAutoScrollZone(
      mouseX,
      mouseY,
      bounds,
      zone,
      zoneOffset
    );
    const velocity = {
      x: config3.x ? intensity.x * speed * (acceleration ? Math.abs(intensity.x) : 1) : 0,
      y: config3.y ? intensity.y * speed * (acceleration ? Math.abs(intensity.y) : 1) : 0
    };
    const isScrolling = velocity.x !== 0 || velocity.y !== 0;
    setState(
      produce((s3) => {
        s3.autoScrolling = {
          x: config3.x && velocity.x !== 0,
          y: config3.y && velocity.y !== 0
        };
        s3.autoScrollVelocity = velocity;
      })
    );
    if (isScrolling && !autoScrollFrameId) {
      autoScrollFrameId = requestAnimationFrame(performAutoScroll);
    } else if (!isScrolling && autoScrollFrameId) {
      cancelAnimationFrame(autoScrollFrameId);
      autoScrollFrameId = null;
    }
  };
  const stopAutoScroll = () => {
    if (autoScrollFrameId) {
      cancelAnimationFrame(autoScrollFrameId);
      autoScrollFrameId = null;
    }
    setState(
      produce((s3) => {
        s3.autoScrolling = { x: false, y: false };
        s3.autoScrollVelocity = { x: 0, y: 0 };
        s3.autoScrollOffset = { x: 0, y: 0 };
      })
    );
  };
  createEventListener(target, "pointerdown", (e3) => {
    if (e3.button !== 0) return;
    const scrollContainer = getScrollContainer();
    if (!(scrollContainer instanceof Window)) {
      cachedScrollContainerBounds = scrollContainer.getBoundingClientRect();
    }
    setState(
      produce((s3) => {
        s3.sx = e3.clientX;
        s3.sy = e3.clientY;
        s3.px = 0;
        s3.py = 0;
        s3.x = 0;
        s3.y = 0;
      })
    );
    window.addEventListener("pointermove", handleDrag);
    window.addEventListener("pointerup", handleDragEnd2);
  });
  createEventListener(target, "pointerup", (e3) => {
    if (!state.dragging) {
      window.removeEventListener("pointermove", handleDrag);
      window.removeEventListener("pointerup", handleDragEnd2);
    }
  });
  const handleDrag = (e3) => {
    const [x3, y3] = [e3.clientX, e3.clientY];
    if (state.dragging) {
      setState(
        produce((s3) => {
          s3.px = s3.x;
          s3.py = s3.y;
          s3.x = x3;
          s3.y = y3;
        })
      );
      document.documentElement.style.cursor = options2()?.draggingCursor;
      options2()?.onDrag?.(e3, state);
      updateAutoScroll(x3, y3);
    } else {
      setState("dragging", true);
      options2()?.onDragStart?.(e3, state);
    }
  };
  const handleDragEnd2 = (e3) => {
    setState("dragging", false);
    document.documentElement.style.cursor = "auto";
    options2()?.onDragEnd?.(e3, state);
    stopAutoScroll();
    cachedScrollContainerBounds = null;
    window.removeEventListener("pointermove", handleDrag);
    window.removeEventListener("pointerup", handleDragEnd2);
  };
  createEffect((isDragging) => {
    return state.dragging;
  });
  onCleanup(() => {
    stopAutoScroll();
    window.removeEventListener("pointermove", handleDrag);
    window.removeEventListener("pointerup", handleDragEnd2);
  });
  return state;
}
function createDraggable(target, options2) {
  return draggable(target, options2);
}

// public/app/ui/base/drag/drag-to-scroll.ts
function useDragToScroll(viewport, options2) {
  const [state, setState] = createStore({
    focus: false,
    canScroll: false,
    dragging: false,
    initialScroll: {
      x: 0,
      y: 0
    }
  });
  const spaceBarPressed = useSpacebar({ preventDefault: false });
  const vp = () => typeof viewport === "function" ? viewport() : viewport;
  createEffect(() => {
    const _vp = vp();
    if (_vp) {
      _vp.tabIndex = -1;
    }
  });
  createEffect(() => {
    const shouldUseSpaceBar = options2()?.useSpacebar ?? false;
    const spaceBarIsPressed = spaceBarPressed();
    if (shouldUseSpaceBar) {
      setState("canScroll", spaceBarIsPressed);
    } else {
      setState("canScroll", true);
    }
  });
  createEventListener(
    () => vp(),
    "focusin",
    () => {
      setState("focus", true);
    }
  );
  createEventListener(
    () => vp(),
    "focusout",
    () => {
      setState("focus", false);
    }
  );
  createEventListener(
    () => vp(),
    "keydown",
    (e3) => {
      if (e3.key === " " && state.focus) {
        e3.preventDefault();
      }
    }
  );
  const leftProp = {
    axe: "x",
    scroll: "scrollLeft",
    total: "scrollWidth",
    client: "clientWidth"
  };
  const topProp = {
    axe: "y",
    scroll: "scrollTop",
    total: "scrollHeight",
    client: "clientHeight"
  };
  const useOneAxe = () => options2()?.axe ? true : false;
  const onDragStart = () => {
    setState(
      produce((s3) => {
        s3.initialScroll.x = vp().scrollLeft;
        s3.initialScroll.y = vp().scrollTop;
        s3.dragging = true;
      })
    );
  };
  const onDrag = (_5, drag) => {
    const target = vp();
    let properties = [];
    if (useOneAxe()) {
      properties.push(options2().axe === "x" ? leftProp : topProp);
    } else {
      properties.push(leftProp, topProp);
    }
    properties.forEach((prop2) => {
      const total = target[prop2.total];
      const client = target[prop2.client];
      const maxScroll = total - client;
      const current = drag[prop2.axe];
      const previous = drag[`p${prop2.axe}`] || drag[`s${prop2.axe}`];
      const delta = maxScroll > 0 ? previous - current : void 0;
      const scrollPos = maxScroll > 0 ? target[prop2.scroll] : void 0;
      const isScrollable = maxScroll > 0 && delta !== void 0 && scrollPos !== void 0 ? delta > 0 && scrollPos < maxScroll || delta < 0 && scrollPos > 0 : false;
      if (isScrollable && delta !== void 0 && scrollPos !== void 0) {
        target[prop2.scroll] = scrollPos + delta;
      }
    });
  };
  const onDragEnd = () => {
    setState("dragging", false);
  };
  draggable(
    () => state.canScroll ? vp() : [],
    () => ({
      container: vp,
      draggingCursor: "grabbing",
      onDragStart,
      onDrag,
      onDragEnd
    })
  );
  return createMemo(() => state.dragging);
}

// public/app/ui/base/color-picker.tsx
var _tmpl$9 = /* @__PURE__ */ template(`<div class="color-picker"><div class="horizontal-container recurrent-color"><button class="menu-colorpicker-color-button is-selected"><span><i class="fa fa-check"></i></span></button></div><div class="horizontal-container gradient-and-hexstring"><div class="gradient-and-hexstring__gradient"><div class="gradient__picker"></div></div><input class="gradient-and-hexstring__hexstring form-control" type="text" maxlength="7" minlength="7"></div><div class="horizontal-container draggable-picker"><div class="draggable-picker__area"><div class="area__picker"></div></div></div></div>`, 23);
var _tmpl$24 = /* @__PURE__ */ template(`<button class="menu-colorpicker-color-button"><span class="recurrent-color__span"></span></button>`, 4);
var _tmpl$32 = /* @__PURE__ */ template(`<div class="color-picker"><div class="horizontal-container gradient-and-hexstring"><input class="gradient-and-hexstring__hexstring form-control" type="text" maxlength="7" minlength="7" pattern="#[0-9a-fA-F]{6}"></div><div class="draggable-picker"></div></div>`, 7);
var _tmpl$42 = /* @__PURE__ */ template(`<div class="horizontal-container recurrent-color"><button class="menu-colorpicker-color-button is-selected"><span><i class="fa fa-check"></i></span></button></div>`, 8);
var _tmpl$52 = /* @__PURE__ */ template(`<div class="gradient__picker"></div>`, 2);
var _tmpl$62 = /* @__PURE__ */ template(`<div class="gradient-and-hexstring__gradient"></div>`, 2);
var _tmpl$72 = /* @__PURE__ */ template(`<div class="area__picker"></div>`, 2);
var _tmpl$82 = /* @__PURE__ */ template(`<div class="draggable-picker__area"></div>`, 2);
function ColorPicker(props2) {
  let gradientPickerEl, pureReactionTriggered = false, areaPickerEl, areaPickerOffset = 5;
  const [hslColor, setSignalHslColor] = createSignal({
    h: 150,
    s: 0.5,
    l: 0.5
  });
  const [gradientPickerPos, setSignalGradientPickerPos] = createSignal(0);
  const [gradientIsDragged, setSignalGradientIsDragged] = createSignal(false);
  const [areaPickerPos, setSignalAreaPickerPos] = createSignal({
    x: 50,
    y: 50
  });
  const [areaIsDragged, setSignalAreaIsDragged] = createSignal(false);
  const [recentColors, setStorageSignalRecentColors] = createStorageSignal("recentColors", [], {
    api: localStorage,
    serializer: (data2) => JSON.stringify(data2 || []),
    deserializer: (data2) => {
      if (data2 && data2 !== void 0 && data2.length > 1) return JSON.parse(data2 || []);
      return [];
    }
  });
  const defaultColors = createMemo(() => {
    return [...new Set(Array.from(props2.defaultColorPalette()).concat(recentColors() || []))];
  });
  function setColorAndOrderPalette(newColor) {
    setColorToPalette(`#${(0, import_tinycolor24.default)(hslColor()).toHex()}`, newColor);
    setColor(newColor);
    return false;
  }
  function setColorToPalette(colorToAdd, colorToPrevent = null) {
    if (!colorToAdd) return;
    setStorageSignalRecentColors((prev) => {
      const cleansedArray = prev.filter((prevColor) => {
        return prevColor !== colorToPrevent;
      });
      return [.../* @__PURE__ */ new Set([colorToAdd, ...cleansedArray])].slice(0, 5);
    });
  }
  onMount(() => {
    if (props2.defaultColor) {
      setColor(props2.defaultColor);
    }
  });
  createEffect(() => {
    let hex = hslColor() ? `#${(0, import_tinycolor24.default)(hslColor()).toHex()}` : null;
    if ((0, import_tinycolor24.default)(hex).isValid()) props2.onChange(hex);
    if (props2.defaultColor && !pureReactionTriggered && hex !== props2.defaultColor) {
      setColorToPalette(props2.defaultColor);
      pureReactionTriggered = true;
    }
  });
  function handleMouseMove(event2) {
    if (gradientIsDragged()) {
      setSignalGradientPickerPosIfSafe(event2);
    }
    if (areaIsDragged()) {
      setSignalAreaPickerPosIfSafe(event2);
    }
  }
  function handleMouseDown(positionCallback, draggedItemSetter, event2) {
    positionCallback(event2);
    draggedItemSetter(true);
  }
  function handleMouseUp() {
    setSignalGradientIsDragged(false);
    setSignalAreaIsDragged(false);
  }
  function updateColorPickerUi() {
    setSignalGradientPickerPosFromColor();
    setSignalAreaPickerPosFromColor();
  }
  function setColor(color) {
    const colorToSet = new import_tinycolor24.default(color.toString());
    if (!(0, import_tinycolor24.default)(colorToSet).isValid()) return;
    setSignalHslColor((0, import_tinycolor24.default)(colorToSet).toHsl());
    updateColorPickerUi();
  }
  function setSignalGradientPickerPosIfSafe(event2) {
    const bbox = gradientPickerEl.getBoundingClientRect();
    const layerX = event2.clientX - bbox.left, width = gradientPickerEl.offsetWidth;
    if (layerX <= width - 2 && layerX >= 0) {
      setSignalGradientPickerPos(layerX);
      let h3 = 359 * layerX / width | 0;
      let {
        s: s3,
        l: l3
      } = hslColor();
      setSignalHslColor({
        h: h3,
        s: s3,
        l: l3
      });
    }
  }
  function setSignalGradientPickerPosFromColor() {
    const {
      h: h3
    } = hslColor();
    let pos = h3 * gradientPickerEl.offsetWidth / 360 | 0;
    if (pos <= gradientPickerEl.offsetLeft) pos = gradientPickerEl.offsetLeft;
    if (pos >= gradientPickerEl.offsetWidth) pos = gradientPickerEl.offsetWidth;
    setSignalGradientPickerPos(pos);
  }
  function setSignalAreaPickerPosIfSafe(event2) {
    const {
      offsetWidth,
      offsetHeight
    } = areaPickerEl, bbox = gradientPickerEl.getBoundingClientRect();
    let x3 = event2.clientX - bbox.left, y3 = event2.clientY - bbox.top - gradientPickerEl.offsetHeight - areaPickerOffset * 3;
    if (x3 > offsetWidth) x3 = offsetWidth;
    if (y3 > offsetHeight) y3 = offsetHeight;
    if (x3 < 0) x3 = 0;
    if (y3 < 0) y3 = 0;
    setSignalAreaPickerPos({
      x: x3 - areaPickerOffset,
      y: y3 - areaPickerOffset
    });
    const l3 = 100 - x3 * 100 / offsetWidth | 0, s3 = y3 * 100 / offsetHeight | 0, {
      h: h3
    } = hslColor();
    setSignalHslColor({
      h: h3,
      s: s3 / 100,
      l: l3 / 100
    });
  }
  function setSignalAreaPickerPosFromColor() {
    let {
      offsetWidth,
      offsetHeight
    } = areaPickerEl;
    let {
      s: s3,
      l: l3
    } = (0, import_tinycolor24.default)(hslColor()).toHsl();
    let x3 = offsetWidth - l3 * 100 * offsetWidth / 100 | 0;
    let y3 = s3 * 100 * offsetHeight / 100 | 0;
    setSignalAreaPickerPos({
      x: x3 - areaPickerOffset,
      y: y3 - areaPickerOffset
    });
  }
  return (() => {
    const _el$ = _tmpl$9.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$2.nextSibling, _el$6 = _el$5.firstChild, _el$7 = _el$6.firstChild, _el$8 = _el$6.nextSibling, _el$9 = _el$5.nextSibling, _el$10 = _el$9.firstChild, _el$11 = _el$10.firstChild;
    _el$.$$mouseup = handleMouseUp;
    _el$.$$mousemove = handleMouseMove;
    insert(_el$2, createComponent(Index, {
      get each() {
        return defaultColors();
      },
      children: (color, i3) => (() => {
        const _el$12 = _tmpl$24.cloneNode(true), _el$13 = _el$12.firstChild;
        _el$12.$$click = () => setColorAndOrderPalette(color());
        createRenderEffect(() => _el$13.style.setProperty("background-color", `${color()}`));
        return _el$12;
      })()
    }), null);
    const _ref$ = gradientPickerEl;
    typeof _ref$ === "function" ? use(_ref$, _el$6) : gradientPickerEl = _el$6;
    _el$6.$$mousedown = (event2) => handleMouseDown(setSignalGradientPickerPosIfSafe, setSignalGradientIsDragged, event2);
    _el$8.$$input = (e3) => setColor(e3.target.value);
    const _ref$2 = areaPickerEl;
    typeof _ref$2 === "function" ? use(_ref$2, _el$10) : areaPickerEl = _el$10;
    _el$10.$$mousedown = (event2) => handleMouseDown(setSignalAreaPickerPosIfSafe, setSignalAreaIsDragged, event2);
    createRenderEffect((_p$) => {
      const _v$ = `${(0, import_tinycolor24.default)(hslColor()).toHslString()}`, _v$2 = `${gradientPickerPos()}px`, _v$3 = `hsl(${hslColor().h},50%, 50%)`, _v$4 = `${areaPickerPos().x}px`, _v$5 = `${areaPickerPos().y}px`;
      _v$ !== _p$._v$ && _el$4.style.setProperty("background-color", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$7.style.setProperty("left", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$10.style.setProperty("background-color", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$11.style.setProperty("left", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$11.style.setProperty("top", _p$._v$5 = _v$5);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0
    });
    createRenderEffect(() => _el$8.value = (0, import_tinycolor24.default)(hslColor()).toHexString());
    return _el$;
  })();
}
function xToL(x3, width) {
  return 100 - x3 * 100 / width | 0;
}
function yToS(y3, height) {
  return y3 * 100 / height | 0;
}
function lToX(l3, width) {
  return width - l3 * 100 * width / 100 | 0;
}
function sToY(s3, height) {
  return s3 * 100 * height / 100 | 0;
}
function hToX(h3, width) {
  return h3 * width / 360 | 0;
}
function xToH(x3, width) {
  return x3 * 360 / width | 0;
}
var ColorPickerContext = createContext();
function useColorPicker() {
  return useContext(ColorPickerContext);
}
function ColorPicker2(props2) {
  const [state, setState] = createStore({
    color: props2.initialColor,
    changeSource: void 0
  });
  const updateColor = (color, source) => {
    setState(produce((draft) => {
      draft.color = color;
      draft.changeSource = source;
    }));
  };
  createEffect(on(() => state.color, (color) => {
    props2.onChange?.(color);
  }, {
    defer: true
  }));
  createEffect(on(() => props2.initialColor, (color, prevColor) => {
    if (color !== prevColor) {
      updateColor(color, void 0);
    }
  }));
  return createComponent(ColorPickerContext.Provider, {
    value: state,
    get children() {
      const _el$14 = _tmpl$32.cloneNode(true), _el$15 = _el$14.firstChild, _el$16 = _el$15.firstChild, _el$17 = _el$15.nextSibling;
      insert(_el$14, createComponent(RecentColors, {
        onSelectColor: (color) => updateColor(color, "recents"),
        get defaultColorPalette() {
          return props2.defaultColorPalette;
        },
        get disabled() {
          return props2.disabled;
        }
      }), _el$15);
      insert(_el$15, createComponent(HorizontalGradientPicker, {
        get disabled() {
          return props2.disabled;
        },
        onChange: (color) => updateColor(color, "gradient")
      }), _el$16);
      _el$16.$$input = (e3) => {
        const inputColor = (0, import_tinycolor24.default)(e3.target.value);
        if (inputColor.isValid()) {
          updateColor(inputColor.toHexString(), void 0);
        }
      };
      _el$17.style.setProperty("height", "70px");
      _el$17.style.setProperty("width", "384px");
      insert(_el$17, createComponent(AreaPicker, {
        get disabled() {
          return props2.disabled;
        },
        onChange: (color) => updateColor(color, "area")
      }));
      createRenderEffect(() => _el$16.disabled = props2.disabled);
      createRenderEffect(() => _el$16.value = (0, import_tinycolor24.default)(state.color).toHexString());
      return _el$14;
    }
  });
}
function RecentColors(props2) {
  const [recentColors, setRecentColors] = makePersisted(createSignal([]), {
    name: "recentColors",
    deserialize: (data2) => {
      if (data2 && data2 !== void 0 && data2.length > 1) return JSON.parse(data2 || []);
      return [];
    }
  });
  const pickerState = useColorPicker();
  const defaultColors = createMemo(() => {
    return [...new Set(Array.from(props2.defaultColorPalette()).concat(recentColors() || []))];
  });
  const updateRecentColors = (colorToAdd, colorToPrevent = null) => {
    if (!colorToAdd) return;
    setRecentColors((prev) => {
      const cleansedArray = prev.filter((prevColor) => {
        return prevColor !== colorToPrevent;
      });
      return [.../* @__PURE__ */ new Set([colorToAdd, ...cleansedArray])].slice(0, 5);
    });
  };
  const onSelectColor = (color) => {
    props2.onSelectColor(color);
  };
  createEffect(on(() => [pickerState.color, pickerState.changeSource], ([color, source], prevInput) => {
    if (!prevInput || !prevInput[0]) return;
    if (source === "recents") {
      updateRecentColors(prevInput[0], color);
    }
  }, {
    defer: true
  }));
  return (() => {
    const _el$18 = _tmpl$42.cloneNode(true), _el$19 = _el$18.firstChild, _el$20 = _el$19.firstChild;
    insert(_el$18, createComponent(Index, {
      get each() {
        return defaultColors();
      },
      children: (color, i3) => (() => {
        const _el$21 = _tmpl$24.cloneNode(true), _el$22 = _el$21.firstChild;
        _el$21.$$click = () => onSelectColor(color());
        createRenderEffect((_p$) => {
          const _v$8 = props2.disabled, _v$9 = `${color()}`;
          _v$8 !== _p$._v$8 && (_el$21.disabled = _p$._v$8 = _v$8);
          _v$9 !== _p$._v$9 && _el$22.style.setProperty("background-color", _p$._v$9 = _v$9);
          return _p$;
        }, {
          _v$8: void 0,
          _v$9: void 0
        });
        return _el$21;
      })()
    }), null);
    createRenderEffect((_p$) => {
      const _v$6 = props2.disabled, _v$7 = `${(0, import_tinycolor24.default)(pickerState.color).toHslString()}`;
      _v$6 !== _p$._v$6 && (_el$19.disabled = _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$20.style.setProperty("background-color", _p$._v$7 = _v$7);
      return _p$;
    }, {
      _v$6: void 0,
      _v$7: void 0
    });
    return _el$18;
  })();
}
function HorizontalGradientPicker(props2) {
  let ref;
  const pickerState = useColorPicker();
  const [state, setState] = createStore({
    x: 0
  });
  const h3 = createMemo(() => (0, import_tinycolor24.default)(pickerState.color).toHsl().h | 0);
  onMount(() => {
    setTimeout(() => {
      const {
        offsetWidth
      } = ref;
      if (pickerState.color) {
        setState({
          x: hToX(h3(), offsetWidth)
        });
      }
    });
  });
  createEffect(on(() => [pickerState.color, pickerState.changeSource], ([, source]) => {
    if (source !== void 0) return;
    const {
      offsetWidth
    } = ref;
    setState({
      x: hToX(h3(), offsetWidth)
    });
  }));
  const bbox = () => ref?.getBoundingClientRect();
  createDraggable(() => props2.disabled ? null : ref, () => ({
    onDragStart: (e3) => onColorChange({
      x: e3.clientX
    }),
    onDrag: (e3) => onColorChange({
      x: e3.clientX
    }),
    onDragEnd: (e3) => {
      onColorChange({
        x: e3.clientX
      });
    }
  }));
  const onColorChange = (position) => {
    if (props2.disabled) return;
    const box = bbox();
    const x3 = Math.max(0, Math.min(position.x - (box?.left ?? 0), ref.offsetWidth));
    const _h = xToH(x3, ref.offsetWidth);
    setState({
      x: x3
    });
    const {
      s: s3,
      l: l3
    } = (0, import_tinycolor24.default)(pickerState.color).toHsl();
    props2.onChange?.((0, import_tinycolor24.default)({
      h: _h,
      s: s3,
      l: l3
    }).toHexString());
  };
  return (() => {
    const _el$23 = _tmpl$62.cloneNode(true);
    _el$23.$$mousedown = (e3) => onColorChange({
      x: e3.clientX
    });
    const _ref$3 = ref;
    typeof _ref$3 === "function" ? use(_ref$3, _el$23) : ref = _el$23;
    insert(_el$23, createComponent(Show, {
      get when() {
        return !props2.disabled || !pickerState.color;
      },
      get children() {
        const _el$24 = _tmpl$52.cloneNode(true);
        createRenderEffect(() => _el$24.style.setProperty("left", `${state.x}px`));
        return _el$24;
      }
    }));
    createRenderEffect(() => _el$23.classList.toggle("disabled", !!props2.disabled));
    return _el$23;
  })();
}
function AreaPicker(props2) {
  let ref;
  const pickerState = useColorPicker();
  const hslColor = () => (0, import_tinycolor24.default)(pickerState.color).toHsl();
  const [state, setState] = createStore({
    h: 0,
    x: 0,
    y: 0,
    dark: false
  });
  const computePosition = (state2) => {
    const box = bbox();
    const x3 = Math.round(Math.max(0, Math.min(state2.x - (box?.left ?? 0), box?.width ?? 0)));
    const y3 = Math.round(Math.max(0, Math.min(state2.y - (box?.top ?? 0), box?.height ?? 0)));
    return {
      x: x3,
      y: y3
    };
  };
  const computedColor = (position) => {
    const hsl = hslColor();
    if (!ref) return (0, import_tinycolor24.default)({
      ...hsl,
      h: state.h
    });
    const l3 = xToL(position.x, ref.offsetWidth), s3 = yToS(position.y, ref.offsetHeight), h3 = state.h;
    return (0, import_tinycolor24.default)({
      h: h3,
      s: s3 / 100,
      l: l3 / 100
    });
  };
  const onColorChange = (s3) => {
    if (props2.disabled) return;
    const pos = computePosition({
      x: s3.x,
      y: s3.y
    });
    const color = computedColor(pos);
    setState({
      ...pos,
      dark: color.isDark()
    });
    props2.onChange?.(color.toHexString());
  };
  const bbox = () => ref?.getBoundingClientRect();
  const onColorInputChange = (color) => {
    const tcolor = (0, import_tinycolor24.default)(color);
    const {
      h: h3,
      s: s3,
      l: l3
    } = tcolor.toHsl();
    const x3 = lToX(l3, ref.offsetWidth);
    const y3 = sToY(s3, ref.offsetHeight);
    setState({
      h: h3,
      x: x3,
      y: y3,
      dark: tcolor.isDark()
    });
  };
  onMount(() => {
    if (pickerState.color) {
      setTimeout(() => {
        onColorInputChange(pickerState.color);
      });
    }
  });
  createEffect(on(() => [pickerState.color, pickerState.changeSource], ([color, source]) => {
    if (source == "area") return;
    onColorInputChange(color);
  }));
  createDraggable(() => props2.disabled ? null : ref, () => ({
    onDragStart: (e3) => onColorChange({
      x: e3.clientX,
      y: e3.clientY
    }),
    onDrag: (e3) => onColorChange({
      x: e3.clientX,
      y: e3.clientY
    }),
    onDragEnd: (e3) => {
      onColorChange({
        x: e3.clientX,
        y: e3.clientY
      });
    }
  }));
  return (() => {
    const _el$25 = _tmpl$82.cloneNode(true);
    _el$25.$$mousedown = (e3) => {
      onColorChange({
        x: e3.clientX,
        y: e3.clientY
      });
    };
    const _ref$4 = ref;
    typeof _ref$4 === "function" ? use(_ref$4, _el$25) : ref = _el$25;
    insert(_el$25, createComponent(Show, {
      get when() {
        return !props2.disabled || !pickerState.color;
      },
      get children() {
        const _el$26 = _tmpl$72.cloneNode(true);
        createRenderEffect((_p$) => {
          const _v$10 = `${state.x}px`, _v$11 = `${state.y}px`, _v$12 = `${state.dark ? 0 : 1}`;
          _v$10 !== _p$._v$10 && _el$26.style.setProperty("left", _p$._v$10 = _v$10);
          _v$11 !== _p$._v$11 && _el$26.style.setProperty("top", _p$._v$11 = _v$11);
          _v$12 !== _p$._v$12 && _el$26.style.setProperty("--area-picker-invert", _p$._v$12 = _v$12);
          return _p$;
        }, {
          _v$10: void 0,
          _v$11: void 0,
          _v$12: void 0
        });
        return _el$26;
      }
    }));
    createRenderEffect((_p$) => {
      const _v$13 = !!props2.disabled, _v$14 = state.h;
      _v$13 !== _p$._v$13 && _el$25.classList.toggle("disabled", _p$._v$13 = _v$13);
      _v$14 !== _p$._v$14 && _el$25.style.setProperty("--area-picker-h", _p$._v$14 = _v$14);
      return _p$;
    }, {
      _v$13: void 0,
      _v$14: void 0
    });
    return _el$25;
  })();
}
delegateEvents(["mousemove", "mouseup", "mousedown", "input", "click"]);

// virtual-ns:sweetalert2
var sweetalert2_default = swal;

// public/app/ui/base/dialogs.js
sweetalert2_default.setDefaults({
  reverseButtons: true,
  background: null,
  confirmButtonColor: "#DD6B55"
});
function dialog(opts) {
  return sweetalert2_default(opts);
}
function yesNoDialog(opts) {
  return new Promise((resolve2, reject2) => {
    sweetalert2_default(Object.assign({
      type: "info",
      closeOnConfirm: true,
      showCancelButton: true,
      cancelButtonText: _4("No"),
      confirmButtonColor: "#288628",
      confirmButtonText: _4("Yes")
    }, opts)).then((isConfirm) => {
      if (isConfirm === true) {
        resolve2();
      } else {
        reject2();
      }
    });
  });
}
function confirmDialog(opts) {
  return new Promise((resolve2, reject2) => {
    sweetalert2_default(Object.assign({
      type: "warning",
      title: _4("Are you sure?"),
      closeOnConfirm: true,
      showCancelButton: true,
      cancelButtonText: _4("Cancel"),
      confirmButtonColor: "#288628",
      confirmButtonText: _4("Confirm")
    }, opts)).then((isConfirm) => {
      if (isConfirm === true) {
        resolve2();
      } else {
        reject2();
      }
    });
  });
}
function confirmDeleteDialog2(title, subtitle, btnLabel) {
  return confirmDialog({
    title: title || _4("Are you sure?"),
    text: subtitle,
    confirmButtonText: btnLabel || _4("Delete")
  });
}
function inputDialog(message, options2) {
  options2 = options2 || {};
  if (options2.required) {
    options2.inputValidator = (value2) => {
      if (!value2) {
        return Promise.reject(_4("You need to write something!"));
      }
      return Promise.resolve(value2);
    };
  }
  return sweetalert2_default(Object.assign({
    title: message,
    input: "text",
    showCancelButton: true,
    cancelButtonText: _4("Cancel")
  }, options2 || {})).then((value2) => {
    if (options2.required && !value2) {
      return Promise.reject();
    }
    return value2;
  });
}
function infoDialog(message, title) {
  return sweetalert2_default({
    title: title ? title : message,
    html: title ? message : null,
    type: "info"
  });
}
function successDialog(message, title) {
  return sweetalert2_default({
    title: title ? title : message,
    text: title ? message : null,
    type: "success"
  });
}
function errorDialog(message, title) {
  if (!message) {
    message = _4("An error occured");
  }
  return sweetalert2_default({
    title: title ? title : message,
    text: title ? message : null,
    type: "error"
  });
}
function requestErrorDialog() {
  return errorDialog(
    _4("Something went wrong while handling a request, please reload the page"),
    _4("An error occured")
  );
}
function catchAsRequestErrorDialog(errorHandlerCallback, resolvePromise = false) {
  return function(resp) {
    if (!errorHandlerCallback || !errorHandlerCallback(resp)) {
      requestErrorDialog();
    }
    return resolvePromise ? Promise.resolve(resp) : Promise.reject(resp);
  };
}
function autoCatchAsRequestErrorDialog(httpCodes, resolvePromise = false) {
  return function(resp) {
    if (resp && httpCodes.includes(resp.status)) {
      resp.json().then((data2) => {
        errorDialog(_4(data2.error));
      }).catch(() => {
        requestErrorDialog();
      });
    } else {
      requestErrorDialog();
    }
    return resolvePromise ? Promise.resolve(resp) : Promise.reject(resp);
  };
}

// public/app/config/help-urls.js
var helpSiteUrls = {
  "en": {
    "help": "https://kantree.io/help",
    "get_started": "https://kantree.io/help/guides/get-started",
    "guides": "https://kantree.io/help/guides",
    "faq": "https://kantree.io/help/faq",
    "blog": "https://kantree.io/blog/features",
    "search": "https://kantree.io/help/search",
    "demo": "http://rdv.digicoop.io/team/kantree-demo/en",
    "sales": "http://rdv.digicoop.io/team/booking/call",
    "community": "https://community.kantree.io/"
  },
  "fr": {
    "help": "https://kantree.io/fr/aide",
    "get_started": "https://kantree.io/fr/aide/guides/demarrage-rapide",
    "guides": "https://kantree.io/fr/aide/guides",
    "faq": "https://kantree.io/fr/aide/faq",
    "blog": "https://kantree.io/fr/blog/produit",
    "search": "https://kantree.io/fr/aide/search",
    "demo": "http://rdv.digicoop.io/team/demo-kantree/fr",
    "sales": "http://rdv.digicoop.io/team/rendez-vous/question",
    "community": "https://community.kantree.io/"
  }
};

// public/app/utils/help-urls.js
function getLocalizedUrls() {
  if (helpSiteUrls[getCurrentLocale()]) {
    return helpSiteUrls[getCurrentLocale()];
  }
  return helpSiteUrls["en"];
}
function getLocalizedUrl(key2) {
  const urls = getLocalizedUrls();
  if (urls[key2]) {
    return urls[key2];
  }
  return helpSiteUrls["en"][key2];
}
function getLocalizedConfigLink(value2) {
  if (isObject2(value2)) {
    if (value2[getCurrentLocale()]) {
      return value2[getCurrentLocale()];
    }
    return value2["en"];
  }
  return value2;
}
function getHelpSiteUrl(key2 = "get_started") {
  if (serverConfig.help_site_url) {
    return getLocalizedConfigLink(serverConfig.help_site_url);
  }
  return getLocalizedUrls()[key2];
}
function getTicketUrl() {
  if (serverConfig.help_ticket_url) {
    return getLocalizedConfigLink(serverConfig.help_ticket_url);
  }
}

// public/app/ui/base/helplink.tsx
var _tmpl$10 = /* @__PURE__ */ template(`<a target="_blank" class="help-link"></a>`, 2);
function HelpLink(props2) {
  const href = () => {
    const baseGuideUrl = getLocalizedUrl("guides");
    return baseGuideUrl + "/" + props2.guide + (props2.anchor ? "#" + props2.anchor : "");
  };
  return (() => {
    const _el$ = _tmpl$10.cloneNode(true);
    insert(_el$, () => props2.children);
    createRenderEffect((_p$) => {
      const _v$ = href(), _v$2 = _4("Help");
      _v$ !== _p$._v$ && setAttribute(_el$, "href", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && setAttribute(_el$, "aria-label", _p$._v$2 = _v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$;
  })();
}

// public/app/ui/base/layout.tsx
var _tmpl$11 = /* @__PURE__ */ template(`<div class="page-container"></div>`, 2);
var _tmpl$25 = /* @__PURE__ */ template(`<div class="page-container-view"></div>`, 2);
function PageContainer(props2) {
  const [local, others] = splitProps(props2, ["children"]);
  return (() => {
    const _el$ = _tmpl$11.cloneNode(true);
    spread(_el$, others, false, true);
    insert(_el$, () => local.children);
    return _el$;
  })();
}
function PageContainerView(props2) {
  const [local, others] = splitProps(props2, ["children"]);
  return (() => {
    const _el$2 = _tmpl$25.cloneNode(true);
    spread(_el$2, others, false, true);
    insert(_el$2, () => local.children);
    return _el$2;
  })();
}
function Box(props2) {
  const [local, others] = splitProps(props2, ["as"]);
  return createComponent(Dynamic, mergeProps({
    get component() {
      return local.as ?? "div";
    }
  }, others));
}
function HStack(props2) {
  const [local, others] = splitProps(props2, ["class"]);
  return createComponent(Box, mergeProps({
    get ["class"]() {
      return classNames("h-stack", local.class);
    }
  }, others));
}
function VStack(props2) {
  const [local, others] = splitProps(props2, ["class"]);
  return createComponent(Box, mergeProps({
    get ["class"]() {
      return classNames("v-stack", local.class);
    }
  }, others));
}

// public/app/ui/utils/ng-component.jsx
var _tmpl$12 = /* @__PURE__ */ template(`<div></div>`, 2);
function NgComponent(props2) {
  const [local, others] = splitProps(props2, ["directive"]);
  let div, mounted = false, el2, scope;
  const excludedKeys = ["class", "id", "className"];
  const solidOwner = getOwner();
  createEffect(() => {
    if (!isBootstraped()) {
      return;
    }
    untrack(() => {
      const $rootScope = ngApp.$injector.get("$rootScope");
      const $compile = ngApp.$injector.get("$compile");
      scope = $rootScope.$new(true);
      scope.$solidOwner = solidOwner;
      let html5 = "<" + local.directive;
      for (const key2 of Object.keys(others)) {
        let value2 = key2;
        if (excludedKeys.includes(key2)) {
          value2 = others[key2];
        } else {
          scope[key2] = others[key2];
        }
        if (isFunction_default(others[key2])) {
          const annotations = ngApp.$injector.annotate(others[key2]);
          value2 = `${key2}(${annotations.join(", ")})`;
        }
        html5 += ` ${denormalized(key2)}="${value2}"`;
      }
      html5 += `></${local.directive.split(" ")[0]}>`;
      el2 = $compile(html5)(scope);
      div.replaceWith(el2[0]);
      mounted = true;
    });
  });
  createEffect(() => {
    for (const key2 of Object.keys(others)) {
      scope[key2] = others[key2];
    }
    if (mounted) {
      scope.$applyAsync();
    }
  });
  onCleanup(() => {
    if (scope) {
      scope.$destroy();
    }
    if (el2) {
      el2.remove();
    }
  });
  return (() => {
    const _el$ = _tmpl$12.cloneNode(true);
    const _ref$ = div;
    typeof _ref$ === "function" ? use(_ref$, _el$) : div = _el$;
    return _el$;
  })();
}
function denormalized(attr) {
  return attr.replace(/[A-Z]/g, (c3) => "-" + c3.toLowerCase());
}

// public/app/ui/base/menu.tsx
var _tmpl$13 = /* @__PURE__ */ template(`<li></li>`, 2);
function PrettyMenu(props2) {
  const [local, others] = splitProps(props2, ["class"]);
  return createComponent(NgComponent, mergeProps({
    directive: "pretty-menu",
    get ["class"]() {
      return classNames("pretty-menu", local.class);
    }
  }, others));
}
function Menu(props2) {
  const [local, others] = splitProps(props2, ["children", "as", "each", "fallback"]);
  return createComponent(Box, mergeProps({
    as: "menu"
  }, others, {
    get children() {
      return createComponent(For, {
        get each() {
          return local.each;
        },
        get fallback() {
          return local.fallback;
        },
        children: (item, i3) => (() => {
          const _el$ = _tmpl$13.cloneNode(true);
          insert(_el$, () => local.children(item, i3));
          return _el$;
        })()
      });
    }
  }));
}

// public/app/ui/base/modal.jsx
var _tmpl$14 = /* @__PURE__ */ template(`<div></div>`, 2);
var _tmpl$26 = /* @__PURE__ */ template(`<h3 class="modal-title"></h3>`, 2);
var ModalContext = createContext();
function ModalProvider(props2) {
  const instance = {
    close: props2.close
  };
  return createComponent(ModalContext.Provider, {
    value: instance,
    get children() {
      return props2.children;
    }
  });
}
function useModal() {
  return useContext(ModalContext);
}
function openModal(Component, options2 = {}) {
  const ModalComponent = (props2) => {
    return createComponent(ModalProvider, {
      close: () => props2.close(),
      get children() {
        return createComponent(Component, {});
      }
    });
  };
  return ngApp.$injector.get("$uibModal").open({
    ...options2,
    template: `<solidjs-component component="$ctrl.ModalComponent" close="$ctrl.$uibModalInstance.close"></solidjs-component>`,
    controllerAs: "$ctrl",
    bindToController: true,
    controller: ["$uibModalInstance", function($uibModalInstance) {
      this.$uibModalInstance = $uibModalInstance;
      this.ModalComponent = ModalComponent;
    }]
  }).result;
}
function Modal(props2) {
  return (() => {
    const _el$ = _tmpl$14.cloneNode(true);
    insert(_el$, () => props2.children);
    return _el$;
  })();
}
function ModalHeader(props2) {
  const modal = useModal();
  return (() => {
    const _el$2 = _tmpl$14.cloneNode(true);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props2.title;
      },
      get children() {
        const _el$3 = _tmpl$26.cloneNode(true);
        insert(_el$3, () => props2.title);
        return _el$3;
      }
    }), null);
    insert(_el$2, () => props2.children, null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return !props2.hideClose;
      },
      get children() {
        return createComponent(Button, {
          style: "close",
          onClick: () => modal.close()
        });
      }
    }), null);
    createRenderEffect(() => className(_el$2, classNames("modal-header", props2.class)));
    return _el$2;
  })();
}
function ModalBody(props2) {
  const [local, other] = splitProps(props2, ["class", "children"]);
  return createComponent(VStack, mergeProps({
    get ["class"]() {
      return classNames("modal-body", local.class);
    }
  }, other, {
    get children() {
      return local.children;
    }
  }));
}
function ModalFooter(props2) {
  return createComponent(HStack, {
    get ["class"]() {
      return classNames("modal-footer", props2.class);
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/ui/base/panel.jsx
var _tmpl$15 = /* @__PURE__ */ template(`<div class="panel-body"></div>`, 2);
var _tmpl$27 = /* @__PURE__ */ template(`<div class="panel"></div>`, 2);
function Panel(props2) {
  props2 = mergeProps({
    withBody: true,
    headerTag: "div"
  }, props2);
  const [local, others] = splitProps(props2, ["children", "header", "withBody", "headerTag"]);
  let resolved = children(() => local.children);
  if (local.withBody) resolved = (() => {
    const _el$ = _tmpl$15.cloneNode(true);
    insert(_el$, resolved);
    return _el$;
  })();
  return (() => {
    const _el$2 = _tmpl$27.cloneNode(true);
    insert(_el$2, createComponent(Dynamic, {
      get component() {
        return local.headerTag;
      },
      "class": "panel-heading",
      get children() {
        return local.header;
      }
    }), null);
    insert(_el$2, resolved, null);
    return _el$2;
  })();
}

// node_modules/core-js/modules/es.object.to-string.js
var TO_STRING_TAG_SUPPORT = require_to_string_tag_support();
var defineBuiltIn = require_define_built_in();
var toString2 = require_object_to_string();
if (!TO_STRING_TAG_SUPPORT) {
  defineBuiltIn(Object.prototype, "toString", toString2, { unsafe: true });
}

// node_modules/core-js/modules/web.dom-collections.for-each.js
var global2 = require_global();
var DOMIterables = require_dom_iterables();
var DOMTokenListPrototype = require_dom_token_list_prototype();
var forEach = require_array_for_each();
var createNonEnumerableProperty = require_create_non_enumerable_property();
var handlePrototype = function(CollectionPrototype) {
  if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {
    createNonEnumerableProperty(CollectionPrototype, "forEach", forEach);
  } catch (error2) {
    CollectionPrototype.forEach = forEach;
  }
};
for (COLLECTION_NAME in DOMIterables) {
  if (DOMIterables[COLLECTION_NAME]) {
    handlePrototype(global2[COLLECTION_NAME] && global2[COLLECTION_NAME].prototype);
  }
}
var COLLECTION_NAME;
handlePrototype(DOMTokenListPrototype);

// node_modules/simplebar/dist/simplebar.esm.js
var import_can_use_dom = __toESM(require_can_use_dom());

// node_modules/core-js/modules/es.parse-int.js
var $2 = require_export();
var $parseInt = require_number_parse_int();
$2({ global: true, forced: parseInt != $parseInt }, {
  parseInt: $parseInt
});

// node_modules/core-js/modules/es.object.assign.js
var $3 = require_export();
var assign2 = require_object_assign();
$3({ target: "Object", stat: true, arity: 2, forced: Object.assign !== assign2 }, {
  assign: assign2
});

// node_modules/core-js/modules/es.array.filter.js
var $4 = require_export();
var $filter = require_array_iteration().filter;
var arrayMethodHasSpeciesSupport = require_array_method_has_species_support();
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport("filter");
$4({ target: "Array", proto: true, forced: !HAS_SPECIES_SUPPORT }, {
  filter: function filter3(callbackfn) {
    return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : void 0);
  }
});

// node_modules/simplebar/dist/simplebar.esm.js
var import_es_array_iterator = __toESM(require_es_array_iterator());

// node_modules/core-js/modules/es.string.iterator.js
var charAt = require_string_multibyte().charAt;
var toString3 = require_to_string();
var InternalStateModule = require_internal_state();
var defineIterator = require_iterator_define();
var createIterResultObject = require_create_iter_result_object();
var STRING_ITERATOR = "String Iterator";
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
defineIterator(String, "String", function(iterated) {
  setInternalState(this, {
    type: STRING_ITERATOR,
    string: toString3(iterated),
    index: 0
  });
}, function next() {
  var state = getInternalState(this);
  var string3 = state.string;
  var index2 = state.index;
  var point;
  if (index2 >= string3.length) return createIterResultObject(void 0, true);
  point = charAt(string3, index2);
  state.index += point.length;
  return createIterResultObject(point, false);
});

// node_modules/core-js/modules/es.weak-map.js
require_es_weak_map_constructor();

// node_modules/core-js/modules/web.dom-collections.iterator.js
var global3 = require_global();
var DOMIterables2 = require_dom_iterables();
var DOMTokenListPrototype2 = require_dom_token_list_prototype();
var ArrayIteratorMethods = require_es_array_iterator();
var createNonEnumerableProperty2 = require_create_non_enumerable_property();
var wellKnownSymbol = require_well_known_symbol();
var ITERATOR = wellKnownSymbol("iterator");
var TO_STRING_TAG = wellKnownSymbol("toStringTag");
var ArrayValues = ArrayIteratorMethods.values;
var handlePrototype2 = function(CollectionPrototype, COLLECTION_NAME) {
  if (CollectionPrototype) {
    if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
      createNonEnumerableProperty2(CollectionPrototype, ITERATOR, ArrayValues);
    } catch (error2) {
      CollectionPrototype[ITERATOR] = ArrayValues;
    }
    if (!CollectionPrototype[TO_STRING_TAG]) {
      createNonEnumerableProperty2(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
    }
    if (DOMIterables2[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
      if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
        createNonEnumerableProperty2(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
      } catch (error2) {
        CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
      }
    }
  }
};
for (COLLECTION_NAME in DOMIterables2) {
  handlePrototype2(global3[COLLECTION_NAME] && global3[COLLECTION_NAME].prototype, COLLECTION_NAME);
}
var COLLECTION_NAME;
handlePrototype2(DOMTokenListPrototype2, "DOMTokenList");

// node_modules/simplebar/dist/simplebar.esm.js
var import_lodash = __toESM(require_lodash());
var import_lodash2 = __toESM(require_lodash2());
var import_lodash3 = __toESM(require_lodash3());

// node_modules/@juggle/resize-observer/lib/utils/resizeObservers.js
var resizeObservers = [];

// node_modules/@juggle/resize-observer/lib/algorithms/hasActiveObservations.js
var hasActiveObservations = function() {
  return resizeObservers.some(function(ro) {
    return ro.activeTargets.length > 0;
  });
};

// node_modules/@juggle/resize-observer/lib/algorithms/hasSkippedObservations.js
var hasSkippedObservations = function() {
  return resizeObservers.some(function(ro) {
    return ro.skippedTargets.length > 0;
  });
};

// node_modules/@juggle/resize-observer/lib/algorithms/deliverResizeLoopError.js
var msg = "ResizeObserver loop completed with undelivered notifications.";
var deliverResizeLoopError = function() {
  var event2;
  if (typeof ErrorEvent === "function") {
    event2 = new ErrorEvent("error", {
      message: msg
    });
  } else {
    event2 = document.createEvent("Event");
    event2.initEvent("error", false, false);
    event2.message = msg;
  }
  window.dispatchEvent(event2);
};

// node_modules/@juggle/resize-observer/lib/ResizeObserverBoxOptions.js
var ResizeObserverBoxOptions;
(function(ResizeObserverBoxOptions2) {
  ResizeObserverBoxOptions2["BORDER_BOX"] = "border-box";
  ResizeObserverBoxOptions2["CONTENT_BOX"] = "content-box";
  ResizeObserverBoxOptions2["DEVICE_PIXEL_CONTENT_BOX"] = "device-pixel-content-box";
})(ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {}));

// node_modules/@juggle/resize-observer/lib/utils/freeze.js
var freeze = function(obj) {
  return Object.freeze(obj);
};

// node_modules/@juggle/resize-observer/lib/ResizeObserverSize.js
var ResizeObserverSize = /* @__PURE__ */ function() {
  function ResizeObserverSize2(inlineSize, blockSize) {
    this.inlineSize = inlineSize;
    this.blockSize = blockSize;
    freeze(this);
  }
  return ResizeObserverSize2;
}();

// node_modules/@juggle/resize-observer/lib/DOMRectReadOnly.js
var DOMRectReadOnly = function() {
  function DOMRectReadOnly2(x3, y3, width, height) {
    this.x = x3;
    this.y = y3;
    this.width = width;
    this.height = height;
    this.top = this.y;
    this.left = this.x;
    this.bottom = this.top + this.height;
    this.right = this.left + this.width;
    return freeze(this);
  }
  DOMRectReadOnly2.prototype.toJSON = function() {
    var _a4 = this, x3 = _a4.x, y3 = _a4.y, top2 = _a4.top, right = _a4.right, bottom = _a4.bottom, left = _a4.left, width = _a4.width, height = _a4.height;
    return { x: x3, y: y3, top: top2, right, bottom, left, width, height };
  };
  DOMRectReadOnly2.fromRect = function(rectangle) {
    return new DOMRectReadOnly2(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
  };
  return DOMRectReadOnly2;
}();

// node_modules/@juggle/resize-observer/lib/utils/element.js
var isSVG = function(target) {
  return target instanceof SVGElement && "getBBox" in target;
};
var isHidden = function(target) {
  if (isSVG(target)) {
    var _a4 = target.getBBox(), width = _a4.width, height = _a4.height;
    return !width && !height;
  }
  var _b = target, offsetWidth = _b.offsetWidth, offsetHeight = _b.offsetHeight;
  return !(offsetWidth || offsetHeight || target.getClientRects().length);
};
var isElement2 = function(obj) {
  var _a4;
  if (obj instanceof Element) {
    return true;
  }
  var scope = (_a4 = obj === null || obj === void 0 ? void 0 : obj.ownerDocument) === null || _a4 === void 0 ? void 0 : _a4.defaultView;
  return !!(scope && obj instanceof scope.Element);
};
var isReplacedElement = function(target) {
  switch (target.tagName) {
    case "INPUT":
      if (target.type !== "image") {
        break;
      }
    case "VIDEO":
    case "AUDIO":
    case "EMBED":
    case "OBJECT":
    case "CANVAS":
    case "IFRAME":
    case "IMG":
      return true;
  }
  return false;
};

// node_modules/@juggle/resize-observer/lib/utils/global.js
var global4 = typeof window !== "undefined" ? window : {};

// node_modules/@juggle/resize-observer/lib/algorithms/calculateBoxSize.js
var cache = /* @__PURE__ */ new WeakMap();
var scrollRegexp = /auto|scroll/;
var verticalRegexp = /^tb|vertical/;
var IE = /msie|trident/i.test(global4.navigator && global4.navigator.userAgent);
var parseDimension = function(pixel) {
  return parseFloat(pixel || "0");
};
var size3 = function(inlineSize, blockSize, switchSizes) {
  if (inlineSize === void 0) {
    inlineSize = 0;
  }
  if (blockSize === void 0) {
    blockSize = 0;
  }
  if (switchSizes === void 0) {
    switchSizes = false;
  }
  return new ResizeObserverSize((switchSizes ? blockSize : inlineSize) || 0, (switchSizes ? inlineSize : blockSize) || 0);
};
var zeroBoxes = freeze({
  devicePixelContentBoxSize: size3(),
  borderBoxSize: size3(),
  contentBoxSize: size3(),
  contentRect: new DOMRectReadOnly(0, 0, 0, 0)
});
var calculateBoxSizes = function(target, forceRecalculation) {
  if (forceRecalculation === void 0) {
    forceRecalculation = false;
  }
  if (cache.has(target) && !forceRecalculation) {
    return cache.get(target);
  }
  if (isHidden(target)) {
    cache.set(target, zeroBoxes);
    return zeroBoxes;
  }
  var cs = getComputedStyle(target);
  var svg4 = isSVG(target) && target.ownerSVGElement && target.getBBox();
  var removePadding = !IE && cs.boxSizing === "border-box";
  var switchSizes = verticalRegexp.test(cs.writingMode || "");
  var canScrollVertically = !svg4 && scrollRegexp.test(cs.overflowY || "");
  var canScrollHorizontally = !svg4 && scrollRegexp.test(cs.overflowX || "");
  var paddingTop = svg4 ? 0 : parseDimension(cs.paddingTop);
  var paddingRight = svg4 ? 0 : parseDimension(cs.paddingRight);
  var paddingBottom = svg4 ? 0 : parseDimension(cs.paddingBottom);
  var paddingLeft = svg4 ? 0 : parseDimension(cs.paddingLeft);
  var borderTop = svg4 ? 0 : parseDimension(cs.borderTopWidth);
  var borderRight = svg4 ? 0 : parseDimension(cs.borderRightWidth);
  var borderBottom = svg4 ? 0 : parseDimension(cs.borderBottomWidth);
  var borderLeft = svg4 ? 0 : parseDimension(cs.borderLeftWidth);
  var horizontalPadding = paddingLeft + paddingRight;
  var verticalPadding = paddingTop + paddingBottom;
  var horizontalBorderArea = borderLeft + borderRight;
  var verticalBorderArea = borderTop + borderBottom;
  var horizontalScrollbarThickness = !canScrollHorizontally ? 0 : target.offsetHeight - verticalBorderArea - target.clientHeight;
  var verticalScrollbarThickness = !canScrollVertically ? 0 : target.offsetWidth - horizontalBorderArea - target.clientWidth;
  var widthReduction = removePadding ? horizontalPadding + horizontalBorderArea : 0;
  var heightReduction = removePadding ? verticalPadding + verticalBorderArea : 0;
  var contentWidth = svg4 ? svg4.width : parseDimension(cs.width) - widthReduction - verticalScrollbarThickness;
  var contentHeight = svg4 ? svg4.height : parseDimension(cs.height) - heightReduction - horizontalScrollbarThickness;
  var borderBoxWidth = contentWidth + horizontalPadding + verticalScrollbarThickness + horizontalBorderArea;
  var borderBoxHeight = contentHeight + verticalPadding + horizontalScrollbarThickness + verticalBorderArea;
  var boxes = freeze({
    devicePixelContentBoxSize: size3(Math.round(contentWidth * devicePixelRatio), Math.round(contentHeight * devicePixelRatio), switchSizes),
    borderBoxSize: size3(borderBoxWidth, borderBoxHeight, switchSizes),
    contentBoxSize: size3(contentWidth, contentHeight, switchSizes),
    contentRect: new DOMRectReadOnly(paddingLeft, paddingTop, contentWidth, contentHeight)
  });
  cache.set(target, boxes);
  return boxes;
};
var calculateBoxSize = function(target, observedBox, forceRecalculation) {
  var _a4 = calculateBoxSizes(target, forceRecalculation), borderBoxSize = _a4.borderBoxSize, contentBoxSize = _a4.contentBoxSize, devicePixelContentBoxSize = _a4.devicePixelContentBoxSize;
  switch (observedBox) {
    case ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX:
      return devicePixelContentBoxSize;
    case ResizeObserverBoxOptions.BORDER_BOX:
      return borderBoxSize;
    default:
      return contentBoxSize;
  }
};

// node_modules/@juggle/resize-observer/lib/ResizeObserverEntry.js
var ResizeObserverEntry = /* @__PURE__ */ function() {
  function ResizeObserverEntry2(target) {
    var boxes = calculateBoxSizes(target);
    this.target = target;
    this.contentRect = boxes.contentRect;
    this.borderBoxSize = freeze([boxes.borderBoxSize]);
    this.contentBoxSize = freeze([boxes.contentBoxSize]);
    this.devicePixelContentBoxSize = freeze([boxes.devicePixelContentBoxSize]);
  }
  return ResizeObserverEntry2;
}();

// node_modules/@juggle/resize-observer/lib/algorithms/calculateDepthForNode.js
var calculateDepthForNode = function(node) {
  if (isHidden(node)) {
    return Infinity;
  }
  var depth2 = 0;
  var parent = node.parentNode;
  while (parent) {
    depth2 += 1;
    parent = parent.parentNode;
  }
  return depth2;
};

// node_modules/@juggle/resize-observer/lib/algorithms/broadcastActiveObservations.js
var broadcastActiveObservations = function() {
  var shallowestDepth = Infinity;
  var callbacks2 = [];
  resizeObservers.forEach(function processObserver(ro) {
    if (ro.activeTargets.length === 0) {
      return;
    }
    var entries2 = [];
    ro.activeTargets.forEach(function processTarget(ot) {
      var entry = new ResizeObserverEntry(ot.target);
      var targetDepth = calculateDepthForNode(ot.target);
      entries2.push(entry);
      ot.lastReportedSize = calculateBoxSize(ot.target, ot.observedBox);
      if (targetDepth < shallowestDepth) {
        shallowestDepth = targetDepth;
      }
    });
    callbacks2.push(function resizeObserverCallback() {
      ro.callback.call(ro.observer, entries2, ro.observer);
    });
    ro.activeTargets.splice(0, ro.activeTargets.length);
  });
  for (var _i = 0, callbacks_1 = callbacks2; _i < callbacks_1.length; _i++) {
    var callback = callbacks_1[_i];
    callback();
  }
  return shallowestDepth;
};

// node_modules/@juggle/resize-observer/lib/algorithms/gatherActiveObservationsAtDepth.js
var gatherActiveObservationsAtDepth = function(depth2) {
  resizeObservers.forEach(function processObserver(ro) {
    ro.activeTargets.splice(0, ro.activeTargets.length);
    ro.skippedTargets.splice(0, ro.skippedTargets.length);
    ro.observationTargets.forEach(function processTarget(ot) {
      if (ot.isActive()) {
        if (calculateDepthForNode(ot.target) > depth2) {
          ro.activeTargets.push(ot);
        } else {
          ro.skippedTargets.push(ot);
        }
      }
    });
  });
};

// node_modules/@juggle/resize-observer/lib/utils/process.js
var process2 = function() {
  var depth2 = 0;
  gatherActiveObservationsAtDepth(depth2);
  while (hasActiveObservations()) {
    depth2 = broadcastActiveObservations();
    gatherActiveObservationsAtDepth(depth2);
  }
  if (hasSkippedObservations()) {
    deliverResizeLoopError();
  }
  return depth2 > 0;
};

// node_modules/@juggle/resize-observer/lib/utils/queueMicroTask.js
var trigger;
var callbacks = [];
var notify = function() {
  return callbacks.splice(0).forEach(function(cb2) {
    return cb2();
  });
};
var queueMicroTask = function(callback) {
  if (!trigger) {
    var toggle_1 = 0;
    var el_1 = document.createTextNode("");
    var config3 = { characterData: true };
    new MutationObserver(function() {
      return notify();
    }).observe(el_1, config3);
    trigger = function() {
      el_1.textContent = "".concat(toggle_1 ? toggle_1-- : toggle_1++);
    };
  }
  callbacks.push(callback);
  trigger();
};

// node_modules/@juggle/resize-observer/lib/utils/queueResizeObserver.js
var queueResizeObserver = function(cb2) {
  queueMicroTask(function ResizeObserver3() {
    requestAnimationFrame(cb2);
  });
};

// node_modules/@juggle/resize-observer/lib/utils/scheduler.js
var watching = 0;
var isWatching = function() {
  return !!watching;
};
var CATCH_PERIOD = 250;
var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true };
var events = [
  "resize",
  "load",
  "transitionend",
  "animationend",
  "animationstart",
  "animationiteration",
  "keyup",
  "keydown",
  "mouseup",
  "mousedown",
  "mouseover",
  "mouseout",
  "blur",
  "focus"
];
var time2 = function(timeout) {
  if (timeout === void 0) {
    timeout = 0;
  }
  return Date.now() + timeout;
};
var scheduled2 = false;
var Scheduler2 = function() {
  function Scheduler3() {
    var _this = this;
    this.stopped = true;
    this.listener = function() {
      return _this.schedule();
    };
  }
  Scheduler3.prototype.run = function(timeout) {
    var _this = this;
    if (timeout === void 0) {
      timeout = CATCH_PERIOD;
    }
    if (scheduled2) {
      return;
    }
    scheduled2 = true;
    var until = time2(timeout);
    queueResizeObserver(function() {
      var elementsHaveResized = false;
      try {
        elementsHaveResized = process2();
      } finally {
        scheduled2 = false;
        timeout = until - time2();
        if (!isWatching()) {
          return;
        }
        if (elementsHaveResized) {
          _this.run(1e3);
        } else if (timeout > 0) {
          _this.run(timeout);
        } else {
          _this.start();
        }
      }
    });
  };
  Scheduler3.prototype.schedule = function() {
    this.stop();
    this.run();
  };
  Scheduler3.prototype.observe = function() {
    var _this = this;
    var cb2 = function() {
      return _this.observer && _this.observer.observe(document.body, observerConfig);
    };
    document.body ? cb2() : global4.addEventListener("DOMContentLoaded", cb2);
  };
  Scheduler3.prototype.start = function() {
    var _this = this;
    if (this.stopped) {
      this.stopped = false;
      this.observer = new MutationObserver(this.listener);
      this.observe();
      events.forEach(function(name2) {
        return global4.addEventListener(name2, _this.listener, true);
      });
    }
  };
  Scheduler3.prototype.stop = function() {
    var _this = this;
    if (!this.stopped) {
      this.observer && this.observer.disconnect();
      events.forEach(function(name2) {
        return global4.removeEventListener(name2, _this.listener, true);
      });
      this.stopped = true;
    }
  };
  return Scheduler3;
}();
var scheduler = new Scheduler2();
var updateCount = function(n4) {
  !watching && n4 > 0 && scheduler.start();
  watching += n4;
  !watching && scheduler.stop();
};

// node_modules/@juggle/resize-observer/lib/ResizeObservation.js
var skipNotifyOnElement = function(target) {
  return !isSVG(target) && !isReplacedElement(target) && getComputedStyle(target).display === "inline";
};
var ResizeObservation = function() {
  function ResizeObservation2(target, observedBox) {
    this.target = target;
    this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX;
    this.lastReportedSize = {
      inlineSize: 0,
      blockSize: 0
    };
  }
  ResizeObservation2.prototype.isActive = function() {
    var size4 = calculateBoxSize(this.target, this.observedBox, true);
    if (skipNotifyOnElement(this.target)) {
      this.lastReportedSize = size4;
    }
    if (this.lastReportedSize.inlineSize !== size4.inlineSize || this.lastReportedSize.blockSize !== size4.blockSize) {
      return true;
    }
    return false;
  };
  return ResizeObservation2;
}();

// node_modules/@juggle/resize-observer/lib/ResizeObserverDetail.js
var ResizeObserverDetail = /* @__PURE__ */ function() {
  function ResizeObserverDetail2(resizeObserver, callback) {
    this.activeTargets = [];
    this.skippedTargets = [];
    this.observationTargets = [];
    this.observer = resizeObserver;
    this.callback = callback;
  }
  return ResizeObserverDetail2;
}();

// node_modules/@juggle/resize-observer/lib/ResizeObserverController.js
var observerMap = /* @__PURE__ */ new WeakMap();
var getObservationIndex = function(observationTargets, target) {
  for (var i3 = 0; i3 < observationTargets.length; i3 += 1) {
    if (observationTargets[i3].target === target) {
      return i3;
    }
  }
  return -1;
};
var ResizeObserverController = function() {
  function ResizeObserverController2() {
  }
  ResizeObserverController2.connect = function(resizeObserver, callback) {
    var detail = new ResizeObserverDetail(resizeObserver, callback);
    observerMap.set(resizeObserver, detail);
  };
  ResizeObserverController2.observe = function(resizeObserver, target, options2) {
    var detail = observerMap.get(resizeObserver);
    var firstObservation = detail.observationTargets.length === 0;
    if (getObservationIndex(detail.observationTargets, target) < 0) {
      firstObservation && resizeObservers.push(detail);
      detail.observationTargets.push(new ResizeObservation(target, options2 && options2.box));
      updateCount(1);
      scheduler.schedule();
    }
  };
  ResizeObserverController2.unobserve = function(resizeObserver, target) {
    var detail = observerMap.get(resizeObserver);
    var index2 = getObservationIndex(detail.observationTargets, target);
    var lastObservation = detail.observationTargets.length === 1;
    if (index2 >= 0) {
      lastObservation && resizeObservers.splice(resizeObservers.indexOf(detail), 1);
      detail.observationTargets.splice(index2, 1);
      updateCount(-1);
    }
  };
  ResizeObserverController2.disconnect = function(resizeObserver) {
    var _this = this;
    var detail = observerMap.get(resizeObserver);
    detail.observationTargets.slice().forEach(function(ot) {
      return _this.unobserve(resizeObserver, ot.target);
    });
    detail.activeTargets.splice(0, detail.activeTargets.length);
  };
  return ResizeObserverController2;
}();

// node_modules/@juggle/resize-observer/lib/ResizeObserver.js
var ResizeObserver2 = function() {
  function ResizeObserver3(callback) {
    if (arguments.length === 0) {
      throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present.");
    }
    if (typeof callback !== "function") {
      throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function.");
    }
    ResizeObserverController.connect(this, callback);
  }
  ResizeObserver3.prototype.observe = function(target, options2) {
    if (arguments.length === 0) {
      throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present.");
    }
    if (!isElement2(target)) {
      throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element");
    }
    ResizeObserverController.observe(this, target, options2);
  };
  ResizeObserver3.prototype.unobserve = function(target) {
    if (arguments.length === 0) {
      throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present.");
    }
    if (!isElement2(target)) {
      throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element");
    }
    ResizeObserverController.unobserve(this, target);
  };
  ResizeObserver3.prototype.disconnect = function() {
    ResizeObserverController.disconnect(this);
  };
  ResizeObserver3.toString = function() {
    return "function ResizeObserver () { [polyfill code] }";
  };
  return ResizeObserver3;
}();

// node_modules/core-js/modules/es.array.reduce.js
var $5 = require_export();
var $reduce = require_array_reduce().left;
var arrayMethodIsStrict = require_array_method_is_strict();
var CHROME_VERSION = require_engine_v8_version();
var IS_NODE = require_engine_is_node();
var STRICT_METHOD = arrayMethodIsStrict("reduce");
var CHROME_BUG = !IS_NODE && CHROME_VERSION > 79 && CHROME_VERSION < 83;
$5({ target: "Array", proto: true, forced: !STRICT_METHOD || CHROME_BUG }, {
  reduce: function reduce(callbackfn) {
    var length = arguments.length;
    return $reduce(this, callbackfn, length, length > 1 ? arguments[1] : void 0);
  }
});

// node_modules/simplebar/dist/simplebar.esm.js
var import_es_regexp_exec = __toESM(require_es_regexp_exec());

// node_modules/core-js/modules/es.string.match.js
var call = require_function_call();
var fixRegExpWellKnownSymbolLogic = require_fix_regexp_well_known_symbol_logic();
var anObject = require_an_object();
var isNullOrUndefined = require_is_null_or_undefined();
var toLength = require_to_length();
var toString4 = require_to_string();
var requireObjectCoercible = require_require_object_coercible();
var getMethod = require_get_method();
var advanceStringIndex = require_advance_string_index();
var regExpExec = require_regexp_exec_abstract();
fixRegExpWellKnownSymbolLogic("match", function(MATCH, nativeMatch, maybeCallNative) {
  return [
    // `String.prototype.match` method
    // https://tc39.es/ecma262/#sec-string.prototype.match
    function match2(regexp) {
      var O4 = requireObjectCoercible(this);
      var matcher2 = isNullOrUndefined(regexp) ? void 0 : getMethod(regexp, MATCH);
      return matcher2 ? call(matcher2, regexp, O4) : new RegExp(regexp)[MATCH](toString4(O4));
    },
    // `RegExp.prototype[@@match]` method
    // https://tc39.es/ecma262/#sec-regexp.prototype-@@match
    function(string3) {
      var rx = anObject(this);
      var S2 = toString4(string3);
      var res = maybeCallNative(nativeMatch, rx, S2);
      if (res.done) return res.value;
      if (!rx.global) return regExpExec(rx, S2);
      var fullUnicode = rx.unicode;
      rx.lastIndex = 0;
      var A4 = [];
      var n4 = 0;
      var result2;
      while ((result2 = regExpExec(rx, S2)) !== null) {
        var matchStr = toString4(result2[0]);
        A4[n4] = matchStr;
        if (matchStr === "") rx.lastIndex = advanceStringIndex(S2, toLength(rx.lastIndex), fullUnicode);
        n4++;
      }
      return n4 === 0 ? null : A4;
    }
  ];
});

// node_modules/core-js/modules/es.function.name.js
var DESCRIPTORS = require_descriptors();
var FUNCTION_NAME_EXISTS = require_function_name().EXISTS;
var uncurryThis = require_function_uncurry_this();
var defineProperty = require_object_define_property().f;
var FunctionPrototype = Function.prototype;
var functionToString = uncurryThis(FunctionPrototype.toString);
var nameRE = /function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/;
var regExpExec2 = uncurryThis(nameRE.exec);
var NAME = "name";
if (DESCRIPTORS && !FUNCTION_NAME_EXISTS) {
  defineProperty(FunctionPrototype, NAME, {
    configurable: true,
    get: function() {
      try {
        return regExpExec2(nameRE, functionToString(this))[1];
      } catch (error2) {
        return "";
      }
    }
  });
}

// node_modules/core-js/modules/es.string.replace.js
var apply = require_function_apply();
var call2 = require_function_call();
var uncurryThis2 = require_function_uncurry_this();
var fixRegExpWellKnownSymbolLogic2 = require_fix_regexp_well_known_symbol_logic();
var fails = require_fails();
var anObject2 = require_an_object();
var isCallable = require_is_callable();
var isNullOrUndefined2 = require_is_null_or_undefined();
var toIntegerOrInfinity = require_to_integer_or_infinity();
var toLength2 = require_to_length();
var toString5 = require_to_string();
var requireObjectCoercible2 = require_require_object_coercible();
var advanceStringIndex2 = require_advance_string_index();
var getMethod2 = require_get_method();
var getSubstitution = require_get_substitution();
var regExpExec3 = require_regexp_exec_abstract();
var wellKnownSymbol2 = require_well_known_symbol();
var REPLACE = wellKnownSymbol2("replace");
var max2 = Math.max;
var min2 = Math.min;
var concat = uncurryThis2([].concat);
var push2 = uncurryThis2([].push);
var stringIndexOf = uncurryThis2("".indexOf);
var stringSlice = uncurryThis2("".slice);
var maybeToString = function(it2) {
  return it2 === void 0 ? it2 : String(it2);
};
var REPLACE_KEEPS_$0 = function() {
  return "a".replace(/./, "$0") === "$0";
}();
var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = function() {
  if (/./[REPLACE]) {
    return /./[REPLACE]("a", "$0") === "";
  }
  return false;
}();
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function() {
  var re2 = /./;
  re2.exec = function() {
    var result2 = [];
    result2.groups = { a: "7" };
    return result2;
  };
  return "".replace(re2, "$<a>") !== "7";
});
fixRegExpWellKnownSymbolLogic2("replace", function(_5, nativeReplace, maybeCallNative) {
  var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? "$" : "$0";
  return [
    // `String.prototype.replace` method
    // https://tc39.es/ecma262/#sec-string.prototype.replace
    function replace4(searchValue, replaceValue) {
      var O4 = requireObjectCoercible2(this);
      var replacer = isNullOrUndefined2(searchValue) ? void 0 : getMethod2(searchValue, REPLACE);
      return replacer ? call2(replacer, searchValue, O4, replaceValue) : call2(nativeReplace, toString5(O4), searchValue, replaceValue);
    },
    // `RegExp.prototype[@@replace]` method
    // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
    function(string3, replaceValue) {
      var rx = anObject2(this);
      var S2 = toString5(string3);
      if (typeof replaceValue == "string" && stringIndexOf(replaceValue, UNSAFE_SUBSTITUTE) === -1 && stringIndexOf(replaceValue, "$<") === -1) {
        var res = maybeCallNative(nativeReplace, rx, S2, replaceValue);
        if (res.done) return res.value;
      }
      var functionalReplace = isCallable(replaceValue);
      if (!functionalReplace) replaceValue = toString5(replaceValue);
      var global5 = rx.global;
      if (global5) {
        var fullUnicode = rx.unicode;
        rx.lastIndex = 0;
      }
      var results2 = [];
      while (true) {
        var result2 = regExpExec3(rx, S2);
        if (result2 === null) break;
        push2(results2, result2);
        if (!global5) break;
        var matchStr = toString5(result2[0]);
        if (matchStr === "") rx.lastIndex = advanceStringIndex2(S2, toLength2(rx.lastIndex), fullUnicode);
      }
      var accumulatedResult = "";
      var nextSourcePosition = 0;
      for (var i3 = 0; i3 < results2.length; i3++) {
        result2 = results2[i3];
        var matched = toString5(result2[0]);
        var position = max2(min2(toIntegerOrInfinity(result2.index), S2.length), 0);
        var captures = [];
        for (var j = 1; j < result2.length; j++) push2(captures, maybeToString(result2[j]));
        var namedCaptures = result2.groups;
        if (functionalReplace) {
          var replacerArgs = concat([matched], captures, position, S2);
          if (namedCaptures !== void 0) push2(replacerArgs, namedCaptures);
          var replacement = toString5(apply(replaceValue, void 0, replacerArgs));
        } else {
          replacement = getSubstitution(matched, S2, position, captures, namedCaptures, replaceValue);
        }
        if (position >= nextSourcePosition) {
          accumulatedResult += stringSlice(S2, nextSourcePosition, position) + replacement;
          nextSourcePosition = position + matched.length;
        }
      }
      return accumulatedResult + stringSlice(S2, nextSourcePosition);
    }
  ];
}, !REPLACE_SUPPORTS_NAMED_GROUPS || !REPLACE_KEEPS_$0 || REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE);

// node_modules/simplebar/dist/simplebar.esm.js
var getOptions2 = function getOptions3(obj) {
  var options2 = Array.prototype.reduce.call(obj, function(acc, attribute2) {
    var option2 = attribute2.name.match(/data-simplebar-(.+)/);
    if (option2) {
      var key2 = option2[1].replace(/\W+(.)/g, function(x3, chr) {
        return chr.toUpperCase();
      });
      switch (attribute2.value) {
        case "true":
          acc[key2] = true;
          break;
        case "false":
          acc[key2] = false;
          break;
        case void 0:
          acc[key2] = true;
          break;
        default:
          acc[key2] = attribute2.value;
      }
    }
    return acc;
  }, {});
  return options2;
};
function getElementWindow(element2) {
  if (!element2 || !element2.ownerDocument || !element2.ownerDocument.defaultView) {
    return window;
  }
  return element2.ownerDocument.defaultView;
}
function getElementDocument(element2) {
  if (!element2 || !element2.ownerDocument) {
    return document;
  }
  return element2.ownerDocument;
}
var cachedScrollbarWidth = null;
var cachedDevicePixelRatio = null;
if (import_can_use_dom.default) {
  window.addEventListener("resize", function() {
    if (cachedDevicePixelRatio !== window.devicePixelRatio) {
      cachedDevicePixelRatio = window.devicePixelRatio;
      cachedScrollbarWidth = null;
    }
  });
}
function scrollbarWidth(el2) {
  if (cachedScrollbarWidth === null) {
    var document2 = getElementDocument(el2);
    if (typeof document2 === "undefined") {
      cachedScrollbarWidth = 0;
      return cachedScrollbarWidth;
    }
    var body3 = document2.body;
    var box = document2.createElement("div");
    box.classList.add("simplebar-hide-scrollbar");
    body3.appendChild(box);
    var width = box.getBoundingClientRect().right;
    body3.removeChild(box);
    cachedScrollbarWidth = width;
  }
  return cachedScrollbarWidth;
}
var SimpleBar = /* @__PURE__ */ function() {
  function SimpleBar2(element2, options2) {
    var _this = this;
    this.onScroll = function() {
      var elWindow = getElementWindow(_this.el);
      if (!_this.scrollXTicking) {
        elWindow.requestAnimationFrame(_this.scrollX);
        _this.scrollXTicking = true;
      }
      if (!_this.scrollYTicking) {
        elWindow.requestAnimationFrame(_this.scrollY);
        _this.scrollYTicking = true;
      }
    };
    this.scrollX = function() {
      if (_this.axis.x.isOverflowing) {
        _this.showScrollbar("x");
        _this.positionScrollbar("x");
      }
      _this.scrollXTicking = false;
    };
    this.scrollY = function() {
      if (_this.axis.y.isOverflowing) {
        _this.showScrollbar("y");
        _this.positionScrollbar("y");
      }
      _this.scrollYTicking = false;
    };
    this.onMouseEnter = function() {
      _this.showScrollbar("x");
      _this.showScrollbar("y");
    };
    this.onMouseMove = function(e3) {
      _this.mouseX = e3.clientX;
      _this.mouseY = e3.clientY;
      if (_this.axis.x.isOverflowing || _this.axis.x.forceVisible) {
        _this.onMouseMoveForAxis("x");
      }
      if (_this.axis.y.isOverflowing || _this.axis.y.forceVisible) {
        _this.onMouseMoveForAxis("y");
      }
    };
    this.onMouseLeave = function() {
      _this.onMouseMove.cancel();
      if (_this.axis.x.isOverflowing || _this.axis.x.forceVisible) {
        _this.onMouseLeaveForAxis("x");
      }
      if (_this.axis.y.isOverflowing || _this.axis.y.forceVisible) {
        _this.onMouseLeaveForAxis("y");
      }
      _this.mouseX = -1;
      _this.mouseY = -1;
    };
    this.onWindowResize = function() {
      _this.scrollbarWidth = _this.getScrollbarWidth();
      _this.hideNativeScrollbar();
    };
    this.hideScrollbars = function() {
      _this.axis.x.track.rect = _this.axis.x.track.el.getBoundingClientRect();
      _this.axis.y.track.rect = _this.axis.y.track.el.getBoundingClientRect();
      if (!_this.isWithinBounds(_this.axis.y.track.rect)) {
        _this.axis.y.scrollbar.el.classList.remove(_this.classNames.visible);
        _this.axis.y.isVisible = false;
      }
      if (!_this.isWithinBounds(_this.axis.x.track.rect)) {
        _this.axis.x.scrollbar.el.classList.remove(_this.classNames.visible);
        _this.axis.x.isVisible = false;
      }
    };
    this.onPointerEvent = function(e3) {
      var isWithinTrackXBounds, isWithinTrackYBounds;
      _this.axis.x.track.rect = _this.axis.x.track.el.getBoundingClientRect();
      _this.axis.y.track.rect = _this.axis.y.track.el.getBoundingClientRect();
      if (_this.axis.x.isOverflowing || _this.axis.x.forceVisible) {
        isWithinTrackXBounds = _this.isWithinBounds(_this.axis.x.track.rect);
      }
      if (_this.axis.y.isOverflowing || _this.axis.y.forceVisible) {
        isWithinTrackYBounds = _this.isWithinBounds(_this.axis.y.track.rect);
      }
      if (isWithinTrackXBounds || isWithinTrackYBounds) {
        e3.preventDefault();
        e3.stopPropagation();
        if (e3.type === "mousedown") {
          if (isWithinTrackXBounds) {
            _this.axis.x.scrollbar.rect = _this.axis.x.scrollbar.el.getBoundingClientRect();
            if (_this.isWithinBounds(_this.axis.x.scrollbar.rect)) {
              _this.onDragStart(e3, "x");
            } else {
              _this.onTrackClick(e3, "x");
            }
          }
          if (isWithinTrackYBounds) {
            _this.axis.y.scrollbar.rect = _this.axis.y.scrollbar.el.getBoundingClientRect();
            if (_this.isWithinBounds(_this.axis.y.scrollbar.rect)) {
              _this.onDragStart(e3, "y");
            } else {
              _this.onTrackClick(e3, "y");
            }
          }
        }
      }
    };
    this.drag = function(e3) {
      var eventOffset;
      var track = _this.axis[_this.draggedAxis].track;
      var trackSize = track.rect[_this.axis[_this.draggedAxis].sizeAttr];
      var scrollbar = _this.axis[_this.draggedAxis].scrollbar;
      var contentSize = _this.contentWrapperEl[_this.axis[_this.draggedAxis].scrollSizeAttr];
      var hostSize = parseInt(_this.elStyles[_this.axis[_this.draggedAxis].sizeAttr], 10);
      e3.preventDefault();
      e3.stopPropagation();
      if (_this.draggedAxis === "y") {
        eventOffset = e3.pageY;
      } else {
        eventOffset = e3.pageX;
      }
      var dragPos = eventOffset - track.rect[_this.axis[_this.draggedAxis].offsetAttr] - _this.axis[_this.draggedAxis].dragOffset;
      var dragPerc = dragPos / (trackSize - scrollbar.size);
      var scrollPos = dragPerc * (contentSize - hostSize);
      if (_this.draggedAxis === "x") {
        scrollPos = _this.isRtl && SimpleBar2.getRtlHelpers().isRtlScrollbarInverted ? scrollPos - (trackSize + scrollbar.size) : scrollPos;
        scrollPos = _this.isRtl && SimpleBar2.getRtlHelpers().isRtlScrollingInverted ? -scrollPos : scrollPos;
      }
      _this.contentWrapperEl[_this.axis[_this.draggedAxis].scrollOffsetAttr] = scrollPos;
    };
    this.onEndDrag = function(e3) {
      var elDocument = getElementDocument(_this.el);
      var elWindow = getElementWindow(_this.el);
      e3.preventDefault();
      e3.stopPropagation();
      _this.el.classList.remove(_this.classNames.dragging);
      elDocument.removeEventListener("mousemove", _this.drag, true);
      elDocument.removeEventListener("mouseup", _this.onEndDrag, true);
      _this.removePreventClickId = elWindow.setTimeout(function() {
        elDocument.removeEventListener("click", _this.preventClick, true);
        elDocument.removeEventListener("dblclick", _this.preventClick, true);
        _this.removePreventClickId = null;
      });
    };
    this.preventClick = function(e3) {
      e3.preventDefault();
      e3.stopPropagation();
    };
    this.el = element2;
    this.minScrollbarWidth = 20;
    this.options = Object.assign({}, SimpleBar2.defaultOptions, options2);
    this.classNames = Object.assign({}, SimpleBar2.defaultOptions.classNames, this.options.classNames);
    this.axis = {
      x: {
        scrollOffsetAttr: "scrollLeft",
        sizeAttr: "width",
        scrollSizeAttr: "scrollWidth",
        offsetSizeAttr: "offsetWidth",
        offsetAttr: "left",
        overflowAttr: "overflowX",
        dragOffset: 0,
        isOverflowing: true,
        isVisible: false,
        forceVisible: false,
        track: {},
        scrollbar: {}
      },
      y: {
        scrollOffsetAttr: "scrollTop",
        sizeAttr: "height",
        scrollSizeAttr: "scrollHeight",
        offsetSizeAttr: "offsetHeight",
        offsetAttr: "top",
        overflowAttr: "overflowY",
        dragOffset: 0,
        isOverflowing: true,
        isVisible: false,
        forceVisible: false,
        track: {},
        scrollbar: {}
      }
    };
    this.removePreventClickId = null;
    if (SimpleBar2.instances.has(this.el)) {
      return;
    }
    this.recalculate = (0, import_lodash.default)(this.recalculate.bind(this), 64);
    this.onMouseMove = (0, import_lodash.default)(this.onMouseMove.bind(this), 64);
    this.hideScrollbars = (0, import_lodash2.default)(this.hideScrollbars.bind(this), this.options.timeout);
    this.onWindowResize = (0, import_lodash2.default)(this.onWindowResize.bind(this), 64, {
      leading: true
    });
    SimpleBar2.getRtlHelpers = (0, import_lodash3.default)(SimpleBar2.getRtlHelpers);
    this.init();
  }
  SimpleBar2.getRtlHelpers = function getRtlHelpers() {
    var dummyDiv = document.createElement("div");
    dummyDiv.innerHTML = '<div class="hs-dummy-scrollbar-size"><div style="height: 200%; width: 200%; margin: 10px 0;"></div></div>';
    var scrollbarDummyEl = dummyDiv.firstElementChild;
    document.body.appendChild(scrollbarDummyEl);
    var dummyContainerChild = scrollbarDummyEl.firstElementChild;
    scrollbarDummyEl.scrollLeft = 0;
    var dummyContainerOffset = SimpleBar2.getOffset(scrollbarDummyEl);
    var dummyContainerChildOffset = SimpleBar2.getOffset(dummyContainerChild);
    scrollbarDummyEl.scrollLeft = 999;
    var dummyContainerScrollOffsetAfterScroll = SimpleBar2.getOffset(dummyContainerChild);
    return {
      // determines if the scrolling is responding with negative values
      isRtlScrollingInverted: dummyContainerOffset.left !== dummyContainerChildOffset.left && dummyContainerChildOffset.left - dummyContainerScrollOffsetAfterScroll.left !== 0,
      // determines if the origin scrollbar position is inverted or not (positioned on left or right)
      isRtlScrollbarInverted: dummyContainerOffset.left !== dummyContainerChildOffset.left
    };
  };
  SimpleBar2.getOffset = function getOffset(el2) {
    var rect = el2.getBoundingClientRect();
    var elDocument = getElementDocument(el2);
    var elWindow = getElementWindow(el2);
    return {
      top: rect.top + (elWindow.pageYOffset || elDocument.documentElement.scrollTop),
      left: rect.left + (elWindow.pageXOffset || elDocument.documentElement.scrollLeft)
    };
  };
  var _proto = SimpleBar2.prototype;
  _proto.init = function init() {
    SimpleBar2.instances.set(this.el, this);
    if (import_can_use_dom.default) {
      this.initDOM();
      this.setAccessibilityAttributes();
      this.scrollbarWidth = this.getScrollbarWidth();
      this.recalculate();
      this.initListeners();
    }
  };
  _proto.initDOM = function initDOM() {
    var _this2 = this;
    if (Array.prototype.filter.call(this.el.children, function(child) {
      return child.classList.contains(_this2.classNames.wrapper);
    }).length) {
      this.wrapperEl = this.el.querySelector("." + this.classNames.wrapper);
      this.contentWrapperEl = this.options.scrollableNode || this.el.querySelector("." + this.classNames.contentWrapper);
      this.contentEl = this.options.contentNode || this.el.querySelector("." + this.classNames.contentEl);
      this.offsetEl = this.el.querySelector("." + this.classNames.offset);
      this.maskEl = this.el.querySelector("." + this.classNames.mask);
      this.placeholderEl = this.findChild(this.wrapperEl, "." + this.classNames.placeholder);
      this.heightAutoObserverWrapperEl = this.el.querySelector("." + this.classNames.heightAutoObserverWrapperEl);
      this.heightAutoObserverEl = this.el.querySelector("." + this.classNames.heightAutoObserverEl);
      this.axis.x.track.el = this.findChild(this.el, "." + this.classNames.track + "." + this.classNames.horizontal);
      this.axis.y.track.el = this.findChild(this.el, "." + this.classNames.track + "." + this.classNames.vertical);
    } else {
      this.wrapperEl = document.createElement("div");
      this.contentWrapperEl = document.createElement("div");
      this.offsetEl = document.createElement("div");
      this.maskEl = document.createElement("div");
      this.contentEl = document.createElement("div");
      this.placeholderEl = document.createElement("div");
      this.heightAutoObserverWrapperEl = document.createElement("div");
      this.heightAutoObserverEl = document.createElement("div");
      this.wrapperEl.classList.add(this.classNames.wrapper);
      this.contentWrapperEl.classList.add(this.classNames.contentWrapper);
      this.offsetEl.classList.add(this.classNames.offset);
      this.maskEl.classList.add(this.classNames.mask);
      this.contentEl.classList.add(this.classNames.contentEl);
      this.placeholderEl.classList.add(this.classNames.placeholder);
      this.heightAutoObserverWrapperEl.classList.add(this.classNames.heightAutoObserverWrapperEl);
      this.heightAutoObserverEl.classList.add(this.classNames.heightAutoObserverEl);
      while (this.el.firstChild) {
        this.contentEl.appendChild(this.el.firstChild);
      }
      this.contentWrapperEl.appendChild(this.contentEl);
      this.offsetEl.appendChild(this.contentWrapperEl);
      this.maskEl.appendChild(this.offsetEl);
      this.heightAutoObserverWrapperEl.appendChild(this.heightAutoObserverEl);
      this.wrapperEl.appendChild(this.heightAutoObserverWrapperEl);
      this.wrapperEl.appendChild(this.maskEl);
      this.wrapperEl.appendChild(this.placeholderEl);
      this.el.appendChild(this.wrapperEl);
    }
    if (!this.axis.x.track.el || !this.axis.y.track.el) {
      var track = document.createElement("div");
      var scrollbar = document.createElement("div");
      track.classList.add(this.classNames.track);
      scrollbar.classList.add(this.classNames.scrollbar);
      track.appendChild(scrollbar);
      this.axis.x.track.el = track.cloneNode(true);
      this.axis.x.track.el.classList.add(this.classNames.horizontal);
      this.axis.y.track.el = track.cloneNode(true);
      this.axis.y.track.el.classList.add(this.classNames.vertical);
      this.el.appendChild(this.axis.x.track.el);
      this.el.appendChild(this.axis.y.track.el);
    }
    this.axis.x.scrollbar.el = this.axis.x.track.el.querySelector("." + this.classNames.scrollbar);
    this.axis.y.scrollbar.el = this.axis.y.track.el.querySelector("." + this.classNames.scrollbar);
    if (!this.options.autoHide) {
      this.axis.x.scrollbar.el.classList.add(this.classNames.visible);
      this.axis.y.scrollbar.el.classList.add(this.classNames.visible);
    }
    this.el.setAttribute("data-simplebar", "init");
  };
  _proto.setAccessibilityAttributes = function setAccessibilityAttributes() {
    var ariaLabel = this.options.ariaLabel || "scrollable content";
    this.contentWrapperEl.setAttribute("tabindex", "0");
    this.contentWrapperEl.setAttribute("role", "region");
    this.contentWrapperEl.setAttribute("aria-label", ariaLabel);
  };
  _proto.initListeners = function initListeners() {
    var _this3 = this;
    var elWindow = getElementWindow(this.el);
    if (this.options.autoHide) {
      this.el.addEventListener("mouseenter", this.onMouseEnter);
    }
    ["mousedown", "click", "dblclick"].forEach(function(e3) {
      _this3.el.addEventListener(e3, _this3.onPointerEvent, true);
    });
    ["touchstart", "touchend", "touchmove"].forEach(function(e3) {
      _this3.el.addEventListener(e3, _this3.onPointerEvent, {
        capture: true,
        passive: true
      });
    });
    this.el.addEventListener("mousemove", this.onMouseMove);
    this.el.addEventListener("mouseleave", this.onMouseLeave);
    this.contentWrapperEl.addEventListener("scroll", this.onScroll);
    elWindow.addEventListener("resize", this.onWindowResize);
    var resizeObserverStarted = false;
    var resizeAnimationFrameId = null;
    var resizeObserver = elWindow.ResizeObserver || ResizeObserver2;
    this.resizeObserver = new resizeObserver(function() {
      if (!resizeObserverStarted || resizeAnimationFrameId !== null) return;
      resizeAnimationFrameId = elWindow.requestAnimationFrame(function() {
        _this3.recalculate();
        resizeAnimationFrameId = null;
      });
    });
    this.resizeObserver.observe(this.el);
    this.resizeObserver.observe(this.contentEl);
    elWindow.requestAnimationFrame(function() {
      resizeObserverStarted = true;
    });
    this.mutationObserver = new elWindow.MutationObserver(this.recalculate);
    this.mutationObserver.observe(this.contentEl, {
      childList: true,
      subtree: true,
      characterData: true
    });
  };
  _proto.recalculate = function recalculate() {
    var elWindow = getElementWindow(this.el);
    this.elStyles = elWindow.getComputedStyle(this.el);
    this.isRtl = this.elStyles.direction === "rtl";
    var isHeightAuto = this.heightAutoObserverEl.offsetHeight <= 1;
    var isWidthAuto = this.heightAutoObserverEl.offsetWidth <= 1;
    var contentElOffsetWidth = this.contentEl.offsetWidth;
    var contentWrapperElOffsetWidth = this.contentWrapperEl.offsetWidth;
    var elOverflowX = this.elStyles.overflowX;
    var elOverflowY = this.elStyles.overflowY;
    this.contentEl.style.padding = this.elStyles.paddingTop + " " + this.elStyles.paddingRight + " " + this.elStyles.paddingBottom + " " + this.elStyles.paddingLeft;
    this.wrapperEl.style.margin = "-" + this.elStyles.paddingTop + " -" + this.elStyles.paddingRight + " -" + this.elStyles.paddingBottom + " -" + this.elStyles.paddingLeft;
    var contentElScrollHeight = this.contentEl.scrollHeight;
    var contentElScrollWidth = this.contentEl.scrollWidth;
    this.contentWrapperEl.style.height = isHeightAuto ? "auto" : "100%";
    this.placeholderEl.style.width = isWidthAuto ? contentElOffsetWidth + "px" : "auto";
    this.placeholderEl.style.height = contentElScrollHeight + "px";
    var contentWrapperElOffsetHeight = this.contentWrapperEl.offsetHeight;
    this.axis.x.isOverflowing = contentElScrollWidth > contentElOffsetWidth;
    this.axis.y.isOverflowing = contentElScrollHeight > contentWrapperElOffsetHeight;
    this.axis.x.isOverflowing = elOverflowX === "hidden" ? false : this.axis.x.isOverflowing;
    this.axis.y.isOverflowing = elOverflowY === "hidden" ? false : this.axis.y.isOverflowing;
    this.axis.x.forceVisible = this.options.forceVisible === "x" || this.options.forceVisible === true;
    this.axis.y.forceVisible = this.options.forceVisible === "y" || this.options.forceVisible === true;
    this.hideNativeScrollbar();
    var offsetForXScrollbar = this.axis.x.isOverflowing ? this.scrollbarWidth : 0;
    var offsetForYScrollbar = this.axis.y.isOverflowing ? this.scrollbarWidth : 0;
    this.axis.x.isOverflowing = this.axis.x.isOverflowing && contentElScrollWidth > contentWrapperElOffsetWidth - offsetForYScrollbar;
    this.axis.y.isOverflowing = this.axis.y.isOverflowing && contentElScrollHeight > contentWrapperElOffsetHeight - offsetForXScrollbar;
    this.axis.x.scrollbar.size = this.getScrollbarSize("x");
    this.axis.y.scrollbar.size = this.getScrollbarSize("y");
    this.axis.x.scrollbar.el.style.width = this.axis.x.scrollbar.size + "px";
    this.axis.y.scrollbar.el.style.height = this.axis.y.scrollbar.size + "px";
    this.positionScrollbar("x");
    this.positionScrollbar("y");
    this.toggleTrackVisibility("x");
    this.toggleTrackVisibility("y");
  };
  _proto.getScrollbarSize = function getScrollbarSize(axis) {
    if (axis === void 0) {
      axis = "y";
    }
    if (!this.axis[axis].isOverflowing) {
      return 0;
    }
    var contentSize = this.contentEl[this.axis[axis].scrollSizeAttr];
    var trackSize = this.axis[axis].track.el[this.axis[axis].offsetSizeAttr];
    var scrollbarSize;
    var scrollbarRatio = trackSize / contentSize;
    scrollbarSize = Math.max(~~(scrollbarRatio * trackSize), this.options.scrollbarMinSize);
    if (this.options.scrollbarMaxSize) {
      scrollbarSize = Math.min(scrollbarSize, this.options.scrollbarMaxSize);
    }
    return scrollbarSize;
  };
  _proto.positionScrollbar = function positionScrollbar(axis) {
    if (axis === void 0) {
      axis = "y";
    }
    if (!this.axis[axis].isOverflowing) {
      return;
    }
    var contentSize = this.contentWrapperEl[this.axis[axis].scrollSizeAttr];
    var trackSize = this.axis[axis].track.el[this.axis[axis].offsetSizeAttr];
    var hostSize = parseInt(this.elStyles[this.axis[axis].sizeAttr], 10);
    var scrollbar = this.axis[axis].scrollbar;
    var scrollOffset = this.contentWrapperEl[this.axis[axis].scrollOffsetAttr];
    scrollOffset = axis === "x" && this.isRtl && SimpleBar2.getRtlHelpers().isRtlScrollingInverted ? -scrollOffset : scrollOffset;
    var scrollPourcent = scrollOffset / (contentSize - hostSize);
    var handleOffset = ~~((trackSize - scrollbar.size) * scrollPourcent);
    handleOffset = axis === "x" && this.isRtl && SimpleBar2.getRtlHelpers().isRtlScrollbarInverted ? handleOffset + (trackSize - scrollbar.size) : handleOffset;
    scrollbar.el.style.transform = axis === "x" ? "translate3d(" + handleOffset + "px, 0, 0)" : "translate3d(0, " + handleOffset + "px, 0)";
  };
  _proto.toggleTrackVisibility = function toggleTrackVisibility(axis) {
    if (axis === void 0) {
      axis = "y";
    }
    var track = this.axis[axis].track.el;
    var scrollbar = this.axis[axis].scrollbar.el;
    if (this.axis[axis].isOverflowing || this.axis[axis].forceVisible) {
      track.style.visibility = "visible";
      this.contentWrapperEl.style[this.axis[axis].overflowAttr] = "scroll";
    } else {
      track.style.visibility = "hidden";
      this.contentWrapperEl.style[this.axis[axis].overflowAttr] = "hidden";
    }
    if (this.axis[axis].isOverflowing) {
      scrollbar.style.display = "block";
    } else {
      scrollbar.style.display = "none";
    }
  };
  _proto.hideNativeScrollbar = function hideNativeScrollbar() {
    this.offsetEl.style[this.isRtl ? "left" : "right"] = this.axis.y.isOverflowing || this.axis.y.forceVisible ? "-" + this.scrollbarWidth + "px" : 0;
    this.offsetEl.style.bottom = this.axis.x.isOverflowing || this.axis.x.forceVisible ? "-" + this.scrollbarWidth + "px" : 0;
  };
  _proto.onMouseMoveForAxis = function onMouseMoveForAxis(axis) {
    if (axis === void 0) {
      axis = "y";
    }
    this.axis[axis].track.rect = this.axis[axis].track.el.getBoundingClientRect();
    this.axis[axis].scrollbar.rect = this.axis[axis].scrollbar.el.getBoundingClientRect();
    var isWithinScrollbarBoundsX = this.isWithinBounds(this.axis[axis].scrollbar.rect);
    if (isWithinScrollbarBoundsX) {
      this.axis[axis].scrollbar.el.classList.add(this.classNames.hover);
    } else {
      this.axis[axis].scrollbar.el.classList.remove(this.classNames.hover);
    }
    if (this.isWithinBounds(this.axis[axis].track.rect)) {
      this.showScrollbar(axis);
      this.axis[axis].track.el.classList.add(this.classNames.hover);
    } else {
      this.axis[axis].track.el.classList.remove(this.classNames.hover);
    }
  };
  _proto.onMouseLeaveForAxis = function onMouseLeaveForAxis(axis) {
    if (axis === void 0) {
      axis = "y";
    }
    this.axis[axis].track.el.classList.remove(this.classNames.hover);
    this.axis[axis].scrollbar.el.classList.remove(this.classNames.hover);
  };
  _proto.showScrollbar = function showScrollbar(axis) {
    if (axis === void 0) {
      axis = "y";
    }
    var scrollbar = this.axis[axis].scrollbar.el;
    if (!this.axis[axis].isVisible) {
      scrollbar.classList.add(this.classNames.visible);
      this.axis[axis].isVisible = true;
    }
    if (this.options.autoHide) {
      this.hideScrollbars();
    }
  };
  _proto.onDragStart = function onDragStart(e3, axis) {
    if (axis === void 0) {
      axis = "y";
    }
    var elDocument = getElementDocument(this.el);
    var elWindow = getElementWindow(this.el);
    var scrollbar = this.axis[axis].scrollbar;
    var eventOffset = axis === "y" ? e3.pageY : e3.pageX;
    this.axis[axis].dragOffset = eventOffset - scrollbar.rect[this.axis[axis].offsetAttr];
    this.draggedAxis = axis;
    this.el.classList.add(this.classNames.dragging);
    elDocument.addEventListener("mousemove", this.drag, true);
    elDocument.addEventListener("mouseup", this.onEndDrag, true);
    if (this.removePreventClickId === null) {
      elDocument.addEventListener("click", this.preventClick, true);
      elDocument.addEventListener("dblclick", this.preventClick, true);
    } else {
      elWindow.clearTimeout(this.removePreventClickId);
      this.removePreventClickId = null;
    }
  };
  _proto.onTrackClick = function onTrackClick(e3, axis) {
    var _this4 = this;
    if (axis === void 0) {
      axis = "y";
    }
    if (!this.options.clickOnTrack) return;
    var elWindow = getElementWindow(this.el);
    this.axis[axis].scrollbar.rect = this.axis[axis].scrollbar.el.getBoundingClientRect();
    var scrollbar = this.axis[axis].scrollbar;
    var scrollbarOffset = scrollbar.rect[this.axis[axis].offsetAttr];
    var hostSize = parseInt(this.elStyles[this.axis[axis].sizeAttr], 10);
    var scrolled = this.contentWrapperEl[this.axis[axis].scrollOffsetAttr];
    var t3 = axis === "y" ? this.mouseY - scrollbarOffset : this.mouseX - scrollbarOffset;
    var dir = t3 < 0 ? -1 : 1;
    var scrollSize = dir === -1 ? scrolled - hostSize : scrolled + hostSize;
    var scrollTo = function scrollTo2() {
      if (dir === -1) {
        if (scrolled > scrollSize) {
          var _this4$contentWrapper;
          scrolled -= _this4.options.clickOnTrackSpeed;
          _this4.contentWrapperEl.scrollTo((_this4$contentWrapper = {}, _this4$contentWrapper[_this4.axis[axis].offsetAttr] = scrolled, _this4$contentWrapper));
          elWindow.requestAnimationFrame(scrollTo2);
        }
      } else {
        if (scrolled < scrollSize) {
          var _this4$contentWrapper2;
          scrolled += _this4.options.clickOnTrackSpeed;
          _this4.contentWrapperEl.scrollTo((_this4$contentWrapper2 = {}, _this4$contentWrapper2[_this4.axis[axis].offsetAttr] = scrolled, _this4$contentWrapper2));
          elWindow.requestAnimationFrame(scrollTo2);
        }
      }
    };
    scrollTo();
  };
  _proto.getContentElement = function getContentElement() {
    return this.contentEl;
  };
  _proto.getScrollElement = function getScrollElement() {
    return this.contentWrapperEl;
  };
  _proto.getScrollbarWidth = function getScrollbarWidth() {
    try {
      if (getComputedStyle(this.contentWrapperEl, "::-webkit-scrollbar").display === "none" || "scrollbarWidth" in document.documentElement.style || "-ms-overflow-style" in document.documentElement.style) {
        return 0;
      } else {
        return scrollbarWidth(this.el);
      }
    } catch (e3) {
      return scrollbarWidth(this.el);
    }
  };
  _proto.removeListeners = function removeListeners() {
    var _this5 = this;
    var elWindow = getElementWindow(this.el);
    if (this.options.autoHide) {
      this.el.removeEventListener("mouseenter", this.onMouseEnter);
    }
    ["mousedown", "click", "dblclick"].forEach(function(e3) {
      _this5.el.removeEventListener(e3, _this5.onPointerEvent, true);
    });
    ["touchstart", "touchend", "touchmove"].forEach(function(e3) {
      _this5.el.removeEventListener(e3, _this5.onPointerEvent, {
        capture: true,
        passive: true
      });
    });
    this.el.removeEventListener("mousemove", this.onMouseMove);
    this.el.removeEventListener("mouseleave", this.onMouseLeave);
    if (this.contentWrapperEl) {
      this.contentWrapperEl.removeEventListener("scroll", this.onScroll);
    }
    elWindow.removeEventListener("resize", this.onWindowResize);
    if (this.mutationObserver) {
      this.mutationObserver.disconnect();
    }
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    this.recalculate.cancel();
    this.onMouseMove.cancel();
    this.hideScrollbars.cancel();
    this.onWindowResize.cancel();
  };
  _proto.unMount = function unMount() {
    this.removeListeners();
    SimpleBar2.instances.delete(this.el);
  };
  _proto.isWithinBounds = function isWithinBounds(bbox) {
    return this.mouseX >= bbox.left && this.mouseX <= bbox.left + bbox.width && this.mouseY >= bbox.top && this.mouseY <= bbox.top + bbox.height;
  };
  _proto.findChild = function findChild2(el2, query2) {
    var matches3 = el2.matches || el2.webkitMatchesSelector || el2.mozMatchesSelector || el2.msMatchesSelector;
    return Array.prototype.filter.call(el2.children, function(child) {
      return matches3.call(child, query2);
    })[0];
  };
  return SimpleBar2;
}();
SimpleBar.defaultOptions = {
  autoHide: true,
  forceVisible: false,
  clickOnTrack: true,
  clickOnTrackSpeed: 40,
  classNames: {
    contentEl: "simplebar-content",
    contentWrapper: "simplebar-content-wrapper",
    offset: "simplebar-offset",
    mask: "simplebar-mask",
    wrapper: "simplebar-wrapper",
    placeholder: "simplebar-placeholder",
    scrollbar: "simplebar-scrollbar",
    track: "simplebar-track",
    heightAutoObserverWrapperEl: "simplebar-height-auto-observer-wrapper",
    heightAutoObserverEl: "simplebar-height-auto-observer",
    visible: "simplebar-visible",
    horizontal: "simplebar-horizontal",
    vertical: "simplebar-vertical",
    hover: "simplebar-hover",
    dragging: "simplebar-dragging"
  },
  scrollbarMinSize: 25,
  scrollbarMaxSize: 0,
  timeout: 1e3
};
SimpleBar.instances = /* @__PURE__ */ new WeakMap();
SimpleBar.initDOMLoadedElements = function() {
  document.removeEventListener("DOMContentLoaded", this.initDOMLoadedElements);
  window.removeEventListener("load", this.initDOMLoadedElements);
  Array.prototype.forEach.call(document.querySelectorAll("[data-simplebar]"), function(el2) {
    if (el2.getAttribute("data-simplebar") !== "init" && !SimpleBar.instances.has(el2)) new SimpleBar(el2, getOptions2(el2.attributes));
  });
};
SimpleBar.removeObserver = function() {
  this.globalObserver.disconnect();
};
SimpleBar.initHtmlApi = function() {
  this.initDOMLoadedElements = this.initDOMLoadedElements.bind(this);
  if (typeof MutationObserver !== "undefined") {
    this.globalObserver = new MutationObserver(SimpleBar.handleMutations);
    this.globalObserver.observe(document, {
      childList: true,
      subtree: true
    });
  }
  if (document.readyState === "complete" || document.readyState !== "loading" && !document.documentElement.doScroll) {
    window.setTimeout(this.initDOMLoadedElements);
  } else {
    document.addEventListener("DOMContentLoaded", this.initDOMLoadedElements);
    window.addEventListener("load", this.initDOMLoadedElements);
  }
};
SimpleBar.handleMutations = function(mutations) {
  mutations.forEach(function(mutation) {
    Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) {
      if (addedNode.nodeType === 1) {
        if (addedNode.hasAttribute("data-simplebar")) {
          !SimpleBar.instances.has(addedNode) && document.documentElement.contains(addedNode) && new SimpleBar(addedNode, getOptions2(addedNode.attributes));
        } else {
          Array.prototype.forEach.call(addedNode.querySelectorAll("[data-simplebar]"), function(el2) {
            if (el2.getAttribute("data-simplebar") !== "init" && !SimpleBar.instances.has(el2) && document.documentElement.contains(el2)) new SimpleBar(el2, getOptions2(el2.attributes));
          });
        }
      }
    });
    Array.prototype.forEach.call(mutation.removedNodes, function(removedNode) {
      if (removedNode.nodeType === 1) {
        if (removedNode.getAttribute("data-simplebar") === "init") {
          SimpleBar.instances.has(removedNode) && !document.documentElement.contains(removedNode) && SimpleBar.instances.get(removedNode).unMount();
        } else {
          Array.prototype.forEach.call(removedNode.querySelectorAll('[data-simplebar="init"]'), function(el2) {
            SimpleBar.instances.has(el2) && !document.documentElement.contains(el2) && SimpleBar.instances.get(el2).unMount();
          });
        }
      }
    });
  });
};
SimpleBar.getOptions = getOptions2;
if (import_can_use_dom.default) {
  SimpleBar.initHtmlApi();
}
var simplebar_esm_default = SimpleBar;

// public/app/stores/utils/createStoreMixin.ts
function createStoreMixin(State) {
  return new Proxy(
    class {
      constructor(initialState) {
        [this._state, this._setState] = createStore(
          JSON.parse(JSON.stringify(new State(initialState)))
        );
      }
      get state() {
        return this._state;
      }
      get setState() {
        return this._setState;
      }
    },
    {
      construct: function(target, args, newTarget) {
        const instance = Reflect.construct(target, args, newTarget);
        return new Proxy(instance, {
          get: function(target2, prop2, receiver) {
            if (prop2 in target2.state) return target2.state[String(prop2)];
            return target2[String(prop2)];
          }
        });
      }
    }
  );
}

// public/app/ui/base/sync-scroll.tsx
var SyncScrollState = class {
  elts = [];
  start = 0;
  current = 0;
};
var SyncScrollStore = class extends createStoreMixin(SyncScrollState) {
  register(elt) {
    if (!this.state.elts.includes(elt)) {
      this.setState("elts", (elts) => [...elts, elt]);
    }
  }
  unregister(elt) {
    if (this.state.elts.includes(elt)) {
      this.setState("elts", (elts) => elts.filter((e3) => e3 !== elt));
    }
  }
  init(source, start) {
    this.setState(produce((s3) => {
      s3.source = source;
      s3.start = start;
    }));
  }
  setCurrent(value2) {
    this.setState("current", value2);
  }
  resetSource() {
    this.setState("source", void 0);
  }
};
var SyncScrollContext = createContext();
function useSyncScroll() {
  return useContext(SyncScrollContext);
}

// public/app/ui/base/virtual.tsx
var _tmpl$16 = /* @__PURE__ */ template(`<div></div>`, 2);
function createVirtualState() {
  const [state, setState] = createStore({
    firstVisibleIndex: 0,
    lastVisibleIndex: 0,
    averageItemHeight: 50,
    paddingTop: 0,
    paddingBottom: 0,
    pendingUpdate: false,
    itemHeights: {},
    visible: false
  });
  return [state, setState];
}
function binarySearch(low, high, target, index2, getHeightUpTo) {
  let result2 = index2;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    const heightBefore = getHeightUpTo(mid);
    if (heightBefore <= target) {
      result2 = mid;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return result2;
}
function genericUpdate(scrollContainer, virtualContainerRef, nbItems, getHeightUpTo, isVisible, overscan = 5) {
  const containerOffset = virtualContainerRef.offsetTop;
  const localScrollTop = scrollContainer.scrollTop() - containerOffset;
  const viewHeight = scrollContainer.getHeight();
  let firstIndex = 0, lastIndex = 0;
  firstIndex = binarySearch(0, nbItems - 1, localScrollTop, 0, getHeightUpTo);
  firstIndex = Math.max(0, firstIndex - overscan);
  lastIndex = binarySearch(firstIndex, nbItems - 1, localScrollTop + viewHeight, nbItems - 1, getHeightUpTo);
  lastIndex = Math.min(nbItems - 1, lastIndex + overscan);
  if (!isVisible) {
    const maxVisible = 10;
    lastIndex = Math.min(lastIndex, firstIndex + maxVisible - 1);
  }
  const paddingTop = getHeightUpTo(firstIndex - 1);
  const paddingBottom = getHeightUpTo(nbItems - 1) - getHeightUpTo(lastIndex);
  return {
    firstVisibleIndex: firstIndex,
    lastVisibleIndex: lastIndex,
    paddingTop: Math.round(paddingTop),
    paddingBottom: Math.round(paddingBottom)
  };
}
var ScrollableContainerContext = createContext(() => ({
  elt: window,
  getHeight: () => window.innerHeight,
  scrollTop: () => window.scrollY,
  scrollToY: (y3) => window.scrollTo(0, y3)
}));
function useScrollableContainer() {
  return useContext(ScrollableContainerContext);
}
var ScrollableContainerProvider = (props2) => {
  return createComponent(ScrollableContainerContext.Provider, {
    get value() {
      return props2.container;
    },
    get children() {
      return props2.children;
    }
  });
};
var VirtualContainerContext = createContext();
function useVirtualContainer() {
  return useContext(VirtualContainerContext);
}
function VirtualContainer(props2) {
  let containerRef;
  const scrollableContainer = useScrollableContainer();
  const [state, setState] = createVirtualState();
  const items = createMemo(() => props2.items.map((item, index2) => ({
    get height() {
      return state.itemHeights[index2] ?? state.averageItemHeight;
    },
    item,
    index: index2
  })), {}, {
    equals: (prev, next2) => {
      if (prev.length !== next2.length) return false;
      return prev.every((wrapper, index2) => {
        return wrapper.item === next2[index2].item;
      });
    }
  });
  let fenwickTree = [];
  let heightSnapshot = [];
  const fenwickAdd = (index2, delta) => {
    for (let i3 = index2 + 1; i3 < fenwickTree.length; i3 += i3 & -i3) {
      fenwickTree[i3] += delta;
    }
  };
  const fenwickSum = (index2) => {
    let sum = 0;
    for (let i3 = index2 + 1; i3 > 0; i3 -= i3 & -i3) {
      sum += fenwickTree[i3];
    }
    return sum;
  };
  const buildFenwick = (length, averageHeight, itemHeights) => {
    fenwickTree = new Array(length + 1).fill(0);
    heightSnapshot = new Array(length);
    for (let i3 = 0; i3 < length; i3 += 1) {
      const height = itemHeights[i3] ?? averageHeight;
      heightSnapshot[i3] = height;
      fenwickAdd(i3, height);
    }
  };
  const ensureFenwick = () => {
    const length = props2.items.length;
    if (length === heightSnapshot.length && fenwickTree.length === length + 1) {
      return;
    }
    const itemHeights = untrack(() => state.itemHeights);
    buildFenwick(length, state.averageItemHeight, itemHeights);
  };
  const isVisible = () => state.visible;
  const getHeightUpTo = (index2) => {
    if (index2 < 0) return 0;
    ensureFenwick();
    return fenwickTree.length ? fenwickSum(index2) : 0;
  };
  const update2 = () => {
    if (!state.visible) return;
    const scrollContainer = scrollableContainer();
    const result2 = genericUpdate(scrollContainer, containerRef, items().length, getHeightUpTo, isVisible());
    setState(produce((draft) => {
      draft.firstVisibleIndex = result2.firstVisibleIndex;
      draft.lastVisibleIndex = result2.lastVisibleIndex;
      draft.paddingTop = result2.paddingTop;
      draft.paddingBottom = result2.paddingBottom;
    }));
  };
  createEffect(() => {
    const paddingTop = state.paddingTop;
    const paddingBottom = state.paddingBottom;
    if (!containerRef) return;
    containerRef.style.cssText = `padding-top: ${paddingTop}px; padding-bottom: ${paddingBottom}px;`;
  });
  const scheduleUpdate = () => {
    if (state.pendingUpdate) return;
    setState("pendingUpdate", true);
    requestAnimationFrame(() => {
      update2();
      setState("pendingUpdate", false);
    });
  };
  const getEltHeight = (index2, height) => {
    if (Math.abs((state.itemHeights[index2] ?? -1) - height) < 0.1) return;
    ensureFenwick();
    const previousHeight = heightSnapshot[index2] ?? state.averageItemHeight;
    batch(() => {
      setState("itemHeights", index2, height);
      const measuredItems = Object.values(state.itemHeights);
      if (measuredItems.length >= 10) {
        const newAverage = measuredItems.reduce((sum, h3) => sum + h3, 0) / measuredItems.length;
        if (Math.abs(newAverage - state.averageItemHeight) > 1) {
          setState("averageItemHeight", newAverage);
        }
      }
    });
    const delta = height - previousHeight;
    if (delta !== 0) {
      heightSnapshot[index2] = height;
      fenwickAdd(index2, delta);
    }
    scheduleUpdate();
  };
  const scrollUpdate = () => {
    scheduleUpdate();
  };
  const resizeUpdate = () => {
    scheduleUpdate();
  };
  let hasListener = false;
  onMount(() => {
    const obs = new IntersectionObserver((entries2) => {
      const entry = entries2[0];
      setState("visible", entry.isIntersecting);
      if (entry.isIntersecting && !hasListener) {
        const scrollContainer = scrollableContainer();
        scrollContainer.elt.addEventListener("scroll", scrollUpdate);
        window.addEventListener("resize", resizeUpdate);
        hasListener = true;
      }
      scheduleUpdate();
    });
    obs.observe(containerRef);
    setTimeout(scheduleUpdate);
    onCleanup(() => {
      obs.unobserve(containerRef);
      if (hasListener) {
        const scrollContainer = scrollableContainer();
        scrollContainer.elt.removeEventListener("scroll", scrollUpdate);
        window.removeEventListener("resize", resizeUpdate);
      }
    });
  });
  const visibleItems = () => items().slice(state.firstVisibleIndex, state.lastVisibleIndex + 1);
  createEffect(on(() => items().length, () => scheduleUpdate(), {
    defer: true
  }));
  createEffect(on(() => [props2.items.length, state.averageItemHeight], ([ilength, avHeight]) => {
    const itemHeights = state.itemHeights;
    buildFenwick(ilength, avHeight, itemHeights);
    scheduleUpdate();
  }));
  return (() => {
    const _el$ = _tmpl$16.cloneNode(true);
    const _ref$ = containerRef;
    typeof _ref$ === "function" ? use(_ref$, _el$) : containerRef = _el$;
    insert(_el$, createComponent(For, {
      get each() {
        return visibleItems();
      },
      children: (wrapper) => {
        const index2 = wrapper.index;
        const itemHeightSetter = (height) => getEltHeight(index2, height);
        return VirtualContainerContext.Provider({
          get value() {
            return {
              itemHeightSetter
            };
          },
          get children() {
            return props2.children(wrapper.item, itemHeightSetter, () => index2);
          }
        });
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.suffixComponent;
      },
      get children() {
        return props2.suffixComponent;
      }
    }), null);
    createRenderEffect(() => className(_el$, props2.class));
    return _el$;
  })();
}

// public/app/ui/base/scroll-container.tsx
var ScrollContainer = (props2) => {
  let ref;
  const [local, others] = splitProps(props2, ["as", "onInitialized", "native", "sync", "children"]);
  const sync2 = useSyncScroll();
  const scrollableContainer = () => {
    const _ref = local.native ? ref : simplebar_esm_default.instances.get(ref)?.getScrollElement();
    return {
      getHeight: () => _ref.clientHeight,
      scrollTop: () => _ref.scrollTop,
      scrollToY: (y3) => _ref.scrollTop = y3,
      elt: _ref
    };
  };
  onMount(() => {
    if (local.native) {
      if (local.onInitialized) local.onInitialized({
        getScrollElement: () => ref
      });
    } else {
      const instance = new simplebar_esm_default(ref);
      if (local.onInitialized) local.onInitialized(instance);
    }
  });
  createEffect(() => {
    const keepSync = props2.sync;
    if (sync2) {
      const scrollElt = props2.native ? ref : simplebar_esm_default.instances.get(ref)?.getScrollElement();
      if (keepSync) {
        sync2.register(scrollElt);
      } else {
        sync2.unregister(scrollElt);
      }
    }
  });
  onCleanup(() => {
    if (sync2) sync2.unregister(ref);
  });
  return createComponent(Dynamic, mergeProps({
    ref(r$) {
      const _ref$ = ref;
      typeof _ref$ === "function" ? _ref$(r$) : ref = r$;
    },
    get component() {
      return local.as ?? "div";
    }
  }, others, {
    get children() {
      return createComponent(ScrollableContainerProvider, {
        container: scrollableContainer,
        get children() {
          return local.children;
        }
      });
    }
  }));
};

// public/app/ui/base/sidebar.jsx
function NavSidebar(props2) {
  return createComponent(NgComponent, mergeProps({
    directive: "nav-sidebar"
  }, props2));
}

// public/app/ui/base/slider.tsx
var _tmpl$17 = /* @__PURE__ */ template(`<span class="slider-thumb"><input type="range" class="visually-hidden" aria-orientation="horizontal"></span>`, 3);
var _tmpl$28 = /* @__PURE__ */ template(`<div><span class="slider-rail"></span><span class="slider-track"></span></div>`, 6);
var _tmpl$33 = /* @__PURE__ */ template(`<span class="slider-mark"></span>`, 2);
var _tmpl$43 = /* @__PURE__ */ template(`<span aria-hidden class="slider-mark-label"></span>`, 2);
var INTENTIONAL_DRAG_COUNT_THRESHOLD = 2;
function ownerDocument(node) {
  return node && node.ownerDocument || document;
}
var cachedSupportsTouchActionNone;
function doesSupportTouchActionNone() {
  if (cachedSupportsTouchActionNone === void 0) {
    if (typeof CSS !== "undefined" && typeof CSS.supports === "function") {
      cachedSupportsTouchActionNone = CSS.supports("touch-action", "none");
    } else {
      cachedSupportsTouchActionNone = true;
    }
  }
  return cachedSupportsTouchActionNone;
}
function clamp3(value2, min3, max3) {
  if (value2 == null) {
    return min3;
  }
  return Math.min(Math.max(min3, value2), max3);
}
function findClosest(values2, currentValue) {
  const {
    index: closestIndex
  } = values2.reduce((acc, value2, index2) => {
    const distance = Math.abs(currentValue - value2);
    if (acc === null || distance < acc.distance || distance === acc.distance) {
      return {
        distance,
        index: index2
      };
    }
    return acc;
  }, null) ?? {};
  return closestIndex;
}
function valueToPercent(value2, min3, max3) {
  return (value2 - min3) * 100 / (max3 - min3);
}
function percentToValue(percent, min3, max3) {
  return (max3 - min3) * percent + min3;
}
function roundValueToStep(value2, step2, min3) {
  const nearest = Math.round((value2 - min3) / step2) * step2 + min3;
  return Number(nearest.toFixed(getDecimalPrecision(step2)));
}
function getDecimalPrecision(num) {
  if (Math.abs(num) < 1) {
    const parts = num.toExponential().split("e-");
    const matissaDecimalPart = parts[0].split(".")[1];
    return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
  }
  const decimalPart = num.toString().split(".")[1];
  return decimalPart ? decimalPart.length : 0;
}
function focusThumb({
  sliderRef,
  thumbRef,
  setActive: setActive2
}) {
  const doc4 = ownerDocument(sliderRef);
  if (!sliderRef.contains(doc4.activeElement) || doc4?.activeElement !== thumbRef) {
    thumbRef.focus();
  }
  if (setActive2) {
    setActive2(true);
  }
}
function Slider(props2) {
  let thumbRef;
  let sliderRef;
  props2 = mergeProps({
    min: 0,
    max: 100,
    step: 1,
    marks: false,
    readonly: false
  }, props2);
  const [value2, setValue2] = createSignal(props2.value !== void 0 ? props2.value : props2.min);
  const [touchId, setTouchId] = createSignal(void 0);
  const [active, setActive2] = createSignal(false);
  const [dragging, setDragging] = createSignal(false);
  const [isFocused, setIsFocused] = createSignal(false);
  const [moveCount, setMoveCount] = createSignal(0);
  let valueSetOnce = false;
  function setValueOnce() {
    setValue2(props2.value !== void 0 ? props2.value : props2.min);
    if (props2.value !== void 0) {
      valueSetOnce = true;
    }
  }
  createEffect(() => {
    if (!valueSetOnce) setValueOnce();
  });
  const readonly = createMemo(() => {
    return props2.readonly || props2.disabled;
  });
  const width = createMemo(() => {
    return `${valueToPercent(value2(), props2.min, props2.max)}%`;
  });
  const marks3 = createMemo(() => {
    if (props2.marks === false) {
      return [];
    }
    const marks4 = [];
    if (props2.marks === true) {
      if (props2.step) {
        for (let i3 = props2.min; i3 <= props2.max; i3 += props2.step) {
          marks4.push({
            value: i3,
            left: `${valueToPercent(i3, props2.min, props2.max)}%`,
            active: i3 <= value2()
          });
        }
        return marks4;
      }
      return [];
    }
    for (const mark2 of props2.marks) {
      if (typeof mark2 === "number") {
        marks4.push({
          value: mark2,
          left: `${valueToPercent(mark2, props2.min, props2.max)}%`,
          active: mark2 <= value2()
        });
      } else {
        marks4.push({
          ...mark2,
          left: `${valueToPercent(mark2.value, props2.min, props2.max)}%`,
          active: mark2.value <= value2()
        });
      }
    }
    return marks4;
  });
  const marksValues = createMemo(() => marks3().map((mark2) => mark2.value));
  const handleChange = props2.onChange && ((event2) => {
    return props2.onChange(value2());
  });
  const handleChangeCommitted = props2.onChangeCommitted && ((event2) => {
    return props2.onChangeCommitted(value2());
  });
  function trackFinger(event2, touchId2) {
    if (touchId2() !== void 0 && event2.changedTouches) {
      const touchEvent = event2;
      for (let i3 = 0; i3 < touchEvent.changedTouches.length; i3 += 1) {
        const touch = touchEvent.changedTouches[i3];
        if (touch.identifier === touchId2()) {
          return {
            x: touch.clientX,
            y: touch.clientY
          };
        }
      }
      return false;
    }
    return {
      x: event2.clientX,
      y: event2.clientY
    };
  }
  function getFingerNewValue({
    finger
  }) {
    const {
      width: width2,
      left
    } = sliderRef.getBoundingClientRect();
    let percent = (finger.x - left) / width2;
    let newValue = percentToValue(percent, props2.min, props2.max);
    if (props2.step) {
      newValue = roundValueToStep(newValue, props2.step, props2.min);
    } else {
      const closestIndex = findClosest(marksValues(), newValue);
      newValue = marksValues()[closestIndex];
    }
    return clamp3(newValue, props2.min, props2.max);
  }
  function handleHiddenInputFocus(event2) {
    setIsFocused(true);
  }
  ;
  function handleHiddenInputBlur(event2) {
    setIsFocused(false);
  }
  ;
  function handleHiddenInputChange(event2) {
    const marksIndex = marksValues().indexOf(value2());
    let newValue = event2.target.valueAsNumber;
    if (marks3() && props2.step == null) {
      newValue = newValue < value2() ? marksValues()[marksIndex - 1] : marksValues()[marksIndex + 1];
    }
    newValue = clamp3(newValue, props2.min, props2.max);
    if (marks3() && props2.step == null) {
      const currentMarkIndex = marksValues().indexOf(value2());
      newValue = newValue < value2() ? marksValues()[currentMarkIndex - 1] : marksValues()[currentMarkIndex + 1];
    }
    setIsFocused(true);
    if (newValue !== value2()) {
      setValue2(newValue);
      handleChange?.(event2);
    }
    handleChangeCommitted?.(event2);
  }
  function handleMouseDown(event2) {
    if (readonly()) {
      return;
    }
    if (event2.defaultPrevented) {
      return;
    }
    if (event2.button !== 0) {
      return;
    }
    event2.preventDefault();
    const finger = trackFinger(event2, touchId);
    if (finger !== false) {
      const newValue = getFingerNewValue({
        finger
      });
      focusThumb({
        sliderRef,
        thumbRef,
        setActive: setActive2
      });
      if (newValue !== value2()) {
        setValue2(newValue);
        handleChange?.(event2);
      }
    }
    setMoveCount(0);
    const doc4 = ownerDocument(sliderRef);
    doc4.addEventListener("mousemove", handleTouchMove);
    doc4.addEventListener("mouseup", handleTouchEnd);
  }
  function handleTouchStart(nativeEvent) {
    if (readonly()) {
      return;
    }
    if (!doesSupportTouchActionNone()) {
      nativeEvent.preventDefault();
    }
    const touch = nativeEvent.changedTouches[0];
    if (touch != null) {
      setTouchId(touch.identifier);
    }
    const finger = trackFinger(nativeEvent, touchId);
    if (finger !== false) {
      const newValue = getFingerNewValue({
        finger
      });
      focusThumb({
        sliderRef,
        thumbRef,
        setActive: setActive2
      });
      if (newValue !== value2()) {
        setValue2(newValue);
        handleChange?.(nativeEvent);
      }
    }
    setMoveCount(0);
    const doc4 = ownerDocument(sliderRef);
    doc4.addEventListener("touchmove", handleTouchMove);
    doc4.addEventListener("touchend", handleTouchEnd);
  }
  ;
  function handleTouchMove(nativeEvent) {
    const finger = trackFinger(nativeEvent, touchId);
    if (!finger) {
      return;
    }
    setMoveCount(moveCount() + 1);
    if (nativeEvent.type === "mousemove" && nativeEvent.buttons === 0) {
      handleTouchEnd(nativeEvent);
      return;
    }
    const newValue = getFingerNewValue({
      finger
    });
    focusThumb({
      sliderRef,
      thumbRef,
      setActive: setActive2
    });
    if (!dragging() && moveCount() > INTENTIONAL_DRAG_COUNT_THRESHOLD) {
      setDragging(true);
    }
    if (newValue !== value2()) {
      setValue2(newValue);
      handleChange?.(nativeEvent);
    }
  }
  function handleTouchEnd(nativeEvent) {
    const finger = trackFinger(nativeEvent, touchId);
    setDragging(false);
    if (!finger) {
      return;
    }
    const newValue = getFingerNewValue({
      finger
    });
    if (nativeEvent.type === "touchend") {
    }
    setActive2(false);
    setValue2(newValue);
    handleChangeCommitted?.(nativeEvent);
    setTouchId(void 0);
    stopListening();
  }
  function stopListening() {
    const doc4 = ownerDocument(sliderRef);
    doc4.removeEventListener("mousemove", handleTouchMove);
    doc4.removeEventListener("mouseup", handleTouchEnd);
    doc4.removeEventListener("touchmove", handleTouchMove);
    doc4.removeEventListener("touchend", handleTouchEnd);
  }
  createEffect(() => {
    if (readonly() && sliderRef.contains(document.activeElement)) {
      document.activeElement?.blur();
    }
  });
  if (readonly() && active()) {
    setActive2(false);
  }
  createEffect(() => {
    sliderRef.addEventListener("touchstart", handleTouchStart, {
      passive: doesSupportTouchActionNone()
    });
    onCleanup(() => {
      sliderRef.removeEventListener("touchstart", handleTouchStart, {
        // @ts-ignore
        passive: doesSupportTouchActionNone()
      });
      stopListening();
    });
  });
  createEffect(() => {
    if (readonly()) {
      stopListening();
    }
  });
  return (() => {
    const _el$ = _tmpl$28.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
    _el$.$$mousedown = handleMouseDown;
    const _ref$ = sliderRef;
    typeof _ref$ === "function" ? use(_ref$, _el$) : sliderRef = _el$;
    insert(_el$, createComponent(For, {
      get each() {
        return marks3();
      },
      children: (mark2) => [(() => {
        const _el$6 = _tmpl$33.cloneNode(true);
        createRenderEffect((_p$) => {
          const _v$21 = !!mark2.active, _v$22 = mark2.left || void 0;
          _v$21 !== _p$._v$21 && _el$6.classList.toggle("slider-mark-active", _p$._v$21 = _v$21);
          _v$22 !== _p$._v$22 && _el$6.style.setProperty("left", _p$._v$22 = _v$22);
          return _p$;
        }, {
          _v$21: void 0,
          _v$22: void 0
        });
        return _el$6;
      })(), createComponent(Show, {
        get when() {
          return mark2.label;
        },
        get children() {
          const _el$7 = _tmpl$43.cloneNode(true);
          insert(_el$7, () => mark2.label);
          createRenderEffect((_p$) => {
            const _v$23 = !!mark2.active, _v$24 = mark2.left;
            _v$23 !== _p$._v$23 && _el$7.classList.toggle("slider-mark-label-active", _p$._v$23 = _v$23);
            _v$24 !== _p$._v$24 && _el$7.style.setProperty("left", _p$._v$24 = _v$24);
            return _p$;
          }, {
            _v$23: void 0,
            _v$24: void 0
          });
          return _el$7;
        }
      })]
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return !readonly();
      },
      get children() {
        return createComponent(Tooltip, {
          get enabled() {
            return props2.valueLabelDisplay === "auto" || props2.valueLabelDisplay === "on";
          },
          get label() {
            return value2();
          },
          get children() {
            const _el$4 = _tmpl$17.cloneNode(true), _el$5 = _el$4.firstChild;
            const _ref$2 = thumbRef;
            typeof _ref$2 === "function" ? use(_ref$2, _el$4) : thumbRef = _el$4;
            _el$5.addEventListener("blur", handleHiddenInputBlur);
            _el$5.addEventListener("focus", handleHiddenInputFocus);
            _el$5.$$input = handleHiddenInputChange;
            createRenderEffect((_p$) => {
              const _v$ = !!active(), _v$2 = !!isFocused(), _v$3 = props2.color || null, _v$4 = width(), _v$5 = props2.min, _v$6 = props2.max, _v$7 = props2.step ?? void 0, _v$8 = readonly(), _v$9 = props2.tabIndex, _v$10 = props2["aria-label"], _v$11 = value2(), _v$12 = props2["aria-labelledby"], _v$13 = props2["aria-valuetext"], _v$14 = props2.max, _v$15 = props2.min, _v$16 = props2.name;
              _v$ !== _p$._v$ && _el$4.classList.toggle("slider-thumb-active", _p$._v$ = _v$);
              _v$2 !== _p$._v$2 && _el$4.classList.toggle("slider-thumb-focus-visible", _p$._v$2 = _v$2);
              _v$3 !== _p$._v$3 && _el$4.style.setProperty("background-color", _p$._v$3 = _v$3);
              _v$4 !== _p$._v$4 && _el$4.style.setProperty("left", _p$._v$4 = _v$4);
              _v$5 !== _p$._v$5 && setAttribute(_el$5, "min", _p$._v$5 = _v$5);
              _v$6 !== _p$._v$6 && setAttribute(_el$5, "max", _p$._v$6 = _v$6);
              _v$7 !== _p$._v$7 && setAttribute(_el$5, "step", _p$._v$7 = _v$7);
              _v$8 !== _p$._v$8 && (_el$5.disabled = _p$._v$8 = _v$8);
              _v$9 !== _p$._v$9 && setAttribute(_el$5, "tabindex", _p$._v$9 = _v$9);
              _v$10 !== _p$._v$10 && setAttribute(_el$5, "aria-label", _p$._v$10 = _v$10);
              _v$11 !== _p$._v$11 && setAttribute(_el$5, "aria-valuenow", _p$._v$11 = _v$11);
              _v$12 !== _p$._v$12 && setAttribute(_el$5, "aria-labelledby", _p$._v$12 = _v$12);
              _v$13 !== _p$._v$13 && setAttribute(_el$5, "aria-valuetext", _p$._v$13 = _v$13);
              _v$14 !== _p$._v$14 && setAttribute(_el$5, "aria-valuemax", _p$._v$14 = _v$14);
              _v$15 !== _p$._v$15 && setAttribute(_el$5, "aria-valuemin", _p$._v$15 = _v$15);
              _v$16 !== _p$._v$16 && setAttribute(_el$5, "name", _p$._v$16 = _v$16);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0,
              _v$3: void 0,
              _v$4: void 0,
              _v$5: void 0,
              _v$6: void 0,
              _v$7: void 0,
              _v$8: void 0,
              _v$9: void 0,
              _v$10: void 0,
              _v$11: void 0,
              _v$12: void 0,
              _v$13: void 0,
              _v$14: void 0,
              _v$15: void 0,
              _v$16: void 0
            });
            createRenderEffect(() => _el$5.value = value2());
            return _el$4;
          }
        });
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$17 = "slider-root" + (props2.classes ? " " + props2.classes : ""), _v$18 = !!dragging(), _v$19 = !!props2.disabled, _v$20 = width();
      _v$17 !== _p$._v$17 && className(_el$, _p$._v$17 = _v$17);
      _v$18 !== _p$._v$18 && _el$.classList.toggle("slider-root-dragging", _p$._v$18 = _v$18);
      _v$19 !== _p$._v$19 && _el$.classList.toggle("slider-root-disabled", _p$._v$19 = _v$19);
      _v$20 !== _p$._v$20 && _el$3.style.setProperty("width", _p$._v$20 = _v$20);
      return _p$;
    }, {
      _v$17: void 0,
      _v$18: void 0,
      _v$19: void 0,
      _v$20: void 0
    });
    return _el$;
  })();
}
var slider_default = Slider;
delegateEvents(["mousedown", "input"]);

// public/app/ui/base/tip.tsx
var _tmpl$18 = /* @__PURE__ */ template(`<button type="button" class="btn-close"></button>`, 2);
var _tmpl$29 = /* @__PURE__ */ template(`<div class="helper-tip"><div></div></div>`, 4);
var _tmpl$34 = /* @__PURE__ */ template(`<p></p>`, 2);
function Tip(props2) {
  const [visible, setVisible] = createSignal(props2.onboardingMarker ? !(currentUser2.onboarded || []).includes(props2.onboardingMarker) : true);
  function handleClose2() {
    if (props2.onboardingMarker) {
      markAsOnboarded(props2.onboardingMarker);
    }
    setVisible(false);
  }
  return createComponent(Show, {
    get when() {
      return visible();
    },
    get children() {
      const _el$ = _tmpl$29.cloneNode(true), _el$2 = _el$.firstChild;
      insert(_el$, createComponent(Icon, {
        get name() {
          return props2.icon || "bi-lightbulb-fill";
        }
      }), _el$2);
      insert(_el$2, () => props2.children);
      insert(_el$, createComponent(Show, {
        get when() {
          return props2.closable || props2.onboardingMarker;
        },
        get children() {
          const _el$3 = _tmpl$18.cloneNode(true);
          _el$3.$$click = handleClose2;
          return _el$3;
        }
      }), null);
      createRenderEffect((_$p) => classList(_el$, props2.classList, _$p));
      return _el$;
    }
  });
}
function MethodTip(props2) {
  return createComponent(Tip, {
    classList: {
      "method-tip": true
    },
    get children() {
      return [(() => {
        const _el$4 = _tmpl$34.cloneNode(true);
        insert(_el$4, () => props2.children);
        return _el$4;
      })(), createComponent(HelpLink, {
        guide: "kantree-method",
        get children() {
          return _4("Learn more about the Kantree Method");
        }
      })];
    }
  });
}
delegateEvents(["click"]);

// public/app/stores/instances.ts
var instances_exports = {};
__export(instances_exports, {
  ActivityStore: () => ActivityStore,
  AutomationRuleStore: () => AutomationRuleStore,
  CardGroupStore: () => CardGroupStore,
  CardGroupTypeStore: () => CardGroupTypeStore,
  CardModelStore: () => CardModelStore,
  CardReminder: () => CardReminder,
  CardStateStore: () => CardStateStore,
  CardStore: () => CardStore,
  CardSubscription: () => CardSubscription,
  FileStore: () => FileStore,
  GroupSubscriptionStore: () => GroupSubscriptionStore,
  IntegrationStore: () => IntegrationStore,
  OrgFeaturedItemStore: () => OrgFeaturedItemStore,
  OrgMemberStore: () => OrgMemberStore,
  OrgStore: () => OrgStore,
  ProjectIntegrationStore: () => ProjectIntegrationStore,
  ProjectLogTypeStore: () => ProjectLogTypeStore,
  ProjectMemberStore: () => ProjectMemberStore,
  ProjectStore: () => ProjectStore,
  RecurringCardStore: () => RecurringCardStore,
  RequestFormStore: () => RequestFormStore,
  RoleStore: () => RoleStore,
  TeamStore: () => TeamStore,
  ViewCategoryStore: () => ViewCategoryStore,
  ViewStore: () => ViewStore,
  activityStore: () => activityStore,
  attributeTypeStore: () => attributeTypeStore,
  automationRuleStore: () => automationRuleStore,
  cardGroupStore: () => cardGroupStore,
  cardGroupSubscriptionStore: () => cardGroupSubscriptionStore,
  cardGroupTypeStore: () => cardGroupTypeStore,
  cardModelStore: () => cardModelStore,
  cardReminderStore: () => cardReminderStore,
  cardStateStore: () => cardStateStore,
  cardStore: () => cardStore,
  cardSubscriptionStore: () => cardSubscriptionStore,
  integrationStore: () => integrationStore,
  integrationTypeStore: () => integrationTypeStore,
  matchGroup: () => matchGroup,
  matchGroupTitle: () => matchGroupTitle,
  matchGroupTitleCaseInsensitive: () => matchGroupTitleCaseInsensitive,
  orgFeaturedItemStore: () => orgFeaturedItemStore,
  orgMemberStore: () => orgMemberStore,
  orgStore: () => orgStore,
  projectIntegrationStore: () => projectIntegrationStore,
  projectLogTypeStore: () => projectLogTypeStore,
  projectMemberStore: () => projectMemberStore,
  projectStore: () => projectStore,
  recurringCardStore: () => recurringCardStore,
  requestFormStore: () => requestFormStore,
  requestStore: () => requestStore,
  roleStore: () => roleStore,
  teamStore: () => teamStore,
  viewCategoryStore: () => viewCategoryStore,
  viewStore: () => viewStore
});

// public/app/stores/core/utils.ts
function computeMoveBounds(currentPosition, position) {
  if (currentPosition === null) {
    return { "shift": 1, "lower": position, "upper": null };
  } else if (position === null) {
    return { "shift": -1, "lower": currentPosition, "upper": null };
  }
  var up = position > currentPosition;
  var shift2 = up ? -1 : 1;
  var lower = Math.min(currentPosition, position);
  lower += up ? 1 : 0;
  var upper = Math.max(currentPosition, position);
  upper -= up ? 0 : 1;
  return { "shift": shift2, "lower": lower, "upper": upper };
}
function offMany(offs) {
  return () => {
    offs.forEach((off) => off && off());
  };
}
function callOrValue(value2) {
  if (value2 === void 0) return void 0;
  if (typeof value2 === "function" && value2.length === 0) {
    return value2();
  }
  return value2;
}
function shallowArrayEquals(a3, b3) {
  if (a3 === b3) return true;
  if (a3.length !== b3.length) return false;
  for (let i3 = 0; i3 < a3.length; i3++) {
    if (a3[i3] !== b3[i3]) return false;
  }
  return true;
}

// public/app/utils/arrays/index.js
function sortBy2(arr, prop2, castToInt = false, defaultCmpFunc = (a3, b3) => 0) {
  let reverse = false;
  let p4 = prop2;
  const first2 = p4 && p4.charAt && p4.charAt(0);
  if (first2 === "+" || first2 === "-") {
    reverse = first2 === "-" ? true : false;
    p4 = p4.substring(1);
  }
  if (p4.indexOf("meta:") === 0) {
    const metaProp = p4.substring(5);
    const metaMap = arr.__metadata;
    if (!(metaMap instanceof Map)) {
      throw new Error("Missing __metadata Map on array when sorting by meta:");
    }
    return arr.sort((a3, b3) => {
      const ma = metaMap.get(a3);
      const mb = metaMap.get(b3);
      const va = ma ? ma[metaProp] : void 0;
      const vb = mb ? mb[metaProp] : void 0;
      const r3 = compare2(va, vb, castToInt, reverse);
      return r3 || defaultCmpFunc(a3, b3, reverse);
    });
  }
  const parts = String(p4).split(".");
  const pathLength = parts.length;
  return arr.sort((a3, b3) => {
    let va = a3;
    let vb = b3;
    for (let i3 = 0; i3 < pathLength; i3++) {
      const k2 = parts[i3];
      va = va == null ? void 0 : va[k2];
      vb = vb == null ? void 0 : vb[k2];
      if (va === void 0 || va === null || vb === void 0 || vb === null) break;
    }
    const r3 = compare2(va, vb, castToInt, reverse);
    return r3 || defaultCmpFunc(a3, b3, reverse);
  });
}
function removeIndex(arr, index2) {
  return arr.slice(0, index2).concat(arr.slice(index2 + 1));
}

// public/app/utils/arrays/indexes.ts
var Index2 = class {
  constructor(props2) {
    this.props = props2;
    this.values = /* @__PURE__ */ new Map();
    this.reset();
  }
  reset() {
    this.values = /* @__PURE__ */ new Map();
    for (const prop2 of this.props) {
      this.values.set(prop2, /* @__PURE__ */ new Map());
    }
  }
  index(obj) {
    this.remove(obj);
    for (const prop2 of this.props) {
      if (obj.hasOwnProperty(prop2)) {
        const value2 = obj[prop2];
        const propEntry = this.values.get(prop2);
        if (!propEntry.has(value2)) {
          propEntry.set(value2, /* @__PURE__ */ new Set());
        }
        propEntry.get(value2).add(obj);
      }
    }
  }
  remove(obj) {
    for (const prop2 of this.props) {
      const value2 = obj[prop2];
      const propEntry = this.values.get(prop2);
      if (propEntry.has(value2)) {
        propEntry.get(value2)?.delete(obj);
      }
    }
  }
  removeMany(objs) {
    const propsMap = /* @__PURE__ */ new Map();
    for (const obj of objs) {
      for (const prop2 of this.props) {
        const value2 = obj[prop2];
        if (!propsMap.has(prop2)) {
          propsMap.set(prop2, /* @__PURE__ */ new Map());
        }
        if (!propsMap.get(prop2).has(value2)) {
          propsMap.get(prop2).set(value2, /* @__PURE__ */ new Set());
        }
        propsMap.get(prop2).get(value2).add(obj);
      }
    }
    for (const [prop2, valuesMap] of propsMap) {
      for (const [value2, objectsToRemove] of valuesMap) {
        const propEntry = this.values.get(prop2);
        if (propEntry.has(value2)) {
          const values2 = propEntry.get(value2);
          const objsToRemoveSet = new Set(objectsToRemove);
          propEntry.set(
            value2,
            new Set([...values2].filter((val) => !objsToRemoveSet.has(val)))
          );
        }
      }
    }
  }
  get(prop2, value2) {
    return this.values.get(prop2)?.get(value2) || /* @__PURE__ */ new Set();
  }
  search(filters) {
    let result2;
    for (const [prop2, value2] of Object.entries(filters)) {
      const matches3 = this.get(prop2, value2);
      if (!result2) {
        result2 = new Set(matches3);
      } else {
        if (matches3.size === 0) return [];
        for (const v3 of result2) {
          if (!matches3.has(v3)) {
            result2.delete(v3);
          }
        }
      }
      if (!result2 || !result2.size) {
        break;
      }
    }
    if (result2 === void 0) return void 0;
    const out = [...result2];
    return out;
  }
};
function splitFilterIndexes(query2, index2) {
  if (!query2 || isFunction_default(query2)) {
    return [query2, null];
  }
  const indexedProps = [];
  for (const prop2 of index2.props) {
    if (typeof query2[prop2] !== "undefined" && typeof query2[prop2] !== "function") {
      indexedProps.push(prop2);
    }
  }
  let filters, indexedFilters;
  if (indexedProps.length) {
    indexedFilters = pick_default(query2, ...indexedProps);
    filters = omit_default(query2, ...indexedProps);
    if (Object.keys(filters).length === 0) {
      filters = null;
    }
  } else {
    filters = query2;
  }
  return [filters, indexedFilters];
}

// public/app/utils/arrays/query.ts
var query_exports = {};
__export(query_exports, {
  and: () => and,
  any: () => any,
  arrayMatch: () => arrayMatch,
  arrayOfObjMatch: () => arrayOfObjMatch,
  cloneQueryArray: () => cloneQueryArray,
  contains: () => contains2,
  isDefined: () => isDefined2,
  isFalsy: () => isFalsy,
  isNull: () => isNull2,
  isTruthy: () => isTruthy,
  isUndefined: () => isUndefined3,
  matchArray: () => matchArray,
  matchObject: () => matchObject,
  matchObjectProperty: () => matchObjectProperty,
  matchStringFuzzy: () => matchStringFuzzy,
  matchValue: () => matchValue,
  mergeFilters: () => mergeFilters,
  neq: () => neq,
  not: () => not,
  notNull: () => notNull,
  objMatch: () => objMatch,
  optional: () => optional,
  or: () => or,
  queryArray: () => queryArray
});
function queryArray(arr, query2, { index: index2, sortBy: sortBy3, limit, sortCastToInt }) {
  let filters = query2, indexedFilters, matches3;
  if (index2) {
    [filters, indexedFilters] = splitFilterIndexes(query2, index2);
  }
  if (indexedFilters) {
    matches3 = index2.search(indexedFilters);
  } else if (!filters) {
    matches3 = Array.isArray(arr) ? [...arr] : Object.values(arr);
  } else {
    matches3 = Array.isArray(arr) ? arr : Object.values(arr);
  }
  const __metadata = /* @__PURE__ */ new Map();
  if (filters) {
    const out = [];
    for (let i3 = 0, len = matches3.length; i3 < len; i3++) {
      const obj = matches3[i3];
      const meta2 = {};
      if (matchObject(obj, filters, meta2)) {
        __metadata.set(obj, meta2);
        out.push(obj);
      }
    }
    matches3 = out;
  }
  matches3.__metadata = __metadata;
  if (sortBy3) {
    if (isFunction_default(sortBy3)) {
      matches3.sort(sortBy3);
    } else {
      sortBy2(matches3, sortBy3, sortCastToInt);
    }
  }
  if (limit) {
    matches3 = matches3.slice(0, limit);
    if (!matches3.__metadata) {
      matches3.__metadata = __metadata;
    }
  }
  return matches3;
}
function mergeFilters(...filters) {
  let out;
  for (const filter4 of filters) {
    if (!out) {
      out = filter4;
    } else if (filter4 && (isFunction_default(out) || isFunction_default(filter4))) {
      const prev = out;
      out = (obj) => matchObject(obj, prev) && matchObject(obj, filter4);
    } else if (filter4) {
      out = Object.assign({}, out || {}, filter4);
    }
  }
  return out || {};
}
function matchValue(value2, cmp4, meta2) {
  if (typeof cmp4 === "function") {
    return cmp4(value2, meta2);
  }
  return value2 === cmp4;
}
function matchObjectProperty(obj, prop2, cmp4, meta2) {
  if (typeof obj[prop2] === "undefined") {
    if (typeof cmp4 === "function") {
      return cmp4(void 0, meta2);
    }
    return false;
  }
  return matchValue(obj[prop2], cmp4, meta2);
}
function matchObject(obj, props2, meta2) {
  if (meta2 === void 0) {
    meta2 = {};
  }
  if (typeof props2 === "function") {
    return props2(obj, meta2);
  }
  for (const key2 in props2) {
    if (!Object.prototype.hasOwnProperty.call(props2, key2)) continue;
    if (!matchObjectProperty(obj, key2, props2[key2], meta2)) return false;
  }
  return true;
}
function matchArray(arr, cmp4) {
  if (!arr) {
    return false;
  }
  for (var i3 = 0; i3 < arr.length; i3++) {
    if (cmp4(arr[i3])) {
      return true;
    }
  }
  return false;
}
function matchStringFuzzy(value2) {
  return function(propValue) {
    return propValue == value2 || propValue.toLowerCase() === value2.toLowerCase() || propValue.replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase() === value2.replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase() || propValue.replace(/ /g, "").toLowerCase() === value2.replace(/ /g, "").toLowerCase();
  };
}
function optional(cmp4) {
  return function(propValue, meta2) {
    return propValue === void 0 || cmp4 === void 0 || matchValue(propValue, cmp4, meta2);
  };
}
function neq(value2) {
  return function(propValue) {
    return propValue !== value2;
  };
}
function isDefined2() {
  return function(propValue) {
    return propValue !== void 0;
  };
}
function isUndefined3() {
  return function(propValue) {
    return propValue === void 0;
  };
}
function isNull2() {
  return function(propValue) {
    return propValue === void 0 || propValue === null;
  };
}
function notNull() {
  return function(propValue) {
    return propValue !== void 0 && propValue !== null;
  };
}
function isTruthy() {
  return function(propValue) {
    return !!propValue;
  };
}
function isFalsy() {
  return function(propValue) {
    return !propValue;
  };
}
function contains2(value2) {
  return function(propValue) {
    return propValue !== void 0 && propValue.indexOf(value2) !== -1;
  };
}
function any(values2) {
  return function(propValue) {
    return values2.indexOf(propValue) !== -1;
  };
}
function arrayMatch(cmp4) {
  return function(propValue, meta2) {
    return matchArray(propValue, function(value2) {
      return matchValue(value2, cmp4, meta2);
    });
  };
}
function objMatch(props2) {
  return function(propValue, meta2) {
    return propValue !== void 0 && propValue !== null && matchObject(propValue, props2, meta2);
  };
}
function arrayOfObjMatch(props2) {
  return function(propValue, meta2) {
    return matchArray(propValue, function(obj) {
      return matchObject(obj, props2, meta2);
    });
  };
}
function not(cmp4) {
  return function(propValue, meta2) {
    return !matchValue(propValue, cmp4, meta2);
  };
}
function and(...args) {
  return function(propValue, meta2) {
    for (let i3 = 0; i3 < args.length; i3++) {
      if (!matchValue(propValue, args[i3], meta2)) {
        return false;
      }
    }
    return true;
  };
}
function or(...args) {
  return function(propValue, meta2) {
    for (let i3 = 0; i3 < args.length; i3++) {
      if (matchValue(propValue, args[i3], meta2)) {
        return true;
      }
    }
    return false;
  };
}
function cloneQueryArray(arr) {
  const _metadata = arr.__metadata;
  const newArr = [...arr];
  newArr.__metadata = _metadata;
  return newArr;
}

// public/app/utils/lock.js
var LockManager = class {
  constructor() {
    this.locks = /* @__PURE__ */ new Map();
  }
  /**
   * Acquire a new Lock.
   * If a lock with the same id is already active, waits for the current lock to release first.
   */
  async acquire(id) {
    if (this.locks.has(id)) {
      await this.locks.get(id).wait();
    }
    const lock = new Lock();
    this.locks.set(id, lock);
    lock.registerReleaseCallback(() => this.locks.delete(id));
    return lock;
  }
  /**
   * Acquire a lock and locks it until callback is finished (will wait for any returned promise to resolve)
   */
  async lock(id, callback) {
    const lock = await this.acquire(id);
    let r3;
    try {
      r3 = await callback();
    } finally {
      lock.release();
    }
    return r3;
  }
  isLocked(id) {
    const lock = this.locks.get(id);
    return lock && !lock.released;
  }
  /**
   * Wait for a lock to release. Either await this method or provide a callback
   *
   * await lockManager.wait('lockId');
   * lockManager.wait('lockId', () => { called on release })
   */
  wait(id, callback = null) {
    if (this.isLocked(id)) {
      if (callback) {
        this.locks.get(id).registerReleaseCallback(callback);
      } else {
        return this.locks.get(id).wait();
      }
    } else if (callback) {
      callback();
    } else {
      return Promise.resolve();
    }
  }
};
var Lock = class {
  constructor() {
    this.released = false;
    this.releaseCallbacks = [];
  }
  registerReleaseCallback(cb2) {
    if (this.released) {
      cb2(...this.releaseArgs);
    } else {
      this.releaseCallbacks.push(cb2);
    }
  }
  release() {
    this.released = true;
    for (let cb2 of this.releaseCallbacks) {
      if (cb2) {
        cb2();
      }
    }
  }
  /**
   * Return a promise that resolves when the lock is released
   */
  wait() {
    return new Promise((resolve2) => this.registerReleaseCallback(resolve2));
  }
};

// public/app/stores/core/store.ts
var StoreError = class extends Error {
};
var StoreNotFoundError = class extends StoreError {
};
var Store = class _Store {
  constructor(options2 = {}, localStorage2, parent, scopeFilters) {
    this.debouncedPersistMap = /* @__PURE__ */ new Map();
    this.missingIdCounter = 0;
    this.listeners = /* @__PURE__ */ new Map();
    this.loaded = false;
    this.loading = null;
    this._options = Object.assign({}, _Store.defaultOptions, options2 || {});
    this._localStorage = localStorage2 ?? null;
    this.parent = parent ?? null;
    this.scopeFilters = scopeFilters ?? null;
    this.localStorageKey = this.options.localStorageKey;
    if (!this.localStorageKey && this.options.typeName) {
      this.localStorageKey = `${this.options.typeName}-store`;
    } else if (!this.localStorageKey && !!this.localStorage) {
      console.warn("Missing localStorageKey for store, localStorage is disabled");
    }
    if (this.isScopedLocalStorage()) {
      const scopeStr = JSON.stringify(scopeFilters);
      let hash = 0, i3, chr;
      if (scopeStr.length) {
        for (i3 = 0; i3 < scopeStr.length; i3++) {
          chr = scopeStr.charCodeAt(i3);
          hash = (hash << 5) - hash + chr;
          hash |= 0;
        }
      }
      this.localStorageKey += `-${hash}`;
    }
    if (!parent) {
      this.reset();
    }
  }
  static {
    this.defaultOptions = {
      primaryKey: "id",
      indexProps: [],
      typeNameProperty: "__type__",
      typeName: null,
      dropDuplicates: false,
      autoLoad: true,
      localStorageKey: null,
      scopedLocalStorageKey: false
    };
  }
  static {
    this.inTransaction = false;
  }
  static {
    this.stagedNotifications = null;
  }
  /**
   * Returns the constructor of the current class as a constructable type.
   */
  get selfConstructor() {
    return this.constructor;
  }
  get root() {
    return this.parent ?? this;
  }
  get options() {
    return this.root._options;
  }
  get data() {
    return this.root._data;
  }
  get setters() {
    return this.root._setter;
  }
  get index() {
    return this.root._index;
  }
  get locks() {
    return this.root._locks;
  }
  get localStorage() {
    return this.root._localStorage;
  }
  reset(keepListeners = false) {
    if (!keepListeners) {
      this.listeners.clear();
    }
    for (const debouncedFn2 of this.debouncedPersistMap.values()) {
      debouncedFn2.clear?.();
    }
    this.debouncedPersistMap.clear();
    [this._data, this._setter] = createStore({});
    this._index = new Index2([this.options.primaryKey, ...this.options.indexProps]);
    this._locks = new LockManager();
    this.loaded = false;
    this.loading = null;
    if (this.options.autoLoad) {
      this.load();
    }
  }
  resetWithoutLocalStorage() {
    this.root._localStorage = null;
    this.root.reset();
  }
  isScopedLocalStorage() {
    return this.parent && this.localStorageKey && this.options.scopedLocalStorageKey && this.scopeFilters && (Array.isArray(this.scopeFilters) && !this.scopeFilters.some((f3) => isFunction_default(f3)) || !isFunction_default(this.scopeFilters));
  }
  /**
   * Persist the store to localStorage provided to constructor
   * Storage key can be overrided
   */
  persist(storageKey = null, scoped = null) {
    if (!this.localStorage) {
      return;
    }
    if (_Store.inTransaction) {
      return;
    }
    let value2 = {};
    if (scoped && this.parent || scoped === null && this.isScopedLocalStorage()) {
      for (const obj of this.query()) {
        value2[this.id(obj)] = unwrap(obj);
      }
    } else {
      value2 = unwrap(this.data);
    }
    return this.localStorage.setItem(storageKey || this.localStorageKey, JSON.stringify(value2));
  }
  schedulePersist(storageKey = null, scoped = null) {
    if (!this.localStorage) {
      return;
    }
    const mapKey = JSON.stringify({ storageKey, scoped });
    if (!this.debouncedPersistMap.has(mapKey)) {
      const debouncedPersist = debounce2(() => this.persist(storageKey, scoped), 1e3);
      this.debouncedPersistMap.set(mapKey, debouncedPersist);
    }
    return this.debouncedPersistMap.get(mapKey)();
  }
  /**
   * Load data from localStorage provided to constructor
   * Only load once unless force=true
   */
  load(force = false, storageKey = null, partial2 = false) {
    if (!this.localStorage || this.root.loaded && !force) {
      return Promise.resolve();
    }
    if (this.loading) {
      return this.loading;
    }
    this.loading = Promise.resolve(this.localStorage.getItem(storageKey || this.localStorageKey)).then((rawData) => {
      let data2 = null;
      if (typeof rawData === "string") {
        try {
          data2 = JSON.parse(rawData);
        } catch (e3) {
          console.error(`[Store:${this.options.typeName}] Failed to parse localStorage data:`, e3);
          data2 = null;
        }
      } else if (rawData) {
        data2 = rawData;
      }
      if (!data2) return;
      const existingIds = new Set(Object.keys(this.data));
      const newIds = new Set(Object.keys(data2));
      if (existingIds.size === 0) {
        this.root._setter(data2);
      } else {
        this.transaction(() => {
          if (!partial2) {
            for (const id of existingIds) {
              if (!newIds.has(id)) {
                this.root._setter(id, void 0);
              }
            }
          }
          for (const [id, obj] of Object.entries(data2)) {
            if (existingIds.has(id)) {
              this.root._setter(id, reconcile(obj));
            } else {
              this.root._setter(id, obj);
            }
          }
        });
      }
      this.root.reindex();
      this.loading = null;
      if (this.options.autoLoad && !storageKey && !this.isScopedLocalStorage()) {
        this.root.loaded = true;
      }
      this.broadcast("loaded");
    }).catch((error2) => {
      console.error(`[Store:${this.options.typeName}] Failed to load from localStorage:`, error2);
      this.loading = null;
    });
    return this.loading;
  }
  /**
   * Can be overrided by subclasses to format the object on insert or update
   */
  format(obj) {
    return obj;
  }
  /**
   * Return the id of an object according to the primary key defined in options
   */
  id(obj) {
    return obj[this.options.primaryKey];
  }
  /**
   * Check if the object matches the current scoped store filters
   */
  match(obj) {
    if (this.scopeFilters) {
      return matchObject(obj, this.resolveScopeFilters());
    }
    return true;
  }
  /**
   * Check if the object with the specified id is present in the store
   */
  exists(id) {
    if (!this.data[id]) {
      return false;
    }
    return this.match(this.data[id]);
  }
  /**
   * Return the object with the specified id, throw an error if it does not exist
   */
  get(id) {
    if (!this.exists(id)) {
      throw new StoreNotFoundError(`Object "${id}" not found` + (this.options.typeName ? `' in ${this.options.typeName} store ` : ""));
    }
    return this.data[id];
  }
  /**
   * Same as get() but return undefined instead of throwing if the object does not exist
   */
  tryGet(id) {
    return this.data[id];
  }
  /**
   * Query the store using queryArray
   */
  query(filters, options2) {
    if (this.scopeFilters) {
      filters = mergeFilters(this.resolveScopeFilters(), filters);
    }
    return queryArray(this.data, filters, { ...options2, index: this.index });
  }
  count() {
    if (this.scopeFilters) {
      return this.query().length;
    }
    return Object.keys(this.data).length;
  }
  generateId() {
    let autoId;
    while (!autoId || this.data[autoId]) {
      autoId = `auto-${this.root.missingIdCounter++}`;
    }
    return autoId;
  }
  /**
   * Insert a new object in the store
   *
   * eventArgs will be pass on to the "inserted" event
   */
  insert(obj, ...eventArgs) {
    let newObj = this.root.format(Object.assign({}, unwrap(obj)));
    if (this.options.typeName) {
      newObj[this.options.typeNameProperty] = this.options.typeName;
    }
    let id = this.id(newObj);
    if (!id) {
      id = newObj[this.options.primaryKey] = this.generateId();
    }
    newObj.$$hashKey = id;
    if (this.data[id]) {
      if (this.options.dropDuplicates) {
        this.root._setter(id, void 0);
      } else {
        throw new StoreError('Duplicate id "' + id + '"' + (this.options.typeName ? " in " + this.options.typeName : ""));
      }
    }
    this.root._setter(id, newObj);
    const result2 = this.data[id];
    this.index.index(result2);
    this.notify("inserted", result2, ...eventArgs);
    if (!_Store.inTransaction) {
      this.schedulePersist();
    }
    return result2;
  }
  /**
   * Update an object.
   *
   * The existing object is matched using the id.
   * The object in store will be updated from "obj" props and from additional "props"
   * eventArgs will be pass on to the "updated" event.
   *
   * if props is an object, values can be functions that will receive the current prop value as param.
   * props can otherwise be a function that will be passed to the solid store setter.
   */
  update(obj, props2, ...eventArgs) {
    const id = this.id(obj);
    const unwrappedOldObj = unwrap(this.root.get(id));
    let newObj = Object.assign({}, unwrappedOldObj, unwrap(obj));
    if (isFunction_default(props2)) {
      Object.assign(newObj, unwrap(props2(newObj)));
    } else if (props2) {
      const propsObj = { ...unwrap(props2) };
      for (const [key2, value2] of Object.entries(propsObj)) {
        if (typeof value2 === "function") {
          propsObj[key2] = value2(newObj[key2], newObj);
        }
      }
      Object.assign(newObj, propsObj);
    }
    const formattedObj = this.root.format(newObj);
    if (!equals(formattedObj, unwrappedOldObj)) {
      this.root._setter(id, reconcile(formattedObj));
      const result2 = this.data[id];
      this.index.index(result2);
      this.notify("updated", result2, ...eventArgs);
      if (!_Store.inTransaction) {
        this.schedulePersist();
      }
      return result2;
    }
    return this.data[id];
  }
  /**
   * Same as update() by only provide an id to match the existing object
   */
  updateById(id, props2, ...eventArgs) {
    if (typeof this.id(props2) !== "undefined" && this.id(props2) !== id) {
      const obj = this.root.get(id);
      this.root._setter(this.id(props2), obj);
      this.root._setter(id, void 0);
      this.index.remove(obj);
      id = this.id(props2);
    }
    return this.update({ [this.options.primaryKey]: id }, props2, ...eventArgs);
  }
  /**
   * Call insert or update depending if the object is already in the store
   */
  upsert(obj, props2, ...eventArgs) {
    if (!this.data[this.id(obj)]) {
      if (props2) {
        Object.assign(obj, props2);
      }
      return this.insert(obj);
    }
    return this.update(obj, props2, ...eventArgs);
  }
  /**
   * Remove an object from the store
   */
  remove(obj, ...eventArgs) {
    return this.removeById(this.id(obj), ...eventArgs);
  }
  /**
   * Remove an object from the store using its id only
   */
  removeById(id, ...eventArgs) {
    let obj = this.root.tryGet(id);
    if (!obj) {
      return;
    }
    this.root._setter(id, void 0);
    this.index.remove(obj);
    this.notify("removed", obj, ...eventArgs);
    if (!_Store.inTransaction) {
      this.schedulePersist();
    }
    return obj;
  }
  /**
   * Empty the store
   */
  clear() {
    this.root.reset(true);
    this.notify("cleared");
    if (!_Store.inTransaction) {
      this.schedulePersist();
    }
  }
  _performOperationOnMany(method, objects, ...args) {
    if (!objects || !objects.length) {
      return [];
    }
    const changed = [];
    this.transaction(() => {
      for (let obj of objects) {
        changed.push(method(obj, ...args));
      }
    });
    return changed;
  }
  insertMany(objects, ...args) {
    return this._performOperationOnMany(this.insert.bind(this), objects, ...args);
  }
  updateMany(objects, ...args) {
    return this._performOperationOnMany(this.update.bind(this), objects, ...args);
  }
  updateManyMatching(filters, ...args) {
    return this.updateMany(this.query(filters), ...args);
  }
  upsertMany(objects, ...args) {
    return this._performOperationOnMany(this.upsert.bind(this), objects, ...args);
  }
  removeMany(objects, ...args) {
    if (!objects || !objects.length) {
      return [];
    }
    const changed = [];
    this.transaction(() => {
      const validObjects = [];
      const validObjectIds = /* @__PURE__ */ new Set();
      for (const obj of objects) {
        const id = this.id(obj);
        if (this.exists(id) && !validObjectIds.has(id)) {
          const storeObj = this.data[id];
          validObjects.push(storeObj);
          validObjectIds.add(id);
        }
      }
      if (!validObjects.length) {
        return;
      }
      this.index.removeMany(validObjects);
      for (const id of validObjectIds) {
        this.root._setter(id, void 0);
      }
      for (const obj of validObjects) {
        changed.push(obj);
        this.notify("removed", obj, ...args);
      }
    });
    if (!_Store.inTransaction) {
      this.schedulePersist();
    }
    return changed;
  }
  removeManyMatching(filters, ...args) {
    return this.removeMany(this.query(filters), ...args);
  }
  removeAll() {
    return this.removeManyMatching({});
  }
  removeAllNotMatching(objects, except = null) {
    const ids = objects.map((o3) => this.id(o3));
    let q;
    q = { [this.options.primaryKey]: (id) => !ids.includes(id) };
    if (except) {
      q = and(objMatch(q), not(objMatch(except)));
    }
    return this.removeManyMatching(q);
  }
  /**
   * Replace all objects in the store using the provided ones
   */
  replace(objects) {
    this.transaction(() => {
      this.removeAllNotMatching(objects);
      this.upsertMany(objects);
    });
  }
  reindex() {
    this.index.reset();
    for (const obj of Object.values(this.data)) {
      this.index.index(obj);
    }
  }
  /**
   * Wrap multiple operations in a single transaction to prevent event dispatching
   */
  transaction(callback) {
    if (_Store.inTransaction) {
      return batch(() => callback.call(this));
    }
    const stagedNotifications = /* @__PURE__ */ new Map();
    _Store.inTransaction = true;
    _Store.stagedNotifications = stagedNotifications;
    const r3 = batch(() => callback.call(this));
    _Store.inTransaction = false;
    _Store.stagedNotifications = null;
    for (const [store2, storeStagedNotifications] of stagedNotifications.entries()) {
      store2.schedulePersist();
      const alreadyBroadcasted = {};
      for (const args of storeStagedNotifications) {
        if (args[1]) {
          const id = store2.id(args[1]);
          if (typeof alreadyBroadcasted[id] === "undefined") {
            alreadyBroadcasted[id] = /* @__PURE__ */ new Set();
          }
          if (alreadyBroadcasted[id].has(args[0])) {
            continue;
          }
          alreadyBroadcasted[id].add(args[0]);
        }
        store2.broadcast(...args);
      }
      store2.broadcast("changed");
    }
    return r3;
  }
  notify(...args) {
    if (this.parent) {
      return this.root.notify(...args);
    }
    if (_Store.inTransaction) {
      if (!_Store.stagedNotifications.has(this)) {
        _Store.stagedNotifications.set(this, []);
      }
      _Store.stagedNotifications.get(this).push(args);
      return;
    }
    const eventName = args[0];
    const otherArgs = args.slice(1);
    this.broadcast(eventName, ...otherArgs);
    this.broadcast("changed");
  }
  _getListeners(eventName) {
    if (!this.listeners.has(eventName)) {
      this.listeners.set(eventName, []);
    }
    return this.listeners.get(eventName);
  }
  broadcast(eventName, ...args) {
    for (const listener of this.root._getListeners(eventName).slice(0)) {
      untrack(() => listener(...args));
    }
  }
  /**
   * Subscribe to a store event
   */
  subscribe(eventName, callback, immediate = false) {
    if (isFunction_default(eventName)) {
      immediate = typeof callback === "undefined" ? false : !!callback;
      callback = eventName;
      eventName = "changed";
    }
    if (this.parent) {
      return this.root.subscribe(eventName, (obj, ...args) => {
        if (obj && !this.match(obj)) {
          return;
        }
        callback(obj, ...args);
      }, immediate);
    }
    if (Array.isArray(eventName)) {
      const dispose3 = offMany(eventName.map((e3) => this.subscribe(e3, callback)));
      if (immediate) {
        untrack(() => callback());
      }
      return dispose3;
    }
    const listeners = this._getListeners(eventName);
    listeners.push(callback);
    const dispose2 = () => {
      let i3 = listeners.indexOf(callback);
      if (i3 >= 0) {
        listeners.splice(i3, 1);
      }
    };
    dispose2.callback = callback;
    if (immediate) {
      untrack(() => callback());
    }
    return dispose2;
  }
  /**
   * Subscribe to events of a specific object
   */
  subscribeToObject(obj, eventName, callback) {
    if (isFunction_default(eventName)) {
      callback = eventName;
      eventName = ["updated", "removed"];
    }
    const dispose2 = this.subscribe(eventName, (obj_, ...eventArgs) => {
      if (this.id(obj_) === this.id(obj)) {
        callback(eventName, ...eventArgs);
        dispose2();
      }
    });
    return dispose2;
  }
  /**
   * Subscribe to an object removal
   */
  subscribeToRemoval(obj, callback) {
    return this.subscribeToObject(obj, "removed", callback);
  }
  /**
   * Return a signal that indicates if the object is removed and/or call the callback when removed
   */
  reactToRemoval(obj, callback = null) {
    const [isRemoved, setRemoved] = createSignal(!this.exists(this.id(obj)));
    onCleanup(this.subscribeToObject(obj, "removed", (...eventArgs) => {
      setRemoved(true);
      callback && callback(...eventArgs);
    }));
    return isRemoved;
  }
  _handleSortResults(results2, opts) {
    if (results2 && Array.isArray(results2) && opts && opts.sortBy) {
      if (isFunction_default(opts.sortBy)) {
        const clone3 = cloneQueryArray(results2);
        clone3.sort(opts.sortBy);
        return clone3;
      }
      return sortBy2(results2, opts.sortBy, opts.sortCastToInt, opts.cmpFunc);
    }
    return results2;
  }
  /**
   * Subscribe to a query, callback will be called everytime the query results change (is not called when an object itself is updated)
   */
  subscribeQuery(filters, options2, callback) {
    let opts;
    let cb2;
    if (isFunction_default(options2) && !callback) {
      cb2 = options2;
      opts = {};
    } else {
      opts = options2 || {};
      cb2 = callback;
    }
    const store2 = filters ? this.scoped(filters) : this;
    let results2 = store2.query({}, opts);
    cb2(results2);
    const listeners = [
      store2.subscribe("loaded", () => {
        results2 = this.query({}, opts);
        cb2(results2);
      }),
      store2.subscribe("inserted", (obj) => {
        if (opts?.sortBy && opts?.limit) {
          results2 = this.query({}, opts);
        } else {
          results2 = cloneQueryArray(results2);
          results2.push(obj);
          if (opts?.sortBy) {
            results2 = this._handleSortResults(results2, opts);
          }
        }
        cb2(results2);
      }),
      store2.root.subscribe("updated", (obj) => {
        if (results2.includes(obj)) {
          if (!store2.match(obj)) {
            const __metadata = results2.__metadata;
            results2 = results2.filter((o3) => store2.id(o3) !== store2.id(obj));
            results2.__metadata = __metadata;
            cb2(results2);
          } else if (opts?.sortBy && opts?.limit) {
            results2 = this.query({}, opts);
            cb2(results2);
          } else if (opts?.sortBy) {
            results2 = this._handleSortResults(results2, opts);
            cb2(results2);
          }
        } else if (store2.match(obj)) {
          results2 = cloneQueryArray(results2);
          results2.push(obj);
          if (opts?.sortBy && opts?.limit) {
            results2 = this.query({}, opts);
          } else if (opts?.sortBy) {
            results2 = this._handleSortResults(results2, opts);
          }
          cb2(results2);
        }
      }),
      store2.subscribe("removed", (obj) => {
        const __metadata = results2.__metadata;
        results2 = results2.filter((o3) => store2.id(o3) !== store2.id(obj));
        results2.__metadata = __metadata;
        cb2(results2);
      }),
      store2.subscribe("cleared", () => {
        results2 = [];
        cb2(results2);
      })
    ];
    if (opts?.subscribeToEvents) {
      for (const event2 of opts.subscribeToEvents) {
        listeners.push(store2.subscribe(event2, () => {
          results2 = this.query({}, opts);
          cb2(results2);
        }));
      }
    }
    return offMany(listeners);
  }
  /**
   * Return a signal that contains the query results and uses subscribeQuery() to update them
   * When using scoped store, scope filters will be treated as potentially reactive
   */
  react(filters, options2) {
    return createReactiveQuery(this, filters, options2);
  }
  /**
   * Acquire a lock of an object of the store
   */
  async lock(obj) {
    const lock = await this.locks.acquire(this.id(obj));
    lock.registerReleaseCallback(() => this.broadcast("unlocked", obj));
    this.broadcast("locked", obj);
    return lock;
  }
  isLocked(obj) {
    return this.locks.isLocked(this.id(obj));
  }
  /**
   * Wait for an object to be unlocked
   */
  unlocked(obj, callback = null) {
    return this.locks.wait(this.id(obj), callback);
  }
  /**
   * Return a scoped store instance
   * If filters is a function, it will only be called when filters are resolved (query() or match())
   */
  scoped(filters, resolved = false) {
    let newFilters;
    if (filters && this.scopeFilters) {
      const existingFilters = Array.isArray(this.scopeFilters) ? this.scopeFilters : [this.scopeFilters];
      newFilters = [...existingFilters, filters];
    } else if (filters) {
      newFilters = [filters];
    } else {
      newFilters = this.scopeFilters;
    }
    const scoped = new this.selfConstructor(null, null, this.root, newFilters);
    if (resolved) {
      return new this.selfConstructor(null, null, this.root, scoped.resolveScopeFilters());
    }
    return scoped;
  }
  resolveScopeFilters() {
    if (!this.scopeFilters) {
      return {};
    }
    if (!Array.isArray(this.scopeFilters)) {
      return this.scopeFilters;
    }
    return mergeFilters(...this.scopeFilters.map(
      (f3) => typeof f3 === "function" && f3.length === 0 ? f3() : f3
    ));
  }
  join(prop2, store2, targetProp = "id") {
    return this.scoped({ [prop2]: any(pluck(store2.query(), targetProp)) });
  }
  /* ANGULARJS */
  $on(scope, eventName, callback) {
    const off = this.subscribe(eventName, (...args) => {
      scope.$applyAsync(() => callback(...args));
    });
    scope.$on("$destroy", off);
    return off;
  }
  watch(obj, eventNames, callback, immediate = true) {
    if (typeof eventNames === "function") {
      immediate = callback ?? true;
      callback = eventNames;
      eventNames = null;
    } else if (typeof eventNames === "string") {
      eventNames = [eventNames];
    }
    if (!eventNames) {
      eventNames = ["inserted", "updated", "removed"];
    }
    if (typeof obj !== "object") {
      obj = { [this.options.primaryKey]: obj };
    }
    if (this.parent) {
      return this.root.watch(obj, eventNames, (obj2) => {
        if (!this.match(obj2)) {
          return;
        }
        callback(obj2);
      }, immediate);
    }
    const off = offMany(eventNames.map((e3) => {
      return this.subscribe(e3, (o3, ...args) => {
        if (this.id(o3) === this.id(obj)) {
          callback(o3, ...args, e3);
        }
      });
    }));
    if (immediate && this.data[this.id(obj)]) {
      callback(this.get(this.id(obj)));
    }
    return off;
  }
  $watch(scope, obj, eventNames, callback, immediate = true) {
    if (typeof eventNames === "function") {
      immediate = callback ?? true;
      callback = eventNames;
      eventNames = null;
    }
    if (typeof obj !== "object") {
      obj = { [this.options.primaryKey]: obj };
    }
    const off = this.watch(obj, eventNames, (...args) => {
      scope.$applyAsync(() => callback(...args));
    }, false);
    scope.$on("$destroy", off);
    if (immediate && this.data[this.id(obj)]) {
      callback(this.get(this.id(obj)));
    }
    return off;
  }
  $watchAll(scope, callback, immediate = true) {
    const off = this.$on(scope, "changed", callback);
    if (callback && immediate) {
      callback();
    }
    return off;
  }
};
function createReactiveQuery(store2, filters, options2) {
  const [results2, setResults] = createSignal([], { equals: shallowArrayEquals });
  let dispose2;
  createEffect(() => {
    if (dispose2) {
      dispose2();
    }
    const resolvedStore = callOrValue(store2);
    const resolvedFilters = callOrValue(filters);
    const resolvedOptions = callOrValue(options2);
    const scopedStore = resolvedStore.scoped(resolvedFilters, true);
    dispose2 = untrack(() => scopedStore.subscribeQuery(null, resolvedOptions, setResults));
  });
  onCleanup(() => dispose2 && dispose2());
  return results2;
}

// public/app/config/special-date-ranges.js
var specialDateRanges = [
  {
    name: "today",
    displayedName: _lazy("Today"),
    startDate: moment_default(),
    endDate: moment_default()
  },
  {
    name: "yesterday",
    displayedName: _lazy("Yesterday"),
    startDate: moment_default().subtract(1, "day"),
    endDate: moment_default().subtract(1, "day")
  },
  // {
  //   name: 'last_three_days',
  //   displayedName: _lazy('Last 3 days'),
  //   startDate: moment().subtract(3, 'day'),
  //   endDate: moment()
  // },
  {
    name: "this_week",
    displayedName: _lazy("This week"),
    startDate: moment_default().startOf("week"),
    endDate: moment_default().endOf("week")
  },
  {
    name: "last_week",
    displayedName: _lazy("Last week"),
    startDate: moment_default().subtract(1, "week").startOf("week"),
    endDate: moment_default().subtract(1, "week").endOf("week")
  },
  {
    name: "last_seven_days",
    displayedName: _lazy("Last 7 days"),
    startDate: moment_default().subtract(6, "day"),
    endDate: moment_default()
  },
  {
    name: "last_thirty_days",
    displayedName: _lazy("Last 30 days"),
    startDate: moment_default().subtract(29, "day"),
    endDate: moment_default()
  },
  {
    name: "this_month",
    displayedName: _lazy("This month"),
    startDate: moment_default().startOf("month"),
    endDate: moment_default().endOf("month")
  },
  {
    name: "this_year",
    displayedName: _lazy("This year"),
    startDate: moment_default().startOf("year"),
    endDate: moment_default().endOf("year")
  }
  // {
  //   name: 'all_time',
  //   displayedName: _lazy('All time'),
  //   startDate: origin,
  //   endDate: moment()
  // }
];

// public/app/utils/dates.js
var customDateFormats = {
  "monthAndDay": "MMM D"
};
function isLocaleDisplayAmPm() {
  return moment_default.localeData()._longDateFormat.LT.toLowerCase().includes("a");
}
function getFirstDayOfWeek() {
  return moment_default().localeData().firstDayOfWeek();
}
function parseTimestamp(timestamp2) {
  if (typeof timestamp2 === "number") {
    return moment_default.unix(timestamp2);
  }
  return moment_default(timestamp2);
}
function formatDate(timestamp2, formatString) {
  if (customDateFormats[formatString]) {
    const localizedKey = formatString.toUpperCase() + "_DATE_FORMAT";
    const localizedFormat = _4(localizedKey);
    formatString = localizedKey !== localizedFormat ? localizedFormat : customDateFormats[formatString];
  }
  return parseTimestamp(timestamp2).format(formatString);
}
function fromNow(timestamp2) {
  return parseTimestamp(timestamp2).fromNow();
}
function getDateDiffLabel(date, onlyCSSClass) {
  if (!date) return;
  if (!moment_default.isMoment(date)) {
    if (typeof date === "number") {
      date = parseTimestamp(date);
    } else {
      date = moment_default(date);
    }
  }
  const diff = date.diff(moment_default(), "second");
  if (diff <= -86400) {
    return ["past", _4("past")];
  } else if (diff >= -86400 && diff < 0) {
    return ["today", _4("today")];
  } else if (diff > 0 && diff <= 86400) {
    return ["soon", _4("soon")];
  }
  return ["", ""];
}
function formatSeconds(seconds, nullText) {
  if (seconds === null || seconds === void 0) {
    return nullText ?? _4("Unknown");
  }
  return formatSecondsIntervalToString(seconds);
}
function formatSecondsIntervalToString(seconds, minimalUnit) {
  var years = Math.floor(seconds / 31536e3);
  if (years) {
    return _n("{count} year", "{count} years", years);
  } else if (minimalUnit === "year") {
    return _4("less than a year");
  }
  var days = Math.floor((seconds %= 31536e3) / 86400);
  if (days) {
    return _n("{count} day", "{count} days", days);
  } else if (minimalUnit === "day") {
    return _4("less than a day");
  }
  var hours = Math.floor((seconds %= 86400) / 3600);
  if (hours) {
    return _n("{count} hour", "{count} hours", hours);
  } else if (minimalUnit === "hour") {
    return _4("less than a hour");
  }
  var minutes = Math.floor((seconds %= 3600) / 60);
  if (minutes) {
    return _n("{count} minute", "{count} minutes", minutes);
  } else if (minimalUnit === "minute") {
    return _4("less than a minute");
  }
  seconds = seconds % 60;
  if (seconds) {
    return _n("{count} second", "{count} seconds", seconds);
  }
  return _4("less than a second");
}
function dateRangeToActiveRange(range2, defaultRange) {
  if (!range2) {
    if (defaultRange) {
      return dateRangeToActiveRange(defaultRange);
    }
    return { start: moment_default(), end: moment_default() };
  }
  if (typeof range2 === "string") {
    const specialDateRange = specialDateRanges.find((date) => range2 === date.name);
    return {
      start: specialDateRange.startDate,
      end: specialDateRange.endDate
    };
  }
  return {
    start: parseTimestamp(range2.start),
    end: parseTimestamp(range2.end)
  };
}

// public/app/utils/registry.js
var Registry = class {
  constructor(options2) {
    this.items = {};
    this.setNameOnItem = !!options2?.setNameOnItem;
  }
  async register(name2, item) {
    item = await Promise.resolve(item);
    this.items[name2] = item;
    if (this.setNameOnItem) {
      item.name = name2;
    }
    return item;
  }
  get(name2, resolveAlias = true) {
    if (!name2) return null;
    if (typeof this.items[name2] === "undefined") {
      return null;
    }
    const spec = this.items[name2];
    if (resolveAlias && spec.alias) {
      return this.items[spec.alias];
    }
    return spec;
  }
  has(name2) {
    return name2 in this.items;
  }
  getAll() {
    return Object.values(this.items);
  }
  forEach(callback) {
    for (let [key2, value2] of Object.entries(this.items)) {
      callback(value2, key2);
    }
  }
};

// public/app/attributes/registry.js
var AttributeTypeRegistry = class extends Registry {
  getAll() {
    return super.getAll().sort((a3, b3) => {
      var aT = a3.title.toUpperCase();
      var bT = b3.title.toUpperCase();
      if (aT < bT) {
        return -1;
      }
      if (aT > bT) {
        return 1;
      }
      return 0;
    });
  }
  filterSupporting(supportFor) {
    return this.getAll().filter((attrType) => typeof attrType[supportFor] !== "undefined" && attrType[supportFor]);
  }
  resolveAttrTypeAlias(typeName2) {
    let attrType = this.get(typeName2, false);
    let attrTypeTitle = attrType.title, attrDefaultOptions = {};
    if (attrType.alias) {
      attrDefaultOptions = attrType.aliasOptions || {};
      attrType = this.get(attrType.alias);
    }
    return { type: attrType, title: attrTypeTitle, options: attrDefaultOptions };
  }
};
var attributeTypeRegistry = new AttributeTypeRegistry({ setNameOnItem: true });

// public/app/stores/favorites.ts
var [favorites, setFavorites] = createStore([]);
function isFavorite(objType, objId) {
  return favorites.some((fav) => fav.object_type === objType && fav.object_id === objId);
}
function addFavorite(objType, objId) {
  setFavorites((prev) => [...prev, { object_type: objType, object_id: objId }]);
}
function removeFavorite(objType, objId) {
  setFavorites((prev) => prev.filter((fav) => !(fav.object_type === objType && fav.object_id === objId)));
}

// public/app/utils/kql.js
function escapeKqlName(name2) {
  name2 = name2.replace(":", "\\:");
  return `{${name2}}`;
}
function unescapeKqlName(name2) {
  if (name2.substr(0, 1) === "{") {
    return name2.substr(1, name2.length - 2);
  }
  return name2;
}
function kqlNameMatch(name1, name2) {
  return name1.replace(/\s/g, "").toLowerCase() === name2.replace(/\s/g, "").toLowerCase();
}
function findClosingParentheses(source, from2 = 0) {
  const nextOpen = source.indexOf("(", from2);
  const nextClose = source.indexOf(")", from2);
  if (nextOpen === -1 && nextClose === -1) {
    return -1;
  }
  if (nextOpen >= 0 && nextOpen < nextClose) {
    return findClosingParentheses(source, nextOpen + 1);
  }
  return nextClose;
}
function stripParentheses(source) {
  if (source.indexOf("(") === 0) {
    const closePos = findClosingParentheses(source, 1);
    if (closePos >= 0 && closePos + 1 === source.length) {
      return source.substring(1, source.length - 1);
    }
  }
  return source;
}

// public/app/stores/model.ts
var import_tinycolor26 = __toESM(require_tinycolor());

// public/app/stores/project.ts
var import_tinycolor25 = __toESM(require_tinycolor());
var ProjectStore = class extends Store {
  format(project) {
    if (project.image_cover_url && !project.image_cover_loaded) {
      project._image_cover_url = project.image_cover_url;
      project.image_cover_url = null;
      project.image_cover_loading = true;
      project.image_cover_loaded = false;
      let c3 = 0;
      const check = () => {
        const img = new Image();
        img.onload = () => {
          this.update(project, {
            image_cover_url: project._image_cover_url,
            image_cover_loading: false,
            image_cover_loaded: true
          });
        };
        img.onerror = () => {
          if (c3++ < 10) {
            setTimeout(check, 1e3);
          }
        };
        img.src = project._image_cover_url;
      };
      setTimeout(check, 10);
    } else if (!project.image_cover_url) {
      project.image_cover_loaded = false;
      project.image_cover_loading = false;
    }
    if (project.is_portfolio && !project.portfolio_project_ids) {
      project.portfolio_project_ids = [];
    }
    if (project.is_portfolio) {
      project.icon = "bi-collection-fill";
    } else {
      project.icon = "bi-columns-gap";
    }
    if (project.color) {
      const tinyCardColor = (0, import_tinycolor25.default)(project.color);
      project.card_model_theme = "card-model-theme-" + tinyCardColor.toHex();
      $invoke(["stylesheetManager", (stylesheetManager) => {
        stylesheetManager.createTheme(
          project.card_model_theme,
          tinyCardColor.toHexString(),
          "/static/app/ui/card-models/ng-components/templates/card.css.html"
        );
      }]);
    } else {
      project.card_model_theme = null;
    }
    project.fromUserOrg = project.owner.type === "user";
    return project;
  }
  getForCard(card, forCardMirror) {
    if (forCardMirror && cardStore.isMirror(card)) {
      if (card.link) {
        return this.get(card.link.project_id);
      } else if (cardStore.exists(card.link_id)) {
        return this.get(cardStore.get(card.link_id).project_id);
      } else {
        throw new StoreNotFoundError('Card mirror "' + card.link_id + '" not found in ' + cardStore.options.typeName);
      }
    }
    return this.get(card.project_id);
  }
  tryGetForCard(card, forCardMirror) {
    try {
      return this.getForCard(card, forCardMirror);
    } catch (e3) {
      if (e3 instanceof StoreNotFoundError) {
        return null;
      }
      throw e3;
    }
  }
  scopedByOrg(org2, options2 = {}) {
    return this.scoped(() => {
      const { withPortfolio = false, withTemplates = false } = callOrValue(options2);
      org2 = callOrValue(org2);
      return {
        owner: query_exports.objMatch({ type: org2.type || "org", id: org2.id }),
        is_portfolio: (is_portfolio) => !!withPortfolio || !is_portfolio,
        is_template: (is_template) => !!withTemplates || !is_template
      };
    });
  }
  scopedByTeam(team, org2, options2) {
    if (team === false) {
      return this.scopedByOrg(org2, options2).scoped({ team: query_exports.isNull() });
    }
    return this.scopedByOrg(org2 || team.owner, options2).scoped(() => ({ team: query_exports.objMatch({ id: callOrValue(team).id }) }));
  }
  scopedForUser() {
    return this.scoped({ dashboard_group: query_exports.isDefined() });
  }
  scopedByCards(cards) {
    return this.scoped(() => {
      const projectsIds = (callOrValue(cards) || []).reduce((accu, card) => {
        if (accu.indexOf(card.project_id) === -1) {
          return accu.concat([card.project_id]);
        }
        return accu;
      }, []);
      return { id: query_exports.any(projectsIds) };
    });
  }
  scopedPortfoliosByOrg(org2) {
    return this.scoped(() => {
      org2 = callOrValue(org2);
      return {
        is_portfolio: true,
        owner: query_exports.objMatch({ type: org2.type || "org", id: org2.id })
      };
    });
  }
  scopedByPortfolio(portfolio) {
    return this.scoped(() => {
      portfolio = callOrValue(portfolio);
      return { id: query_exports.any(portfolio.portfolio_project_ids) };
    });
  }
  upsertAfterCreation(project) {
    let dashboardGroup = null;
    if (project.owner.type === "org") {
      if (!project.is_archived) {
        dashboardGroup = project.owner.id;
      }
    } else if (project.owner.type === "user") {
      dashboardGroup = "user";
    }
    if (project.is_template) {
      dashboardGroup = null;
    }
    this.upsert({ ...project, dashboard_group: dashboardGroup });
  }
};
var projectStore = new ProjectStore({
  typeName: "project"
}, idbLocalStorage);

// public/app/stores/model.ts
var CardModelStore = class extends Store {
  format(model) {
    if (!model.attributes) {
      model.attributes = [];
    }
    if (!model.attribute_containers) {
      model.attribute_containers = [];
    }
    for (let attr of model.attributes) {
      attr.$$hashKey = attr.id;
      attr.model_id = model.id;
      attr.model_is_base = model.base_model_type;
      if (!attr.model_is_base) {
        attr.model_name = model.name;
      } else if (model.base_model_type === "org") {
        attr.model_name = _4("Team");
      } else {
        attr.model_name = _4("Workspace");
      }
    }
    if (model.card_color) {
      const tinyCardColor = (0, import_tinycolor26.default)(model.card_color);
      model.style_class_name = "card-model-theme-" + tinyCardColor.toHex();
      $invoke(["stylesheetManager", (stylesheetManager) => {
        stylesheetManager.createTheme(
          model.style_class_name,
          tinyCardColor.toHexString(),
          "/static/app/ui/card-models/ng-components/templates/card.css.html"
        );
      }]);
    } else {
      model.style_class_name = null;
    }
    return model;
  }
  schedulePersist(storageKey = null) {
    if (!this.localStorage) {
      return;
    }
    this._idChainCache = /* @__PURE__ */ new Map();
    this._extendedAttributesCache = /* @__PURE__ */ new Map();
    return super.schedulePersist(storageKey);
  }
  scopedByEnabled(project, excludeOrgBaseModel = false, excludeTopLevelCardModel = false) {
    return this.scoped(() => {
      project = callOrValue(project);
      const q = { used_by: query_exports.contains(project.id) };
      if (callOrValue(excludeOrgBaseModel) || !project.use_org_attributes) {
        q["base_model_type"] = query_exports.neq("org");
      }
      if (callOrValue(excludeTopLevelCardModel) || !project.is_portfolio) {
        q["base_model_type"] = q["base_model_type"] ? query_exports.and(q["base_model_type"], query_exports.neq("top_level_card")) : query_exports.neq("top_level_card");
      }
      return q;
    });
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({ owner: query_exports.objMatch({ id: callOrValue(org2).id }) }));
  }
  scopedByCards(cards) {
    return this.scoped(() => {
      const modelsIds = (callOrValue(cards) || []).reduce((accu, card) => {
        const cardModel = this.getForCard(card);
        if (cardModel && accu.indexOf(cardModel.id) === -1) {
          accu = accu.concat([cardModel.id]);
        }
        const project = projectStore.tryGetForCard(card);
        if (project) {
          accu = accu.concat(this.getCardBaseModels(project).map((m3) => m3.id));
        }
        return accu;
      }, []);
      return { id: query_exports.any(modelsIds) };
    });
  }
  getForCard(card) {
    if (card.model_id) {
      return this.get(card.model_id);
    } else {
      return this.getProjectModel({ id: card.project_id });
    }
  }
  upsertOrgModels(org2, project) {
    let models = [];
    if (org2.attributes) {
      const orgModel = this.tryGet(`org${org2.id}`);
      models.push(this.upsert({
        id: `org${org2.id}`,
        attributes: org2.attributes,
        base_model_type: "org",
        base_model_id: org2.id,
        used_by: orgModel ? project ? uniq(orgModel.used_by.concat([project.id])) : orgModel.used_by : project ? [project.id] : []
      }));
    }
    if (org2.top_level_card_attributes && !project?.is_portfolio) {
      models.push(this.upsert({
        id: "top_level_card" + org2.id,
        attributes: org2.top_level_card_attributes,
        base_model_type: "top_level_card",
        base_model_id: org2.id,
        used_by: project ? [project.id] : []
      }));
    }
    return models;
  }
  getOrgModel(org2, project) {
    const modelId = "org" + org2.id;
    if (!this.exists(modelId)) {
      this.upsertOrgModels(org2, project);
    }
    return this.get(modelId);
  }
  getTopLevelCardModel(org2, project) {
    const modelId = "top_level_card" + org2.id;
    if (!this.exists(modelId)) {
      this.upsertOrgModels(org2, project);
    }
    return this.get(modelId);
  }
  upsertProjectModels(project) {
    const model = {
      id: "project" + project.id,
      name: _4("No type"),
      card_color: null,
      indicator: null,
      base_model_type: "project",
      base_model_id: project.id,
      used_by: [project.id]
    };
    if (project.attributes) {
      model["attributes"] = JSON.parse(JSON.stringify(project.attributes));
    }
    if (project.attribute_containers) {
      model["attribute_containers"] = project.attribute_containers;
    }
    let models = [this.upsert(model)];
    if (project.owner) {
      models = [...models, this.upsertOrgModels(project.owner, project)];
    }
    return models;
  }
  getProjectModel(project) {
    const modelId = "project" + project.id;
    if (!this.exists(modelId)) {
      this.upsertProjectModels(project);
    }
    return this.get(modelId);
  }
  tryGetProjectModel(project) {
    return this.tryGet("project" + project.id);
  }
  getCardBaseModels(project) {
    if (!project) return [];
    let models = [this.getProjectModel(project)];
    if (project.use_org_attributes) {
      try {
        models.unshift(this.getOrgModel(project.owner, project));
      } catch (e3) {
      }
    }
    return models;
  }
  getIdChain(model, project) {
    if (!this._idChainCache) {
      this._idChainCache = /* @__PURE__ */ new Map();
    }
    const chainId = `${model.id}${project ? `-${project.id}` : ""}`;
    if (this._idChainCache.has(chainId)) {
      return this._idChainCache.get(chainId);
    }
    const chain3 = [model.id];
    if (model.extends_id) {
      if (this.exists(model.extends_id)) {
        const parents = Array.from(this.getIdChain(this.get(model.extends_id), project));
        parents.reverse();
        chain3.push(parents);
      } else {
        chain3.push(model.extends_id);
      }
    }
    chain3.reverse();
    this._idChainCache.set(chainId, chain3);
    return chain3;
  }
  getModelChain(model, project) {
    return this.getIdChain(model, project).map((id) => this.tryGet(id)).filter(Boolean);
  }
  getExtendedModelProp(model, project, prop2) {
    let value2 = null;
    if (model) {
      this.getModelChain(model, project).forEach((model2) => {
        if (model2[prop2]) {
          value2 = model2[prop2];
        }
      });
    }
    return value2;
  }
  getExtendedModelAttributes(model, project, sort = true) {
    if (model?.base_model_type === "top_level_card" || model?.base_model_type === "org") {
      if (sort) {
        return Array.from(this.get(model.id).attributes).sort((a3, b3) => a3.name.localeCompare(b3.name));
      } else {
        return Array.from(this.get(model.id).attributes);
      }
    }
    let attributes = [];
    if (!model || model.base_model_id) {
      for (const m3 of this.getCardBaseModels(project)) {
        attributes = attributes.concat(m3.attributes);
      }
    } else if (model && !model.base_model_id) {
      if (!this._extendedAttributesCache) {
        this._extendedAttributesCache = /* @__PURE__ */ new Map();
      }
      const key2 = project ? [model.id, project.id].join(":") : model.id;
      if (!this._extendedAttributesCache.has(key2)) {
        for (const m3 of this.getCardBaseModels(project)) {
          attributes = attributes.concat(m3.attributes);
        }
        for (const m3 of this.getModelChain(model, project)) {
          attributes = attributes.concat(m3.attributes);
        }
        this._extendedAttributesCache.set(key2, attributes);
      } else {
        attributes = this._extendedAttributesCache.get(key2);
      }
    }
    if (sort) {
      return attributes.sort((a3, b3) => a3.name.localeCompare(b3.name));
    } else {
      return attributes;
    }
  }
  getAttributesFromModels(filters, withModel = false) {
    const out = [];
    for (const model of this.query()) {
      for (const attr of model.attributes) {
        if (!filters || query_exports.matchObject(attr, filters)) {
          if (withModel) {
            out.push([attr, model]);
          } else {
            out.push(attr);
          }
        }
      }
    }
    return out;
  }
  getSupportingAttributes(support, filters, withModel = false) {
    const types2 = [];
    attributeTypeRegistry.filterSupporting(support).forEach((attrType) => {
      types2.push(attrType.name);
    });
    return this.getAttributesFromModels(Object.assign({}, filters, {
      type: query_exports.any(types2)
    }), withModel);
  }
  getGroupableAttributes(filters, withModel) {
    return this.getSupportingAttributes("groupable", filters, withModel);
  }
  getSortableAttributes(filters, withModel) {
    return this.getSupportingAttributes("sortable", filters, withModel);
  }
  getAggregatableAttributes(filters, withModel) {
    return this.getSupportingAttributes("aggregates", filters, withModel);
  }
  getAttribute(id, withModel) {
    const attrs2 = this.getAttributesFromModels({ id }, withModel);
    if (attrs2.length) {
      return attrs2[0];
    }
  }
  getAttributeOwner(attr) {
    return this.get(attr.model_id);
  }
  addAttributes(model, attrs2) {
    const newAttrs = [], existingAttrs = [];
    this.update(model, { attributes: (attributes) => {
      let modelAttributes = [];
      outer: for (let modelAttr of attributes) {
        for (const attr of attrs2) {
          if (modelAttr.id === attr.id) {
            modelAttr = { ...modelAttr, ...attr };
            modelAttributes.push(modelAttr);
            existingAttrs.push(modelAttr);
            continue outer;
          }
        }
        modelAttributes.push(modelAttr);
      }
      for (const attr of attrs2) {
        if (!existingAttrs.find((a3) => a3.id === attr.id)) {
          modelAttributes.push(attr);
          newAttrs.push(attr);
        }
      }
      return modelAttributes;
    } });
    return [newAttrs, existingAttrs];
  }
  updateAttribute(model, attr) {
    const newModel = this.update(model, { attributes: (attributes) => attributes.map((modelAttr) => {
      if (modelAttr.id === attr.id) {
        return { ...modelAttr, ...attr };
      }
      return modelAttr;
    }) });
    return newModel.attributes.find((modelAttr) => modelAttr.id === attr.id);
  }
  updateAttributes(attrs2) {
    const indexed = {};
    for (let attr of attrs2) {
      indexed[attr.id] = attr;
    }
    for (const [attr, model] of this.getAttributesFromModels({}, true)) {
      if (typeof indexed[attr.id] !== "undefined") {
        this.updateAttribute(model, indexed[attr.id]);
      }
    }
  }
  removeAttribute(model, attr) {
    const index2 = model.attributes.findIndex((modelAttr) => modelAttr.id === attr.id);
    this.update(model, { attributes: removeIndex(model.attributes, index2) });
  }
  removeAttributesFromIntegration(model) {
    this.update(model, { attributes: (attrs2) => attrs2.map((attr) => ({ ...attr, is_from_integration: null })) });
  }
  updateAttrContainers(model, containers) {
    if (model.base_model_id) {
      const project = projectStore.get(model.base_model_id);
      projectStore.update(project, { attribute_containers: containers });
    }
    this.update(model, { attribute_containers: containers });
  }
  getModelsWithAttributes(filters, project) {
    const models = [];
    this.query().forEach((model) => {
      for (let attr of this.getExtendedModelAttributes(model, project)) {
        if (query_exports.matchObject(attr, filters)) {
          models.push(model);
          break;
        }
      }
    });
    return models;
  }
  getCardAvailableAttributes(card, filters, sort) {
    let model, attributes;
    const project = projectStore.tryGetForCard(card, true);
    model = this.tryGet(card.model_id);
    attributes = this.getExtendedModelAttributes(model, project, sort);
    if (filters) {
      attributes = attributes.filter((attr) => query_exports.matchObject(attr, filters));
    }
    return attributes;
  }
  isAttributeAvailableForCard(card, attribute2) {
    for (const attr of this.getCardAvailableAttributes(card, void 0, false)) {
      if (attr.id === attribute2.id) return true;
    }
    return false;
  }
  getCardModel(card) {
    const project = projectStore.tryGetForCard(card, true);
    let cardCustomModel;
    cardCustomModel = card.model_id ? this.tryGet(card.model_id) : null;
    return cardCustomModel || (project ? this.getProjectModel(project) : null);
  }
};
var cardModelStore = new CardModelStore({
  typeName: "cardModel"
}, idbLocalStorage);

// public/app/stores/group-type.ts
var CardGroupTypeStore = class extends Store {
  scopedWithAttribute(withAttribute) {
    return this.scoped(() => {
      withAttribute = callOrValue(withAttribute);
      return {
        attribute_id: (id) => withAttribute ? true : id === null || id === void 0
      };
    });
  }
  scopedByEnabled(project, withAttribute) {
    return this.scopedWithAttribute(withAttribute).scoped(() => ({
      used_by: query_exports.contains(callOrValue(project).id)
    }));
  }
  scopedByAvailableForCard(project, card, withAttribute) {
    if (!withAttribute) {
      return this.scopedByEnabled(project, false);
    }
    return this.scopedByEnabled(project, true).scoped(() => {
      card = callOrValue(card);
      return {
        attribute_id: (attrId) => {
          if (attrId === null || attrId === void 0) {
            return true;
          }
          var attr = cardModelStore.getAttribute(attrId);
          if (!attr) {
            return false;
          }
          var model = cardModelStore.getAttributeOwner(attr);
          if (model.base_model_type) {
            return true;
          }
          return model.id === card.model_id;
        }
      };
    });
  }
  scopedByCards(cards, withAttribute) {
    var projectsIds = (cards || []).reduce((accu, card) => {
      if (accu.indexOf(card.project_id) === -1) {
        return accu.concat([card.project_id]);
      }
      return accu;
    }, []);
    return this.scopedByProjects(projectsIds.map((id) => ({ id })), withAttribute);
  }
  scopedByProjects(projects, withAttribute) {
    return this.scopedWithAttribute(withAttribute).scoped(() => {
      const projectsIds = callOrValue(projects).map((p4) => p4.id);
      return {
        used_by: (propValue) => query_exports.matchArray(propValue, (usedByProjectId) => projectsIds.includes(usedByProjectId))
      };
    });
  }
  scopedByOrg(org2, withAttribute) {
    return this.scopedWithAttribute(withAttribute).scoped(() => {
      org2 = callOrValue(org2);
      return {
        owner: query_exports.objMatch({
          id: org2.id,
          type: org2.type || "org"
        })
      };
    });
  }
  scopedByProjectOwner(project, withAttribute) {
    return this.scopedWithAttribute(withAttribute).scoped(() => {
      project = callOrValue(project);
      return {
        owner: query_exports.objMatch({
          id: project.owner.id,
          type: project.owner.type
        })
      };
    });
  }
  queryByName(project, name2, withAttribute) {
    return this.scopedByEnabled(project, withAttribute).query({
      name: (v3) => kqlNameMatch(v3, name2)
    });
  }
  scopedByName(name2) {
    return this.scoped(() => {
      name2 = callOrValue(name2);
      return { name: (v3) => kqlNameMatch(v3, name2) };
    });
  }
  asAttributes() {
    return this.query().map((gt) => {
      return {
        type: "group_type",
        id: -gt.id,
        name: gt.name,
        container: "",
        group_type_id: gt.id,
        auto_group_type_attribute: true,
        is_project_specific: gt.is_project_specific
      };
    });
  }
};
var cardGroupTypeStore = new CardGroupTypeStore({
  typeName: "cardGroupType"
}, idbLocalStorage);

// public/app/stores/group.ts
var CardGroupStore = class extends Store {
  format(obj) {
    if (obj.start_date && typeof obj.start_date === "string") {
      obj.start_date = moment_default(obj.start_date, "YYYY-MM-DD").toDate();
    }
    if (obj.end_date && typeof obj.end_date === "string") {
      obj.end_date = moment_default(obj.end_date, "YYYY-MM-DD").toDate();
    }
    return obj;
  }
  getActiveByParent(parent) {
    var active;
    var project = projectStore.getForCard(parent);
    this.query({
      parent_id: query_exports.any([void 0, parent.id, project.top_level_card.id]),
      owner: query_exports.objMatch({ id: project.owner.id, type: project.owner.type }),
      is_active: true
    }).forEach((group2) => {
      if (!active || group2.end_date < active.end_date) {
        active = group2;
      }
    });
    return active;
  }
  scopedByType(groupType, parent, isArchived) {
    return this.scoped(() => {
      groupType = callOrValue(groupType);
      parent = callOrValue(parent);
      isArchived = callOrValue(isArchived);
      const project = projectStore.getForCard(parent);
      const q = { type_id: groupType ? groupType.id : null };
      if (isArchived !== void 0) {
        q["is_archived"] = isArchived;
      }
      if (groupType && groupType.scope === "org") {
        q["owner"] = query_exports.objMatch({
          id: project.owner.id,
          type: project.owner.type
        });
      } else if (groupType && groupType.scope === "project") {
        q["parent_id"] = project.top_level_card.id;
      } else {
        q["parent_id"] = parent.id;
      }
      return q;
    });
  }
  scopedByAvailableForChildren(card, isArchived) {
    return this.scoped(() => {
      card = callOrValue(card);
      isArchived = callOrValue(isArchived);
      const project = projectStore.getForCard(card);
      const q = { parent_id: query_exports.any([void 0, card.id, project.top_level_card.id]) };
      if (isArchived !== void 0) {
        q["is_archived"] = isArchived;
      }
      return q;
    });
  }
  scopedByCards(cards, groupType) {
    return this.scoped(() => {
      groupType = callOrValue(groupType);
      const groupsIds = (callOrValue(cards) || []).reduce((cardAccu, card) => {
        return (card?.groups || []).reduce((groupAccu, group2) => {
          if (group2.id && !groupAccu.includes(group2.id)) {
            return groupAccu.concat([group2.id]);
          }
          return groupAccu;
        }, cardAccu);
      }, []);
      const q = { id: query_exports.any(groupsIds) };
      if (groupType) {
        q["type_id"] = groupType.id;
      }
      return q;
    });
  }
  getForCard(card) {
    if (!card.groups || !card.groups.length) {
      return [];
    }
    return this.query({ id: query_exports.any(card.groups.map((group2) => group2.id)) });
  }
  refreshProgress(group2, delta = 0, finishedDelta = 0) {
    if (!group2 || !this.exists(group2.id)) return;
    group2 = this.get(group2.id);
    const props2 = {
      nb_cards: group2.nb_cards + delta,
      nb_finished_cards: group2.nb_finished_cards + finishedDelta
    };
    props2.progress = Math.round(props2.nb_finished_cards * 100 / props2.nb_cards);
    this.update(group2, props2);
  }
  relocate(group2, position) {
    this.transaction(() => {
      this.reorder(group2, position, group2.position);
      this.update(group2, { position });
    });
  }
  reorder(group2, position, currentPosition) {
    var bounds = computeMoveBounds(currentPosition, position);
    var q = {
      id: query_exports.neq(group2.id),
      type_id: group2.type_id,
      position: (value2) => value2 >= bounds.lower && (bounds.upper === null || value2 <= bounds.upper)
    };
    if (group2.scope != "org") {
      q.parent_id = group2.parent_id;
    }
    this.updateManyMatching(q, {
      position: (v3) => v3 + bounds.shift
    });
  }
  toggleAllFlowIndicators(parent, groupType, show) {
    this.updateManyMatching({
      type_id: groupType.id,
      parent_id: parent.id
    }, {
      show_flow_indicator: show
    });
  }
  createDynamicGroup(parent, item) {
    var project = parent ? projectStore.getForCard(parent) : null;
    return this.insert(Object.assign({
      auto_assign_user: null,
      card_state: null,
      color: null,
      default_card_model_id: null,
      description: null,
      is_creation_hidden: false,
      end_date: null,
      icon: null,
      is_active: false,
      is_archived: false,
      max_cards_limit: null,
      nb_cards: 0,
      nb_finished_cards: 0,
      owner: project ? project.owner : null,
      parent_id: parent ? parent.id : null,
      position: this.count(),
      progress: 0,
      scope: "project",
      show_flow_indicator: false,
      start_date: null,
      title: "dynamic",
      type_id: null,
      is_dynamic: true,
      getCardStore: () => null,
      handleCardEnter: () => null,
      handleCardLeave: () => null
    }, item));
  }
};
var cardGroupStore = new CardGroupStore({
  typeName: "cardGroup",
  indexProps: ["is_archived", "type_id", "parent_id"]
}, idbLocalStorage);

// public/app/stores/card.ts
var CardStore = class extends Store {
  format(card) {
    if (card.attributes) {
      for (const attr of card.attributes) {
        if (attr.type === "members") {
          if (isArray_default(attr.value)) {
            for (const user of attr.value) {
              if (isObject2(user)) {
                user.$$hashKey = user.id;
              }
            }
          }
        }
      }
    }
    card.is_editable = !card._temp && !!card.id && !card.is_archived && !card.is_parent_archived;
    return card;
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({
      is_template: query_exports.isFalsy(),
      owner: query_exports.objMatch({ type: "org", id: callOrValue(org2).id })
    }));
  }
  scopedByProject(project, isArchived = false) {
    if (isArchived === void 0) {
      return this.scoped(() => ({
        is_template: query_exports.isFalsy(),
        project_id: callOrValue(project).id
      }));
    }
    return this.scoped(() => ({
      is_template: query_exports.isFalsy(),
      project_id: callOrValue(project).id,
      is_archived: callOrValue(isArchived)
    }));
  }
  scopedByParent(parent, isArchived, includeDescendants) {
    return this.scoped(() => {
      parent = callOrValue(parent);
      const q = {
        is_template: !!parent.is_template
      };
      if (parent) {
        if (callOrValue(includeDescendants)) {
          q["path"] = query_exports.arrayOfObjMatch({ id: parent.id.toString() });
        } else {
          q["parent_id"] = parent.id;
        }
      }
      if (isArchived !== void 0) {
        q["is_archived"] = callOrValue(isArchived);
      }
      return q;
    });
  }
  scopedByParentAndGroup(parent, group2, isArchived, includeDescendants) {
    return this.scopedByParent(parent, isArchived, includeDescendants).scoped(() => ({
      groups: matchGroup(callOrValue(group2).id)
    }));
  }
  scopedByUngrouped(groupType) {
    return this.scoped(() => ({
      groups: query_exports.not(query_exports.arrayMatch((group2) => {
        return group2.type_id === callOrValue(groupType).id && cardGroupStore.exists(group2.id) && !cardGroupStore.get(group2.id).is_archived;
      }))
    }));
  }
  scopedByStateValue(state) {
    return this.scoped(() => ({
      state: callOrValue(state)
    }));
  }
  scopedByAttributeValue(attributeId, value2, matchMissingValue, valueMatcher) {
    return this.scoped(() => {
      attributeId = callOrValue(attributeId);
      value2 = callOrValue(value2);
      matchMissingValue = callOrValue(matchMissingValue);
      valueMatcher = callOrValue(valueMatcher);
      return {
        attributes: (attributes) => {
          for (var i3 = 0; i3 < attributes.length; i3++) {
            if (attributes[i3].id === attributeId) {
              if (valueMatcher) {
                return valueMatcher(value2, attributes[i3].value);
              }
              if (Array.isArray(attributes[i3].value)) {
                return attributes[i3].value.some((attrValue) => equals(attrValue, value2) || attrValue.id === value2);
              } else {
                return attributes[i3].value === value2;
              }
            }
          }
          return matchMissingValue || false;
        }
      };
    });
  }
  scopedByAttributeValueOrGroup(groupByName, value2, caseInsensitive2 = false) {
    return this.scoped(() => {
      groupByName = callOrValue(groupByName);
      value2 = callOrValue(value2);
      caseInsensitive2 = callOrValue(caseInsensitive2);
      return query_exports.or(
        query_exports.objMatch({
          attributes: (attributes) => {
            return attributes.filter((attribute2) => attribute2.name === groupByName).some((attribute2) => {
              var attrType = attributeTypeRegistry.get(attribute2.type);
              if (attrType && isFunction_default(attrType.equals)) {
                return attrType.equals(attribute2, value2);
              }
              if (Array.isArray(attribute2.value)) {
                return attribute2.value.some((attrValue) => {
                  if (isString_default(attrValue)) {
                    return attrValue.localeCompare(value2, void 0, { sensitivity: caseInsensitive2 ? "accent" : "variant" }) === 0;
                  }
                  return equals(attrValue, value2) || attrValue.id === value2;
                });
              }
              if (isString_default(attribute2.value)) {
                return value2.localeCompare(attribute2.value, void 0, { sensitivity: caseInsensitive2 ? "accent" : "variant" }) === 0;
              }
              return attribute2.value === value2;
            });
          }
        }),
        query_exports.objMatch({
          groups: caseInsensitive2 ? matchGroupTitleCaseInsensitive(
            value2
            /*, groupByName*/
          ) : matchGroupTitle(
            value2
            /*, groupByName*/
          )
        })
      );
    });
  }
  scopedByMemberAttribute(userId) {
    return this.scoped(() => {
      userId = callOrValue(userId);
      return {
        is_template: query_exports.isFalsy(),
        attributes: query_exports.arrayMatch((attr) => {
          if (attr.type === "members" && attr.value) {
            for (var i3 = 0; i3 < attr.value.length; i3++) {
              if (attr.value[i3].id === userId) {
                return true;
              }
            }
          }
          return false;
        })
      };
    });
  }
  isCardDescendantOf(card, parent) {
    if (parent.id === card.parent_id) {
      return true;
    }
    if (card.parent_id === null || card.parent_id === void 0) {
      return false;
    }
    var newCard = this.tryGet(card.parent_id);
    if (!newCard) {
      return false;
    }
    return this.isCardDescendantOf(newCard, parent);
  }
  isMirror(card) {
    return card && card.is_link && !card.link_has_own_attributes;
  }
  isValidMirror(card) {
    return card && card.is_link && !card.link_has_own_attributes && !card.broken_link;
  }
  isValidLink(card) {
    return card && card.is_link && !card.broken_link;
  }
  isTemporaryCard(card) {
    return card._temp === true;
  }
  createBaseCardObj(parent, title) {
    return {
      project_id: parent.project_id,
      parent_id: parent.id,
      path: [{ id: parent.id, title: parent.title, ref: parent.ref }],
      model_id: null,
      is_archived: false,
      groups: [],
      attributes: [],
      board_created: false,
      state: "undecided",
      title: title || "",
      is_template: false
    };
  }
  createTemporaryCard(parent, title, groups, data2) {
    const pos = Math.max(0, ...pluck(this.query({
      project_id: parent.project_id
    }), "position")) + 1;
    data2 = Object.assign({}, data2, this.createBaseCardObj(parent, title), {
      _temp: true,
      position: pos
    });
    if (!isArray_default(groups)) {
      groups = [groups];
    }
    for (let group2 of groups) {
      if (!group2) continue;
      if (group2.default_card_model_id) {
        data2.model_id = group2.default_card_model_id;
      }
      if (group2.card_state) {
        data2.state = group2.card_state;
      }
      if (group2.auto_assign_user) {
        data2.attributes[group2.auto_assign_user] = {
          type: "members",
          value: [{
            "id": currentUser2.id,
            "username": currentUser2.username,
            "display_name": currentUser2.display_name,
            "avatar": currentUser2.avatar
          }],
          async: false
        };
      }
      data2.groups.push({
        id: group2.id,
        type_id: group2.type_id,
        position: this.scopedByParentAndGroup(parent, group2, false).count()
      });
    }
    data2.finished = ["closed", "dropped", "completed"].indexOf(data2.state) !== -1;
    return this.insert(data2, false);
  }
  insert(card, refreshParentAndGroupsProgress = false) {
    return this.transaction(() => {
      card = super.insert(card);
      if (refreshParentAndGroupsProgress) {
        this.refreshParentAndGroupsProgress(card, 1, card.finished ? 1 : 0);
      }
      return card;
    });
  }
  update(card, props2, ...eventArgs) {
    return this.transaction(() => {
      var wasFinished = this.get(card.id).finished;
      card = super.update(card, props2, ...eventArgs);
      if (wasFinished !== card.finished) {
        this.refreshParentAndGroupsProgress(card, 0, wasFinished && !card.finished ? -1 : !wasFinished && card.finished ? 1 : 0);
      }
      this.updateManyMatching({ is_link: true, link: query_exports.objMatch({ id: card.id }) }, {
        title: card.title,
        full_title: card.full_title,
        nb_children: card.nb_children,
        nb_finished_children: card.nb_finished_children,
        nb_completed_pct: card.nb_completed_pct,
        board_created: card.board_created
      }, void 0, ...eventArgs);
      this.updateManyMatching({ is_link: true, link: query_exports.objMatch({ id: card.id }), link_has_own_attributes: false }, {
        model_id: card.model_id,
        attributes: card.attributes,
        nb_comments: card.nb_comments,
        state: card.state,
        finished: card.finished,
        image_cover_url: card.image_cover_url
      }, void 0, ...eventArgs);
      return card;
    });
  }
  remove(card) {
    return this.transaction(() => {
      card = super.remove(card);
      this.updateManyMatching({ is_link: true, link: query_exports.objMatch({ id: card.id }) }, {
        broken_link: true
      });
      return card;
    });
  }
  removeMany(cards) {
    return this.transaction(() => {
      const removedCards = super.removeMany(cards);
      const cardIds = removedCards.map((card) => card.id);
      this.updateManyMatching({ is_link: true, link: query_exports.objMatch({ id: query_exports.any(cardIds) }) }, { broken_link: true });
      return removedCards;
    });
  }
  refreshParentAndGroupsProgress(card, delta = 0, finishedDelta = 0) {
    if (this.exists(card.parent_id)) {
      const parent = this.get(card.parent_id);
      const props2 = {
        nb_children: parent.nb_children + delta,
        nb_finished_children: parent.nb_finished_children + finishedDelta
      };
      props2.nb_completed_pct = Math.round(props2.nb_finished_children * 100 / props2.nb_children);
      this.update(parent, props2);
    }
    cardGroupStore.transaction(() => {
      for (let group2 of card.groups) {
        cardGroupStore.refreshProgress(group2, delta, finishedDelta);
      }
    });
  }
  reorderCards(card, newPosition, oldPosition) {
    if (!card) return;
    if (newPosition === oldPosition) return;
    const bounds = computeMoveBounds(oldPosition, newPosition);
    this.transaction(() => {
      if (card.position !== newPosition) {
        this.update(card, { position: newPosition });
      }
      this.updateManyMatching({
        id: query_exports.neq(card.id),
        project_id: card.project_id,
        position: (value2) => value2 >= bounds.lower && (bounds.upper === null || value2 <= bounds.upper)
      }, {
        position: (position) => position + bounds.shift
      });
    });
  }
  reorderGroup(card, group2, position, currentPosition) {
    if (!group2) return;
    var bounds = computeMoveBounds(currentPosition, position);
    this.updateManyMatching({
      id: query_exports.neq(card.id),
      parent_id: (parent_id) => card.parent_id ? card.parent_id === parent_id : true,
      groups: query_exports.arrayOfObjMatch({
        id: group2.id,
        position: (value2) => value2 >= bounds.lower && (bounds.upper === null || value2 <= bounds.upper)
      }),
      is_archived: false
    }, {
      groups: (groups) => {
        return Array.from(groups, (g3) => {
          if (g3.id === group2.id) {
            return Object.assign({}, g3, { position: g3.position + bounds.shift });
          }
          return Object.assign({}, g3);
        });
      }
    });
  }
  reorderGroupsAfterCreation(card) {
    this.transaction(() => {
      for (let group2 of card.groups) {
        this.reorderGroup(card, group2, group2.position);
      }
    });
  }
  reorderGroupsAfterRemoval(card) {
    this.transaction(() => {
      for (let group2 of card.groups) {
        this.reorderGroup(card, group2, null, group2.position);
      }
    });
  }
  _findCardGroups(card, props2) {
    return card.groups.map((g3, i3) => {
      return {
        group_id: g3.id,
        group: cardGroupStore.tryGet(g3.id),
        position: g3.position,
        index: i3
      };
    }).filter((g3) => !!g3.group && query_exports.matchObject(g3.group, props2));
  }
  addToGroup(card, group2, position) {
    this.relocate(card, group2, position, false, false);
  }
  removeFromGroup(card, group2) {
    var current = this._findCardGroups(card, { id: group2.id })[0];
    if (current) {
      this.transaction(() => {
        this.reorderGroup(card, group2, null, current.position);
        this.update(card, { groups: (groups) => removeIndex(groups, current.index) });
      });
    }
  }
  switchGroup(card, oldGroup, newGroup, position) {
    this.transaction(() => {
      this.removeFromGroup(card, oldGroup);
      this.addToGroup(card, newGroup, position);
    });
  }
  relocate(card, group2, position, ignoreSameCurrentPosition, removeFromCurrents = true) {
    this.transaction(() => {
      var currents = this._findCardGroups(card, { type_id: group2.type_id });
      var current = currents.find((cg) => cg.group_id === group2.id);
      if (!ignoreSameCurrentPosition && current && current.position === position) {
        return;
      }
      if (position === void 0 || position === null) {
        position = group2.nb_cards;
      } else {
        this.reorderGroup(card, group2, position, current ? current.position : null);
      }
      this.update(card, produce((card_) => {
        if (!current) {
          var g3 = {
            id: group2.id,
            type_id: group2.type_id,
            scope: group2.scope,
            title: group2.title,
            position
          };
          if (typeof group2.parent_id !== "undefined") {
            g3.parent_id = group2.parent_id;
          } else {
            g3.owner = angular_default.copy(group2.owner);
          }
          card_.groups.push(g3);
          cardGroupStore.refreshProgress(group2, 1, card.finished ? 1 : 0);
        } else {
          card_.groups[current.index].position = position;
        }
        if (!current && removeFromCurrents) {
          currents.slice(0).reverse().forEach((cg, idx, array) => {
            if (cg.group_id !== group2.id) {
              card_.groups.splice(cg.index, 1);
              if (cg.group) {
                this.reorderGroup(card, cg.group, null, cg.position);
                cardGroupStore.refreshProgress(cg.group, -1, card_.finished ? -1 : 0);
              }
            }
          });
        }
      }));
    });
  }
  relocateAllInGroupToParent(group2, parent) {
    this.transaction(() => {
      this.updateManyMatching({
        groups: matchGroup(group2.id)
      }, {
        parent_id: parent.id
      });
    });
  }
  relocateAllInGroupToGroup(group2, dest, limitToStates) {
    this.transaction(() => {
      this.query({
        groups: matchGroup(group2.id),
        is_archived: false,
        state: (state) => !limitToStates || limitToStates.indexOf(state) !== -1
      }).forEach((card) => {
        if (dest) {
          this.relocate(card, dest);
        } else {
          this.removeCardFromGroups(card, { id: group2.id });
        }
      });
    });
  }
  addAllInGroupToGroup(group2, dest, limitToStates) {
    this.transaction(() => {
      this.query({
        groups: matchGroup(group2.id),
        is_archived: false,
        state: (state) => !limitToStates || limitToStates.indexOf(state) !== -1
      }).forEach((card) => {
        this.addToGroup(card, dest);
      });
    });
  }
  removeAllInGroupFromGroupType(group2, groupType, limitToStates) {
    this.transaction(() => {
      this.query({
        groups: matchGroup(group2.id),
        is_archived: false,
        state: (state) => !limitToStates || limitToStates.indexOf(state) !== -1
      }).forEach((card) => {
        this.removeCardFromGroupType(card, groupType);
      });
    });
  }
  removeCardFromGroups(card, props2) {
    this.transaction(() => {
      this._findCardGroups(card, props2).forEach((cg) => {
        this.reorderGroup(card, cg.group, null, cg.position);
        cardGroupStore.refreshProgress(cg.group, -1, card.finished ? -1 : 0);
        this.update(card, { groups: (groups) => removeIndex(groups, cg.index) });
      });
    });
  }
  removeCardFromGroupType(card, groupType) {
    this.removeCardFromGroups(card, { type_id: groupType.id });
  }
  clearGroupsAfterDeletion(group2) {
    this.transaction(() => {
      this.query({
        groups: query_exports.arrayOfObjMatch({ id: group2.id })
      }).forEach((card) => {
        this.update(card, { groups: (groups) => {
          for (let i3 = groups.length - 1; i3 >= 0; i3--) {
            if (groups[i3].id === group2.id) {
              groups = removeIndex(groups, i3);
            }
          }
          return groups;
        } });
      });
    });
  }
  clearGroupsAfterGroupTypeDisabled(groupType) {
    this.transaction(() => {
      this.query({
        groups: query_exports.arrayOfObjMatch({ type_id: groupType.id })
      }).forEach((card) => {
        this.update(card, { groups: (groups) => {
          for (let i3 = groups.length - 1; i3 >= 0; i3--) {
            if (groups[i3].type_id === groupType.id) {
              groups = removeIndex(groups, i3);
            }
          }
          return groups;
        } });
      });
    });
  }
  setCardsStateFromGroup(group2, state) {
    const finished = ["dropped", "completed", "closed"].includes(state);
    this.updateManyMatching({
      groups: matchGroup(group2.id),
      is_archived: false
    }, {
      state,
      finished
    });
  }
  archive(card) {
    this.transaction(() => {
      removeFavorite("card", card.id);
      this.update(card, { is_archived: true });
      this.reorderGroupsAfterRemoval(card);
      this.refreshParentAndGroupsProgress(card, -1, card.finished ? -1 : 0);
    });
  }
  archiveAllFromGroup(group2, limitToStates) {
    this.updateManyMatching({
      groups: matchGroup(group2.id),
      is_archived: false,
      state: (state) => !limitToStates || limitToStates.indexOf(state) !== -1
    }, {
      is_archived: true
    });
  }
  restore(card) {
    this.transaction(() => {
      this.refreshParentAndGroupsProgress(card, 1, card.finished ? 1 : 0);
      this.update(card, {
        is_archived: false,
        groups: (groups) => groups.map((group2) => {
          if (cardGroupStore.exists(group2.id)) {
            return Object.assign({}, group2, { position: cardGroupStore.get(group2.id).nb_cards });
          }
          return group2;
        })
      });
    });
  }
};
function matchGroup(groupId) {
  return function(groups, meta2) {
    return query_exports.matchArray(groups, (g3) => {
      if (g3.id === groupId) {
        meta2.position = g3.position;
        return true;
      }
      return false;
    });
  };
}
function matchGroupTitle(groupTitle, groupTypeName) {
  return function(groups) {
    return query_exports.matchArray(groups, (g3) => {
      if (groupTypeName) {
        if (!cardGroupTypeStore.exists(g3.type_id)) return false;
        if (cardGroupTypeStore.get(g3.type_id).name !== groupTypeName) return false;
      }
      return groupTitle === g3.title;
    });
  };
}
function matchGroupTitleCaseInsensitive(groupTitle, groupTypeName) {
  return function(groups) {
    return query_exports.matchArray(groups, (g3) => {
      if (groupTypeName) {
        if (!cardGroupTypeStore.exists(g3.type_id)) return false;
        if (cardGroupTypeStore.get(g3.type_id).name.localeCompare(groupTypeName, void 0, { sensitivity: "accent" }) !== 0) return false;
      }
      if (!groupTitle) return !g3.title;
      return g3.title && g3.title.localeCompare(groupTitle, void 0, { sensitivity: "accent" }) === 0;
    });
  };
}
var cardStore = new CardStore({
  typeName: "card",
  // autoLoad: false,
  // scopedLocalStorageKey: true,
  indexProps: ["is_archived", "parent_id", "project_id", "is_link"]
}, idbLocalStorage);

// public/app/stores/activity.ts
var ActivityStore = class extends Store {
  format(activity) {
    if (typeof activity.actor === "string") {
      activity.actor = { username: activity.actor, display_name: activity.actor };
    }
    if (activity.object && activity.object.type === "Card") {
      activity.card_id = activity.object.id;
    }
    if (activity.target && activity.target.type === "Card") {
      activity.card_id = activity.target.id;
    }
    activity.formatted_date = formatDate(activity.date, "LL");
    activity.formatted_date_complete = formatDate(activity.date, "LLL");
    activity.date_hours_only = formatDate(activity.date, "LT");
    return activity;
  }
  scopedForCard(card) {
    return this.scoped(() => (activity) => {
      card = callOrValue(card);
      return activity.card_id && activity.card_id === card.id || activity.object && activity.object.type === "Card" && activity.object.id === card.id || activity.target && activity.target.type === "Card" && activity.target.id === card.id;
    });
  }
  scopedByActivitiesOnly() {
    return this.scoped({ stream_type: "activity" });
  }
  getCardStream(card) {
    return this.scopedForCard(card).scoped(() => (activity) => {
      return activity.stream_type !== "activity" || !activity.object || activity.object.type !== "CardComment" && activity.object.type !== "CardLog";
    });
  }
  scopedByProject(project) {
    return this.scoped(() => {
      project = callOrValue(project);
      query_exports.or(
        query_exports.objMatch({ project_id: project.id }),
        function(activity) {
          const cardsIds = uniq(["object", "target", "origin"].filter((prop2) => activity[prop2] && activity[prop2].type === "Card").map((prop2) => activity[prop2].id));
          return cardsIds.some((id) => {
            const card = cardStore.tryGet(id);
            return card && card.project_id === project.id;
          });
        }
      );
    });
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({ org_id: callOrValue(org2).id }));
  }
  scopedByUpdates() {
    return this.scoped({ verb: "POST_UPDATE" });
  }
};
var activityStore = new ActivityStore({
  typeName: "activity",
  autoLoad: false
  //scopedLocalStorageKey: true
}, idbLocalStorage);

// public/app/stores/automation-rule.ts
var AutomationRuleStore = class extends Store {
  scopedByProject(project) {
    return this.scoped(() => ({ project_id: callOrValue(project).id }));
  }
  scopedByGroup(project, group2) {
    return this.scoped(() => ({
      project_id: callOrValue(project).id,
      trigger_event: "card_added_to_group",
      trigger_options: query_exports.objMatch({
        group: query_exports.objMatch({
          id: callOrValue(group2).id
        })
      })
    }));
  }
};
var automationRuleStore = new AutomationRuleStore({
  typeName: "automationRule"
}, idbLocalStorage);

// public/app/stores/card-reminder.ts
var CardReminder = class extends Store {
  scopedByCard(card) {
    return this.scoped(() => ({ card_id: callOrValue(card).id }));
  }
  getForCard(card) {
    return this.query({ card_id: card.id });
  }
};
var cardReminderStore = new CardReminder({
  typeName: "cardReminder",
  dropDuplicates: true
}, idbLocalStorage);

// public/app/stores/card-subscription.ts
var CardSubscription = class extends Store {
  id(obj) {
    return obj.card_id;
  }
  getForCard(card) {
    return this.tryGet(card.id);
  }
  isSubscribed(card) {
    return this.exists(card.id);
  }
  subscribeTo(card, data2) {
    this.upsert(Object.assign({ card_id: card.id, send_emails: true }, data2 || {}));
  }
  unsubscribeFrom(card) {
    var s3 = this.getForCard(card);
    if (s3) {
      this.remove(s3);
    }
  }
};
var cardSubscriptionStore = new CardSubscription({
  typeName: "cardSubscription",
  dropDuplicates: true
});

// public/app/config/files.js
var fileTypes = [
  [new RegExp("^image\\/", "i"), "fa-file-image-o"],
  [new RegExp("^audio\\/", "i"), "fa-file-audio-o"],
  [new RegExp("^video\\/", "i"), "fa-file-video-o"],
  [new RegExp("^text\\/csv$", "i"), "fa-file-excel-o"],
  [new RegExp("^text\\/rtf$", "i"), "fa-file-word-o"],
  [new RegExp("^application\\/pdf$", "i"), "fa-file-pdf-o"],
  [new RegExp("^application\\/vnd\\.(oasis.opendocument.text|openxmlformats-officedocument.wordprocessingml.document)$", "i"), "fa-file-word-o"],
  [new RegExp("^application\\/vnd\\.(oasis.opendocument.spreadsheet|ms-excel|openxmlformats-officedocument.spreadsheetml.sheet)$", "i"), "fa-file-excel-o"],
  [new RegExp("^application\\/vnd\\.(oasis.opendocument.presentation|ms-powerpoint|openxmlformats-officedocument.presentationml.presentation)$", "i"), "fa-file-powerpoint-o"],
  [new RegExp("^application\\/(zip|gzip)$", "i"), "fa-file-archive-o"]
];
var fileProviders = [];
var filePreviewers = [
  [new RegExp("^image\\/", "i"), "imageFilePreviewer"],
  [new RegExp("^video\\/", "i"), "videoFilePreviewer"],
  [new RegExp("^application\\/pdf$", "i"), "pdfFilePreviewer"]
];

// public/app/stores/file.ts
var FileStore = class extends Store {
  format(file) {
    if (file instanceof File) {
      file = {
        file,
        name: file.name,
        mimetype: file.type
      };
    }
    file.caption = file.name;
    file.fileTypeIcon = "fa-file-o";
    for (let [regexp, icon] of fileTypes) {
      if (regexp.test(file.mimetype)) {
        file.fileTypeIcon = icon;
        break;
      }
    }
    return file;
  }
  queryByMimetype(regexp) {
    return this.query({ mimetype: (mimetype) => mimetype && regexp.test(mimetype) });
  }
};

// public/app/stores/form.ts
var RequestFormStore = class extends Store {
  scopedByProject(project) {
    return this.scoped(() => ({ project_id: callOrValue(project).id }));
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({ owner: query_exports.objMatch({ id: callOrValue(org2).id, type: "org" }) }));
  }
};
var requestFormStore = new RequestFormStore({
  typeName: "requestForm"
}, idbLocalStorage);

// public/app/stores/group-subscription.ts
var GroupSubscriptionStore = class extends Store {
  id(obj) {
    return obj.group_id;
  }
  getForGroup(group2) {
    return this.query({ group_id: group2.id })?.[0];
  }
  isSubscribed(group2) {
    return this.query({ group_id: group2.id }).length === 1;
  }
  getAllForCard(card, withGroup) {
    return (card.groups || []).reduce((accu, group2) => {
      var subscription = this.query({ group_id: group2.id, notify_card_changes: true })?.[0];
      if (subscription) {
        if (withGroup) {
          return accu.concat([[subscription, group2]]);
        } else {
          return accu.concat(subscription);
        }
      }
      return accu;
    }, []);
  }
  isSubscribedToCard(card) {
    return (card.groups || []).some((group2) => {
      return this.query({ group_id: group2.id, notify_card_changes: true }).length > 0;
    });
  }
  subscribeTo(group2, data2) {
    this.upsert(Object.assign({ group_id: group2.id, send_emails: true, notify_card_changes: false }, data2));
  }
  toggleCardNotifications(group2) {
    var s3 = this.getForGroup(group2);
    if (s3) {
      this.update(s3, { notify_card_changes: !s3.notify_card_changes });
    }
  }
  unsubscribeFrom(group2) {
    var s3 = this.getForGroup(group2);
    if (s3) {
      this.remove(s3);
    }
  }
};
var cardGroupSubscriptionStore = new GroupSubscriptionStore({
  typeName: "cardGroupSubscription",
  dropDuplicates: true
});

// public/app/stores/integration.ts
var IntegrationStore = class extends Store {
  scopedByOrg(org2) {
    return this.scoped(() => ({ org_id: callOrValue(org2).id }));
  }
};
var integrationStore = new IntegrationStore();

// public/app/stores/log-type.ts
var ProjectLogTypeStore = class extends Store {
  format(logType) {
    if (!logType.attributes) {
      logType.attributes = [];
    }
    for (let attr of logType.attributes) {
      attr.$$hashKey = attr.id;
    }
    return logType;
  }
  scopedByProject(project) {
    return this.scoped(() => ({ used_by: query_exports.contains(callOrValue(project).id) }));
  }
};
var projectLogTypeStore = new ProjectLogTypeStore({
  typeName: "projectLogType"
}, idbLocalStorage);

// public/app/stores/org-member.ts
var OrgMemberStore = class extends Store {
  scopedByOrg(org2) {
    return this.scoped(() => ({ org_id: callOrValue(org2).id }));
  }
  scopedByTeam(team, permissionFilter) {
    return this.scoped(() => {
      const filter4 = { id: callOrValue(team).id };
      permissionFilter = callOrValue(permissionFilter);
      if (permissionFilter !== void 0) {
        filter4["perm"] = permissionFilter;
      }
      return { teams: query_exports.arrayOfObjMatch(filter4) };
    });
  }
  scopedByUsers() {
    return this.scoped({ user: query_exports.isDefined() });
  }
};
var orgMemberStore = new OrgMemberStore({
  typeName: "orgMember"
}, idbLocalStorage);

// public/app/stores/org.ts
var OrgStore = class extends Store {
  format(org2) {
    if (org2.ai_enabled === null) {
      org2.ai_enabled = serverConfig.has_global_ai_config;
    }
    org2.ai_assistant_enabled = serverConfig.ai_assistant && org2?.ai_enabled && org2?.ai_assistant;
    return org2;
  }
  getFromTeam(team) {
    return this.get(team.owner.id);
  }
  getForProject(project) {
    return this.get(project.owner.id);
  }
  tryGetForProject(project) {
    if (!project) return;
    return this.tryGet(project.owner.id);
  }
  scopedByCurrentUser() {
    return this.scoped({ is_member: query_exports.isTruthy() });
  }
  scopedByProjects(projects) {
    return this.scoped(() => {
      projects = callOrValue(projects);
      const orgIds = [];
      for (const project of projects) {
        const org2 = this.tryGetForProject(project);
        if (org2) {
          orgIds.push(org2.id);
        }
      }
      return { id: query_exports.any(orgIds) };
    });
  }
};
var OrgFeaturedItemStore = class extends Store {
  format(item) {
    if (item.type === "project") {
      item.icon = "bi-columns-gap";
    } else if (item.type === "request_form") {
      item.icon = "kfi-form";
    } else if (item.type === "file") {
      for (let [regexp, icon] of fileTypes) {
        if (regexp.test(item.object.mimetype)) {
          item.icon = icon;
          break;
        }
      }
    }
    return item;
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({ org_id: callOrValue(org2).id }));
  }
};
var orgStore = new OrgStore({
  typeName: "org"
}, idbLocalStorage);
var orgFeaturedItemStore = new OrgFeaturedItemStore();

// public/app/stores/project-integration.ts
var ProjectIntegrationStore = class extends Store {
  format(integration) {
    if (typeof integration.instance_id === "undefined") {
      integration.instance_id = integration.id;
      integration.id = integration.id + "-" + integration.project_id;
    }
    return integration;
  }
  scopedByProject(project) {
    return this.scoped(() => ({ project_id: callOrValue(project).id }));
  }
};
var projectIntegrationStore = new ProjectIntegrationStore();

// public/app/stores/project-member.ts
var ProjectMemberStore = class extends Store {
  format(member) {
    if (member.user) {
      member.user.$$hashKey = member.user.id;
    }
    if (member.id) return member;
    return Object.assign({}, member, {
      id: member.project_id + "-" + member.user.id
    });
  }
  scopedByProject(project) {
    return this.scoped(() => {
      const p4 = callOrValue(project);
      return { project_id: p4?.id ? p4.id : p4 };
    });
  }
  scopedByUsers() {
    return this.scoped({ user: query_exports.isDefined() });
  }
  upsertManyForProject(project, members) {
    this.upsertMany(members.map((m3) => Object.assign(m3, { project_id: project.id })));
  }
  upsertUserOrgOwner(project) {
    return this.upsert({
      id: `project-owner-${project.id}`,
      project_id: project.id,
      permission: 5,
      user: project.owner.user,
      is_org_member: true,
      is_org_admin: true
    });
  }
  getAll(project, { grouped = true } = {}) {
    const members = this.scopedByProject(project).query();
    if (!grouped) return members;
    const guests = [];
    const org2 = [];
    const owners = [];
    for (const member of members) {
      if (member.is_org_owner && project.fromUserOrg) {
        owners.push(member);
      } else if (member.is_org_member) {
        org2.push(member);
      } else {
        guests.push(member);
      }
    }
    return { guests, org: org2, owners };
  }
  getUserOrgOwner(project) {
    return this.getByUserId(`project-owner-${project.id}`);
  }
  getByUserId(userId) {
    return this.query({ user: query_exports.objMatch({ id: userId }) })?.[0];
  }
};
var projectMemberStore = new ProjectMemberStore({
  typeName: "projectMember"
}, idbLocalStorage);

// public/app/stores/recurring-card.ts
var RecurringCardStore = class extends Store {
  scopedByProject(project) {
    return this.scoped(() => ({ project_id: callOrValue(project).id }));
  }
};
var recurringCardStore = new RecurringCardStore({
  typeName: "projectTask"
}, idbLocalStorage);

// public/app/stores/role.ts
var RoleStore = class extends Store {
  scopedByUser() {
    return this.scoped({ owner: query_exports.objMatch({ type: "user" }) });
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({ owner: query_exports.objMatch({ id: callOrValue(org2).id }) }));
  }
  scopedByOrgForGuest(org2, project) {
    if (project && project.is_public) {
      return this.scopedByOrg(org2);
    } else {
      return this.scoped(() => ({
        owner: query_exports.objMatch({ id: callOrValue(org2).id }),
        is_authorized_as_guest: true
      }));
    }
  }
  getAllForProject(project, { grouped = true } = {}) {
    const org2 = this.scopedByOrg(project.owner).query();
    if (!grouped) return org2;
    const guests = this.scopedByOrgForGuest(project.owner, project).query();
    return { org: org2, guests };
  }
  getAllForPortfolio(project, { grouped = true } = {}) {
    const org2 = this.scopedByOrg(project.owner).query({ is_builtin: query_exports.any(["ADMIN", "MEMBER", "OBSERVER"]) });
    if (!grouped) return org2;
    const guests = [].concat(this.scopedByOrgForGuest(project.owner, project).query({ is_builtin: "OBSERVER" }));
    return { org: org2, guests };
  }
};
var roleStore = new RoleStore({
  typeName: "role"
}, idbLocalStorage);

// public/app/stores/state.ts
function sortStateGroups(a3, b3) {
  if (a3.group_type_id > b3.group_type_id) {
    return 1;
  }
  if (a3.group_type_id < b3.group_type_id) {
    return -1;
  }
  if (a3.position > b3.position) {
    return 1;
  }
  if (a3.position < b3.position) {
    return -1;
  }
  return a3.title.localeCompare(b3.title);
}
var CardStateStore = class extends Store {
  insert(obj) {
    if (typeof obj.id !== "number" && this.exists(obj.id)) {
      return this.get(obj.id);
    }
    return Store.prototype.insert.call(this, obj);
  }
  getForCard(card) {
    if (card.state_alias_id && this.exists(card.state_alias_id)) {
      return this.get(card.state_alias_id);
    }
    return this.get(card.state);
  }
  getAvailableAliasesForCard(card, filterState, filterGroups) {
    var project = projectStore.getForCard(card);
    var aliasStates = this.join("id", cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(project, true))).query().map((alias) => cardGroupStore.tryGet(alias.id)).filter((group2) => {
      if (group2) {
        return (!filterGroups || filterGroups.indexOf(group2.id)) !== -1 && (group2.scope === "org" && group2.owner.id === project.owner.id || group2.scope === "project" && group2.parent_id === project.top_level_card.id || group2.scope === "card" && group2.parent_id === card.parent_id);
      }
      return false;
    }).sort(sortStateGroups).map((group2) => this.get(group2.id));
    if (filterState) {
      return aliasStates.filter((state) => state.id === filterState || state.alias && state.alias == filterState);
    }
    return aliasStates;
  }
  getAvailableForCard(card, filterState) {
    var aliasStates = this.getAvailableAliasesForCard(card, filterState);
    var aliases = aliasStates.map((state) => state.alias);
    var builtinStates = this.getBuiltinStates(filterState);
    return builtinStates.reduce((states, state) => {
      if (aliases.includes(state.id)) {
        return states.concat(
          aliasStates.reduce((groups, group2) => {
            if (group2.alias === state.id) {
              return groups.concat([group2]);
            } else {
              return groups;
            }
          }, [])
        );
      } else {
        return states.concat([state]);
      }
    }, []);
  }
  getBuiltinStates(filterState) {
    const builtinStates = this.query({ alias: query_exports.isUndefined() });
    if (filterState) {
      return builtinStates.filter((state) => state.id === filterState || state.alias && state.alias == filterState);
    } else {
      return builtinStates;
    }
  }
  createOrUpdateAliasFromGroup(group2) {
    if (group2.card_state && !group2.is_archived) {
      var state = this.get(group2.card_state);
      this.upsert({
        id: group2.id,
        parent_id: group2.parent_id,
        alias: group2.card_state,
        label: group2.title,
        icon: group2.icon || state.icon,
        finished: state.finished
      });
      cardStore.updateManyMatching({
        state_alias_id: group2.id,
        state: query_exports.neq(group2.card_state)
      }, { state_alias_id: null });
    } else if (this.exists(group2.id)) {
      this.remove({ id: group2.id });
      cardStore.updateManyMatching({ state_alias_id: group2.id }, { state_alias_id: null });
    }
  }
};
var cardStateStore = new CardStateStore({
  typeName: "cardState"
}, idbLocalStorage);
cardStateStore.load().then(() => {
  cardStateStore.upsertMany([
    {
      id: "undecided",
      label: _lazy("Undecided"),
      finished: false
    },
    {
      id: "dropped",
      label: _lazy("Dropped"),
      icon: "times",
      finished: true
    },
    {
      id: "accepted",
      label: _lazy("Accepted"),
      finished: false
    },
    {
      id: "in_progress",
      label: _lazy("In Progress"),
      icon: "play",
      finished: false
    },
    {
      id: "waiting",
      label: _lazy("Waiting"),
      icon: "pause",
      finished: false
    },
    {
      id: "completed",
      label: _lazy("Completed"),
      icon: "check-square-o",
      finished: true
    },
    {
      id: "closed",
      label: _lazy("Closed"),
      finished: true
    }
  ]);
});

// public/app/stores/team.ts
var TeamStore = class extends Store {
  getForProject(project) {
    return this.get(project?.team?.id);
  }
  tryGetForProject(project) {
    return this.tryGet(project?.team?.id);
  }
  scopedByOrg(org2) {
    return this.scoped(() => ({ owner: query_exports.objMatch({ id: callOrValue(org2).id }) }));
  }
  scopedByProjects(projects) {
    return this.scoped(() => {
      projects = callOrValue(projects);
      const teamIds = [];
      for (const project of projects) {
        const team = this.tryGetForProject(project);
        if (team) {
          teamIds.push(team.id);
        }
      }
      return { id: query_exports.any(teamIds) };
    });
  }
};
var teamStore = new TeamStore({
  typeName: "team"
}, idbLocalStorage);

// public/app/stores/view-categories.ts
var ViewCategoryStore = class extends Store {
  scopedByProject(project) {
    return this.scoped(() => ({ project_id: callOrValue(project).id }));
  }
  reorder(category, position) {
    this.transaction(() => {
      var bounds = computeMoveBounds(category.position, position);
      var q = {
        id: query_exports.neq(category.id),
        position: (value2) => value2 >= bounds.lower && (bounds.upper === null || value2 <= bounds.upper)
      };
      this.updateManyMatching(q, { position: (v3) => v3 + bounds.shift });
      this.update(category, { position });
    });
  }
};
var viewCategoryStore = new ViewCategoryStore({
  typeName: "view-category"
}, idbLocalStorage);

// public/app/apps/app-registry.js
var AppRegistry = class extends Registry {
  get(name2, resolveAlias, fallbackToDefault = true) {
    const app = super.get(name2, resolveAlias);
    if ((!app || app.hidden) && fallbackToDefault) {
      return this.getDefault();
    }
    return app;
  }
  getDefault() {
    for (const [name2, app] of Object.entries(this.items)) {
      if (!!app.default) return app;
    }
    return null;
  }
  getAll({ withHidden = false } = {}) {
    return super.getAll().filter((app) => {
      const filters = [];
      if (withHidden === "only") return !!app.hidden;
      if (!withHidden) return !app.hidden;
    });
  }
};

// public/app/apps/cards/app-registry.js
var CardsAppRegistry = class extends AppRegistry {
  get(name2, ...args) {
    if (name2 === "checklist") name2 = "list";
    return super.get(name2, ...args);
  }
};
var cardsAppRegistry = new CardsAppRegistry({ setNameOnItem: true });

// public/app/stores/utils/role.js
function structureIsLocked(project) {
  return project?.locked_structure;
}
function getCurrentUserProjectMember(project) {
  return projectMemberStore.scopedByProject(project).getByUserId(currentUser2.id);
}
function isCurrentUserMemberOfProject(project) {
  return isAuthenticated() && !!getCurrentUserProjectMember(project);
}
function isAllowed(perms, objType, projectId, objId, actions2) {
  if (!perms) {
    return false;
  }
  projectId = projectId ? projectId : null;
  objId = objId ? objId : null;
  if (!Array.isArray(actions2)) {
    actions2 = [actions2];
  }
  var isAllowed2 = true;
  actions2.forEach(function(action) {
    var _isAllowed = false;
    for (var i3 = 0; i3 < perms.length; i3++) {
      if (perms[i3].object_type == objType) {
        if (perms[i3].object_id) {
          if (perms[i3].object_id == objId) {
            _isAllowed = perms[i3].actions.indexOf(action) > -1;
            break;
          }
        } else {
          _isAllowed = perms[i3].actions.indexOf(action) > -1;
        }
      }
    }
    isAllowed2 = isAllowed2 && _isAllowed;
  });
  return isAllowed2;
}
function isAllowedFuzzy(perms, objType, projectId, actions2) {
  if (!perms) {
    return false;
  }
  projectId = projectId || null;
  if (!Array.isArray(actions2)) {
    actions2 = [actions2];
  }
  return actions2.some(function(action) {
    return perms.some(function(perm) {
      return perm.object_type === objType && perm.actions.indexOf(action) !== -1;
    });
  });
}
function matchingPerm(perms, perm) {
  return isAllowed(perms, perm.object_type, perm.project_id, perm.object_id, perm.actions);
}
function matchingPerms(a3, b3) {
  for (var i3 = 0; i3 < b3.length; i3++) {
    if (!matchingPerm(a3, b3[i3])) {
      return false;
    }
  }
  return true;
}
function override(a3, b3) {
  var overriden = angular_default.copy(a3);
  b3.forEach(function(perm) {
    var found2 = false;
    for (var i3 = 0; i3 < overriden.length; i3++) {
      if (perm.object_type === overriden[i3].object_type) {
        overriden[i3] = perm;
        found2 = true;
        break;
      }
    }
    if (!found2) {
      overriden.push(perm);
    }
  });
  return overriden;
}
function getSpecificPerms(perms, type, objectId, action) {
  var specificPerms = [];
  specificPerms = perms.filter(function(a3) {
    if (type === "base" && (a3.project_id || a3.object_id)) {
      return false;
    }
    if (type === "project" && (!a3.project_id || a3.project_id !== objectId || a3.object_id)) {
      return false;
    }
    if (type === "object" && (!a3.project_id || !a3.object_id || a3.object_id !== objectId)) {
      return false;
    }
    if (!action) {
      return true;
    }
    for (var i3 = 0; i3 < action.map.length; i3++) {
      if (action.map[i3].object_type === a3.object_type) {
        return true;
      }
    }
    return false;
  });
  return specificPerms;
}
function isOverriden(perms, type, objectId, action) {
  if (!action) {
    return false;
  }
  var specificPerms = type === "object" ? getSpecificPerms(perms, "object", objectId, action) : getSpecificPerms(perms, "project", objectId, action);
  if (!specificPerms.length) {
    return false;
  }
  var basePerms = getSpecificPerms(perms, "base", objectId, action);
  if (type === "object") {
    var projectPerms = getSpecificPerms(perms, "project", objectId, action);
    basePerms = override(basePerms, projectPerms);
  }
  var isAllowed2 = matchingPerms(basePerms, action.map);
  specificPerms = override(basePerms, specificPerms);
  return matchingPerms(specificPerms, action.map) !== isAllowed2;
}
function filterPermissionsForObject(perms, project, objectType, objectId) {
  return perms.filter(function(perm) {
    return (!perm.project_id || perm.project_id === project.id) && perm.object_type === objectType && (!perm.object_id || perm.object_id === objectId);
  });
}
function isAllowedInProject(project, objType, actions2, objId) {
  return currentUser2.is_kantree_admin || isAllowed(project.user_permissions, objType, project.id, objId, actions2);
}
function isAllowedInProjectFuzzy(project, objType, actions2) {
  return currentUser2.is_kantree_admin || isAllowedFuzzy(project.user_permissions, objType, project.id, actions2);
}
function isSettingsButtonVisible(project) {
  return canManageSettings(project) || canManageMembers(project) || canManageAttributes(project) || canManageRecurring(project) || canManagePIIData(project) || isAllowedInProject(project, "card_model", ["CREATE", "EDIT", "DELETE"]) || isAllowedInProject(project, "card_group_type", ["CREATE", "EDIT", "DELETE"]);
}
function canAddCard(project, group_id) {
  if (group_id && !isAllowedInProject(project, "card_group", "MOVE_CARDS", group_id)) {
    return false;
  }
  return isAllowedInProject(project, "card", "CREATE");
}
function canEditCard(project, card_id) {
  return isAllowedInProject(project, "card", ["EDIT", "SWITCH_MODEL"], card_id);
}
function canArchiveCard(project, card_id) {
  return isAllowedInProject(project, "card", "ARCHIVE", card_id);
}
function canDeleteCard(project, card_id) {
  return isAllowedInProject(project, "card", "DELETE", card_id);
}
function canCreateComment(project) {
  return isAllowedInProject(project, "card_comment", "CREATE");
}
function canCreateLog(project) {
  return isAllowedInProject(project, "card_log", "CREATE");
}
function canDeleteLog(project, log_id) {
  return isAllowedInProject(project, "card_log", "DELETE", log_id);
}
function canAddGroup(project) {
  return isAllowedInProject(project, "card_group", "CREATE");
}
function canEditGroup(project, group_id) {
  return isAllowedInProject(project, "card_group", "EDIT", group_id);
}
function canDeleteGroup(project, group_id) {
  return isAllowedInProject(project, "card_group", "DELETE", group_id);
}
function canManageSettings(project) {
  return isAllowedInProject(project, "project", "OPTIONS", project.id);
}
function canManageAttributes(project) {
  return !structureIsLocked(project) && isAllowedInProject(project, "project", "MANAGE_ATTRIBUTES", project.id);
}
function canManageViews(project) {
  return !structureIsLocked(project) && isAllowedInProject(project, "project", "MANAGE_SHARED_VIEWS", project.id);
}
function canManageRecurring(project) {
  return isAllowedInProject(project, "project", "MANAGE_RECURRING", project.id);
}
function canManagePIIData(project) {
  return isAllowedInProject(project, "project", "MANAGE_PII_DATA", project.id);
}
function canImportData(project) {
  return isAllowedInProject(project, "project", "IMPORT_DATA", project.id);
}
function canExportData(project) {
  return isAllowedInProject(project, "project", "EXPORT_DATA", project.id);
}
function canManageMembers(project) {
  return isAllowedInProject(project, "project", "ACCESS", project.id);
}
function canManageAutomations(project) {
  return isAllowedInProject(project, "project", "MANAGE_AUTO_ACTIONS", project.id);
}
function canRunAutomations(project) {
  return canManageAutomations(project) || isAllowedInProject(project, "project", "RUN_AUTO_ACTIONS", project.id);
}
function canEditCardModel(project, objId = void 0) {
  return !structureIsLocked(project) && isAllowedInProject(project, "card_model", "EDIT", objId);
}
function canCreateCardModel(project, objId = void 0) {
  return !structureIsLocked(project) && isAllowedInProject(project, "card_model", "CREATE", objId);
}
function canDeleteCardModel(project, objId = void 0) {
  return !structureIsLocked(project) && isAllowedInProject(project, "card_model", "DELETE", objId);
}
function canOpenGroupActionsMenu(project, group_id) {
  return isAllowedInProject(project, "card_group", "EDIT", group_id) || isAllowedInProject(project, "card_group", "DELETE", group_id) || isAllowedInProject(project, "card_group", "MOVE_CARDS");
}
function canEditAttribute(project, attr) {
  return project && !["__project__", "__state__"].includes(attr.type) && isAllowedInProject(project, "attribute", "EDIT", attr.id) && (attr.type !== "group_type" || canMoveCardsInThisGroupType(project, attr.group_type_id));
}
function canEditSomeAttributes(project, attrs2) {
  if (!attrs2) {
    return false;
  }
  return (Array.isArray(attrs2) ? attrs2 : [attrs2]).some((attr) => {
    if (Array.isArray(attr)) return canEditSomeAttributes(project, attr);
    return canEditAttribute(project, attr);
  }, this);
}
function getActionsForCardComment(project, comment4) {
  var actions2 = [];
  if (typeof comment4 === "undefined" || comment4.user && currentUser2 && comment4.user.id === currentUser2.id) {
    if (isAllowedInProject(project, "card_comment", "CREATE")) {
      actions2.push("edit_temporarily");
    }
    if (isAllowedInProject(project, "card_comment", "DELETE_MINE")) {
      if (comment4 && comment4.user.id === currentUser2.id) {
        actions2.push("delete");
      } else {
        actions2.push("delete_mine");
      }
    }
  }
  if (isAllowedInProject(project, "card_comment", "EDIT")) {
    actions2.push("edit");
    actions2.push("pin");
  }
  if (isAllowedInProject(project, "card_comment", "DELETE")) {
    actions2.push("delete");
  }
  return actions2;
}
function getActionsForCardLog(project, comment4) {
  var actions2 = [];
  if (isAllowedInProject(project, "card_log", "DELETE")) {
    actions2.push("delete");
  } else if (isAllowedInProject(project, "card_log", "DELETE_MINE")) {
    actions2.push("delete_mine");
  }
  return actions2;
}
function getActionsForCardActivities(project) {
  var actions2 = [];
  actions2.push.apply(actions2, getActionsForCardComment(project).map(function(action) {
    return "comments:" + action;
  }));
  actions2.push.apply(actions2, getActionsForCardLog(project).map(function(action) {
    return "logs:" + action;
  }));
  return actions2;
}
function canMoveCardsInThisGroupType(project, groupTypeId) {
  if (currentUser2.is_kantree_admin) return true;
  var perms = project.user_permissions;
  if (!perms) return false;
  var allowedGroupsIds = perms.filter(function(perm) {
    return perm.object_type === "card_group" && perm.actions.indexOf("MOVE_CARDS") !== -1;
  }).map(function(perm) {
    return perm.object_id;
  });
  return allowedGroupsIds.some(function(id) {
    if (!id) {
      return true;
    }
    var group2 = cardGroupStore.tryGet(id);
    if (group2 && group2.type_id === groupTypeId) {
      return true;
    }
    return false;
  });
}
function canSortGroupBy(project, groupBy2) {
  if (groupBy2.isGroupType(void 0, true) && !canMoveCardsInThisGroupType(project, groupBy2.getGroupType(true).id)) {
    return false;
  }
  if (groupBy2.isAttribute() && !isAllowedInProject(project, "attribute", "EDIT", groupBy2.getAttribute().id)) {
    return false;
  }
  return true;
}
function getGroupsEnablingCardMoving(project) {
  if (currentUser2.is_kantree_admin) return true;
  var perms = project.user_permissions;
  if (!perms) {
    return false;
  }
  var allowedGroupsIds = perms.filter(function(perm) {
    return perm.object_type === "card_group" && perm.actions.indexOf("MOVE_CARDS") !== -1;
  }).map(function(perm) {
    return perm.object_id;
  });
  if (allowedGroupsIds.some(function(id) {
    return !id;
  })) {
    return true;
  } else {
    return allowedGroupsIds;
  }
}

// public/app/apps/cards/common/mode-options.js
function getCommonModeOptions(options2, onChange) {
  return [
    {
      label: _4("Descendants"),
      checkbox: true,
      value: () => (options2 || {}).include_descendants,
      toggle: () => onChange({ include_descendants: !(options2 || {}).include_descendants })
    },
    {
      label: _4("Archived"),
      checkbox: true,
      value: () => (options2 || {}).include_archived,
      toggle: () => onChange({ include_archived: !(options2 || {}).include_archived })
    }
  ];
}
function getActionsOptions(options2 = {}, onChange, project = void 0) {
  let result2 = [];
  if (!options2.showActions && !isScreensizeXS()) {
    result2 = [
      {
        label: "--",
        enabled: () => canRunAutomations(project),
        // doesn't work right now but maybe later ?
        offline: false,
        public: false,
        mobile: false
      },
      {
        subheader: _4("Actions"),
        offline: false,
        public: false,
        mobile: false,
        enabled: () => canRunAutomations(project),
        help: _4("Add action buttons that trigger automation rules to the topbar of this view")
      },
      {
        label: _4("Add actions"),
        icon: "bolt",
        offline: false,
        public: false,
        mobile: false,
        enabled: () => canRunAutomations(project),
        action: () => {
          onChange({ showActions: !options2.showActions });
          $broadcast("openActionsMenu");
        }
      }
    ];
  }
  return result2;
}
function getFullScreenOption() {
  return {
    label: _4("Show in full screen"),
    icon: "bi-fullscreen",
    action: () => toggleFullscreen(document.querySelector("project-cards-app cards-app"))
  };
}

// public/app/ui/system/toast.jsx
var _tmpl$19 = /* @__PURE__ */ template(`<div id="toast-notifications"></div>`, 2);
var _tmpl$210 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$35 = /* @__PURE__ */ template(`<div class="progress"><div></div></div>`, 4);
var _tmpl$44 = /* @__PURE__ */ template(`<div class="toast-notification"><div class="content"><div><div class="title"></div></div></div><button>&times;</button></div>`, 10);
var defaultOptions = {
  ttl: 1e4,
  // set to 0 to close manually
  type: "info",
  progress: false
};
var toastTypes = {
  info: {
    icon: "bi-info-circle-fill",
    color: "#64bbdd"
  },
  warning: {
    icon: "bi-exclamation-triangle-fill",
    color: "#dd6464"
  },
  success: {
    icon: "bi-check-circle-fill",
    color: "#64dda6"
  },
  error: {
    icon: "bi-exclamation-octagon-fill",
    color: "#dd6464"
  },
  loader: {
    icon: "spin fa-spinner",
    color: "#64bbdd",
    ttl: 0
  }
};
var [toasts, setToasts] = createStore([]);
function removeToast(toast) {
  setToasts((toasts2) => toasts2.filter((t3) => t3 !== unwrap(toast)));
}
function toastNotify(options2, type) {
  if (typeof options2 === "string") {
    options2 = {
      title: options2,
      type
    };
  }
  let toast = Object.assign({}, defaultOptions, options2);
  if (toast.type) {
    Object.assign(toast, toastTypes[toast.type]);
  }
  setToasts((toasts2) => [...toasts2, toast]);
  const instance = {
    close() {
      removeToast(toast);
    },
    update(options3) {
      setToasts((toasts2) => {
        Object.assign(toasts2.find((t3) => t3 === toast), options3);
        return toasts2;
      });
    }
  };
  if (toast.ttl) {
    setTimeout(() => instance.close(), toast.ttl);
  }
  return instance;
}
function ToastNotificationsContainer() {
  return (() => {
    const _el$ = _tmpl$19.cloneNode(true);
    insert(_el$, createComponent(For, {
      each: toasts,
      children: (item) => createComponent(ToastNotification, mergeProps(item, {
        onClose: () => removeToast(item)
      }))
    }));
    return _el$;
  })();
}
function ToastNotification(props2) {
  return (() => {
    const _el$2 = _tmpl$44.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.firstChild, _el$9 = _el$3.nextSibling;
    insert(_el$3, createComponent(Icon, {
      get name() {
        return props2.icon;
      },
      get style() {
        return {
          color: props2.color
        };
      }
    }), _el$4);
    insert(_el$5, () => props2.title);
    insert(_el$4, createComponent(Show, {
      get when() {
        return props2.text;
      },
      get children() {
        const _el$6 = _tmpl$210.cloneNode(true);
        createRenderEffect(() => _el$6.innerHTML = props2.text);
        return _el$6;
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props2.progress !== false;
      },
      get children() {
        const _el$7 = _tmpl$35.cloneNode(true), _el$8 = _el$7.firstChild;
        createRenderEffect(() => _el$8.style.setProperty("width", props2.progress + "%"));
        return _el$7;
      }
    }), _el$9);
    addEventListener(_el$9, "click", props2.onClose, true);
    createRenderEffect(() => _el$2.style.setProperty("border-top-color", props2.color));
    return _el$2;
  })();
}
delegateEvents(["click"]);

// public/app/attributes/automation-trigger-btn.js
attributeTypeRegistry.register("automation_trigger_btn", {
  title: _lazy("Automation Trigger Button"),
  description: _lazy("Trigger a manual automation rule"),
  icon: "bolt",
  //category: 'automation',
  visibleByDefault: false,
  noAttributeValue: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-automation-trigger-btn",
  widgetHideAttributeName: true,
  getReprWidgets(obj, attr, modelAttr) {
    const project = projectStore.get(obj.project_id);
    const canRun = canRunAutomations(project);
    const disabled = !modelAttr.valid_options || !modelAttr.options || !modelAttr.options.rule || !canRun;
    let label = _4("Run action");
    if (modelAttr.options && modelAttr.options.label) {
      label = modelAttr.options.label;
    } else if (!disabled) {
      label = _4("Run {rule}", { rule: modelAttr.options.rule.name });
    }
    let disabledTooltip;
    if (disabled) {
      if (!canRun) {
        disabledTooltip = _4("You don't have the permission to run this automation rule");
      } else {
        disabledTooltip = _4("This button is not configured correctly. Check the field options");
      }
    }
    function onDOMLoad(element2, options2 = {}) {
      if (!options2.editable || disabled) return;
      function onClick(event2) {
        if (disabled) return;
        event2.stopPropagation();
        element2.disabled = true;
        const i3 = document.createElement("i");
        i3.classList.add("fa", "fa-spin", "fa-spinner");
        element2.prepend(i3);
        api_default.project_automations.trigger_automation_rule.post({ project_id: project.id, rule_id: modelAttr.options.rule.id, card_id: obj.id }).then(() => {
          toastNotify(_4("Triggered automation"), "success");
        }).finally(() => {
          setTimeout(() => {
            element2.disabled = false;
            i3.remove();
          }, 1e3);
        });
      }
      const $element2 = jquery_default(element2);
      $element2.on("click", onClick);
      return function dispose2() {
        $element2.off("click", onClick);
      };
    }
    return {
      type: "button",
      value: true,
      onDOMLoad,
      options: {
        label,
        disabled,
        disabledTooltip
      }
    };
  }
});

// public/app/utils/solid.ts
function untrackDecorator(func) {
  return function(...args) {
    return untrack(() => func(...args));
  };
}
function createHardMemo(fn, value2, options2) {
  return createMemo(fn, value2, Object.assign({ equals }, options2 || {}));
}

// public/app/loaders/utils.js
function getRequestSignature(action, params, options2) {
  return action.endpoint + JSON.stringify(params || {}) + JSON.stringify(options2 || {});
}
var requestsInProgress = /* @__PURE__ */ new Map();
function request(action, params, options2) {
  const reqId = getRequestSignature(action, params, options2);
  if (requestsInProgress.has(reqId)) {
    return requestsInProgress.get(reqId);
  }
  const req = action.get(params, Object.assign({}, options2 || {}, { resolveWithResponse: true }));
  requestsInProgress.set(reqId, req);
  return req.finally(() => {
    requestsInProgress.delete(reqId);
  });
}
function fetchAllPaginated(action, params, { signal = null, onProgress = null, limitToPage = null } = {}) {
  let allResults = [];
  const loadPage = async (page) => {
    if (signal?.aborted) {
      throw new DOMException("Aborted", "AbortError");
    }
    const [results2, response] = await action.get(
      { ...params, page },
      { resolveWithResponse: true, signal }
    );
    allResults = allResults.concat(results2);
    if (onProgress) {
      onProgress(results2, allResults);
    }
    const nextPage = response.headers.get("X-Kantree-NextPage");
    const shouldStop = signal?.aborted || limitToPage && page >= limitToPage;
    if (nextPage && !shouldStop) {
      return loadPage(parseInt(nextPage));
    }
    return allResults;
  };
  return loadPage(1);
}
async function loadMany(store2, action, params, options2, { preload = null, format: format2 = null, sideload = null } = {}) {
  let [objects, response] = await request(action, params, options2);
  const ctx = {};
  if (preload) {
    objects = await Promise.all(objects.map((o3) => preload(o3, ctx)));
  }
  if (store2.loading) {
    await store2.loading;
  }
  return store2.transaction(() => {
    objects = objects.map((obj) => {
      obj = store2.upsert(format2 ? format2(obj, ctx) : obj);
      if (sideload) {
        sideload(obj, ctx);
      }
      return obj;
    });
    return options2?.resolveWithResponse ? [objects, response] : objects;
  });
}
async function load(store2, action, params, options2, { preload = null, format: format2 = null, sideload = null } = {}) {
  let [obj, response] = await request(action, params, options2);
  const ctx = {};
  if (preload) {
    obj = await preload(obj, ctx);
  }
  if (store2.loading) {
    await store2.loading;
  }
  obj = store2.upsert(format2 ? format2(obj, ctx) : obj);
  if (sideload) {
    sideload(obj, ctx);
  }
  return options2?.resolveWithResponse ? [obj, response] : obj;
}
async function getOrLoad(store2, id, action, params, options2, callbacks2) {
  try {
    if (store2.loading) {
      await store2.loading;
    }
    return store2.get(id);
  } catch (e3) {
    if (!(e3 instanceof StoreNotFoundError)) {
      throw e3;
    }
    return load(store2, action, params, options2, callbacks2);
  }
}
function loadPaginated(store2, action, params, options2, progressCallback, beforeFullfilledCallback, callbacks2) {
  let cancelPagination = false;
  let allResults = [];
  options2 = Object.assign({}, options2 || {}, { resolveWithResponse: true });
  const loadPage = async function(page) {
    const [results2, response] = await loadMany(store2, action, Object.assign({}, params, { page }), options2, callbacks2);
    allResults = allResults.concat(results2);
    const nextPage = response.headers.get("X-Kantree-NextPage");
    if (options2.limitToPage && page >= options2.limitToPage) {
      cancelPagination = true;
    }
    if (nextPage && !cancelPagination) {
      if (progressCallback && progressCallback(results2) === false) {
        cancelPagination = true;
      }
      if (!cancelPagination) {
        return loadPage(parseInt(nextPage));
      }
    }
    if (beforeFullfilledCallback) {
      return beforeFullfilledCallback(allResults, cancelPagination);
    }
    return allResults;
  };
  const promise = loadPage(1);
  promise.cancelLoadPaginated = () => {
    cancelPagination = true;
  };
  return promise;
}
var StoreLoader = class {
  constructor(store2, { params = {}, options: options2 = {}, preload = null, format: format2 = null, sideload = null } = {}) {
    this.store = store2;
    this.params = params;
    this.options = options2;
    this.callbacks = { preload, sideload, format: format2 };
  }
  prepareArgs(action, params, options2) {
    params = Object.assign({}, this.params, params || {});
    options2 = Object.assign({}, this.options, options2 || {});
    return [action, params, options2, this.callbacks];
  }
  loadMany(action, params, options2) {
    return loadMany(this.store, ...this.prepareArgs(action, params, options2));
  }
  load(action, params, options2) {
    return load(this.store, ...this.prepareArgs(action, params, options2));
  }
  getOrLoad(id, action, params, options2) {
    return getOrLoad(this.store, id, ...this.prepareArgs(action, params, options2));
  }
  loadPaginated(action, params, options2, progressCallback, beforeFullfilledCallback) {
    let callbacks2;
    [action, params, options2, callbacks2] = this.prepareArgs(action, params, options2);
    return loadPaginated(this.store, action, params, options2, progressCallback, beforeFullfilledCallback, callbacks2);
  }
};

// public/app/loaders/card-reminder.js
async function loadRemindersForCard(card, options2 = {}) {
  try {
    const reminders = await loadMany(cardReminderStore, api_default.cards.list_reminders, { card_id: card.id }, options2);
    cardReminderStore.scopedByCard(card).removeAllNotMatching(reminders);
    return reminders;
  } catch (r3) {
    cardReminderStore.scopedByCard(card).removeAll();
    throw r3;
  }
}

// public/app/loaders/role.js
function loadAllRolesForOrg(org2) {
  const isUserOrg = !org2 || org2.type == "user";
  const action = isUserOrg ? api_default.user.list_roles : api_default.organizations.list_roles;
  return loadMany(roleStore, action, { org_id: !isUserOrg ? org2.id : null });
}
function loadAllRolesForProject(project) {
  return loadMany(roleStore, api_default.projects.list_roles, { project_id: project.id });
}

// public/app/loaders/project.js
function sideLoadProject(_project) {
  const project = JSON.parse(JSON.stringify(unwrap(_project)));
  _project.top_level_card = cardStore.upsert(_project.top_level_card);
  if (project.owner && project.owner.type === "org") {
    if (!orgStore.exists(project.owner.id)) {
      loadAllRolesForProject(project);
      orgStore.insert(project.owner);
    } else if (project.owner.attributes) {
      const { id, attributes, top_level_card_attributes } = project.owner;
      orgStore.upsert({ id, attributes, top_level_card_attributes });
    }
  }
  if (project.attributes) {
    cardModelStore.upsertProjectModels(project);
  }
  if (project.status) {
    return _project;
  }
  if (project.models) {
    cardModelStore.scopedByEnabled(project).scoped({
      base_model_id: query_exports.isUndefined()
    }).replace(project.models);
  }
  if (project.group_types) {
    cardGroupTypeStore.scopedByEnabled(project, true).replace(project.group_types);
  }
  if (project.log_types) {
    projectLogTypeStore.scopedByProject(project).replace(project.log_types);
  }
  if (project.views) {
    viewStore.scopedByProject(project).scoped({ _draft: query_exports.isFalsy() }).replace(project.views);
  }
  if (project.view_categories) {
    viewCategoryStore.scopedByProject(project).replace(project.view_categories);
  }
  if (project.members || project.owner.type === "user") {
    projectMemberStore.scopedByProject(project).removeAll();
  }
  if (project.members) {
    projectMemberStore.upsertManyForProject(project, project.members);
  }
  if (project.owner.type === "user") {
    projectMemberStore.upsertUserOrgOwner(project);
  }
  if (project.card_subscriptions) {
    cardSubscriptionStore.join("card_id", cardStore.scopedByProject(project)).replace(project.card_subscriptions);
  }
  if (project.group_subscriptions) {
    cardGroupSubscriptionStore.join(
      "group_id",
      cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(project, true)).join("parent_id", cardStore.scopedByProject(project))
    ).replace(project.group_subscriptions);
  }
  if (project.request_forms) {
    requestFormStore.scopedByProject(project).replace(project.request_forms);
  }
  return _project;
}
function sideLoadBoard(_project) {
  if (typeof _project.board === "undefined") {
    return;
  }
  const project = JSON.parse(JSON.stringify(unwrap(_project)));
  const board = cardStore.upsert(project.board);
  if (project.board_groups) {
    cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(project, true).scoped({ scope: query_exports.not("org") })).join("parent_id", cardStore.scopedByProject(project)).removeAll();
    cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(project, true).scoped({ scope: "org" })).removeAll();
    cardGroupStore.upsertMany(project.board_groups);
  }
  if (project.board_states) {
    cardStateStore.join(
      "id",
      cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(project, true)).join("parent_id", cardStore.scopedByProject(project))
    ).replace(project.board_states);
  }
  return board;
}
var loader = new StoreLoader(projectStore, { format: sideLoadProject });
function loadProject(id, options2) {
  return loader.load(api_default.projects.get_project, { project_id: id }, options2);
}
function getOrLoadProject(id, options2) {
  return loader.getOrLoad(id, api_default.projects.get_project, { project_id: id }, options2);
}
function loadProjectsForOrg(org2, withArchived = false, withTeamProjects = false) {
  return loader.loadMany(withTeamProjects ? api_default.organizations.list_all_projects : api_default.organizations.list_projects, {
    org_id: org2.id,
    with_archived: withArchived
  });
}
function loadPortfoliosForOrg(org2) {
  return loader.loadMany(api_default.organizations.list_portfolios, {
    org_id: org2.id
  });
}
function loadAllProjectsForTeam(team, withArchived = false) {
  return loader.loadMany(api_default.teams.list_projects, {
    org_id: team.owner.id,
    team_id: team.id,
    with_archived: withArchived
  });
}
async function loadAllProjectsForPortfolio(portfolio, withMembers = true) {
  return loader.loadMany(api_default.project_portfolio.list_portfolio_projects, {
    project_id: portfolio.id,
    with_members: withMembers ? 1 : 0
  }).then((projects) => {
    projectStore.update(portfolio, { portfolio_project_ids: (projects || []).map((p4) => p4.id) });
    return projects;
  });
}
function loadAllArchivedProjectsForOrg(org2) {
  return loader.loadMany(api_default.organizations.list_archived_projects, { org_id: org2.id });
}
function loadProjectTemplatesForOrg(org2) {
  return loader.loadMany(api_default.organizations.list_templates, { org_id: org2.id });
}
async function loadProjectGuide(project) {
  const guide = await api_default.projects.get_project_guide.get({ project_id: project.id });
  projectStore.update(project, { guide });
}

// virtual-ns:frasco-push
var frasco_push_default = FrascoPushConnection;

// public/app/services/push.js
var getPushConnection = singleton(async function() {
  await loadServerConfig();
  await loadCurrentUser();
  if (!isAuthenticated()) {
    throw Error("User must be authenticated to start push connection");
  }
  const conn = new frasco_push_default(serverConfig.socketio_url, currentUser2.socketio_token, false);
  conn.addEventListener("socketIdChanged", (e3) => {
    api_default.options.headers.set("X-SocketIO-SID", e3.detail.id);
  });
  conn.addEventListener("connectionLost", () => notifyConnectionLost());
  conn.addEventListener("connected", () => notifyConnectionRecovered());
  conn.addEventListener("reconnected", () => notifyConnectionRecovered());
  createEffect(() => {
    if (conn.token != currentUser2.socketio_token) {
      conn.refreshToken(currentUser2.socketio_token);
    }
  });
  await conn.connect();
  return conn;
});
function closePushConnection() {
  if (getPushConnection.instance) {
    getPushConnection().then((conn) => {
      conn.close();
      getPushConnection.instance = null;
    });
  }
}

// public/app/config/roles.js
var availableOrgRoles = [
  { id: 0, name: _lazy("Contractor"), description: _lazy("Cannot access the team page and has to be explicitely added to each workspace") },
  { id: 1, name: _lazy("User"), description: _lazy("Can join and collaborate on any workspace") },
  { id: 2, name: _lazy("Manager"), description: _lazy("A user who can also manage workspaces, card types, contexts and templates of the team") },
  { id: 3, name: _lazy("Admin"), description: _lazy("A manager who can manage users and access all workspaces") },
  { id: 4, name: _lazy("Owner"), description: _lazy("An admin who manages billing and team details") }
];
var availableTeamRoles = [
  { id: 1, name: _lazy("User"), description: _lazy("Can join and collaborate on any workspace") },
  { id: 2, name: _lazy("Manager"), description: _lazy("A user who can also manage workspaces of the team") },
  { id: 3, name: _lazy("Admin"), description: _lazy("A manager who can manage users and access all workspaces") }
];
var roleActionLabels = {
  "CREATE": _lazy("Create"),
  "EDIT": _lazy("Edit"),
  "DELETE": _lazy("Delete")
};
var rolePermissionMap = [
  {
    key: "cards",
    label: _lazy("Cards"),
    actions: [
      {
        label: _lazy("Create"),
        map: [
          { object_type: "card", actions: ["CREATE"] }
        ]
      },
      {
        label: _lazy("Edit"),
        map: [
          { object_type: "attribute", actions: ["EDIT"] },
          { object_type: "card", actions: ["EDIT", "SWITCH_MODEL"] }
        ]
      },
      {
        label: _lazy("Archive"),
        map: [
          { object_type: "card", actions: ["ARCHIVE"] }
        ]
      },
      {
        label: _lazy("Delete"),
        map: [
          { object_type: "card", actions: ["DELETE"] }
        ]
      },
      {
        label: _lazy("Post a comment"),
        map: [
          { object_type: "card_comment", actions: ["CREATE"] }
        ]
      },
      {
        label: _lazy("Moderate comments"),
        map: [
          { object_type: "card_comment", actions: ["EDIT", "DELETE"] }
        ]
      },
      {
        label: _lazy("Remove my comments"),
        map: [
          { object_type: "card_comment", actions: ["DELETE_MINE"] }
        ]
      },
      {
        label: _lazy("Log things on cards"),
        map: [
          { object_type: "card_log", actions: ["CREATE"] }
        ]
      },
      {
        label: _lazy("Remove my logs"),
        map: [
          { object_type: "card_log", actions: ["DELETE_MINE"] }
        ]
      },
      {
        label: _lazy("Moderate logs"),
        map: [
          { object_type: "card_log", actions: ["EDIT", "DELETE"] }
        ]
      },
      {
        label: _lazy("Create or remove form requests"),
        map: [
          { object_type: "request", actions: ["CREATE", "DELETE"] }
        ]
      }
    ]
  },
  {
    key: "board",
    label: _lazy("Board"),
    actions: [
      {
        label: _lazy("Create and edit groups"),
        map: [
          { object_type: "card_group", actions: ["CREATE", "EDIT"] }
        ]
      },
      {
        label: _lazy("Move cards in groups"),
        map: [
          { object_type: "card_group", actions: ["MOVE_CARDS"] }
        ]
      },
      {
        label: _lazy("Delete groups"),
        map: [
          { object_type: "card_group", actions: ["DELETE"] }
        ]
      }
    ]
  },
  {
    key: "project",
    label: _lazy("Workspace"),
    actions: [
      {
        label: _lazy("Manage sub-boards"),
        map: [
          { object_type: "project", actions: ["MANAGE_SUB_BOARDS"] }
        ]
      },
      {
        label: _lazy("Manage recurring cards"),
        map: [
          { object_type: "project", actions: ["MANAGE_RECURRING"] }
        ]
      },
      {
        label: _lazy("Manage card reminders"),
        map: [
          { object_type: "project", actions: ["MANAGE_REMINDERS"] }
        ]
      },
      {
        label: _lazy("Manage shared views"),
        map: [
          { object_type: "project", actions: ["MANAGE_SHARED_VIEWS"] }
        ]
      },
      {
        label: _lazy("Manage contexts"),
        map: [
          { object_type: "card_group_type", actions: ["CREATE", "EDIT", "DELETE"] }
        ]
      },
      {
        label: _lazy("Manage types"),
        map: [
          { object_type: "card_model", actions: ["CREATE", "EDIT", "DELETE"] }
        ]
      },
      {
        label: _lazy("Manage log categories"),
        map: [
          { object_type: "card_log_type", actions: ["CREATE", "EDIT", "DELETE"] }
        ]
      },
      {
        label: _lazy("Manage forms"),
        map: [
          { object_type: "request_form", actions: ["CREATE", "EDIT", "DELETE"] }
        ]
      },
      {
        label: _lazy("Manage automations"),
        map: [
          { object_type: "project", actions: ["MANAGE_AUTO_ACTIONS"] }
        ]
      },
      {
        label: _lazy("Run manual automations (when cannot manage automations)"),
        map: [
          { object_type: "project", actions: ["RUN_AUTO_ACTIONS"] }
        ]
      },
      {
        label: _lazy("Manage members"),
        map: [
          { object_type: "project", actions: ["ACCESS"] }
        ]
      },
      {
        label: _lazy("Manage workspace settings"),
        map: [
          { object_type: "project", actions: ["OPTIONS"] }
        ]
      },
      {
        label: _lazy("Generate PII reports"),
        map: [
          { object_type: "project", actions: ["MANAGE_PII_DATA"] }
        ]
      },
      {
        label: _lazy("Add, edit or remove fields"),
        map: [
          { object_type: "project", actions: ["MANAGE_ATTRIBUTES"] }
        ]
      },
      {
        label: _lazy("Import data into the workspace"),
        map: [
          { object_type: "project", actions: ["IMPORT_DATA"] }
        ]
      },
      {
        label: _lazy("Export data from the workspace"),
        map: [
          { object_type: "project", actions: ["EXPORT_DATA"] }
        ]
      }
    ]
  }
];

// public/app/stores/utils/team.js
function isTeamManager(team) {
  return team.is_member && team.permission >= 2 || currentUser2.is_kantree_admin;
}
function isTeamAdmin(team) {
  return team.is_member && team.permission >= 3 || currentUser2.is_kantree_admin;
}
function isTeamMember(team) {
  return team.is_member;
}
function getRoleLabelForTeam(team) {
  const perm = currentUser2.is_kantree_admin ? 3 : team?.permission;
  return availableTeamRoles.find((p4) => p4.id === perm)?.name;
}

// public/app/stores/utils/org.js
function isCurrentUserPersonalOrg(org2) {
  return isAuthenticated() && org2 && org2.type === "user" && org2.id == currentUser2.id;
}
function isCurrentUserMemberOf(org2, team, considerAdminAsMember = true) {
  team = team ? teamStore.tryGet(team.id) : null;
  return isAuthenticated() && org2 && (considerAdminAsMember && currentUser2.is_kantree_admin || // kantree admin
  isCurrentUserPersonalOrg(org2) || // self user org
  typeof org2.permission !== "undefined" && org2.permission >= 3 || // Is org Admin
  !team && typeof org2.permission !== "undefined" && org2.permission >= 1 || // no team and org Member
  team && isTeamMember(team));
}
function isCurrentUserManagerOf(org2, team) {
  team = team ? teamStore.tryGet(team.id) : null;
  return isAuthenticated() && org2 && (currentUser2.is_kantree_admin || // kantree admin
  isCurrentUserPersonalOrg(org2) || // self user org
  typeof org2.permission !== "undefined" && org2.permission >= 3 || // Is org Admin
  !team && typeof org2.permission !== "undefined" && org2.permission >= 2 || // no team and org Manager
  team && isTeamManager(team));
}
function isCurrentUserAdminOf(org2) {
  return isAuthenticated() && org2 && (typeof org2.permission !== "undefined" && org2.permission >= 3 || isCurrentUserPersonalOrg(org2));
}
function isCurrentUserOwnerOf(project, considerAdminAsMember = true) {
  return !!project.owner && (project.owner.type === "user" && project.owner.id === currentUser2.id || project.owner.type === "org" && isCurrentUserMemberOf(orgStore.tryGet(project.owner.id) || project.owner, project.team, considerAdminAsMember));
}
function canCurrentUserCreateProjectsIn(org2, team) {
  return isCurrentUserManagerOf(org2, team);
  return isCurrentUserManagerOf(org2, team) && org2.can_create_projects && !org2.locked;
}
function hasPermission(org2) {
  return org2.permission !== null && typeof org2.permission !== "undefined";
}
function isOrgLocked(org2) {
  return org2.locked && !currentUser2.is_kantree_admin;
}
function isOrgMember(org2) {
  return currentUser2.is_kantree_admin || hasPermission(org2);
}
function isOrgManager(org2) {
  return currentUser2.is_kantree_admin || hasPermission(org2) && org2.permission >= 2;
}
function isOrgAdmin(org2) {
  return currentUser2.is_kantree_admin || hasPermission(org2) && org2.permission >= 3;
}
function isOrgOwner(org2) {
  return currentUser2.is_kantree_admin || hasPermission(org2) && org2.permission === 4;
}
function getRoleLabelForOrg(org2) {
  const perm = currentUser2.is_kantree_admin ? 3 : org2?.permission;
  return availableOrgRoles.find((p4) => p4.id === perm)?.name;
}

// public/app/loaders/attr-type.js
function getOrLoadAttrType(name2) {
  return getOrLoad(attributeTypeStore, name2, api_default.attr_types.get_attr_type, { name: name2 });
}
var loadAllAttrTypes = memoize2(() => {
  return loadMany(attributeTypeStore, api_default.attr_types.list_attr_types, {});
});

// public/app/services/app-context.ts
var pinnedOrgFilterScopes = [["pinned"]];
var [appContext, setAppContext] = createStore({
  org: null,
  orgs: [],
  teams: [],
  pinnedOrgs: [],
  pinnedOrgIds: [],
  projectsCount: 0
});
var [isAppContextLoaded, setAppContextLoaded] = createSignal(false);
var [recentlyOpenedBoards, setRecentlyOpenBoards] = createSignal([]);
var onAppContextUpdate = createEvent();
var userProjectStore = projectStore.scoped({ dashboard_group: query_exports.isDefined(), is_archived: false });
var personalProjectStore = projectStore.scoped({ dashboard_group: "user", is_archived: false });
var sharedProjectStore = projectStore.scoped({ dashboard_group: "shared", is_archived: false });
var favoriteProjectStore = projectStore.scoped(() => (project) => !project.is_archived && (isFavorite("project", project.id) || isFavorite("card", project.top_level_card_id)));
var favoriteCardStore = cardStore.scoped(() => (card) => !card.is_archived && (!card.parent_id && isFavorite("project", card.project_id) || card.parent_id && isFavorite("card", card.id)));
createEffect(() => {
  if (isAuthenticated()) {
    getPushConnection().then((conn) => {
      for (let event2 of ["join_org", "leave_org", "join_project", "leave_project", "join_team", "leave_team"]) {
        conn.on(event2, () => fetchCurrentUserData().then(() => fetchAppContextData()));
      }
    });
  }
});
var loadAppContext = oncePromise(async () => {
  if (isAppContextLoaded()) {
    return;
  }
  await Promise.all([loadCurrentUser(), projectStore.load(), orgStore.load(), loadAllAttrTypes()]);
  if (isAuthenticated() && isConnected()) {
    await fetchAppContextData();
    setAppContextLoaded(true);
  }
});
async function fetchAppContextData() {
  const data2 = await api_default.user.list_app_context_content.get({}, { ignoreErrorHandlers: true });
  const projects = [], orgs = [];
  setFavorites(data2["favorites"]);
  if (typeof data2["user"] !== "undefined") {
    projects.push(...data2["user"].map((c3) => {
      c3.dashboard_group = "user";
      return c3;
    }));
  }
  if (typeof data2["shared"] !== "undefined" && data2["shared"].length) {
    projects.push(...data2["shared"].map((c3) => {
      c3.dashboard_group = "shared";
      return c3;
    }));
  }
  const roles = /* @__PURE__ */ new Set();
  for (let [org2, orgProjects, teams] of data2["orgs"]) {
    projects.push(...orgProjects.map((p4, idx) => {
      p4.dashboard_group = org2.id;
      return p4;
    }));
    for (const role of org2["roles"]) {
      roles.add(role);
    }
    orgs.push(orgStore.upsert(org2));
    teamStore.upsertMany(teams);
  }
  roleStore.upsertMany(Array.from(roles));
  projectStore.updateManyMatching({ dashboard_group: query_exports.notNull() }, { dashboard_group: null });
  orgStore.removeAllNotMatching(orgs);
  projectStore.transaction(() => {
    for (let project of projects) {
      projectStore.upsert(project);
      sideLoadProject(project);
    }
  });
  updateAppContext();
}
function addToRecentlyOpenedBoards(boards) {
  if (!boards) return;
  if (!Array.isArray(boards)) {
    boards = [boards];
  }
  const recentlyOpenedBoardsIds = boards.map((board) => board.id).concat(get(currentUser2.app_params, "recently_opened", [])).filter((id, idx, arr) => arr.indexOf(id) === idx).slice(0, 5);
  saveUserAppParams({ "recently_opened": recentlyOpenedBoardsIds });
  updateRecentlyOpenedBoards();
}
var updateAppContext = untrackDecorator(() => {
  const state = {};
  state.projectsCount = userProjectStore.count();
  const orgIds = currentUser2.orgs || [];
  state.orgs = orgStore.query({ type: "org", id: query_exports.any(orgIds) }, { sortBy: "name" }).map((org2) => {
    const orgProjectStore = projectStore.scoped({ dashboard_group: org2.id, is_archived: false });
    const projectTeamIds = pluck(orgProjectStore.query(), "team.id").filter(Boolean);
    const orgTeamIds = pluck(teamStore.scopedByOrg(org2).query({ is_member: true }), "id");
    const teamIds = uniq(projectTeamIds.concat(orgTeamIds));
    const joinedTeams = teamStore.query({ is_member: true, id: query_exports.any(teamIds) }, { sortBy: "name" });
    const joinedTeamIds = pluck(joinedTeams, "id");
    const teams = [{
      uuid: `org${org2.id}`,
      name: org2.name,
      org: org2,
      canCreate: currentUser2.is_kantree_admin || org2.can_create_projects && !isOrgLocked(org2) && isOrgManager(org2),
      store: orgProjectStore.scoped({ team: query_exports.or(query_exports.isFalsy(), query_exports.objMatch({
        id: (id) => !joinedTeamIds.includes(id)
      })) }),
      allProjectStore: orgProjectStore
    }];
    joinedTeams.forEach((team) => {
      teams.push({
        uuid: `org${org2.id}-team${team.id}`,
        name: `${org2.name} / ${team.name}`,
        org: org2,
        team,
        canCreate: currentUser2.is_kantree_admin || org2.can_create_projects && !isOrgLocked(org2) && (isOrgAdmin(org2) || isTeamManager(team)),
        store: orgProjectStore.scopedByTeam(team, org2)
      });
    });
    return {
      id: org2.id,
      org: org2,
      projectStore: orgProjectStore,
      teams,
      canCreate: teams.some((t3) => t3.canCreate)
    };
  });
  state.teams = [];
  for (let org2 of state.orgs) {
    state.teams.push(...org2.teams);
  }
  const hiddenOrgs = get(currentUser2.app_params, "hiddenOrgs", []);
  state.pinnedOrgs = state.orgs.filter((o3) => !hiddenOrgs.includes(o3.id));
  state.org = state.pinnedOrgs.length === 1 ? state.pinnedOrgs[0].org : null;
  setAppContext(state);
  updateRecentlyOpenedBoards();
  onAppContextUpdate();
});
var updateRecentlyOpenedBoards = untrackDecorator(() => {
  const ids = get(currentUser2.app_params, "recently_opened", []);
  const cards = cardStore.query({ id: query_exports.any(ids) });
  setRecentlyOpenBoards(cards.sort((a3, b3) => ids.indexOf(a3.id) - ids.indexOf(b3.id)).filter((board) => {
    const project = projectStore.tryGet(board.project_id);
    if (project) {
      return !project.is_template && !project.is_archived;
    }
    return false;
  }));
});

// public/app/ui/project/filter-scopes-utils.js
function getProjectsFromFilterScopes(filterScopes, filterScopeNullForAll = true) {
  const availableProjects = userProjectStore.query();
  if (!filterScopes && filterScopeNullForAll) return availableProjects;
  if (!filterScopes?.length) return [];
  const projects = [];
  for (let scope of filterScopes) {
    if (scope[0] === "user") {
      if (scope.length === 1 || scope.slice(1).find((userId) => userId === currentUser2.id)) {
        projects.push(...availableProjects);
      }
      ;
    } else if (scope[0] === "org") {
      const orgs = appContext.orgs.filter((o3) => scope.includes(o3.id));
      for (let org2 of orgs) {
        projects.push(...org2.projectStore.query());
      }
    } else if (scope[0] === "org_no_team") {
      const orgs = appContext.teams.filter((t3) => !t3.team && scope.includes(t3.org.id));
      for (let org2 of orgs) {
        projects.push(...org2.store.query());
      }
    } else if (scope[0] === "team") {
      const teams = appContext.teams.filter((t3) => t3.team && scope.includes(t3.team.id));
      for (let team of teams) {
        projects.push(...team.store.query());
      }
    } else if (scope[0] === "projects") {
      projects.push(...scope.slice(1).filter((projectId) => availableProjects.some((p4) => p4.id === projectId)).map((projectId) => projectStore.tryGet(projectId)));
    } else if (scope[0] === "project") {
      const project = projectStore.tryGet(scope[1]);
      if (project) {
        projects.push(project);
      }
    } else if (scope[0] === "portfolio" && projectStore.exists(parseInt(scope[1]))) {
      projects.push(...projectStore.scopedByPortfolio(projectStore.get(parseInt(scope[1]))).query({}, { sortBy: "title" }));
    } else if (scope[0] === "favorites") {
      projects.push(...pluck(favoriteCardStore.query({ parent_id: null }), "project_id").map((id) => projectStore.tryGet(id)));
    } else if (scope[0] === "pinned") {
      const availableProjectsGroups = groupBy_default(availableProjects, "dashboard_group");
      projects.push(...availableProjectsGroups["user"] || []);
      projects.push(...availableProjectsGroups["shared"] || []);
      for (let org2 of appContext.pinnedOrgs) {
        if (availableProjectsGroups[org2.id.toString(10)]) {
          projects.push(...availableProjectsGroups[org2.id.toString(10)]);
        }
      }
    }
  }
  return uniq(compact(projects), false, (p4) => p4.id);
}
function getStoresForFilterScopes(filterScopes) {
  if (filterScopes?.[0]?.[0] === "portfolio") {
    const portfolio = projectStore.tryGet(parseInt(filterScopes[0][1]));
    const org2 = orgStore.tryGetForProject(portfolio);
    const team = teamStore.tryGetForProject(portfolio);
    return {
      "project": portfolio ? projectStore.scopedByPortfolio(portfolio) : void 0,
      "team": team ? void 0 : org2 ? teamStore.scopedByOrg(org2) : void 0
      // 'organization': org ?
      //   orgStore.scoped(() => ({id: org.id})) :
      //   (portfolio ?
      //     orgStore.scopedByProjects(compact(portfolio.portfolio_project_ids.map(id => projectStore.tryGet(id)))) :
      //     undefined),
      // 'team': team ? teamStore.scoped(() => ({id: team.id})) : (org ? teamStore.scopedByOrg(org) : undefined)
    };
  } else if (filterScopes) {
    const projects = getProjectsFromFilterScopes(filterScopes);
    return {
      "project": projectStore.scoped(() => ({ id: query_exports.any(pluck(projects, "id")) })),
      "organization": orgStore.scopedByProjects(projects),
      "team": teamStore.scopedByProjects(projects)
    };
  }
}
function getLabelForFilterScopes2(filterScopes, selectedProjectsCount) {
  if (filterScopes?.length === 1) {
    if (filterScopes[0][0] === "user") {
      return _4("all");
    }
    if (filterScopes[0][0] === "favorites") {
      return _4("favorites");
    }
    if (filterScopes[0][0] === "pinned") {
      return _4("from selected orgs");
    }
  }
  return selectedProjectsCount;
}
function filterScopesToString(filterScopes) {
  if (Array.isArray(filterScopes)) {
    return filterScopes.reduce((accu, scope) => {
      return accu + " " + scope[0] + (scope.length > 1 ? ":" + scope.slice(1).join(",") : "");
    }, "").trim();
  }
  return filterScopes;
}

// public/app/loaders/model.js
async function loadModelExtendChain(model) {
  if (model.extends_id) {
    await getOrLoadModel(model.extends_id);
  }
  return model;
}
var loader2 = new StoreLoader(cardModelStore, { preload: loadModelExtendChain });
function loadModel(id, options2) {
  return loader2.load(api_default.card_models.get_model, { model_id: id }, options2);
}
function getOrLoadModel(id, options2) {
  return loader2.getOrLoad(id, api_default.card_models.get_model, { model_id: id }, options2);
}
function getOrLoadModelForCard(card, options2) {
  if (card.model_id) {
    return getOrLoadModel(card.model_id, options2);
  }
  return Promise.resolve();
}
function loadAllEnabledModelsForProject(project) {
  return loader2.loadMany(api_default.project_models.list_enabled_models, { project_id: project.id });
}
function loadAllModelsForProjectOwner(project) {
  if (project.owner.type === "org") {
    return loadAllModelsForOrg(project.owner);
  }
  return loadAllModelsForUser();
}
function loadAllModelsForOrg(org2) {
  return loader2.loadMany(api_default.organizations.list_models, { org_id: org2.slug });
}
function loadAllModelsForUser() {
  return loader2.loadMany(api_default.user.list_models);
}

// public/app/loaders/card.js
async function sideLoadCard(card) {
  if (!card.project_id) {
    return;
  }
  if (!projectStore.exists(card.project_id) || !projectStore.get(card.project_id).attributes) {
    if (typeof card.project === "undefined") {
      try {
        await loadProject(card.project_id, { ignoreErrorHandlers: true });
      } catch {
      }
    } else {
      await sideLoadProject(card.project);
    }
  } else {
    let needUpsert = false;
    try {
      if ((!cardModelStore.tryGetProjectModel({ id: card.project_id }) || cardModelStore.getProjectModel({ id: card.project_id }).attributes.length === 0) && !!projectStore.get(card.project_id).attributes?.length) {
        needUpsert = true;
      }
    } catch {
      needUpsert = true;
    }
    if (needUpsert) {
      cardModelStore.upsertProjectModels(projectStore.get(card.project_id));
    }
  }
  try {
    await getOrLoadModelForCard(card, { ignoreErrorHandlers: true });
  } catch (r3) {
    console.error("Card (id:%d) model (id:%d) could not be sideloaded", card.id, card.model_id);
  }
  if (cardStore.isValidMirror(card) && card.link) {
    await sideLoadCard(card.link);
  }
}
var loader3 = new StoreLoader(cardStore, { sideload: sideLoadCard });
function loadCard(id, options2) {
  return loader3.load(api_default.cards.get_card, { card_id: id }, options2);
}
function getOrLoadCard(id, options2) {
  return loader3.getOrLoad(id, api_default.cards.get_card, { card_id: id }, options2);
}
function loadCardByRef(project, ref, options2) {
  return loader3.load(api_default.projects.get_card_by_ref, {
    project_id: project.id,
    ref
  }, options2);
}
function loadChildCardsOf(parent, options2) {
  return loader3.loadPaginated(api_default.cards.list_children, {
    card_id: parent.id,
    sort: "smart"
  }, options2, null, (cards, canceled) => {
    cardStore.scopedByParent(parent, false).scoped({ _temp: query_exports.isFalsy() }).removeAllNotMatching(cards, { ref: 0 });
    return cards;
  });
}
function loadArchivedChildCardsOf(parent, options2) {
  return loader3.loadPaginated(api_default.cards.list_archived_children, {
    card_id: parent.id
  }, options2, null, (cards, canceled) => {
    cardStore.scopedByParent(parent, true).removeAllNotMatching(cards);
    return cards;
  });
}
function loadDescendantCardsOf(parent, options2) {
  return loader3.loadPaginated(api_default.cards.list_descendants, {
    card_id: parent.id,
    sort: "smart"
  }, options2, null, (cards, canceled) => {
    cardStore.scopedByParent(parent, false).scoped({ _temp: query_exports.isFalsy() }).removeAllNotMatching(cards);
    return cards;
  });
}
function loadArchivedDescendantCardsOf(parent, options2) {
  return loader3.loadPaginated(api_default.cards.list_archived_descendants, {
    card_id: parent.id
  }, options2, null, (cards, canceled) => {
    cardStore.scopedByParent(parent, true).removeAllNotMatching(cards);
    return cards;
  });
}
function removeAllNotMatchingCards(store2, project, cards) {
  store2.scoped({ _temp: query_exports.isFalsy() }).scoped(query_exports.not(query_exports.objMatch({ id: project.top_level_card_id }))).removeAllNotMatching(cards, { ref: 0 });
}
function loadAllCardsOf(project, filter4 = null, summaryOnly = false, options2 = null, progressCallback = null) {
  return loader3.loadPaginated(api_default.projects.list_cards, {
    project_id: project.id,
    sort: "smart",
    filter: filter4,
    summary_only: summaryOnly,
    per_page: summaryOnly ? 1e3 : 100
  }, options2, progressCallback, (cards) => {
    if (summaryOnly && !cards.length) {
      return [];
    }
    if (!summaryOnly) {
      removeAllNotMatchingCards(cardStore.scopedByProject(project, false), project, cards);
    }
    return cards;
  });
}
function loadSomeCardsOfProject(project, cardIds) {
  return loader3.loadPaginated(api_default.projects.list_cards, {
    project_id: project.id,
    card_ids: cardIds,
    sort: "smart"
  });
}
function loadAllArchivedCardsOf(project) {
  return loader3.loadPaginated(api_default.projects.list_cards, {
    project_id: project.id,
    with_archived: true
  }, {}, null, (cards, canceled) => {
    cardStore.scopedByProject(project, true).scoped({ id: query_exports.not(project.top_level_card_id) }).removeAllNotMatching(cards);
    return cards;
  });
}
function searchCards(query2 = "", filterScopes = null, limit = null, options2 = {}) {
  query2 = query2?.trim();
  if (filterScopes?.[0]?.[0] === "portfolio") {
    return searchCardsInPortfolio({ id: filterScopes[0][1] }, query2, null, options2);
  }
  return loader3.loadPaginated(api_default.search.search, {
    filters: query2,
    filter_scopes: filterScopesToString(filterScopes),
    limit,
    sort: "smart"
  }, options2);
}
function searchCardsInPortfolio(portfolio, query2 = "", limit = null, options2 = {}) {
  return loader3.loadPaginated(api_default.project_portfolio.search, {
    project_id: portfolio.id,
    filters: query2,
    limit,
    sort: "smart"
  }, options2);
}

// public/app/utils/async-api-response.js
var AsyncJobFailed = class extends Error {
};
var NotReadyError = class extends Error {
};
async function getAsyncJobResult(id) {
  const r3 = await api_default.async_job.get.get({ id });
  if (!r3.done) {
    throw new NotReadyError();
  }
  if (r3.failed) {
    errorDialog(_4("An error occured while generating your download, please try again later or contact our support team"));
    throw new AsyncJobFailed();
  }
  return r3.data;
}
function waitForAsyncJobResult(id, maxRetries = 10) {
  if (id.async_id) {
    id = id.async_id;
  }
  return new Promise(async (resolve2, reject2) => {
    let tries = 1;
    const check = async () => {
      try {
        const url2 = await getAsyncJobResult(id);
        resolve2(url2);
      } catch (e3) {
        if (e3 instanceof NotReadyError) {
          if (tries++ > maxRetries) {
            reject2("too_many_retries");
          } else {
            setTimeout(check, 1e3);
          }
        } else {
          reject2("failed");
        }
      }
    };
    setTimeout(check, 1e3);
  });
}
function waitForAsyncDownload(id, message) {
  let toast;
  if (message) {
    toast = toastNotify({ title: message, type: "loader", ttl: 0 });
  }
  return waitForAsyncJobResult(id).then((url2) => {
    return new Promise((resolve2, reject2) => {
      setTimeout(() => {
        window.open(url2, "_blank");
        if (toast) {
          toast.close();
        }
        resolve2(url2);
      }, 5e3);
    });
  }).catch((r3) => {
    if (r3 === "too_many_retries") {
      infoDialog(_4("Your export seems to take longer than usual. You will receive an email when it is finished."));
    }
    return Promise.reject(r3);
  });
}

// public/app/services/offline-sync.js
var [queue, setQueue] = createStore([]);
var [isSyncing, setSyncing] = createSignal(false);
var [autoSyncOnReconnect, setAutoSyncOnReconnect] = createSignal(true);
makeEventListener(window, "beforeunload", (e3) => {
  if (isSyncNeeded() || isSyncing()) {
    const msg2 = _4("Some data have not been synchronized and will be lost if you leave the page");
    e3.returnValue = msg2;
    return msg2;
  }
});
var syncTimeout;
createEffect(() => {
  if (isConnected()) {
    if (syncTimeout) {
      clearTimeout(syncTimeout);
    }
    syncTimeout = setTimeout(() => {
      syncTimeout = null;
      if (autoSyncOnReconnect()) {
        sync();
      }
    }, 1e4);
  } else if (syncTimeout) {
    clearTimeout(syncTimeout);
    syncTimeout = null;
  }
});
function queueRemoteAction(label, remoteAction, localFallback) {
  if (isConnected()) {
    return Promise.resolve(remoteAction());
  }
  const syncId = uuid4();
  setQueue((prev) => [...prev, { id: syncId, label, action: remoteAction }]);
  let promise;
  if (localFallback) {
    promise = localFallback(syncId);
  }
  return Promise.resolve(promise);
}
function waitForQueuedRemoteAction(label, remoteAction, localFallback) {
  return new Promise((resolve2, reject2) => {
    queueRemoteAction(label, async (syncId) => {
      try {
        const r3 = await remoteAction(syncId);
        resolve2(r3);
      } catch (r3) {
        reject2(r3);
      }
    }, localFallback);
  });
}
function numberOfQueuedSyncItems() {
  return queue.length;
}
function isSyncNeeded() {
  return queue.length > 0;
}
var stopSync;
async function sync(isRetry) {
  if (isSyncing()) return;
  stopSync = false;
  setSyncing(true);
  const failed = await _syncNext([]);
  if (failed.length > 0 && (!isOnline() || queue.length > 0)) {
    setQueue((prev) => [...failed, ...prev]);
    setSyncing(false);
    return;
  }
  if (queue.length === 0 && failed.length > 0) {
    const html5 = `
      <p>${_4("The following items failed to synchronized:")}</p>
      <ul>
        ${failed.map((info) => "<li>" + info.label + "</li>")}
      </ul>
    `;
    const dialogOpts = {
      title: _4("Error during synchronization"),
      html: html5,
      type: "error"
    };
    if (!isRetry) {
      try {
        await confirmDialog(Object.assign(dialogOpts, {
          confirmButtonText: _4("Try again")
        }));
        setQueue((prev) => [...failed, ...prev]);
        setTimeout(() => sync(true), 5e3);
      } catch {
        setSyncing(false);
      }
    } else {
      setSyncing(false);
      dialog(dialogOpts);
    }
  } else {
    setSyncing(false);
  }
}
async function _syncNext(failed) {
  if (queue.length === 0 || stopSync || !isOnline()) {
    stopSync = false;
    return Promise.resolve(failed);
  }
  const info = queue[0];
  setQueue((prev) => prev.slice(1));
  try {
    await info.action(info.id);
  } catch (e3) {
    console.log(e3);
    failed.push(info);
  }
  return _syncNext(failed);
}

// public/app/actions/project.ts
async function updateProject(project, data2 = {}) {
  project = await api_default.projects.update_project.put(Object.assign({ project_id: project.id }, data2));
  project = projectStore.update(project);
  cardStore.upsert(project.top_level_card);
  fetchAppContextData();
  return project;
}
async function toggleProjectSystemApp(project, app) {
  const toggle = (app2) => {
    const newApps = unwrap(project.system_apps);
    if (newApps.includes(app2)) {
      newApps.splice(newApps.indexOf(app2), 1);
    } else {
      newApps.push(app2);
    }
    projectStore.update(project, { system_apps: newApps });
  };
  toggle(app);
  try {
    await updateProject(project, { system_apps: project.system_apps });
  } catch (r3) {
    toggle(app);
    throw r3;
  }
}
async function updateProjectGuide(project, content2) {
  await api_default.projects.update_project_guide.post({ project_id: project.id, content: content2 });
  return projectStore.update(project, { guide: content2, has_guide: !!content2 });
}
async function archiveProject(project) {
  project = await api_default.projects.archive_project.post({ project_id: project.id });
  project = projectStore.update(project);
  cardStore.upsert(project.top_level_card);
  fetchAppContextData();
  return project;
}
async function restoreProject(project) {
  project = await api_default.projects.restore_project.delete({ project_id: project.id });
  project = projectStore.update(project);
  cardStore.upsert(project.top_level_card);
  fetchAppContextData();
  return project;
}
async function _deleteProject(project) {
  await api_default.projects.delete_project.delete({ project_id: project.id }, { ignoreErrorHandlers: true });
  if (project.top_level_card && cardStore.exists(project.top_level_card.id)) {
    cardStore.remove(project.top_level_card);
  }
  if (projectStore.exists(project.id)) {
    projectStore.remove(project);
  }
  cardStore.schedulePersist();
  projectStore.schedulePersist();
  const mapKey = JSON.stringify({ storageKey: null, scoped: null });
  return Promise.all([
    cardStore.debouncedPersistMap.get(mapKey).immediate(),
    projectStore.debouncedPersistMap.get(mapKey).immediate()
  ]);
}
async function deleteProject(project) {
  let pushRoom;
  let errorTimeout;
  const projectPage = ngApp.$injector.get("projectPage");
  if (projectPage.isProjectActive(project)) {
    projectPage.scopeManager.keepPushRoomOpenedOnDestroy = true;
    pushRoom = projectPage.scopeManager.pushRoom;
  } else {
    pushRoom = await getPushConnection().then((conn) => conn.join(project.push_id));
  }
  let toast = toastNotify(_4("Deleting the workspace"), "loader");
  let mainPromise = _deleteProject(project).catch((r3) => {
    if (projectPage.isProjectActive(project)) {
      projectPage.scopeManager.keepPushRoomOpenedOnDestroy = false;
    } else {
      pushRoom.leave();
    }
    return Promise.reject(r3);
  });
  Promise.all([
    mainPromise,
    new Promise((resolve2, reject2) => {
      errorTimeout = setTimeout(() => reject2(), 35e3);
      pushRoom.on("project_deleted", () => {
        resolve2(null);
      });
    }),
    new Promise((resolve2) => {
      setTimeout(() => resolve2(null), 3e3);
    })
  ]).then(() => {
    clearTimeout(errorTimeout);
    errorTimeout = null;
    toast?.close();
    pushRoom.leave();
    fetchAppContextData();
    toastNotify(_4("Workspace deleted"), "success");
  }).catch(() => {
    clearTimeout(errorTimeout);
    errorTimeout = null;
    if (projectPage.isProjectActive(project)) {
      projectPage.scopeManager.keepPushRoomOpenedOnDestroy = false;
    } else {
      pushRoom.leave();
    }
    toastNotify(_4("An error occurred. The workspace has not been deleted"), "error");
  });
  return mainPromise;
}
async function joinProject(project) {
  await api_default.project_members.join_project.post({ project_id: project.id });
  fetchAppContextData();
}
function exportProject(project, format2, filter4, attributes, includeDescendants, cardIds) {
  return api_default.projects.export_project.post({
    project_id: project.id,
    format: format2,
    card_ids: cardIds || null,
    filter: filter4 || null,
    attributes,
    include_descendants: includeDescendants
  });
}
async function moveProjectTo(project, org2, team, withCopy, withErrorHandler = true) {
  if (!org2) {
    throw new Error("No org selected");
  }
  const orgId = org2.type === "org" ? org2.id : null;
  if (withCopy) {
    try {
      const newProject = await api_default.projects.copy_project.post({
        project_id: project.id,
        org_id: orgId,
        team_id: team ? team.id : null
      });
      return projectStore.upsert({ ...newProject, dashboard_group: orgId ? orgId : "user" });
    } catch (r4) {
      if (withErrorHandler) return autoCatchAsRequestErrorDialog([403, 409, 412])(r4);
      throw r4;
    }
  }
  let r3;
  try {
    r3 = await api_default.projects.relocate_project_to_other_org.post({
      project_id: project.id,
      org_id: orgId,
      team_id: team ? team.id : null
    });
  } catch (r4) {
    if (withErrorHandler) return autoCatchAsRequestErrorDialog([403, 409, 412])(r4);
    throw r4;
  }
  const toast = toastNotify(_4("Your workspace is being moved"));
  try {
    await waitForAsyncJobResult(r3.async_id);
    toast.close();
    const p4 = await loadProject(project.id);
    return projectStore.upsert({ ...p4, dashboard_group: orgId ? orgId : "user" });
  } catch (r4) {
    toast.close();
    errorDialog(_4("An error ocurred while moving your workspace, please try again later or contact our support team"));
    throw r4;
  }
}
async function convertProjectToCard(card, parent, groups, withCopy, withErrorHandler = true) {
  if (withCopy) {
    errorDialog(_4("Converting workspace to card with copy is temporarily disabled"));
    throw new Error("Converting workspace to card with copy is temporarily disabled");
  }
  await openMoveWarningDialog();
  let resp;
  const group_id = groups ? groups.map((g3) => g3.id) : null;
  const parent_id = parent ? parent.id : null;
  try {
    resp = await api_default.projects.convert_project_to_card.post({ project_id: card.project_id, parent_id, group_id });
  } catch (r3) {
    if (withErrorHandler) return autoCatchAsRequestErrorDialog([403, 409, 412])(r3);
    throw r3;
  }
  const toast = toastNotify(_4("Your workspace is being converted to a card"));
  const old_project_id = card.project_id;
  try {
    await waitForAsyncJobResult(resp.async_id);
  } catch (r3) {
    errorDialog(_4("An error ocurred while converting your workspace, please try again later or contact our support team"));
    throw r3;
  } finally {
    toast.close();
  }
  card = await loadCard(card.id);
  const target_project_slug = projectStore.get(card.project_id).slug;
  if (projectStore.exists(old_project_id)) {
    projectStore.remove({ id: old_project_id });
  }
  ;
  return [card, target_project_slug];
}
async function toggleProjectAsFavorite(project) {
  if (isFavorite("project", project.id)) {
    await api_default.cards.unfavorite.delete({ card_id: project.top_level_card_id });
    removeFavorite("project", project.id);
  } else {
    await api_default.cards.favorite.post({ card_id: project.top_level_card_id });
    addFavorite("project", project.id);
  }
  projectStore.broadcast("favorites");
  cardStore.broadcast("favorites");
}
async function batch3(project, operation, params, batchParams) {
  if (isFunction_default(batchParams)) {
    batchParams = batchParams();
  }
  const r3 = await api_default.projects.batch_card_actions.post(Object.assign({
    project_id: project.id,
    operation,
    params
  }, batchParams));
  const toast = toastNotify(_4("Batch operation in progress"), "loader");
  $broadcast("projectBatchStart", toast);
  return r3;
}
async function updateProjectAccess(project, settings = {}) {
  let p4 = await api_default.projects.update_project_access.put(Object.assign({ project_id: project.id }, settings));
  p4 = projectStore.update(p4);
  await loadAllRolesForProject(project);
}
async function batchUpdateCardDates(projectId, cards) {
  return await api_default.projects.batch_dates.post(Object.assign({ project_id: projectId }, { cards }));
}

// public/app/utils/upload.js
function upload(config3, progressCallback) {
  config3 = Object.assign({ arrayKey: "" }, config3);
  return new Promise((resolve2, reject2) => {
    const xhr = new XMLHttpRequest();
    if (progressCallback) {
      xhr.upload.addEventListener("progress", (event2) => {
        progressCallback(event2);
      });
      xhr.upload.addEventListener("load", (event2) => {
        progressCallback({ ...event2, loaded: event2.total });
      });
    }
    xhr.onload = function() {
      let response;
      if (xhr.getResponseHeader("Content-Type").includes("application/json")) {
        response = JSON.parse(xhr.response);
      } else {
        response = xhr.response;
      }
      resolvePromise(xhr.status, response, "complete");
    };
    xhr.onerror = function() {
      resolvePromise(-1, null, "error");
    };
    xhr.onabort = function() {
      resolvePromise(-1, null, "abort");
    };
    xhr.ontimeout = function() {
      resolvePromise(-1, null, "timeout");
    };
    try {
      xhr.open(config3.method || "POST", config3.url);
      xhr.send(convertToFormData(config3.data, config3));
    } catch (e3) {
      reject2({ data: null, status: -1, xhrStatus: e3 });
    }
    function resolvePromise(status, response, xhrStatus) {
      (200 <= status && status < 300 ? resolve2 : reject2)({
        data: response,
        status,
        xhrStatus
      });
    }
  });
}
function convertToFormData(obj, config3) {
  const formData = new FormData();
  for (const [key2, val] of Object.entries(obj)) {
    if (isDate_default(val)) {
      formData.append(key2, val.toISOString());
    } else if (isFile(val)) {
      formData.append(key2, val, val.name);
    } else if (isObject2(val)) {
      for (const k2 in val) {
        let objectKey = config3.objectKey ?? "[i]";
        if (val.length && parseInt(k2) > -1) {
          objectKey = config3.arrayKey ?? objectKey;
        }
        formData.append(key2 + objectKey.replace(/[ik]/g, k2), val[k2]);
      }
    } else {
      formData.append(key2, val);
    }
  }
  return formData;
}
function isFile(file) {
  return file != null && (file instanceof window.Blob || file.flashId && file.name && file.size);
}

// public/app/actions/card.ts
async function onApiResponse(apiPromise, lock) {
  try {
    const card = await apiPromise;
    return cardStore.update(card);
  } finally {
    if (lock) {
      lock.release();
    }
  }
}
async function _createCard(tmpCard, parent, data2) {
  try {
    let card = await api_default.cards.create_child.post(Object.assign({ card_id: parent.id }, data2 || {}));
    if (tmpCard) {
      card = cardStore.updateById(tmpCard.id, Object.assign({ _temp: false, offline: null }, card));
      cardStore.refreshParentAndGroupsProgress(card, 1, card.finished ? 1 : 0);
    } else {
      card = cardStore.insert(card, true);
    }
    sideLoadCard(card).catch(() => null);
    cardSubscriptionStore.subscribeTo(card);
    return card;
  } catch (r3) {
    if (tmpCard) {
      cardStore.remove(tmpCard);
    }
    throw r3;
  }
}
function createCard(parent, title, groups, model) {
  const data2 = { title };
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const groupsIds = groups.filter(Boolean).map((g3) => g3.id);
  if (groupsIds.length) {
    data2["group_id"] = groupsIds;
  }
  if (model) {
    data2["model_id"] = model.id;
  }
  let tmpCard = cardStore.createTemporaryCard(parent, title, groups, model ? { model_id: model.id } : null);
  return [tmpCard, waitForQueuedRemoteAction(
    _4("New card: " + title),
    async (syncId) => {
      const lock = await cardStore.lock(tmpCard);
      try {
        return await _createCard(tmpCard, parent, data2);
      } finally {
        lock.release();
      }
    },
    (syncId) => {
      return cardStore.update(tmpCard, { offline: syncId });
    }
  )];
}
function createManyCards(parent, titles, groups, attributes) {
  let tmpCards = titles.match(/[^\r\n]+/g).map((title) => title?.trim()).filter(Boolean).map((title) => {
    return cardStore.createTemporaryCard(parent, title, groups);
  });
  const data2 = {
    card_id: parent.id,
    title: titles,
    force_array: true
  };
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const groupsIds = groups.filter(Boolean).map((g3) => g3.id);
  if (groupsIds.length) {
    data2["group_id"] = groupsIds;
  }
  if (attributes) {
    data2["attributes"] = attributes;
  }
  return [tmpCards, waitForQueuedRemoteAction(
    _4("New card(s): " + titles),
    async (syncId) => {
      try {
        const cards = await api_default.cards.create_child.post(data2);
        return tmpCards.map((card, i3) => {
          card = cardStore.updateById(card.id, Object.assign(cards[i3], { _temp: false, offline: null }));
          cardStore.refreshParentAndGroupsProgress(card, 1, card.finished ? 1 : 0);
          cardSubscriptionStore.subscribeTo(card);
          return card;
        });
      } catch (r3) {
        for (const card of tmpCards) {
          cardStore.remove(card);
        }
        throw r3;
      }
    },
    (syncId) => {
      cardStore.transaction(() => {
        for (const card of tmpCards) {
          cardStore.update(card, { offline: syncId });
        }
      });
      return tmpCards;
    }
  )];
}
function createCardLink(parent, targetId, hasOwnAttributes, groups) {
  const data2 = {
    link_to: targetId,
    link_has_own_attributes: hasOwnAttributes || false
  };
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const groupsIds = groups.filter(Boolean).map((g3) => g3.id);
  if (groupsIds.length) {
    data2["group_id"] = groupsIds;
  }
  return _createCard(null, parent, data2);
}
async function updateCard(card, data2) {
  const lock = await cardStore.lock(card);
  card = await onApiResponse(api_default.cards.update.put(Object.assign({ card_id: card.id }, data2)), lock);
  if (data2?.title && card && !card.parent_id) {
    const project = projectStore.tryGet(card.project_id);
    if (project && project.title !== data2.title) {
      projectStore.update(project, { title: data2.title });
    }
  }
  return card;
}
async function relocateCard(card, groups, position) {
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const groupsIds = groups.filter(Boolean).map((g3) => g3.id);
  groups.forEach((group2) => {
    cardStore.relocate(card, group2, position);
  });
  const lock = await cardStore.lock(card);
  try {
    return await onApiResponse(api_default.cards.relocate.post({
      card_id: card.id,
      parent_id: card.parent_id,
      group_id: groupsIds,
      position
    }), lock);
  } catch (r3) {
    throw r3;
  }
}
async function addCardToGroup(card, groups, position) {
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const groupsIds = groups.filter(Boolean).map((g3) => g3.id);
  groups.forEach((group2) => {
    cardStore.addToGroup(card, group2, position);
  });
  const lock = await cardStore.lock(card);
  try {
    return await onApiResponse(api_default.cards.add_to_group.post({ card_id: card.id, group_id: groupsIds, position }), lock);
  } catch (r3) {
    throw r3;
  }
}
async function moveCardInUngrouped(card, position) {
  const oldPosition = card.position;
  cardStore.reorderCards(card, position, oldPosition);
  const lock = await cardStore.lock(card);
  try {
    const newCard = await onApiResponse(api_default.cards.relocate.post({ card_id: card.id, position }), lock);
    cardStore.reorderCards(newCard, newCard.position, position);
    return newCard;
  } catch (r3) {
    cardStore.reorderCards(card, oldPosition, position);
    throw r3;
  }
}
async function removeCardFromGroup(card, groups) {
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const groupsIds = groups.filter(Boolean).map((g3) => g3.id);
  groups.forEach((group2) => {
    cardStore.removeFromGroup(card, group2);
  });
  const lock = await cardStore.lock(card);
  try {
    return await onApiResponse(api_default.cards.remove_from_group.post({ card_id: card.id, group_id: groupsIds }), lock);
  } catch (r3) {
    throw r3;
  }
}
function toggleCardGroup(card, group2) {
  if (cardStore._findCardGroups(card, { id: group2.id }).length) {
    return removeCardFromGroup(card, group2);
  } else {
    return addCardToGroup(card, group2);
  }
}
async function removeCardFromGroupType(card, groupType, position) {
  const oldPosition = card.position;
  cardStore.reorderCards(card, position, oldPosition);
  cardStore.removeCardFromGroupType(card, groupType);
  const lock = await cardStore.lock(card);
  try {
    const newCard = await onApiResponse(api_default.cards.remove_from_group_type.post({
      card_id: card.id,
      type_id: groupType.id,
      position
    }), lock);
    cardStore.reorderCards(newCard, newCard.position, position);
    return newCard;
  } catch (r3) {
    cardStore.reorderCards(card, oldPosition, position);
    throw r3;
  }
}
async function setCardState(card, state) {
  const lock = await cardStore.lock(card);
  card = await onApiResponse(api_default.cards.update.put({ card_id: card.id, state: state.id }), lock);
  if (state.alias) {
    if (cardGroupStore.exists(state.id)) {
      cardStore.relocate(card, cardGroupStore.get(state.id));
    }
  }
  return card;
}
function toggleCardAsCompleted(card) {
  return setCardState(card, card.finished ? cardStateStore.getAvailableForCard(card, "waiting")[0] : cardStateStore.getAvailableForCard(card, "completed")[0]);
}
async function removeBoard(card) {
  const lock = await cardStore.lock(card);
  return onApiResponse(api_default.cards.remove_board.delete({ card_id: card.id }), lock);
}
async function toggleCardAsFavorite(card) {
  if (isFavorite("card", card.id)) {
    await api_default.cards.unfavorite.delete({ card_id: card.id });
    removeFavorite("card", card.id);
  } else {
    await api_default.cards.favorite.post({ card_id: card.id });
    addFavorite("card", card.id);
  }
  cardStore.broadcast("favorites");
}
async function toggleCardSubscription(card) {
  if (cardSubscriptionStore.isSubscribed(card)) {
    await api_default.cards.unsubscribe.delete({ card_id: card.id });
    cardSubscriptionStore.unsubscribeFrom(card);
  } else {
    await api_default.cards.subscribe.post({ card_id: card.id });
    cardSubscriptionStore.subscribeTo(card);
  }
  return loadRemindersForCard(card);
}
async function archiveCard(card) {
  if (card.is_archived) throw new Error("Card is already archived");
  const lock = await cardStore.lock(card);
  cardStore.archive(card);
  if (!card.parent_id && projectStore.exists(card.project_id)) {
    projectStore.update({ id: card.project_id }, { is_archived: true });
  }
  try {
    return await onApiResponse(api_default.cards.archive.post({ card_id: card.id }), lock);
  } catch (r3) {
    cardStore.restore(card);
    if (!card.parent_id && projectStore.exists(card.project_id)) {
      projectStore.update({ id: card.project_id }, { is_archived: false });
    }
    throw r3;
  }
}
async function restoreCard(card) {
  if (!card.is_archived) throw new Error("Card is not archived");
  const lock = await cardStore.lock(card);
  cardStore.restore(card);
  if (!card.parent_id && projectStore.exists(card.project_id)) {
    projectStore.update({ id: card.project_id }, { is_archived: false });
  }
  try {
    return await onApiResponse(api_default.cards.restore.delete({ card_id: card.id }), lock);
  } catch (r3) {
    cardStore.archive(card);
    if (!card.parent_id && projectStore.exists(card.project_id)) {
      projectStore.update({ id: card.project_id }, { is_archived: true });
    }
    throw r3;
  }
}
async function deleteCard(card) {
  await api_default.cards.delete.delete({ card_id: card.id });
  cardStore.transaction(() => {
    cardStore.archive(card);
    cardStore.remove(card);
  });
}
async function duplicateCard(card) {
  const newCard = await api_default.cards.copy.post({ card_id: card.id });
  if (!newCard.parent_id) {
    getOrLoadProject(newCard.project_id, { ignoreErrorHandlers: true });
  }
  if (newCard.nb_children) {
    loadDescendantCardsOf(newCard);
  }
  return cardStore.insert(newCard);
}
function openMoveWarningDialog() {
  return confirmDialog({
    title: _4("Move information"),
    text: _4("This action will involve recomputing all card references. Note that access rights may also be impacted"),
    confirmButtonText: _4("Move")
  });
}
async function convertCardToProject(card, org2, team, withCopy) {
  if (!org2) {
    throw new Error("No org selected");
  }
  await openMoveWarningDialog();
  const orgId = org2.type === "org" ? org2.id : null;
  let resp;
  try {
    resp = await api_default.cards.convert_to_project.post({
      card_id: card.id,
      org_id: orgId,
      team_id: team ? team.id : null,
      with_copy: withCopy
    });
  } catch (r3) {
    return autoCatchAsRequestErrorDialog([403, 409, 412])(r3);
  }
  const toast = toastNotify(_4("Your card is being converted into a workspace"));
  try {
    await waitForAsyncJobResult(resp.async_id);
  } catch (r3) {
    errorDialog(_4("An error ocurred while converting your card, please try again later or contact our support team"));
    throw r3;
  } finally {
    toast.close();
  }
  const c3 = await loadCard(withCopy ? resp.card_id : card.id);
  let project = await loadProject(c3.project_id);
  project = projectStore.upsert({ ...project, dashboard_group: orgId ? orgId : "user" });
  return withCopy ? null : project;
}
async function moveCardTo(card, parent, groups, withCopy) {
  if (!Array.isArray(groups)) {
    groups = [groups];
  }
  const group_id = groups ? groups.map((g3) => g3.id) : null;
  const parent_id = parent ? parent.id : null;
  let movedCard;
  try {
    if (parent.project_id === card.project_id) {
      if (withCopy) {
        movedCard = await api_default.cards.copy.post({ card_id: card.id, parent_id, group_id });
      } else {
        movedCard = await api_default.cards.relocate.post({ card_id: card.id, parent_id, group_id });
      }
    } else {
      if (card.parent_id) {
        try {
          await openMoveWarningDialog();
        } catch (r3) {
          throw r3;
        }
        if (withCopy) {
          movedCard = await api_default.cards.copy.post({ card_id: card.id, parent_id, group_id });
        } else {
          movedCard = await api_default.cards.relocate.post({ card_id: card.id, parent_id, group_id });
        }
      } else {
        return convertProjectToCard(card, parent, groups, withCopy, false);
      }
    }
  } catch (r3) {
    return autoCatchAsRequestErrorDialog([403, 409, 412])(r3);
  }
  if (movedCard) {
    if (withCopy) {
      cardStore.insert(movedCard);
    } else {
      if (card.parent_id !== movedCard.parent_id) {
        cardStore.remove(card);
      } else {
        groups.forEach(function(group2) {
          cardStore.relocate(card, group2);
        });
      }
      cardStore.upsert(movedCard);
    }
  }
  return [movedCard];
}
async function switchCardModel(card, targetModel, sourceModel) {
  const lock = await cardStore.lock(card);
  if (sourceModel && sourceModel.attributes.length > 0) {
    await confirmDialog({
      title: _4("Changing the type can delete fields"),
      text: _4("If the new type does not have the same fields as the current one, the current value of the missing fields will be lost.")
    });
  }
  return onApiResponse(api_default.cards.switch_model.post({ card_id: card.id, model_id: targetModel.id }), lock);
}
async function setCardAttribute(card, attributeId, value2) {
  if (value2 === "") {
    return clearCardAttribute(card, attributeId);
  }
  const lock = await cardStore.lock(card);
  try {
    const attr = await api_default.cards.set_attribute.post({ card_id: card.id, attr_id: attributeId, value: value2 });
    const index2 = _getAttributeIndex(card, attributeId);
    cardStore.update(card, (card2) => {
      let attributes = [...card2.attributes];
      if (typeof index2 !== "undefined") {
        attributes.splice(index2, 1);
      }
      attributes.push(attr);
      return { ...card2, attributes, updated_at: moment_default().unix() };
    });
    const attrs2 = cardModelStore.getCardAvailableAttributes(card, { id: attributeId });
    if (attrs2 && attrs2.length && attrs2[0].type === "date") {
      loadRemindersForCard(card);
    }
    return attr;
  } finally {
    lock.release();
  }
}
async function appendCardAttribute(card, attributeId, value2) {
  const lock = await cardStore.lock(card);
  try {
    const attr = await api_default.cards.append_attribute.post({ card_id: card.id, attr_id: attributeId, value: value2 });
    const index2 = _getAttributeIndex(card, attributeId);
    cardStore.update(card, (card2) => {
      let attributes = [...card2.attributes];
      if (typeof index2 !== "undefined") {
        attributes.splice(index2, 1);
      }
      attributes.push(attr);
      return { ...card2, attributes, updated_at: moment_default().unix() };
    });
    return attr;
  } finally {
    lock.release();
  }
}
function appendFilesToCardAttribute(card, attributeId, files, progressCallback, withErrorHandler = true) {
  return upload({
    url: api_default.project_files.upload_file.url({ project_id: card.project_id }),
    data: { files }
  }, progressCallback).then((resp) => {
    var value2 = resp.data.map((file) => file.id);
    return appendCardAttribute(card, attributeId, value2);
  }, (r3) => {
    if (withErrorHandler) {
      errorDialog(_4("An error ocurred while uploading your file"));
    }
    throw r3;
  });
}
async function popCardAttribute(card, attributeId, value2) {
  const index2 = _getAttributeIndex(card, attributeId);
  if (index2 !== void 0 && card.attributes[index2].value.length == 1) {
    return clearCardAttribute(card, attributeId);
  }
  const lock = await cardStore.lock(card);
  try {
    const attr = await api_default.cards.pop_attribute.post({ card_id: card.id, attr_id: attributeId, value: value2 });
    cardStore.update(card, (card2) => {
      ;
      if (typeof index2 !== "undefined") {
        let attributes = [...card2.attributes];
        attributes.splice(index2, 1);
        attributes.push(attr);
        return { ...card2, attributes, updated_at: moment_default().unix() };
      }
    });
    return attr;
  } finally {
    lock.release();
  }
}
async function clearCardAttribute(card, attributeId) {
  const lock = await cardStore.lock(card);
  try {
    await api_default.cards.clear_attribute.delete({ card_id: card.id, attr_id: attributeId });
    const index2 = _getAttributeIndex(card, attributeId);
    cardStore.update(card, (card2) => {
      ;
      if (typeof index2 !== "undefined") {
        let attributes = [...card2.attributes];
        attributes.splice(index2, 1);
        return { ...card2, attributes, updated_at: moment_default().unix() };
      }
    });
    var attrs2 = cardModelStore.getCardAvailableAttributes(card, { id: attributeId });
    if (attrs2 && attrs2.length && attrs2[0].type === "date") {
      loadRemindersForCard(card);
    }
  } finally {
    lock.release();
  }
}
function _getAttributeIndex(card, attributeId) {
  if (typeof card.attributes !== "undefined") {
    for (var i3 = 0; i3 < card.attributes.length; i3++) {
      if (!isNaN(attributeId) && card.attributes[i3].id === parseInt(attributeId, 10)) {
        return i3;
      } else if (card.attributes[i3].name === attributeId) {
        return i3;
      }
    }
  }
}
function postCardComment(card, message, showInRequest) {
  return queueRemoteAction(
    _4("Comment on {card}", { card: card.title }),
    async (syncId) => {
      const comment4 = await api_default.card_stream.post_comment.post({
        card_id: card.id,
        message,
        show_in_request: showInRequest
      });
      activityStore.insert(comment4);
      if (cardStore.exists(card.id)) {
        cardStore.update(card, {
          nb_comments: card.nb_comments + 1,
          updated_at: moment_default().unix()
        });
      }
      if (syncId) {
        activityStore.removeById(syncId);
      }
      return comment4;
    },
    (syncId) => {
      const comment4 = {
        id: syncId,
        date: moment_default().unix(),
        user: {
          "id": currentUser2.id,
          "username": currentUser2.username,
          "display_name": currentUser2.display_name,
          "avatar": currentUser2.avatar
        },
        card_id: card.id,
        project_id: card.project_id,
        message,
        is_pinned: false,
        show_in_request: showInRequest,
        stream_type: "comment",
        offline: true
      };
      return activityStore.insert(comment4);
    }
  );
}
async function editCardComment(card, comment4, message) {
  const c3 = await api_default.card_stream.edit_comment.put({ card_id: card.id, comment_id: comment4.id, message });
  return activityStore.update(c3);
}
async function deleteCardComment(card, comment4) {
  await api_default.card_stream.delete_comment.delete({ card_id: card.id, comment_id: comment4.id });
  activityStore.remove(comment4);
  cardStore.update(card, {
    nb_comments: card.nb_comments - 1,
    updated_at: moment_default().unix()
  });
}
async function addCardLog(card, logType, attributes, date, withErrorHandler = true) {
  try {
    const { log: log2, type } = await api_default.card_stream.add_log.post({
      card_id: card.id,
      type: logType.id,
      attributes,
      date,
      return_log_type: true
    });
    activityStore.insert(log2);
    projectLogTypeStore.upsert(type);
    cardStore.update(card, { updated_at: moment_default().unix() });
    return [log2, type];
  } catch (r3) {
    if (withErrorHandler) {
      errorDialog(_4("An error ocurred while saving your log"));
    }
    throw r3;
  }
}
async function deleteCardLog(card, log2) {
  await api_default.card_stream.delete_log.delete({ card_id: card.id, log_id: log2.id });
  activityStore.remove(log2);
  cardStore.update(card, { updated_at: moment_default().unix() });
}
async function addCardReminder(card, targets, remindingDate) {
  const reminder = await api_default.card_reminders.create_reminder.post({
    card_id: card.id,
    targets,
    reminding_date: remindingDate
  });
  return cardReminderStore.insert(reminder);
}
async function deleteCardReminder(card, reminder) {
  await api_default.card_reminders.delete_reminder.delete({ card_id: card.id, reminder_id: reminder.id });
  cardReminderStore.remove(reminder);
}
async function createCardRequest(card, form, email2) {
  const request2 = await api_default.cards.create_card_request.post({ card_id: card.id, request_form_id: form.id, email: email2 });
  cardStore.update(card, { from_request: request2 });
  return request2;
}
async function deleteCardRequest(card) {
  await api_default.cards.delete_card_request.delete({ card_id: card.id });
  cardStore.update(card, { from_request: null });
}

// public/app/attributes/utils/index.js
function createDynamicGroupForAttribute(store2, card, model, modelAttr, value2, title, supportsAppend, matchUngrouped, valueMatcher) {
  return store2.createDynamicGroup(card, {
    title: title || value2,
    getCardStore(withArchived, includeDescendants) {
      return cardStore.scopedByParent(card, withArchived, includeDescendants).scopedByAttributeValue(modelAttr.id, value2, matchUngrouped, valueMatcher);
    },
    handleCardEnter: (card2, append2) => {
      if (!cardModelStore.isAttributeAvailableForCard(card2, modelAttr)) {
        return Promise.reject("This drop cannot be done: wrong card type");
      }
      if (append2 && supportsAppend) {
        return appendCardAttribute(card2, modelAttr.id, value2);
      } else {
        return setCardAttribute(card2, modelAttr.id, value2);
      }
    },
    handleCardLeave: (card2) => {
      return clearCardAttribute(card2, modelAttr.id);
    },
    attribute_id: modelAttr.id,
    attribute_value: value2,
    match_ungrouped: matchUngrouped
  });
}
function cmp2(a3, b3) {
  if (typeof a3 === "string") {
    return a3.localeCompare(b3);
  }
  return a3 < b3 ? -1 : a3 > b3 ? 1 : 0;
}
function getAttributesInContainer(attributeGroup, container) {
  return attributeGroup.filter((attr) => {
    var attrContainer = attributeGroup.getPosition(attr)[0] || "";
    return typeof container === "undefined" || attrContainer === "*" || attrContainer === (container || "");
  });
}
function sortAttributes(attributeGroup, container) {
  const out = [];
  let attributes = getAttributesInContainer(attributeGroup, container);
  const orgAttrs = [];
  const projectAttrs = [];
  attributes = attributes.filter((attr) => {
    if (attr.model_is_base) {
      if (attr.model_is_base === "org") {
        orgAttrs.push(attr);
      } else {
        projectAttrs.push(attr);
      }
      return false;
    }
    return true;
  });
  orgAttrs.sort((a3, b3) => cmp2(a3.position, b3.position));
  projectAttrs.sort((a3, b3) => cmp2(a3.position, b3.position));
  out.push(...orgAttrs, ...projectAttrs);
  const relativeAttributes = {};
  attributes = attributes.filter((attr) => {
    var position = attributeGroup.getPosition(attr);
    if (position[1] === null) {
      return true;
    }
    if (!relativeAttributes[position[1]]) {
      relativeAttributes[position[1]] = [];
    }
    relativeAttributes[position[1]].push(attr);
    return false;
  });
  for (let [position, attrs2] of Object.entries(relativeAttributes)) {
    attrs2.sort((a3, b3) => -cmp2(attributeGroup.getPosition(a3)[2], attributeGroup.getPosition(b3)[2]));
    const spliceStart = out.findIndex((a3) => a3.model_is_base === "project" && a3.position === parseInt(position, 10));
    Array.prototype.splice.apply(out, [spliceStart, 0].concat(attrs2));
  }
  attributes.sort((a3, b3) => cmp2(a3.position, b3.position));
  return out.concat(attributes);
}
function confirmAttrDeletion() {
  return confirmDeleteDialog2(
    _4("Are you sure?"),
    _4("Be careful, this field will be <strong>removed from all the cards</strong> that have it. <strong>ALL ASSOCIATED DATA will be LOST.</strong>")
  );
}
function isEmptyValue(value2) {
  if (typeof value2 === "string") {
    return value2.trim() === "";
  } else if (value2 === null || value2 === void 0) {
    return true;
  }
  return false;
}
function defaultAttributeFilters(project, attr, append2) {
  return [
    {
      label: _4("Empty"),
      action: () => {
        append2("{" + attr.name + "}=empty");
      }
    },
    {
      label: _4("Not empty"),
      action: () => {
        append2("{" + attr.name + "}!=empty");
      }
    },
    {
      input: true,
      placeholder: _4("Value"),
      submit: (value2) => {
        append2("{" + attr.name + "}~=" + value2);
      },
      resetOnSubmit: true
    }
  ];
}
function isAttributeConfigured(attr) {
  const attrType = attributeTypeStore.tryGet(attr.type);
  const attrReqOpts = attrType ? attrType.options.filter((opt) => opt.required) : [];
  let configured = true;
  for (const opt of attrReqOpts) {
    if (!attr.options[opt.name] || attr.options[opt.name].length === 0) {
      configured = false;
      break;
    }
  }
  return configured;
}

// public/app/config/filter-editor.js
function getMembersOptions(projectMemberStore2) {
  return projectMemberStore2.query({}, { sortBy: "user.display_name" }).map((member) => {
    return {
      label: member.user.display_name,
      value: "@" + escapeKqlName(member.user.username)
    };
  });
}
var filterEditorShortcuts = [
  {
    func_name: "FULL_TEXT_SEARCH",
    label: _lazy("Search across all text content"),
    getMatchValue(node) {
      return node[3][2];
    },
    toString(value2) {
      return `"${value2}"`;
    }
  },
  {
    func_name: "CONTAINS_MEMBER",
    factory(stores) {
      return {
        label: _4("All cards assigned to"),
        placeholder: _4("Username"),
        options: stores["projectMember"] ? getMembersOptions(stores["projectMember"]) : void 0,
        getMatchValue(node) {
          return node[3][1];
        },
        toString(value2) {
          return value2.indexOf("@") === 0 ? value2 : `CONTAINS_MEMBER?(${value2})`;
        }
      };
    }
  },
  {
    func_name: "MENTIONS",
    factory(stores) {
      return {
        label: _4("Cards where member is mentioned"),
        placeholder: _4("Username"),
        options: stores["projectMember"] ? getMembersOptions(stores["projectMember"]) : void 0,
        getMatchValue(node) {
          return node[3][1];
        },
        toString(value2) {
          return `MENTIONS?(${value2})`;
        }
      };
    }
  },
  {
    func_name: "IS_SUBSCRIBED",
    label: _lazy("All cards you are subscribed to"),
    noValue: true,
    toString() {
      return "IS_SUBSCRIBED?()";
    }
  },
  {
    func_name: "PARENT",
    label: _lazy("Parent card matches a condition"),
    getMatchValue(node) {
      return node[3][2];
    },
    toString(value2) {
      return `PARENT?(${value2})`;
    }
  },
  {
    func_name: "CHILDREN",
    label: _lazy("Child cards match a condition"),
    getMatchValue(node) {
      return node[3][2];
    },
    toString(value2) {
      return `CHILDREN?(${value2})`;
    }
  },
  {
    func_name: "DESCENDANTS",
    label: _lazy("Descendants match a condition"),
    getMatchValue(node) {
      return node[3][2];
    },
    toString(value2) {
      return `DESCENDANTS?(${value2})`;
    }
  }
];
var filterEditorSpecialFields = [
  {
    name: "project",
    label: _lazy("Workspace"),
    type: "text",
    disabled(stores) {
      return !stores["project"];
    },
    nodeBuilder(stores) {
      return {
        operators: [
          { label: _lazy("Is"), op: "=" }
        ],
        options: {
          "=": stores["project"].query({}, { sortBy: "title" }).map((p4) => ({ label: p4.title, value: p4.title }))
        }
      };
    }
  },
  {
    name: "organization",
    label: _lazy("Organization"),
    type: "text",
    disabled(stores) {
      return !stores["organization"];
    },
    nodeBuilder(stores) {
      return {
        operators: [
          { label: _lazy("Is"), op: "=" }
        ],
        options: {
          "=": stores["organization"].query({}, { sortBy: "name" }).map((o3) => ({ label: o3.name, value: o3.name }))
        }
      };
    }
  },
  {
    name: "team",
    label: _lazy("Team"),
    type: "text",
    disabled(stores) {
      return !stores["team"];
    },
    nodeBuilder(stores) {
      return {
        operators: [
          { label: _lazy("Is"), op: "=" }
        ],
        options: {
          "=": stores["team"].query({}, { sortBy: "name" }).map((t3) => ({ label: t3.name, value: t3.name }))
        }
      };
    }
  },
  {
    name: "id",
    label: _lazy("Card ID"),
    type: "text"
  },
  {
    name: "ref",
    label: _lazy("Card Ref"),
    type: "text"
  },
  {
    name: "created at",
    label: _lazy("Creation date"),
    type: "date"
  },
  {
    name: "updated at",
    label: _lazy("Last update date"),
    type: "date"
  },
  {
    name: "started at",
    label: _lazy("Started at (state became doing)"),
    type: "date"
  },
  {
    name: "finished at",
    label: _lazy("Finished at (state became done)"),
    type: "date"
  },
  {
    name: "state",
    label: _lazy("State"),
    type: "text",
    nodeBuilder(stores) {
      return {
        operators: [
          { label: _lazy("Is"), op: "=" }
        ],
        options: {
          "=": cardStateStore.getBuiltinStates().map((s3) => ({ label: s3.label, value: s3.id }))
        }
      };
    }
  },
  {
    name: "type",
    label: _lazy("Card type"),
    type: "text",
    nodeBuilder(stores) {
      const models = stores["cardModel"].query({ base_model_id: query_exports.isUndefined() }, { sortBy: "name" });
      if (!models.length) {
        return {
          operators: [
            { label: _lazy("Is empty"), op: "empty" }
          ],
          options: {
            empty: false
          }
        };
      }
      return {
        operators: [
          { label: _lazy("Is"), op: "=" },
          { label: _lazy("Is empty"), op: "empty" },
          { label: _lazy("Is not empty"), op: "not_empty" }
        ],
        options: {
          empty: false,
          not_empty: false,
          "=": models.map((m3) => ({ label: m3.name, value: m3.name }))
        }
      };
    }
  },
  {
    name: "archived",
    label: _lazy("Is archived"),
    type: "bool"
  },
  {
    name: "nb children",
    label: _lazy("Number of child cards"),
    type: "number"
  },
  {
    name: "nb comments",
    label: _lazy("Number of comments"),
    type: "number"
  },
  {
    name: "last comment at",
    label: _lazy("Date last comment was posted"),
    type: "date"
  }
];

// public/app/ui/editors/filter-editor/node-utils.js
function buildNodeTypeList(stores, userDefinedFields) {
  const nodeTypes = [];
  for (let shortcut of filterEditorShortcuts) {
    if (shortcut.func_name) {
      shortcut = createFunctionNode(shortcut, stores);
    }
    nodeTypes.push(Object.assign(shortcut, { category: _4("Shortcuts") }));
  }
  const contexts = [], fields2 = [];
  for (let field2 of userDefinedFields || []) {
    if (field2.type === "context") {
      contexts.push(Object.assign(createGroupTypeNode(field2.name, field2.id, stores), { category: _4("Contexts") }));
    } else {
      fields2.push(Object.assign(
        createAttributeNode(field2.name, field2.type, field2.attribute, field2.label, stores),
        { category: field2.model ? _4("Fields from {model}", { model: field2.model }) : _4("Fields") }
      ));
    }
  }
  nodeTypes.push(...contexts);
  nodeTypes.push(...fields2);
  for (let field2 of filterEditorSpecialFields) {
    if (field2.disabled !== true && (!isFunction_default(field2.disabled) || !field2.disabled(stores))) {
      nodeTypes.push(Object.assign(createAttributeNode(field2.name, field2.type, null, field2.label, stores, field2.nodeBuilder), { category: _4("Special fields") }));
    }
  }
  return nodeTypes;
}
function createGroupTypeNode(name2, groupTypeId, stores) {
  const node = {
    label: name2,
    name: name2,
    operators: [
      { label: _4("Any"), op: "any" },
      { label: _4("None"), op: "none" },
      { label: _4("Includes"), op: "includes" },
      { label: _4("Does not include"), op: "does_not_include" }
    ],
    options: {
      any: false,
      none: false
    },
    match(node2) {
      let not2 = false;
      if (node2[0] === "Not") {
        node2 = node2[2];
        not2 = true;
      }
      if (node2[0] === "ConditionFunc" && node2[2] === "IS_IN_GROUP_TYPE" && name2.toLowerCase() === node2[3][2].toLowerCase()) {
        return [not2 ? "none" : "any", null];
      }
      if (node2[0] === "ConditionFunc" && node2[2] === "IS_IN_GROUP" && node2.length === 5 && name2.toLowerCase() === node2[4][2].toLowerCase()) {
        return [not2 ? "does_not_include" : "includes", node2[3][2]];
      }
    },
    transform: (value2, op) => {
      if (op === "any") {
        return `#${escapeKqlName(name2)}:*`;
      }
      if (op === "none") {
        return `not #${escapeKqlName(name2)}:*`;
      }
      let out = `#${escapeKqlName(name2)}:${escapeKqlName(value2)}`;
      return op == "does_not_include" ? `not ${out}` : out;
    }
  };
  const groupType = groupTypeId ? cardGroupTypeStore.tryGet(groupTypeId) : null;
  if (!groupType || !stores["group"]) {
    return node;
  }
  node["options"]["includes"] = node["options"]["does_not_include"] = stores["group"](groupType).query().map((g3) => {
    return { label: g3.title, value: g3.title };
  });
  return node;
}
function createAttributeNode(name2, type, attr, label, stores, nodeBuilder) {
  let nodeType = {
    label: label || name2,
    name: name2,
    operators: [
      { label: _4("Equals to"), op: "=" },
      { label: _4("Different from"), op: "!=" },
      { label: _4("Is empty"), op: "empty" },
      { label: _4("Is not empty"), op: "not_empty" }
    ],
    options: {
      empty: false,
      not_empty: false
    },
    match: (node) => matchAttributeNode(name2, node),
    transformEscapeValue: null,
    transform: (value2, op) => transformAttributeNode(name2, value2, op, nodeType.transformEscapeValue)
  };
  const attrType = attributeTypeRegistry.get(type);
  if (attrType && attrType.buildFilterEditorNode) {
    Object.assign(nodeType, attrType.buildFilterEditorNode(stores, name2, attr));
  }
  if (nodeBuilder) {
    Object.assign(nodeType, nodeBuilder(stores));
  }
  return nodeType;
}
function matchAttributeNode(name2, node) {
  let op, value2;
  if (node[0] === "Comparison" && node[2][0] === "Attribute" && node[2][2].toLowerCase() === name2.toLowerCase()) {
    if (node[4][0] === "Empty") {
      op = node[3] === "!=" ? "not_empty" : "empty";
      value2 = null;
    } else {
      op = node[3];
      value2 = valueFromNode(node[4]);
    }
  }
  if (node[0] === "Contains" && node[2][0] === "Attribute" && node[2][2].toLowerCase() === name2.toLowerCase()) {
    op = "in";
    value2 = valueFromNode(node[3]);
  }
  if (node[0] === "FullTextMatch" && node[2][0] === "Attribute" && node[2][2].toLowerCase() === name2.toLowerCase()) {
    op = "~=";
    value2 = valueFromNode(node[3]);
  }
  if (op !== void 0 || value2 !== void 0) {
    return [op, value2];
  }
}
function valueFromNode(node) {
  return node[0] === "Scalar" ? node[2] : node[1];
}
function transformAttributeNode(name2, value2, op, escapeValue = null) {
  if (!op) {
    op = "=";
  }
  let out = escapeKqlName(name2);
  if (op.includes("empty")) {
    return out + (op === "not_empty" ? "!= empty" : "= empty");
  }
  if (escapeValue === null && !value2.match(/^@{1,2}[a-z0-9_]+$/i) && !value2.match(/^#[0-9]+$/) && !value2.match(/^[0-9]+(\.[0-9]+)?$/)) {
    escapeValue = true;
  }
  if (escapeValue) {
    value2 = `"${value2}"`;
  }
  if (op === "in") {
    return value2 + " in " + out;
  }
  return out + op + value2;
}
function createFunctionNode(spec, stores) {
  let name2 = spec.func_name;
  if (spec.factory) {
    spec = spec.factory(stores);
  }
  return Object.assign({
    match(node) {
      if (node[0] === "ConditionFunc" && node[2] === name2) {
        return [null, spec.getMatchValue ? spec.getMatchValue(node, stores) : ""];
      }
    },
    transform(value2) {
      return spec.toString(value2, stores);
    }
  }, spec);
}

// public/app/attributes/bool.js
attributeTypeRegistry.register("bool", {
  title: _4("Yes/No value"),
  description: _4("Toggle between enabled or disabled state"),
  icon: "check-square-o",
  important: true,
  groupable: true,
  defaultValueIsUngrouped: true,
  defaultValue: false,
  sortable: true,
  filterable: true,
  batchable: true,
  copyable: true,
  widgetDirective: "attribute-type-bool",
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "icon",
      value: true,
      tooltip: modelAttr.name,
      options: {
        icon: attr.value ? "check" : "times",
        cssclass: attr.value ? "is-true" : "is-false"
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(new Number(attrA.value), new Number(attrB.value));
  },
  fillCardGroupByStore(card, model, modelAttr, store2) {
    createDynamicGroupForAttribute(store2, card, model, modelAttr, true, _4("Yes"));
    createDynamicGroupForAttribute(store2, card, model, modelAttr, false, _4("No"), false, true);
  },
  equals(attr, value2) {
    if (attr.value === true) {
      return value2 === true || value2 === _4("Yes");
    } else if (attr.value === false) {
      return value2 === false || value2 === _4("No");
    }
    return false;
  },
  buildFilterEditorNode(stores, name2, attr) {
    return {
      operators: null,
      options: [
        { label: _4("Yes"), value: true },
        { label: _4("No"), value: false }
      ],
      transformEscapeValue: false,
      match(node) {
        const m3 = matchAttributeNode(name2, node);
        if (m3) {
          return [null, node[4][2]];
        }
      }
    };
  },
  getFilters(project, attr, append2) {
    return [
      {
        label: _4("Yes"),
        action: () => {
          append2("{" + attr.name + "}=yes");
        }
      },
      {
        label: _4("No"),
        action: () => {
          append2("{" + attr.name + "}=no");
        }
      }
    ];
  }
});

// public/app/attributes/card.js
attributeTypeRegistry.register("card", {
  title: _lazy("Multiple choice from global search query"),
  description: _lazy("Create a relationship with a card from any workspace by selecting it from a dropdown filled by a search query"),
  icon: "link",
  category: "relationships",
  hidden: true,
  requireValidOptions: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-select",
  widgetOptions: {
    valueIsAlwayArray: true,
    action: $invokeDecorator(["$scope", "cardModal", "$q", ($scope2, cardModal, $q) => {
      $q.when(getOrLoadCard($scope2.value[0], { ignoreErrorHandlers: true }), (card) => {
        cardModal.open(card);
      });
    }], ["$scope"]),
    actionDisabled: (attribute2) => !attribute2.valid_options
  },
  editorDirective: "attribute-type-select-editor",
  editorOptions: {
    async: true
  },
  batchable: true,
  copyable: true,
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: attr.value[1],
      tooltip: modelAttr.name
    };
  },
  formatValueItemToServer(value2) {
    return value2[0];
  }
});

// public/app/attributes/attr-group/base.ts
var AttributeGroup = class extends Array {
  constructor(attributes) {
    super();
    this.listeners = [];
    this.deleted = [];
    if (attributes) {
      this.push(...attributes);
    }
  }
  static get [Symbol.species]() {
    return Array;
  }
  /**
   * Add listener to AttributeGroup.listeners
   * @returns a function that removes listener from AttributeGroup.listeners
   */
  listen(listener) {
    this.listeners.push(listener);
    return function() {
      var idx = this.listeners.indexOf(listener);
      if (idx > -1) {
        this.listeners.splice(idx, 1);
      }
    }.bind(this);
  }
  /**
   * Same as listen but:
   * - listener is called in an angularjs digest loop
   * - listener is deregistered if scope is destroyed
   * @returns a deregister function on both listener and angular "$destroy" event
   */
  $listen(scope, listener) {
    const deregisterListener = this.listen((obj) => {
      scope.$evalAsync(() => {
        listener(obj);
      });
    });
    const deregisterScopeListener = scope.$on(
      "$destroy",
      () => deregisterListener()
    );
    return () => {
      deregisterListener();
      deregisterScopeListener();
    };
  }
  /**
   * Calls all AttributeGroup.listeners on obj
   */
  _emit(obj) {
    this.listeners.forEach((listener) => listener(obj));
  }
  /**
   * @returns the index of the attr in AttributeGroup.
   * If some attributes have the same id or name, returns the first index in the array
   */
  indexOfAttr(attr) {
    var id = attr;
    if (typeof attr === "object") {
      id = attr.id || attr.name;
    }
    if (typeof id === "string") {
      id = id.toLowerCase();
    }
    for (var i3 = 0; i3 < this.length; i3++) {
      if (this[i3].id && this[i3].id == id || this[i3].name.toLowerCase() == id) {
        return i3;
      }
    }
    return -1;
  }
  /**
   * @returns the corresponding attr in AttributeGroup.
   * If some attributes have the same id or name, returns the first attr in the array
   */
  get(id) {
    var i3 = this.indexOfAttr(id);
    return i3 >= 0 ? this[i3] : null;
  }
  exists(id) {
    return this.indexOfAttr(id) !== -1;
  }
  create(obj, typeName2, container, position) {
    const attr = this._createAttributeObject(typeName2, container);
    attr.position = position || this.reduce((sum, attr2) => {
      if (attr2.container == container) {
        return sum + 1;
      }
      return sum;
    }, 0);
    this.splice(attr.position, 0, attr);
    return Promise.resolve(attr);
  }
  _createAttributeObject(typeName2, container) {
    const resolvedType = attributeTypeRegistry.resolveAttrTypeAlias(typeName2);
    const name2 = _4("{type} n\xB0{number}", {
      type: resolvedType.title.toLowerCase(),
      number: this.reduce((accu, attr) => {
        if (attr.type === resolvedType.type.name) {
          return accu + 1;
        }
        return accu;
      }, 1)
    });
    return {
      type: resolvedType.type.name,
      name: name2,
      description: null,
      default_value: null,
      container: container || null,
      options: resolvedType.options,
      is_pii: false
    };
  }
  update(attr, props2) {
    return Promise.resolve(Object.assign({}, attr, props2));
  }
  getPosition(attr) {
    return [attr.container, null, attr.position];
  }
  move(attr, position) {
    const attrIndex2 = this.indexOfAttr(attr);
    if (attrIndex2 !== -1) {
      const attribute2 = this[attrIndex2];
      this.splice(attrIndex2, 1);
      this.splice(position, 0, attribute2);
      return Promise.resolve(attribute2);
    }
    return Promise.resolve();
  }
  remove(attr) {
    var i3 = this.indexOfAttr(attr);
    if (i3 !== -1) {
      this.deleted.push(this.splice(i3, 1)[0]);
    }
    return Promise.resolve();
  }
  getAttributeChoices(obj, attr) {
    return Promise.resolve([]);
  }
  getObjAttributes(obj, withAttribute = false) {
    if (typeof obj.attributes === "undefined") {
      return [];
    }
    const out = [];
    for (const attr of this) {
      let objAttr = this.getObjAttribute(obj, attr);
      if (objAttr) {
        out.push(withAttribute ? [objAttr, attr] : objAttr);
      }
    }
    return out;
  }
  getObjAttribute(obj, attr) {
    if (typeof obj.attributes === "undefined") {
      return;
    }
    let id = attr;
    if (typeof attr !== "number" && typeof attr !== "string") {
      id = attr.id || attr.name;
    }
    return obj.attributes.find((a3) => {
      return (a3.id == id || a3.name == id) && this.exists(a3.id || a3.name);
    });
  }
  getOrCreateObjAttribute(obj, attr) {
    let objAttr = this.getObjAttribute(obj, attr);
    if (!objAttr && this.exists(attr)) {
      const attribute2 = this.get(attr);
      objAttr = {
        type: attribute2.type,
        id: attribute2.id,
        name: attribute2.name
      };
      if (!obj.attributes) {
        obj.attributes = [];
      }
      obj.attributes.push(objAttr);
    }
    return objAttr;
  }
  setObjAttribute(obj, attr, value2) {
    const objAttr = this.getOrCreateObjAttribute(obj, attr);
    if (!objAttr) return Promise.resolve();
    const attribute2 = this.get(attr);
    const attrType = attributeTypeRegistry.get(attribute2.type);
    if (typeof attrType.formatLocalValue !== "undefined") {
      value2 = attrType.formatLocalValue(value2, objAttr.value);
    }
    objAttr.value = value2;
    this._emit(obj);
    return Promise.resolve();
  }
  appendObjAttribute(obj, attr, value2) {
    const objAttr = this.getOrCreateObjAttribute(obj, attr);
    if (!objAttr) return Promise.resolve();
    const attribute2 = this.get(attr);
    const attrType = attributeTypeRegistry.get(attribute2.type);
    if (typeof attrType.formatLocalValue !== "undefined") {
      value2 = attrType.formatLocalValue(value2, objAttr.value);
    }
    if (!objAttr.value) {
      objAttr.value = [];
    }
    objAttr.value.push(value2);
    this._emit(obj);
    return Promise.resolve();
  }
  appendFilesObjAttribute(obj, attr, files) {
    const p4 = Promise.all(
      files.map((file) => this.appendObjAttribute(obj, attr, file))
    );
    this._emit(obj);
    return p4;
  }
  popObjAttribute(obj, attr, value2) {
    const objAttr = this.getOrCreateObjAttribute(obj, attr);
    if (!objAttr) return Promise.resolve();
    const attribute2 = this.get(attr);
    const attrType = attributeTypeRegistry.get(attribute2.type);
    if (objAttr.value) {
      if (typeof attrType.popValue !== "undefined") {
        attrType.popValue(objAttr.value, value2);
      } else {
        const i3 = objAttr.value.indexOf(value2);
        if (i3 !== -1) {
          objAttr.value.splice(i3, 1);
        }
      }
    }
    this._emit(obj);
    return Promise.resolve();
  }
  clearObjAttribute(obj, attr) {
    if (typeof obj.attributes === "undefined") {
      return Promise.resolve();
    }
    let id = attr;
    if (typeof attr !== "number" && typeof attr !== "string") {
      id = attr.id || attr.name;
    }
    for (let i3 = 0; i3 < obj.attributes.length; i3++) {
      if (obj.attributes[i3].id === id || obj.attributes[i3].name === id) {
        obj.attributes.splice(i3, 1);
      }
    }
    this._emit(obj);
    return Promise.resolve();
  }
  getObjAttributeValue(obj, attr) {
    const objAttr = this.getObjAttribute(obj, attr);
    if (!objAttr) return [null, Promise.resolve()];
    const attribute2 = this.get(attr);
    const attrType = attributeTypeRegistry.get(attribute2.type);
    if (objAttr) {
      return [
        objAttr.value,
        attribute2.is_async ? this.fetchAsyncValue(obj, attr) : Promise.resolve(objAttr.value)
      ];
    } else if (attrType.statelessAsync) {
      return [void 0, this.fetchAsyncValue(obj, attr)];
    }
    return [null, Promise.resolve()];
  }
  fetchAsyncValue(obj, attr) {
    return Promise.resolve(null);
  }
  formatValueToServer(attr, value2) {
    const attrType = attributeTypeRegistry.get(attr.type);
    if (attrType && typeof attrType.formatValueToServer !== "undefined") {
      return attrType.formatValueToServer(value2, attr);
    }
    if (attrType.arrayValue) {
      if (Array.isArray(value2)) {
        return value2.map((item) => this.formatValueItemToServer(attr, item));
      } else return [];
    }
    return this.formatValueItemToServer(attr, value2);
  }
  formatValueItemToServer(attr, item) {
    const attrType = attributeTypeRegistry.get(attr.type);
    if (attrType && typeof attrType.formatValueItemToServer !== "undefined") {
      return attrType.formatValueItemToServer(item, attr);
    }
    return item;
  }
  formatObjToServer(obj, extractFiles) {
    const data2 = {};
    for (const [objAttr, attr] of this.getObjAttributes(obj, true)) {
      data2[attr.id || attr.name] = this.formatValueToServer(
        attr,
        objAttr.value
      );
    }
    return data2;
  }
  extractFilesFromServerData(data2) {
    const filteredData = {}, files = {};
    for (const [attrId, value2] of Object.entries(data2)) {
      const attr = this.get(attrId);
      const attrType = attributeTypeRegistry.get(attr.type);
      if (attrType.isFile) {
        files[attrId] = value2;
      } else {
        filteredData[attrId] = value2;
      }
    }
    return [filteredData, files];
  }
  sort(...args) {
    if (args.length) {
      return super.sort(...args);
    }
    return super.sort((a3, b3) => a3.name.localeCompare(b3.name));
  }
  makeComparisonFunc(attr, reverse) {
    const r3 = reverse ? -1 : 1;
    const attrType = attributeTypeRegistry.get(attr.type);
    const defaultCmp = (a3, b3) => a3?.title.localeCompare(b3?.title) || a3?.created_at > b3?.created_at ? 1 : -1;
    return (a3, b3) => {
      const attrA = this.getObjAttribute(a3, attr);
      const attrB = this.getObjAttribute(b3, attr);
      if (!attrType.noAttributeValue) {
        if ((!attrA || attrA.value === null) && attrB && attrB.value !== null) {
          return 1;
        }
        if (attrA && attrA !== null && (!attrB || attrB.value === null)) {
          return -1;
        }
        if ((!attrA || attrA.value === null) && (!attrB || attrB.value === null)) {
          return defaultCmp(a3, b3) * r3;
        }
      }
      const cmp4 = attrType.compare(a3, attrA, b3, attrB, attr);
      if (!cmp4) return defaultCmp(a3, b3) * r3;
      return cmp4 * r3;
    };
  }
};

// public/app/attributes/attr-group/batch.ts
var BatchAttributeGroup = class extends AttributeGroup {
  constructor(project, attributes, batchParams) {
    super(attributes);
    this.project = project;
    this.batchParams = batchParams;
  }
  _batch(op, attr, value2) {
    const params = { attr_id: attr.id };
    if (value2 !== void 0) {
      params["value"] = value2;
    }
    return batch3(this.project, op, params, this.batchParams);
  }
  setObjAttribute(obj, attr, value2) {
    return this._batch(
      "set_attribute",
      attr,
      this.formatValueToServer(attr, value2)
    );
  }
  appendObjAttribute(obj, attr, value2) {
    return this._batch(
      "append_attribute",
      attr,
      this.formatValueItemToServer(attr, value2)
    );
  }
  popObjAttribute(obj, attr, value2) {
    return this._batch(
      "pop_attribute",
      attr,
      this.formatValueItemToServer(attr, value2)
    );
  }
  clearObjAttribute(obj, attr) {
    return this._batch("clear_attribute", attr);
  }
  getAttributeChoices(obj, attr) {
    return api_default.projects.get_attribute_choices.get(
      {
        project_id: this.project.id,
        attr_id: attr.id
      },
      { ignoreErrorHandlers: true }
    ).catch(() => []);
  }
};

// public/app/attributes/attr-group/form.js
var RequestFormAttributeGroup = class _RequestFormAttributeGroup extends AttributeGroup {
  constructor(requestForm, attributes) {
    super(attributes);
    this.requestForm = requestForm;
  }
  getAttributeChoices(obj, attr) {
    return api_default.request_form.list_field_choices.get({
      request_form_id: this.requestForm.id,
      field_id: attr.id
    }, { ignoreErrorHandlers: true }).catch(() => []);
  }
  static fromRequestForm(requestForm) {
    const attributes = new _RequestFormAttributeGroup(requestForm);
    (requestForm.fields || []).forEach((field2, i3) => {
      if (field2.type === "text") {
        attributes.push({
          type: "statictext",
          id: 0,
          name: field2.description,
          position: i3
        });
      } else if (field2.type === "header") {
        attributes.push({
          type: "header",
          id: 0,
          name: field2.label,
          position: i3
        });
      } else if (field2.type === "title") {
        attributes.push({
          type: "text",
          id: field2.id,
          name: field2.label,
          description: field2.description,
          required: field2.required,
          position: i3
        });
      } else if (field2.type === "attribute") {
        attributes.push(Object.assign({}, field2.attribute, {
          id: field2.id,
          name: field2.label,
          description: field2.description,
          required: field2.required,
          container: null,
          position: i3
        }));
      }
    });
    return attributes;
  }
};

// public/app/attributes/attr-group/log.ts
var CardLogAttributeGroup = class extends AttributeGroup {
  constructor(project, logType, attributes) {
    super(attributes);
    this.project = project;
    this.logType = logType;
  }
  update(attr, props2) {
    return Promise.resolve(Object.assign(attr, props2));
  }
  getAttributeChoices(obj, attr) {
    return api_default.project_log_types.list_attribute_choices.get(
      {
        project_id: this.project.id,
        type_id: this.logType.id,
        type_name: attr.type
      },
      { ignoreErrorHandlers: true }
    ).catch(() => []);
  }
  _createAttributeObject(typeName2, container) {
    const obj = super._createAttributeObject(typeName2, container);
    obj.id = "tmp_" + uuid4();
    return obj;
  }
  async move(attr, position, container) {
    const movedAttribute = await super.move(attr, position);
    if (movedAttribute) {
      const bounds = computeMoveBounds(movedAttribute.position, position);
      if (movedAttribute.position !== position) {
        this.forEach((attribute2) => {
          const pos = attribute2.position;
          if (pos >= bounds.lower && (bounds.upper === null || pos <= bounds.upper)) {
            attribute2.position = attribute2.position + bounds.shift;
          }
        });
        movedAttribute.position = position;
        movedAttribute.container = container || null;
      }
      return movedAttribute;
    }
  }
};

// public/app/actions/model.ts
function formatData(model) {
  return {
    name: model.name,
    attributes: model.attributes || [],
    extends_from_id: model.extends_id || null,
    children_default_model_id: model.children_default_model_id || null,
    indicator: model.indicator || null,
    card_color: model.card_color || null,
    only_show_own_attributes: model.only_show_own_attributes || false,
    hide_children_attributes: model.hide_children_attributes || false
  };
}
async function createModelInProject(model, project) {
  model = await api_default.card_models.create_model.post(Object.assign({ project_id: project.id }, formatData(model)));
  return cardModelStore.insert(model);
}
async function createModelInOrg(model, org2) {
  model = await api_default.card_models.create_model.post(Object.assign({ org_id: org2.id }, formatData(model)));
  return cardModelStore.insert(model);
}
async function updateModel(model) {
  model = await api_default.card_models.update_model.put(Object.assign({ model_id: model.id }, formatData(model)));
  return cardModelStore.upsert(model);
}
async function deleteModel(model) {
  try {
    await api_default.card_models.delete_model.delete({ model_id: model.id });
    cardModelStore.remove(model);
  } catch (r3) {
    if (r3.status === 412) {
      errorDialog(
        _4("This type cannot be deleted"),
        _4("This type is being used. You cannot delete it.")
      );
    }
    throw r3;
  }
}
async function duplicateModel(model) {
  const newModel = await api_default.card_models.copy_model.post({ model_id: model.id });
  return cardModelStore.insert(newModel);
}
async function duplicateModelInProject(model, project) {
  const newModel = await api_default.project_models.copy_model.post({ project_id: project.id, model_id: model.id });
  return cardModelStore.insert(newModel);
}
async function shareModel(model) {
  try {
    await confirmDialog({
      text: _4("This type will be available for all workspaces in your team."),
      confirmButtonText: _4("Yes, share it")
    });
    model = await api_default.card_models.share_model.put({ model_id: model.id });
    return cardModelStore.update(model);
  } catch (r3) {
    if (r3) {
      return autoCatchAsRequestErrorDialog([412, 403])(r3);
    }
  }
}
async function makeModelPrivate(model, project) {
  try {
    model = await api_default.card_models.make_model_private.put({ model_id: model.id, project_id: project.id });
    return cardModelStore.update(model);
  } catch (r3) {
    return autoCatchAsRequestErrorDialog([412, 403])(r3);
  }
}
async function enableModelForProject(model, project) {
  model = await api_default.project_models.enable_model.put({ project_id: project.id, model_id: model.id });
  return cardModelStore.upsert(model);
}
async function disableOrDeleteModel(model, project) {
  const deleted = await api_default.project_models.disable_or_delete_model.delete({ project_id: project.id, model_id: model.id });
  if (deleted) {
    cardModelStore.remove(model);
  } else {
    cardModelStore.update(model, (model2) => {
      const idx = model2.used_by.indexOf(project.id);
      if (idx > -1) {
        model2 = { ...model2, used_by: removeIndex(model2.used_by, idx) };
      }
      return model2;
    });
  }
  cardStore.scopedByProject(project).updateManyMatching({ model_id: model.id }, { model_id: null });
  return deleted;
}
function getAttributesServiceForCard(project, model, attr) {
  if (attr) {
    model = cardModelStore.getAttributeOwner(attr);
  } else if (!model && project) {
    model = cardModelStore.getProjectModel(project);
  }
  const r3 = { model };
  if (model.base_model_id) {
    if (model.base_model_type === "project") {
      r3.service = api_default.projects;
      r3.params = { project_id: project.id };
    } else if (model.base_model_type === "top_level_card") {
      r3.service = api_default.organization_top_level_card_attrs;
      r3.params = { org_id: model.base_model_id };
    } else {
      r3.service = api_default.organizations;
      r3.params = { org_id: model.base_model_id };
    }
  } else {
    r3.service = api_default.card_models;
    r3.params = { model_id: model.id, project_id: project.id };
  }
  return r3;
}
async function createAttribute(project, _model, attr, position) {
  const { service, params, model } = getAttributesServiceForCard(project, _model);
  const attrs2 = await service.create_attributes.post(Object.assign(params, { attributes: [attr] }));
  if (position !== null && position !== void 0) {
    const existingAttributesIndex = cardModelStore.getExtendedModelAttributes(model, project).map((a3) => a3.id);
    const newAttr = attrs2.find((a3) => !existingAttributesIndex.includes(a3.id));
    return _moveAttribute(project, model, newAttr, true, attr.container, position);
  } else {
    const [newAttrs, existingAttrs] = cardModelStore.addAttributes(model, attrs2);
    return newAttrs[0];
  }
}
var onAttributeRenamed = createEvent();
async function updateAttribute(project, _model, attr, props2) {
  attr = Object.assign({}, attr, props2);
  const { service, params, model } = getAttributesServiceForCard(project, _model, attr);
  attr = await service.update_attribute.put(Object.assign(params, {
    attr_id: attr.id,
    name: attr.name,
    description: attr.description,
    default_value: attr.default_value,
    is_pii: attr.is_pii,
    options: attr.options
  }));
  if (attr.type === "group_type" && attr.group_type_id) {
    const gt = { ...cardGroupTypeStore.tryGet(attr.group_type_id) };
    if (gt) {
      gt.name = attr.name;
      gt.singular_name = attr.name;
      gt.plural_name = attr.name;
      gt.one_group_per_card = attr.options && !!attr.options.one_group_per_card;
      gt.auto_random_color = attr.options && !!attr.options.auto_random_color;
      cardGroupTypeStore.update(gt);
    }
  }
  const oldAttr = cardModelStore.getAttribute(attr.id);
  if (oldAttr.name !== attr.name) {
    onAttributeRenamed(attr.name, oldAttr.name);
  }
  return cardModelStore.updateAttribute(model, attr);
}
function updateModelAfterAttributesMove(project, model) {
  const models = cardModelStore.scopedByEnabled(project).query();
  if (models.length > 2 || (!model || model.base_model_id) && models.length > 1) {
    loadAllEnabledModelsForProject(project);
  }
}
async function _moveAttribute(project, _model, attr, isNewAttr, container, position) {
  const { service, params, model } = getAttributesServiceForCard(project, _model);
  const attrs2 = await service.move_attribute.post(Object.assign(params, { attr_id: attr.id, position, container }));
  cardModelStore.transaction(() => {
    if (isNewAttr) {
      const existingModelAttributesIndex = model.attributes.map((a3) => a3.id);
      const modelAttrs = attrs2.filter((a3) => existingModelAttributesIndex.includes(a3.id));
      const newAttr = attrs2.find((a3) => a3.id === attr.id);
      cardModelStore.addAttributes(model, modelAttrs.concat([newAttr]));
    } else {
      cardModelStore.updateAttributes(attrs2);
    }
    if (project) {
      updateModelAfterAttributesMove(project, model);
    }
  });
  return attrs2;
}
function moveAttribute(project, model, attr, container, position) {
  return _moveAttribute(project, model, attr, false, container, position);
}
async function removeAttribute(project, _model, attr) {
  const { service, params, model } = getAttributesServiceForCard(project, _model, attr);
  await service.delete_attribute.delete(Object.assign(params, { attr_id: attr.id }));
  cardModelStore.removeAttribute(model, attr);
}
async function changeAttributeOwner(project, _model, target, attr) {
  if (target !== null && target === _model || _model === null && target === project) {
    throw new Error("No change in owner");
  }
  const { service, params, model } = getAttributesServiceForCard(project, _model, attr);
  const _attr = await service.change_owner.post(Object.assign(params, {
    attr_id: attr.id,
    target_type: target === project ? "project" : "model",
    target_id: target.id
  }));
  cardModelStore.removeAttribute(model, attr);
  if (target === project) {
    target = cardModelStore.getProjectModel(project);
  }
  cardModelStore.addAttributes(target, [_attr]);
  return _attr;
}
async function updateAttrContainers(project, _model, _containers) {
  const { service, params, model } = getAttributesServiceForCard(project, _model);
  const { containers } = await service.update_attribute_containers.put(Object.assign(params, { containers: _containers }));
  cardModelStore.updateAttrContainers(model, containers);
}
async function renameAttrContainer(project, _model, oldName, newName) {
  const { service, params, model } = getAttributesServiceForCard(project, _model);
  const { attributes, containers } = await service.update_attribute_containers.put(
    Object.assign(params, { rename_container: [oldName, newName] })
  );
  cardModelStore.transaction(() => {
    cardModelStore.updateAttributes(attributes);
    updateModelAfterAttributesMove(project, model);
    cardModelStore.updateAttrContainers(model, containers);
  });
}
async function removeAttrContainer(project, _model, name2) {
  const { service, params, model } = getAttributesServiceForCard(project, _model);
  const { attributes, containers } = await service.update_attribute_containers.put(
    Object.assign(params, { remove_container: name2 })
  );
  cardModelStore.transaction(() => {
    cardModelStore.updateAttrContainers(model, containers);
    cardModelStore.updateAttributes(attributes);
    updateModelAfterAttributesMove(project, model);
  });
}

// public/app/attributes/attr-group/model.ts
var ModelAttributeGroup = class extends AttributeGroup {
  constructor(project, model, attributes) {
    super(attributes);
    this.project = project;
    this.model = model;
  }
  _emitResult(promise) {
    return promise.then((obj) => {
      this._emit(obj);
      return obj;
    });
  }
  create(obj, typeName2, container, position) {
    return createAttribute(
      this.project,
      this.model,
      this._createAttributeObject(typeName2, container),
      position
    );
  }
  update(attr, props2) {
    return updateAttribute(this.project, this.model, attr, props2);
  }
  changeOwner(attr, newOwner) {
    var oldOwner = !attr.model_is_base ? this.model : null;
    return changeAttributeOwner(this.project, oldOwner, newOwner, attr);
  }
  getPosition(attr) {
    if (attr.positions && this.project && typeof attr.positions[String(this.project.id)] !== "undefined") {
      return attr.positions[String(this.project.id)];
    }
    return [attr.container, null, null];
  }
  move(attr, position, container) {
    return moveAttribute(this.project, this.model, attr, container, position);
  }
  remove(attr) {
    return removeAttribute(this.project, this.model, attr);
  }
  fetchAsyncValue(obj, modelAttr) {
    return api_default.cards.get_attribute_value.get({
      card_id: obj.id,
      attr_id: modelAttr.id
    }, { ignoreErrorHandlers: true }).catch(() => null);
  }
  setObjAttribute(obj, attr, value2) {
    return this._emitResult(setCardAttribute(obj, attr.id, this.formatValueToServer(attr, value2)));
  }
  appendObjAttribute(obj, attr, value2) {
    return this._emitResult(appendCardAttribute(obj, attr.id, this.formatValueItemToServer(attr, value2)));
  }
  appendFilesObjAttribute(obj, attr, files, progressCallback, withErrorHandler) {
    return this._emitResult(appendFilesToCardAttribute(obj, attr.id, files, progressCallback, withErrorHandler));
  }
  popObjAttribute(obj, attr, value2) {
    return this._emitResult(popCardAttribute(obj, attr.id, this.formatValueItemToServer(attr, value2)));
  }
  clearObjAttribute(obj, attr) {
    return this._emitResult(clearCardAttribute(obj, attr.id));
  }
  getAttributeChoices(obj, attr) {
    return api_default.cards.list_attribute_choices.get({
      card_id: obj.id,
      attr_id: attr.id
    }, { ignoreErrorHandlers: true }).catch(() => []);
  }
  openEditor(obj, attr, element2, scope) {
    ngApp.$injector.get("attributeEditor").open(jquery_default(element2).get(0), scope, this.project, this, attr, obj);
  }
};

// public/app/attributes/attr-group/named.ts
var NamedAttributeGroup = class extends AttributeGroup {
  constructor(attributes, name2, label, model) {
    super(attributes);
    this.id = name2;
    this.name = name2;
    this.label = label;
    this.model = model;
  }
  get sanitizedName() {
    if (!this._sanitizedName) {
      this._sanitizedName = ngApp.$injector?.get("$sanitize")?.(this.name);
    }
    return this._sanitizedName;
  }
  get icon() {
    if (this.fromDifferentTypes) return "bi-intersect";
    if (typeof this[0].id === "string" || this[0].id < 0) return;
    return this.getType()?.icon;
  }
  get fromDifferentTypes() {
    return new Map(
      this.map((a3) => [`${a3.type}:${this.getMenuSectionForAttr(a3)}`, a3])
    ).size > 1;
  }
  /**
   * @returns attribute type object of attr, or a default one if NamedAttributeGroup contains more than one attribute
   */
  getType(forced = true, attr = null) {
    if (!attr && !forced && this.fromDifferentTypes) {
      return { name: "multiple", title: "From multiple type" };
    }
    return attributeTypeRegistry.get((attr || this[0]).type);
  }
  get visibleByDefault() {
    return this.some((a3) => this.getType(a3)?.visibleByDefault !== false);
  }
  /**
   * Get the menu section for the first attribute of NamedAttributeGroup
   */
  get menuSection() {
    return this.getMenuSectionForAttr(this[0]);
  }
  getMenuSectionForAttr(attr) {
    if (typeof attr.id === "string") {
      return "others";
    }
    if (attr.id < 0) {
      return "contexts";
    }
    return "fields";
  }
  getCardAvailableAttributes(card) {
    return this.filter((a3) => {
      if (a3.is_dynamic) return true;
      if (a3.auto_group_type_attribute)
        return cardGroupTypeStore.scopedByCards([card]).exists(a3.group_type_id);
      return cardModelStore.isAttributeAvailableForCard(card, a3);
    });
  }
  getFirstAvailableAttributes(card) {
    for (const a3 of this) {
      if (a3.is_dynamic || a3.auto_group_type_attribute && cardGroupTypeStore.scopedByCards([card]).exists(a3.group_type_id) || !a3.auto_group_type_attribute && cardModelStore.isAttributeAvailableForCard(card, a3)) {
        return a3;
      }
    }
  }
  /**
   * Find first editable attribute of attrs,
   * this attribute cannot be computed nor with no editable perm on it.
   * If possible, it will be a project attribute
   */
  findEditableAttribute(project) {
    let attr = this.find((attr2) => {
      return !attr2.is_computed && this.getAttrSource(attr2).type !== "model" && canEditAttribute(project, attr2);
    });
    if (!attr) {
      attr = this.find((attr2) => {
        return !attr2.is_computed && this.getAttrSource(attr2).type === "model" && canEditAttribute(project, attr2);
      });
    }
    return attr;
  }
  equals(namedAttributeGroup) {
    return this.id === namedAttributeGroup.id && equals(this, namedAttributeGroup);
  }
  getAttrSource(attr) {
    var project, groupType, model, owner, type;
    if (attr.auto_group_type_attribute) {
      type = "group_type";
      groupType = cardGroupTypeStore.tryGet(attr.group_type_id);
      if (groupType.is_project_specific) {
        project = projectStore.tryGet(groupType.used_by[0]);
        owner = (project || {}).owner;
      } else {
        owner = (projectStore.tryGet(
          groupType.used_by.find(function(projectId) {
            return projectStore.exists(projectId);
          })
        ) || {}).owner;
      }
    } else {
      model = cardModelStore.getAttributeOwner(attr);
      if (model) {
        if (model.base_model_type === "project") {
          type = "project";
          project = projectStore.tryGet(model.base_model_id);
          owner = (project || {}).owner;
          model = null;
        } else if (model.base_model_type === "org") {
          type = "org";
          owner = orgStore.tryGet(model.base_model_id);
          model = null;
        } else {
          type = "model";
          if (model.is_project_specific) {
            project = projectStore.tryGet(model.used_by[0]);
          }
          owner = model.owner;
        }
      } else {
        type = "other";
      }
    }
    return {
      type,
      group_type: groupType ? groupType.name : void 0,
      model: model ? model.name : void 0,
      project: project ? project.title : void 0,
      owner: owner ? owner.name : void 0
    };
  }
  /**
   * Get an attribute of the object by its id or name.
   *
   * Edge case:
   * If there are 2 attributes with the same name,
   * and the first one has no value while the second one has a value,
   * this method returns nothing because the first matching attribute will be used.
   */
  getObjAttribute(obj, attr) {
    return super.getObjAttribute(obj, attr);
  }
  getModels() {
    if (this.model) return [this.model];
    const models = /* @__PURE__ */ new Set();
    this.forEach((attr) => {
      const model = cardModelStore.getAttributeOwner(attr);
      if (model) models.add(model);
    });
    return [...models];
  }
};

// public/app/attributes/attr-group/options-widget.js
var OptionsWidgetAttributeGroup = class extends AttributeGroup {
  constructor(attributes, project) {
    super(attributes);
    this.project = project;
  }
  _emitResult(promise) {
    return promise.then((obj) => {
      this._emit(obj);
      return obj;
    });
  }
  appendFilesObjAttribute(obj, attr, files, progressCallback, withErrorHandler) {
    return this._emitResult(upload({
      url: api_default.project_files.upload_file.url({ project_id: this.project.id }),
      data: { files },
      arrayKey: ""
    }, progressCallback).then((resp) => {
      return Promise.all(resp.data.map((file) => this.appendObjAttribute(obj, attr, file)));
    }, (r3) => {
      if (withErrorHandler) {
        errorDialog(_("An error ocurred while uploading your file"));
      }
      throw r3;
    }));
  }
  getAttributeChoices(obj, attr) {
    return api_default.projects.get_attribute_choices.get({
      project_id: this.project.id,
      attr_id: attr.id
    }, { ignoreErrorHandlers: true }).catch(() => []);
  }
};

// public/app/ui/attributes/select-widget-utils.ts
function getSelectOptions(attribute2) {
  const attrType = attributeTypeRegistry.get(attribute2.type);
  const options2 = typeof attrType.getWidgetOptions !== "undefined" ? attrType.getWidgetOptions(attribute2) : attrType.widgetOptions;
  return Object.assign(
    {
      action: null,
      actionIcon: "fa-external-link",
      actionTooltip: "Open",
      useItemsAsValue: false
    },
    options2 || {}
  );
}
async function getSelectChoices(attributeGroup, attribute2, obj) {
  const options2 = getSelectOptions(attribute2);
  if (options2.useOptions) {
    return Promise.resolve(
      (attribute2?.options?.items || []).map((item) => [item, item])
    );
  } else if (options2.items) {
    return Promise.resolve(options2.items);
  } else {
    return attributeGroup.getAttributeChoices(obj, attribute2);
  }
}
function isSelected(options2, value2, item) {
  if (!value2) {
    return false;
  }
  const formattedValue = _formatAttributeValueAsSelectChoice(options2, value2);
  if (options2.multi) {
    return formattedValue.some((i3) => i3[0] == item);
  }
  return formattedValue[0] == item;
}
function _formatAttributeValueAsSelectChoice(options2, value2) {
  if (!value2) return [];
  if (!Array.isArray(value2)) {
    if (options2.multi) {
      return [[value2, value2]];
    }
    return [value2, value2];
  }
  if (!Array.isArray(value2[0])) {
    if (options2.multi) {
      if (options2.valueIsAlwayArray) {
        return [value2];
      } else {
        return value2.map((v3) => [v3, v3]);
      }
    }
    if (options2.valueIsAlwayArray) {
      return value2;
    } else {
      return [value2[0], value2[0]];
    }
  }
  if (options2.multi) {
    return value2;
  }
  return value2[0];
}
function formatAttributeValueAsSelectChoice(options2, value2, choices) {
  let attributeValue = _formatAttributeValueAsSelectChoice(options2, value2);
  if (!options2.useItemsAsValue) {
    return attributeValue;
  } else {
    if (!!options2.multi) {
      const returningValue = [];
      for (const val of attributeValue) {
        for (const choice of choices) {
          if (choice[0] === val[0]) {
            returningValue.push(choice);
            break;
          }
        }
      }
      return returningValue;
    } else {
      for (const choice of choices) {
        if (choice[0] === attributeValue[0]) {
          return choice;
        }
      }
      return [];
    }
  }
}

// public/app/attributes/choice.js
attributeTypeRegistry.register("choice", {
  title: _lazy("Multiple choice"),
  description: _lazy("Choose a value from a list of items"),
  icon: "list-ol",
  hidden: true,
  groupable: true,
  filterable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  availableFor: ["card", "form"],
  widgetDirective: "attribute-type-select",
  editorDirective: "attribute-type-select-editor",
  getWidgetOptions(modelAttr) {
    return {
      valueIsAlwayArray: true,
      useOptions: !modelAttr.is_from_integration,
      useItemsAsValue: modelAttr.is_from_integration,
      multi: !!modelAttr.options.multi
    };
  },
  getReprWidgets(obj, attr, modelAttr) {
    return attr.value.map((v3) => {
      return {
        type: "label",
        value: v3[1],
        tooltip: modelAttr.name
      };
    });
  },
  formatValueToServer(value2, modelAttr) {
    if (modelAttr.options.multi) {
      return value2.map(this.formatValueItemToServer);
    }
    return this.formatValueItemToServer(value2);
  },
  formatValueItemToServer(value2, modelAttr) {
    return value2[0];
  },
  fillCardGroupByStore(card, model, modelAttr, store2) {
    const project = projectStore.getForCard(card);
    const attrGroup = new ModelAttributeGroup(project, model, cardModelStore.getExtendedModelAttributes(model, project));
    getSelectChoices(attrGroup, modelAttr, card).then((items) => {
      for (let item of items) {
        createDynamicGroupForAttribute(
          store2,
          card,
          model,
          modelAttr,
          item[0],
          item[1],
          !!modelAttr.options.multi,
          false,
          (value2, attrValue) => attrValue.find((item2) => item2[0] === value2)
        );
      }
    });
  },
  isGroupByStoreAppendable(modelAttr) {
    return !!modelAttr.options.multi;
  },
  getFilters(project, attr, append2) {
    return [{
      label: _4("No value"),
      action: () => {
        append2("{" + attr.name + "}=empty");
      }
    }].concat((attr.options.items || []).map((item) => {
      return {
        label: item,
        action: () => {
          append2("{" + attr.name + '}="' + item + '"');
        }
      };
    }));
  }
});

// node_modules/marked/lib/marked.esm.js
function getDefaults() {
  return {
    async: false,
    baseUrl: null,
    breaks: false,
    extensions: null,
    gfm: true,
    headerIds: true,
    headerPrefix: "",
    highlight: null,
    langPrefix: "language-",
    mangle: true,
    pedantic: false,
    renderer: null,
    sanitize: false,
    sanitizer: null,
    silent: false,
    smartLists: false,
    smartypants: false,
    tokenizer: null,
    walkTokens: null,
    xhtml: false
  };
}
var defaults2 = getDefaults();
function changeDefaults(newDefaults) {
  defaults2 = newDefaults;
}
var escapeTest = /[&<>"']/;
var escapeReplace = /[&<>"']/g;
var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
var escapeReplacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
var getEscapeReplacement = (ch) => escapeReplacements[ch];
function escape(html5, encode3) {
  if (encode3) {
    if (escapeTest.test(html5)) {
      return html5.replace(escapeReplace, getEscapeReplacement);
    }
  } else {
    if (escapeTestNoEncode.test(html5)) {
      return html5.replace(escapeReplaceNoEncode, getEscapeReplacement);
    }
  }
  return html5;
}
var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function unescape(html5) {
  return html5.replace(unescapeTest, (_5, n4) => {
    n4 = n4.toLowerCase();
    if (n4 === "colon") return ":";
    if (n4.charAt(0) === "#") {
      return n4.charAt(1) === "x" ? String.fromCharCode(parseInt(n4.substring(2), 16)) : String.fromCharCode(+n4.substring(1));
    }
    return "";
  });
}
var caret = /(^|[^\[])\^/g;
function edit(regex, opt) {
  regex = typeof regex === "string" ? regex : regex.source;
  opt = opt || "";
  const obj = {
    replace: (name2, val) => {
      val = val.source || val;
      val = val.replace(caret, "$1");
      regex = regex.replace(name2, val);
      return obj;
    },
    getRegex: () => {
      return new RegExp(regex, opt);
    }
  };
  return obj;
}
var nonWordAndColonTest = /[^\w:]/g;
var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
function cleanUrl(sanitize, base3, href) {
  if (sanitize) {
    let prot;
    try {
      prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, "").toLowerCase();
    } catch (e3) {
      return null;
    }
    if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) {
      return null;
    }
  }
  if (base3 && !originIndependentUrl.test(href)) {
    href = resolveUrl(base3, href);
  }
  try {
    href = encodeURI(href).replace(/%25/g, "%");
  } catch (e3) {
    return null;
  }
  return href;
}
var baseUrls = {};
var justDomain = /^[^:]+:\/*[^/]*$/;
var protocol = /^([^:]+:)[\s\S]*$/;
var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
function resolveUrl(base3, href) {
  if (!baseUrls[" " + base3]) {
    if (justDomain.test(base3)) {
      baseUrls[" " + base3] = base3 + "/";
    } else {
      baseUrls[" " + base3] = rtrim(base3, "/", true);
    }
  }
  base3 = baseUrls[" " + base3];
  const relativeBase = base3.indexOf(":") === -1;
  if (href.substring(0, 2) === "//") {
    if (relativeBase) {
      return href;
    }
    return base3.replace(protocol, "$1") + href;
  } else if (href.charAt(0) === "/") {
    if (relativeBase) {
      return href;
    }
    return base3.replace(domain, "$1") + href;
  } else {
    return base3 + href;
  }
}
var noopTest = { exec: function noopTest2() {
} };
function merge(obj) {
  let i3 = 1, target, key2;
  for (; i3 < arguments.length; i3++) {
    target = arguments[i3];
    for (key2 in target) {
      if (Object.prototype.hasOwnProperty.call(target, key2)) {
        obj[key2] = target[key2];
      }
    }
  }
  return obj;
}
function splitCells(tableRow, count) {
  const row = tableRow.replace(/\|/g, (match2, offset, str) => {
    let escaped = false, curr = offset;
    while (--curr >= 0 && str[curr] === "\\") escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells2 = row.split(/ \|/);
  let i3 = 0;
  if (!cells2[0].trim()) {
    cells2.shift();
  }
  if (cells2.length > 0 && !cells2[cells2.length - 1].trim()) {
    cells2.pop();
  }
  if (cells2.length > count) {
    cells2.splice(count);
  } else {
    while (cells2.length < count) cells2.push("");
  }
  for (; i3 < cells2.length; i3++) {
    cells2[i3] = cells2[i3].trim().replace(/\\\|/g, "|");
  }
  return cells2;
}
function rtrim(str, c3, invert2) {
  const l3 = str.length;
  if (l3 === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l3) {
    const currChar = str.charAt(l3 - suffLen - 1);
    if (currChar === c3 && !invert2) {
      suffLen++;
    } else if (currChar !== c3 && invert2) {
      suffLen++;
    } else {
      break;
    }
  }
  return str.slice(0, l3 - suffLen);
}
function findClosingBracket(str, b3) {
  if (str.indexOf(b3[1]) === -1) {
    return -1;
  }
  const l3 = str.length;
  let level = 0, i3 = 0;
  for (; i3 < l3; i3++) {
    if (str[i3] === "\\") {
      i3++;
    } else if (str[i3] === b3[0]) {
      level++;
    } else if (str[i3] === b3[1]) {
      level--;
      if (level < 0) {
        return i3;
      }
    }
  }
  return -1;
}
function checkSanitizeDeprecation(opt) {
  if (opt && opt.sanitize && !opt.silent) {
    console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options");
  }
}
function repeatString(pattern2, count) {
  if (count < 1) {
    return "";
  }
  let result2 = "";
  while (count > 1) {
    if (count & 1) {
      result2 += pattern2;
    }
    count >>= 1;
    pattern2 += pattern2;
  }
  return result2 + pattern2;
}
function outputLink(cap2, link2, raw2, lexer2) {
  const href = link2.href;
  const title = link2.title ? escape(link2.title) : null;
  const text3 = cap2[1].replace(/\\([\[\]])/g, "$1");
  if (cap2[0].charAt(0) !== "!") {
    lexer2.state.inLink = true;
    const token = {
      type: "link",
      raw: raw2,
      href,
      title,
      text: text3,
      tokens: lexer2.inlineTokens(text3)
    };
    lexer2.state.inLink = false;
    return token;
  }
  return {
    type: "image",
    raw: raw2,
    href,
    title,
    text: escape(text3)
  };
}
function indentCodeCompensation(raw2, text3) {
  const matchIndentToCode = raw2.match(/^(\s+)(?:```)/);
  if (matchIndentToCode === null) {
    return text3;
  }
  const indentToCode = matchIndentToCode[1];
  return text3.split("\n").map((node) => {
    const matchIndentInNode = node.match(/^\s+/);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
var Tokenizer = class {
  constructor(options2) {
    this.options = options2 || defaults2;
  }
  space(src) {
    const cap2 = this.rules.block.newline.exec(src);
    if (cap2 && cap2[0].length > 0) {
      return {
        type: "space",
        raw: cap2[0]
      };
    }
  }
  code(src) {
    const cap2 = this.rules.block.code.exec(src);
    if (cap2) {
      const text3 = cap2[0].replace(/^ {1,4}/gm, "");
      return {
        type: "code",
        raw: cap2[0],
        codeBlockStyle: "indented",
        text: !this.options.pedantic ? rtrim(text3, "\n") : text3
      };
    }
  }
  fences(src) {
    const cap2 = this.rules.block.fences.exec(src);
    if (cap2) {
      const raw2 = cap2[0];
      const text3 = indentCodeCompensation(raw2, cap2[3] || "");
      return {
        type: "code",
        raw: raw2,
        lang: cap2[2] ? cap2[2].trim() : cap2[2],
        text: text3
      };
    }
  }
  heading(src) {
    const cap2 = this.rules.block.heading.exec(src);
    if (cap2) {
      let text3 = cap2[2].trim();
      if (/#$/.test(text3)) {
        const trimmed = rtrim(text3, "#");
        if (this.options.pedantic) {
          text3 = trimmed.trim();
        } else if (!trimmed || / $/.test(trimmed)) {
          text3 = trimmed.trim();
        }
      }
      return {
        type: "heading",
        raw: cap2[0],
        depth: cap2[1].length,
        text: text3,
        tokens: this.lexer.inline(text3)
      };
    }
  }
  hr(src) {
    const cap2 = this.rules.block.hr.exec(src);
    if (cap2) {
      return {
        type: "hr",
        raw: cap2[0]
      };
    }
  }
  blockquote(src) {
    const cap2 = this.rules.block.blockquote.exec(src);
    if (cap2) {
      const text3 = cap2[0].replace(/^ *>[ \t]?/gm, "");
      return {
        type: "blockquote",
        raw: cap2[0],
        tokens: this.lexer.blockTokens(text3, []),
        text: text3
      };
    }
  }
  list(src) {
    let cap2 = this.rules.block.list.exec(src);
    if (cap2) {
      let raw2, istask, ischecked, indent, i3, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly;
      let bull = cap2[1].trim();
      const isordered = bull.length > 1;
      const list2 = {
        type: "list",
        raw: "",
        ordered: isordered,
        start: isordered ? +bull.slice(0, -1) : "",
        loose: false,
        items: []
      };
      bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
      if (this.options.pedantic) {
        bull = isordered ? bull : "[*+-]";
      }
      const itemRegex = new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`);
      while (src) {
        endEarly = false;
        if (!(cap2 = itemRegex.exec(src))) {
          break;
        }
        if (this.rules.block.hr.test(src)) {
          break;
        }
        raw2 = cap2[0];
        src = src.substring(raw2.length);
        line = cap2[2].split("\n", 1)[0];
        nextLine = src.split("\n", 1)[0];
        if (this.options.pedantic) {
          indent = 2;
          itemContents = line.trimLeft();
        } else {
          indent = cap2[2].search(/[^ ]/);
          indent = indent > 4 ? 1 : indent;
          itemContents = line.slice(indent);
          indent += cap2[1].length;
        }
        blankLine = false;
        if (!line && /^ *$/.test(nextLine)) {
          raw2 += nextLine + "\n";
          src = src.substring(nextLine.length + 1);
          endEarly = true;
        }
        if (!endEarly) {
          const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?: [^\\n]*)?(?:\\n|$))`);
          const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
          const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
          const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
          while (src) {
            rawLine = src.split("\n", 1)[0];
            line = rawLine;
            if (this.options.pedantic) {
              line = line.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
            }
            if (fencesBeginRegex.test(line)) {
              break;
            }
            if (headingBeginRegex.test(line)) {
              break;
            }
            if (nextBulletRegex.test(line)) {
              break;
            }
            if (hrRegex.test(src)) {
              break;
            }
            if (line.search(/[^ ]/) >= indent || !line.trim()) {
              itemContents += "\n" + line.slice(indent);
            } else if (!blankLine) {
              itemContents += "\n" + line;
            } else {
              break;
            }
            if (!blankLine && !line.trim()) {
              blankLine = true;
            }
            raw2 += rawLine + "\n";
            src = src.substring(rawLine.length + 1);
          }
        }
        if (!list2.loose) {
          if (endsWithBlankLine) {
            list2.loose = true;
          } else if (/\n *\n *$/.test(raw2)) {
            endsWithBlankLine = true;
          }
        }
        if (this.options.gfm) {
          istask = /^\[[ xX]\] /.exec(itemContents);
          if (istask) {
            ischecked = istask[0] !== "[ ] ";
            itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
          }
        }
        list2.items.push({
          type: "list_item",
          raw: raw2,
          task: !!istask,
          checked: ischecked,
          loose: false,
          text: itemContents
        });
        list2.raw += raw2;
      }
      list2.items[list2.items.length - 1].raw = raw2.trimRight();
      list2.items[list2.items.length - 1].text = itemContents.trimRight();
      list2.raw = list2.raw.trimRight();
      const l3 = list2.items.length;
      for (i3 = 0; i3 < l3; i3++) {
        this.lexer.state.top = false;
        list2.items[i3].tokens = this.lexer.blockTokens(list2.items[i3].text, []);
        const spacers = list2.items[i3].tokens.filter((t3) => t3.type === "space");
        const hasMultipleLineBreaks = spacers.every((t3) => {
          const chars = t3.raw.split("");
          let lineBreaks = 0;
          for (const char of chars) {
            if (char === "\n") {
              lineBreaks += 1;
            }
            if (lineBreaks > 1) {
              return true;
            }
          }
          return false;
        });
        if (!list2.loose && spacers.length && hasMultipleLineBreaks) {
          list2.loose = true;
          list2.items[i3].loose = true;
        }
      }
      return list2;
    }
  }
  html(src) {
    const cap2 = this.rules.block.html.exec(src);
    if (cap2) {
      const token = {
        type: "html",
        raw: cap2[0],
        pre: !this.options.sanitizer && (cap2[1] === "pre" || cap2[1] === "script" || cap2[1] === "style"),
        text: cap2[0]
      };
      if (this.options.sanitize) {
        const text3 = this.options.sanitizer ? this.options.sanitizer(cap2[0]) : escape(cap2[0]);
        token.type = "paragraph";
        token.text = text3;
        token.tokens = this.lexer.inline(text3);
      }
      return token;
    }
  }
  def(src) {
    const cap2 = this.rules.block.def.exec(src);
    if (cap2) {
      if (cap2[3]) cap2[3] = cap2[3].substring(1, cap2[3].length - 1);
      const tag = cap2[1].toLowerCase().replace(/\s+/g, " ");
      return {
        type: "def",
        tag,
        raw: cap2[0],
        href: cap2[2],
        title: cap2[3]
      };
    }
  }
  table(src) {
    const cap2 = this.rules.block.table.exec(src);
    if (cap2) {
      const item = {
        type: "table",
        header: splitCells(cap2[1]).map((c3) => {
          return { text: c3 };
        }),
        align: cap2[2].replace(/^ *|\| *$/g, "").split(/ *\| */),
        rows: cap2[3] && cap2[3].trim() ? cap2[3].replace(/\n[ \t]*$/, "").split("\n") : []
      };
      if (item.header.length === item.align.length) {
        item.raw = cap2[0];
        let l3 = item.align.length;
        let i3, j, k2, row;
        for (i3 = 0; i3 < l3; i3++) {
          if (/^ *-+: *$/.test(item.align[i3])) {
            item.align[i3] = "right";
          } else if (/^ *:-+: *$/.test(item.align[i3])) {
            item.align[i3] = "center";
          } else if (/^ *:-+ *$/.test(item.align[i3])) {
            item.align[i3] = "left";
          } else {
            item.align[i3] = null;
          }
        }
        l3 = item.rows.length;
        for (i3 = 0; i3 < l3; i3++) {
          item.rows[i3] = splitCells(item.rows[i3], item.header.length).map((c3) => {
            return { text: c3 };
          });
        }
        l3 = item.header.length;
        for (j = 0; j < l3; j++) {
          item.header[j].tokens = this.lexer.inline(item.header[j].text);
        }
        l3 = item.rows.length;
        for (j = 0; j < l3; j++) {
          row = item.rows[j];
          for (k2 = 0; k2 < row.length; k2++) {
            row[k2].tokens = this.lexer.inline(row[k2].text);
          }
        }
        return item;
      }
    }
  }
  lheading(src) {
    const cap2 = this.rules.block.lheading.exec(src);
    if (cap2) {
      return {
        type: "heading",
        raw: cap2[0],
        depth: cap2[2].charAt(0) === "=" ? 1 : 2,
        text: cap2[1],
        tokens: this.lexer.inline(cap2[1])
      };
    }
  }
  paragraph(src) {
    const cap2 = this.rules.block.paragraph.exec(src);
    if (cap2) {
      const text3 = cap2[1].charAt(cap2[1].length - 1) === "\n" ? cap2[1].slice(0, -1) : cap2[1];
      return {
        type: "paragraph",
        raw: cap2[0],
        text: text3,
        tokens: this.lexer.inline(text3)
      };
    }
  }
  text(src) {
    const cap2 = this.rules.block.text.exec(src);
    if (cap2) {
      return {
        type: "text",
        raw: cap2[0],
        text: cap2[0],
        tokens: this.lexer.inline(cap2[0])
      };
    }
  }
  escape(src) {
    const cap2 = this.rules.inline.escape.exec(src);
    if (cap2) {
      return {
        type: "escape",
        raw: cap2[0],
        text: escape(cap2[1])
      };
    }
  }
  tag(src) {
    const cap2 = this.rules.inline.tag.exec(src);
    if (cap2) {
      if (!this.lexer.state.inLink && /^<a /i.test(cap2[0])) {
        this.lexer.state.inLink = true;
      } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap2[0])) {
        this.lexer.state.inLink = false;
      }
      if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap2[0])) {
        this.lexer.state.inRawBlock = true;
      } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap2[0])) {
        this.lexer.state.inRawBlock = false;
      }
      return {
        type: this.options.sanitize ? "text" : "html",
        raw: cap2[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap2[0]) : escape(cap2[0]) : cap2[0]
      };
    }
  }
  link(src) {
    const cap2 = this.rules.inline.link.exec(src);
    if (cap2) {
      const trimmedUrl = cap2[2].trim();
      if (!this.options.pedantic && /^</.test(trimmedUrl)) {
        if (!/>$/.test(trimmedUrl)) {
          return;
        }
        const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
        if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
          return;
        }
      } else {
        const lastParenIndex = findClosingBracket(cap2[2], "()");
        if (lastParenIndex > -1) {
          const start = cap2[0].indexOf("!") === 0 ? 5 : 4;
          const linkLen = start + cap2[1].length + lastParenIndex;
          cap2[2] = cap2[2].substring(0, lastParenIndex);
          cap2[0] = cap2[0].substring(0, linkLen).trim();
          cap2[3] = "";
        }
      }
      let href = cap2[2];
      let title = "";
      if (this.options.pedantic) {
        const link2 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
        if (link2) {
          href = link2[1];
          title = link2[3];
        }
      } else {
        title = cap2[3] ? cap2[3].slice(1, -1) : "";
      }
      href = href.trim();
      if (/^</.test(href)) {
        if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
          href = href.slice(1);
        } else {
          href = href.slice(1, -1);
        }
      }
      return outputLink(cap2, {
        href: href ? href.replace(this.rules.inline._escapes, "$1") : href,
        title: title ? title.replace(this.rules.inline._escapes, "$1") : title
      }, cap2[0], this.lexer);
    }
  }
  reflink(src, links) {
    let cap2;
    if ((cap2 = this.rules.inline.reflink.exec(src)) || (cap2 = this.rules.inline.nolink.exec(src))) {
      let link2 = (cap2[2] || cap2[1]).replace(/\s+/g, " ");
      link2 = links[link2.toLowerCase()];
      if (!link2 || !link2.href) {
        const text3 = cap2[0].charAt(0);
        return {
          type: "text",
          raw: text3,
          text: text3
        };
      }
      return outputLink(cap2, link2, cap2[0], this.lexer);
    }
  }
  emStrong(src, maskedSrc, prevChar2 = "") {
    let match2 = this.rules.inline.emStrong.lDelim.exec(src);
    if (!match2) return;
    if (match2[3] && prevChar2.match(/[\p{L}\p{N}]/u)) return;
    const nextChar2 = match2[1] || match2[2] || "";
    if (!nextChar2 || nextChar2 && (prevChar2 === "" || this.rules.inline.punctuation.exec(prevChar2))) {
      const lLength = match2[0].length - 1;
      let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
      const endReg = match2[0][0] === "*" ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
      endReg.lastIndex = 0;
      maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
      while ((match2 = endReg.exec(maskedSrc)) != null) {
        rDelim = match2[1] || match2[2] || match2[3] || match2[4] || match2[5] || match2[6];
        if (!rDelim) continue;
        rLength = rDelim.length;
        if (match2[3] || match2[4]) {
          delimTotal += rLength;
          continue;
        } else if (match2[5] || match2[6]) {
          if (lLength % 3 && !((lLength + rLength) % 3)) {
            midDelimTotal += rLength;
            continue;
          }
        }
        delimTotal -= rLength;
        if (delimTotal > 0) continue;
        rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
        if (Math.min(lLength, rLength) % 2) {
          const text4 = src.slice(1, lLength + match2.index + rLength);
          return {
            type: "em",
            raw: src.slice(0, lLength + match2.index + rLength + 1),
            text: text4,
            tokens: this.lexer.inlineTokens(text4)
          };
        }
        const text3 = src.slice(2, lLength + match2.index + rLength - 1);
        return {
          type: "strong",
          raw: src.slice(0, lLength + match2.index + rLength + 1),
          text: text3,
          tokens: this.lexer.inlineTokens(text3)
        };
      }
    }
  }
  codespan(src) {
    const cap2 = this.rules.inline.code.exec(src);
    if (cap2) {
      let text3 = cap2[2].replace(/\n/g, " ");
      const hasNonSpaceChars = /[^ ]/.test(text3);
      const hasSpaceCharsOnBothEnds = /^ /.test(text3) && / $/.test(text3);
      if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
        text3 = text3.substring(1, text3.length - 1);
      }
      text3 = escape(text3, true);
      return {
        type: "codespan",
        raw: cap2[0],
        text: text3
      };
    }
  }
  br(src) {
    const cap2 = this.rules.inline.br.exec(src);
    if (cap2) {
      return {
        type: "br",
        raw: cap2[0]
      };
    }
  }
  del(src) {
    const cap2 = this.rules.inline.del.exec(src);
    if (cap2) {
      return {
        type: "del",
        raw: cap2[0],
        text: cap2[2],
        tokens: this.lexer.inlineTokens(cap2[2])
      };
    }
  }
  autolink(src, mangle2) {
    const cap2 = this.rules.inline.autolink.exec(src);
    if (cap2) {
      let text3, href;
      if (cap2[2] === "@") {
        text3 = escape(this.options.mangle ? mangle2(cap2[1]) : cap2[1]);
        href = "mailto:" + text3;
      } else {
        text3 = escape(cap2[1]);
        href = text3;
      }
      return {
        type: "link",
        raw: cap2[0],
        text: text3,
        href,
        tokens: [
          {
            type: "text",
            raw: text3,
            text: text3
          }
        ]
      };
    }
  }
  url(src, mangle2) {
    let cap2;
    if (cap2 = this.rules.inline.url.exec(src)) {
      let text3, href;
      if (cap2[2] === "@") {
        text3 = escape(this.options.mangle ? mangle2(cap2[0]) : cap2[0]);
        href = "mailto:" + text3;
      } else {
        let prevCapZero;
        do {
          prevCapZero = cap2[0];
          cap2[0] = this.rules.inline._backpedal.exec(cap2[0])[0];
        } while (prevCapZero !== cap2[0]);
        text3 = escape(cap2[0]);
        if (cap2[1] === "www.") {
          href = "http://" + text3;
        } else {
          href = text3;
        }
      }
      return {
        type: "link",
        raw: cap2[0],
        text: text3,
        href,
        tokens: [
          {
            type: "text",
            raw: text3,
            text: text3
          }
        ]
      };
    }
  }
  inlineText(src, smartypants2) {
    const cap2 = this.rules.inline.text.exec(src);
    if (cap2) {
      let text3;
      if (this.lexer.state.inRawBlock) {
        text3 = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap2[0]) : escape(cap2[0]) : cap2[0];
      } else {
        text3 = escape(this.options.smartypants ? smartypants2(cap2[0]) : cap2[0]);
      }
      return {
        type: "text",
        raw: cap2[0],
        text: text3
      };
    }
  }
};
var block = {
  newline: /^(?: *(?:\n|$))+/,
  code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
  fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
  hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
  heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
  blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
  list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
  html: "^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",
  def: /^ {0,3}\[(label)\]: *(?:\n *)?<?([^\s>]+)>?(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
  table: noopTest,
  lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
  // regex template, placeholders will be replaced according to different paragraph
  // interruption rules of commonmark and the original markdown spec:
  _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
  text: /^[^\n]+/
};
block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
block.def = edit(block.def).replace("label", block._label).replace("title", block._title).getRegex();
block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
block.listItemStart = edit(/^( *)(bull) */).replace("bull", block.bullet).getRegex();
block.list = edit(block.list).replace(/bull/g, block.bullet).replace("hr", "\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def", "\\n+(?=" + block.def.source + ")").getRegex();
block._tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
block.html = edit(block.html, "i").replace("comment", block._comment).replace("tag", block._tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
block.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex();
block.blockquote = edit(block.blockquote).replace("paragraph", block.paragraph).getRegex();
block.normal = merge({}, block);
block.gfm = merge({}, block.normal, {
  table: "^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"
  // Cells
});
block.gfm.table = edit(block.gfm.table).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex();
block.gfm.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("table", block.gfm.table).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex();
block.pedantic = merge({}, block.normal, {
  html: edit(
    `^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`
  ).replace("comment", block._comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  heading: /^(#{1,6})(.*)(?:\n+|$)/,
  fences: noopTest,
  // fences not supported
  paragraph: edit(block.normal._paragraph).replace("hr", block.hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", block.lheading).replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").getRegex()
});
var inline = {
  escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
  autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
  url: noopTest,
  tag: "^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",
  // CDATA section
  link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
  reflink: /^!?\[(label)\]\[(ref)\]/,
  nolink: /^!?\[(ref)\](?:\[\])?/,
  reflinkSearch: "reflink|nolink(?!\\()",
  emStrong: {
    lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,
    //        (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left.  (5) and (6) can be either Left or Right.
    //          () Skip orphan inside strong  () Consume to delim (1) #***                (2) a***#, a***                   (3) #***a, ***a                 (4) ***#              (5) #***#                 (6) a***a
    rDelimAst: /^[^_*]*?\_\_[^_*]*?\*[^_*]*?(?=\_\_)|[^*]+(?=[^*])|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,
    rDelimUnd: /^[^_*]*?\*\*[^_*]*?\_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/
    // ^- Not allowed for _
  },
  code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
  br: /^( {2,}|\\)\n(?!\s*$)/,
  del: noopTest,
  text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
  punctuation: /^([\spunctuation])/
};
inline._punctuation = "!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~";
inline.punctuation = edit(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex();
inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;
inline.escapedEmSt = /\\\*|\\_/g;
inline._comment = edit(block._comment).replace("(?:-->|$)", "-->").getRegex();
inline.emStrong.lDelim = edit(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex();
inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, "g").replace(/punct/g, inline._punctuation).getRegex();
inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, "g").replace(/punct/g, inline._punctuation).getRegex();
inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
inline.autolink = edit(inline.autolink).replace("scheme", inline._scheme).replace("email", inline._email).getRegex();
inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
inline.tag = edit(inline.tag).replace("comment", inline._comment).replace("attribute", inline._attribute).getRegex();
inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
inline.link = edit(inline.link).replace("label", inline._label).replace("href", inline._href).replace("title", inline._title).getRegex();
inline.reflink = edit(inline.reflink).replace("label", inline._label).replace("ref", block._label).getRegex();
inline.nolink = edit(inline.nolink).replace("ref", block._label).getRegex();
inline.reflinkSearch = edit(inline.reflinkSearch, "g").replace("reflink", inline.reflink).replace("nolink", inline.nolink).getRegex();
inline.normal = merge({}, inline);
inline.pedantic = merge({}, inline.normal, {
  strong: {
    start: /^__|\*\*/,
    middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
    endAst: /\*\*(?!\*)/g,
    endUnd: /__(?!_)/g
  },
  em: {
    start: /^_|\*/,
    middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
    endAst: /\*(?!\*)/g,
    endUnd: /_(?!_)/g
  },
  link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", inline._label).getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", inline._label).getRegex()
});
inline.gfm = merge({}, inline.normal, {
  escape: edit(inline.escape).replace("])", "~|])").getRegex(),
  _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
  url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
  _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
  del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
  text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
});
inline.gfm.url = edit(inline.gfm.url, "i").replace("email", inline.gfm._extended_email).getRegex();
inline.breaks = merge({}, inline.gfm, {
  br: edit(inline.br).replace("{2,}", "*").getRegex(),
  text: edit(inline.gfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
});
function smartypants(text3) {
  return text3.replace(/---/g, "\u2014").replace(/--/g, "\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018").replace(/'/g, "\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C").replace(/"/g, "\u201D").replace(/\.{3}/g, "\u2026");
}
function mangle(text3) {
  let out = "", i3, ch;
  const l3 = text3.length;
  for (i3 = 0; i3 < l3; i3++) {
    ch = text3.charCodeAt(i3);
    if (Math.random() > 0.5) {
      ch = "x" + ch.toString(16);
    }
    out += "&#" + ch + ";";
  }
  return out;
}
var Lexer = class _Lexer {
  constructor(options2) {
    this.tokens = [];
    this.tokens.links = /* @__PURE__ */ Object.create(null);
    this.options = options2 || defaults2;
    this.options.tokenizer = this.options.tokenizer || new Tokenizer();
    this.tokenizer = this.options.tokenizer;
    this.tokenizer.options = this.options;
    this.tokenizer.lexer = this;
    this.inlineQueue = [];
    this.state = {
      inLink: false,
      inRawBlock: false,
      top: true
    };
    const rules = {
      block: block.normal,
      inline: inline.normal
    };
    if (this.options.pedantic) {
      rules.block = block.pedantic;
      rules.inline = inline.pedantic;
    } else if (this.options.gfm) {
      rules.block = block.gfm;
      if (this.options.breaks) {
        rules.inline = inline.breaks;
      } else {
        rules.inline = inline.gfm;
      }
    }
    this.tokenizer.rules = rules;
  }
  /**
   * Expose Rules
   */
  static get rules() {
    return {
      block,
      inline
    };
  }
  /**
   * Static Lex Method
   */
  static lex(src, options2) {
    const lexer2 = new _Lexer(options2);
    return lexer2.lex(src);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(src, options2) {
    const lexer2 = new _Lexer(options2);
    return lexer2.inlineTokens(src);
  }
  /**
   * Preprocessing
   */
  lex(src) {
    src = src.replace(/\r\n|\r/g, "\n");
    this.blockTokens(src, this.tokens);
    let next2;
    while (next2 = this.inlineQueue.shift()) {
      this.inlineTokens(next2.src, next2.tokens);
    }
    return this.tokens;
  }
  /**
   * Lexing
   */
  blockTokens(src, tokens = []) {
    if (this.options.pedantic) {
      src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
    } else {
      src = src.replace(/^( *)(\t+)/gm, (_5, leading, tabs) => {
        return leading + "    ".repeat(tabs.length);
      });
    }
    let token, lastToken, cutSrc, lastParagraphClipped;
    while (src) {
      if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.space(src)) {
        src = src.substring(token.raw.length);
        if (token.raw.length === 1 && tokens.length > 0) {
          tokens[tokens.length - 1].raw += "\n";
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.code(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.fences(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.heading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.hr(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.blockquote(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.list(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.html(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.def(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.raw;
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else if (!this.tokens.links[token.tag]) {
          this.tokens.links[token.tag] = {
            href: token.href,
            title: token.title
          };
        }
        continue;
      }
      if (token = this.tokenizer.table(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.lheading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startBlock) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startBlock.forEach(function(getStartIndex) {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
        lastToken = tokens[tokens.length - 1];
        if (lastParagraphClipped && lastToken.type === "paragraph") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        lastParagraphClipped = cutSrc.length !== src.length;
        src = src.substring(token.raw.length);
        continue;
      }
      if (token = this.tokenizer.text(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    this.state.top = true;
    return tokens;
  }
  inline(src, tokens = []) {
    this.inlineQueue.push({ src, tokens });
    return tokens;
  }
  /**
   * Lexing/Compiling
   */
  inlineTokens(src, tokens = []) {
    let token, lastToken, cutSrc;
    let maskedSrc = src;
    let match2;
    let keepPrevChar, prevChar2;
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match2 = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match2[0].slice(match2[0].lastIndexOf("[") + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match2.index) + "[" + repeatString("a", match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    while ((match2 = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match2.index) + "[" + repeatString("a", match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }
    while ((match2 = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match2.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);
    }
    while (src) {
      if (!keepPrevChar) {
        prevChar2 = "";
      }
      keepPrevChar = false;
      if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.escape(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.tag(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.link(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.reflink(src, this.tokens.links)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar2)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.codespan(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.br(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.del(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.autolink(src, mangle)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startInline) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startInline.forEach(function(getStartIndex) {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (token = this.tokenizer.inlineText(cutSrc, smartypants)) {
        src = src.substring(token.raw.length);
        if (token.raw.slice(-1) !== "_") {
          prevChar2 = token.raw.slice(-1);
        }
        keepPrevChar = true;
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    return tokens;
  }
};
var Renderer = class {
  constructor(options2) {
    this.options = options2 || defaults2;
  }
  code(code2, infostring, escaped) {
    const lang2 = (infostring || "").match(/\S*/)[0];
    if (this.options.highlight) {
      const out = this.options.highlight(code2, lang2);
      if (out != null && out !== code2) {
        escaped = true;
        code2 = out;
      }
    }
    code2 = code2.replace(/\n$/, "") + "\n";
    if (!lang2) {
      return "<pre><code>" + (escaped ? code2 : escape(code2, true)) + "</code></pre>\n";
    }
    return '<pre><code class="' + this.options.langPrefix + escape(lang2, true) + '">' + (escaped ? code2 : escape(code2, true)) + "</code></pre>\n";
  }
  /**
   * @param {string} quote
   */
  blockquote(quote) {
    return `<blockquote>
${quote}</blockquote>
`;
  }
  html(html5) {
    return html5;
  }
  /**
   * @param {string} text
   * @param {string} level
   * @param {string} raw
   * @param {any} slugger
   */
  heading(text3, level, raw2, slugger) {
    if (this.options.headerIds) {
      const id = this.options.headerPrefix + slugger.slug(raw2);
      return `<h${level} id="${id}">${text3}</h${level}>
`;
    }
    return `<h${level}>${text3}</h${level}>
`;
  }
  hr() {
    return this.options.xhtml ? "<hr/>\n" : "<hr>\n";
  }
  list(body3, ordered, start) {
    const type = ordered ? "ol" : "ul", startatt = ordered && start !== 1 ? ' start="' + start + '"' : "";
    return "<" + type + startatt + ">\n" + body3 + "</" + type + ">\n";
  }
  /**
   * @param {string} text
   */
  listitem(text3) {
    return `<li>${text3}</li>
`;
  }
  checkbox(checked) {
    return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox"' + (this.options.xhtml ? " /" : "") + "> ";
  }
  /**
   * @param {string} text
   */
  paragraph(text3) {
    return `<p>${text3}</p>
`;
  }
  /**
   * @param {string} header
   * @param {string} body
   */
  table(header, body3) {
    if (body3) body3 = `<tbody>${body3}</tbody>`;
    return "<table>\n<thead>\n" + header + "</thead>\n" + body3 + "</table>\n";
  }
  /**
   * @param {string} content
   */
  tablerow(content2) {
    return `<tr>
${content2}</tr>
`;
  }
  tablecell(content2, flags) {
    const type = flags.header ? "th" : "td";
    const tag = flags.align ? `<${type} align="${flags.align}">` : `<${type}>`;
    return tag + content2 + `</${type}>
`;
  }
  /**
   * span level renderer
   * @param {string} text
   */
  strong(text3) {
    return `<strong>${text3}</strong>`;
  }
  /**
   * @param {string} text
   */
  em(text3) {
    return `<em>${text3}</em>`;
  }
  /**
   * @param {string} text
   */
  codespan(text3) {
    return `<code>${text3}</code>`;
  }
  br() {
    return this.options.xhtml ? "<br/>" : "<br>";
  }
  /**
   * @param {string} text
   */
  del(text3) {
    return `<del>${text3}</del>`;
  }
  /**
   * @param {string} href
   * @param {string} title
   * @param {string} text
   */
  link(href, title, text3) {
    href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
    if (href === null) {
      return text3;
    }
    let out = '<a href="' + escape(href) + '"';
    if (title) {
      out += ' title="' + title + '"';
    }
    out += ">" + text3 + "</a>";
    return out;
  }
  /**
   * @param {string} href
   * @param {string} title
   * @param {string} text
   */
  image(href, title, text3) {
    href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
    if (href === null) {
      return text3;
    }
    let out = `<img src="${href}" alt="${text3}"`;
    if (title) {
      out += ` title="${title}"`;
    }
    out += this.options.xhtml ? "/>" : ">";
    return out;
  }
  text(text3) {
    return text3;
  }
};
var TextRenderer = class {
  // no need for block level renderers
  strong(text3) {
    return text3;
  }
  em(text3) {
    return text3;
  }
  codespan(text3) {
    return text3;
  }
  del(text3) {
    return text3;
  }
  html(text3) {
    return text3;
  }
  text(text3) {
    return text3;
  }
  link(href, title, text3) {
    return "" + text3;
  }
  image(href, title, text3) {
    return "" + text3;
  }
  br() {
    return "";
  }
};
var Slugger = class {
  constructor() {
    this.seen = {};
  }
  /**
   * @param {string} value
   */
  serialize(value2) {
    return value2.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig, "").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, "").replace(/\s/g, "-");
  }
  /**
   * Finds the next safe (unique) slug to use
   * @param {string} originalSlug
   * @param {boolean} isDryRun
   */
  getNextSafeSlug(originalSlug, isDryRun) {
    let slug = originalSlug;
    let occurenceAccumulator = 0;
    if (this.seen.hasOwnProperty(slug)) {
      occurenceAccumulator = this.seen[originalSlug];
      do {
        occurenceAccumulator++;
        slug = originalSlug + "-" + occurenceAccumulator;
      } while (this.seen.hasOwnProperty(slug));
    }
    if (!isDryRun) {
      this.seen[originalSlug] = occurenceAccumulator;
      this.seen[slug] = 0;
    }
    return slug;
  }
  /**
   * Convert string to unique id
   * @param {object} [options]
   * @param {boolean} [options.dryrun] Generates the next unique slug without
   * updating the internal accumulator.
   */
  slug(value2, options2 = {}) {
    const slug = this.serialize(value2);
    return this.getNextSafeSlug(slug, options2.dryrun);
  }
};
var Parser = class _Parser {
  constructor(options2) {
    this.options = options2 || defaults2;
    this.options.renderer = this.options.renderer || new Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;
    this.textRenderer = new TextRenderer();
    this.slugger = new Slugger();
  }
  /**
   * Static Parse Method
   */
  static parse(tokens, options2) {
    const parser4 = new _Parser(options2);
    return parser4.parse(tokens);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(tokens, options2) {
    const parser4 = new _Parser(options2);
    return parser4.parseInline(tokens);
  }
  /**
   * Parse Loop
   */
  parse(tokens, top2 = true) {
    let out = "", i3, j, k2, l22, l3, row, cell, header, body3, token, ordered, start, loose, itemBody, item, checked, task, checkbox, ret;
    const l4 = tokens.length;
    for (i3 = 0; i3 < l4; i3++) {
      token = tokens[i3];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
        ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
        if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(token.type)) {
          out += ret || "";
          continue;
        }
      }
      switch (token.type) {
        case "space": {
          continue;
        }
        case "hr": {
          out += this.renderer.hr();
          continue;
        }
        case "heading": {
          out += this.renderer.heading(
            this.parseInline(token.tokens),
            token.depth,
            unescape(this.parseInline(token.tokens, this.textRenderer)),
            this.slugger
          );
          continue;
        }
        case "code": {
          out += this.renderer.code(
            token.text,
            token.lang,
            token.escaped
          );
          continue;
        }
        case "table": {
          header = "";
          cell = "";
          l22 = token.header.length;
          for (j = 0; j < l22; j++) {
            cell += this.renderer.tablecell(
              this.parseInline(token.header[j].tokens),
              { header: true, align: token.align[j] }
            );
          }
          header += this.renderer.tablerow(cell);
          body3 = "";
          l22 = token.rows.length;
          for (j = 0; j < l22; j++) {
            row = token.rows[j];
            cell = "";
            l3 = row.length;
            for (k2 = 0; k2 < l3; k2++) {
              cell += this.renderer.tablecell(
                this.parseInline(row[k2].tokens),
                { header: false, align: token.align[k2] }
              );
            }
            body3 += this.renderer.tablerow(cell);
          }
          out += this.renderer.table(header, body3);
          continue;
        }
        case "blockquote": {
          body3 = this.parse(token.tokens);
          out += this.renderer.blockquote(body3);
          continue;
        }
        case "list": {
          ordered = token.ordered;
          start = token.start;
          loose = token.loose;
          l22 = token.items.length;
          body3 = "";
          for (j = 0; j < l22; j++) {
            item = token.items[j];
            checked = item.checked;
            task = item.task;
            itemBody = "";
            if (item.task) {
              checkbox = this.renderer.checkbox(checked);
              if (loose) {
                if (item.tokens.length > 0 && item.tokens[0].type === "paragraph") {
                  item.tokens[0].text = checkbox + " " + item.tokens[0].text;
                  if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
                    item.tokens[0].tokens[0].text = checkbox + " " + item.tokens[0].tokens[0].text;
                  }
                } else {
                  item.tokens.unshift({
                    type: "text",
                    text: checkbox
                  });
                }
              } else {
                itemBody += checkbox;
              }
            }
            itemBody += this.parse(item.tokens, loose);
            body3 += this.renderer.listitem(itemBody, task, checked);
          }
          out += this.renderer.list(body3, ordered, start);
          continue;
        }
        case "html": {
          out += this.renderer.html(token.text);
          continue;
        }
        case "paragraph": {
          out += this.renderer.paragraph(this.parseInline(token.tokens));
          continue;
        }
        case "text": {
          body3 = token.tokens ? this.parseInline(token.tokens) : token.text;
          while (i3 + 1 < l4 && tokens[i3 + 1].type === "text") {
            token = tokens[++i3];
            body3 += "\n" + (token.tokens ? this.parseInline(token.tokens) : token.text);
          }
          out += top2 ? this.renderer.paragraph(body3) : body3;
          continue;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return;
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
  /**
   * Parse Inline Tokens
   */
  parseInline(tokens, renderer2) {
    renderer2 = renderer2 || this.renderer;
    let out = "", i3, token, ret;
    const l3 = tokens.length;
    for (i3 = 0; i3 < l3; i3++) {
      token = tokens[i3];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
        ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
        if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(token.type)) {
          out += ret || "";
          continue;
        }
      }
      switch (token.type) {
        case "escape": {
          out += renderer2.text(token.text);
          break;
        }
        case "html": {
          out += renderer2.html(token.text);
          break;
        }
        case "link": {
          out += renderer2.link(token.href, token.title, this.parseInline(token.tokens, renderer2));
          break;
        }
        case "image": {
          out += renderer2.image(token.href, token.title, token.text);
          break;
        }
        case "strong": {
          out += renderer2.strong(this.parseInline(token.tokens, renderer2));
          break;
        }
        case "em": {
          out += renderer2.em(this.parseInline(token.tokens, renderer2));
          break;
        }
        case "codespan": {
          out += renderer2.codespan(token.text);
          break;
        }
        case "br": {
          out += renderer2.br();
          break;
        }
        case "del": {
          out += renderer2.del(this.parseInline(token.tokens, renderer2));
          break;
        }
        case "text": {
          out += renderer2.text(token.text);
          break;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return;
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
};
function marked(src, opt, callback) {
  if (typeof src === "undefined" || src === null) {
    throw new Error("marked(): input parameter is undefined or null");
  }
  if (typeof src !== "string") {
    throw new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected");
  }
  if (typeof opt === "function") {
    callback = opt;
    opt = null;
  }
  opt = merge({}, marked.defaults, opt || {});
  checkSanitizeDeprecation(opt);
  if (callback) {
    const highlight = opt.highlight;
    let tokens;
    try {
      tokens = Lexer.lex(src, opt);
    } catch (e3) {
      return callback(e3);
    }
    const done = function(err) {
      let out;
      if (!err) {
        try {
          if (opt.walkTokens) {
            marked.walkTokens(tokens, opt.walkTokens);
          }
          out = Parser.parse(tokens, opt);
        } catch (e3) {
          err = e3;
        }
      }
      opt.highlight = highlight;
      return err ? callback(err) : callback(null, out);
    };
    if (!highlight || highlight.length < 3) {
      return done();
    }
    delete opt.highlight;
    if (!tokens.length) return done();
    let pending = 0;
    marked.walkTokens(tokens, function(token) {
      if (token.type === "code") {
        pending++;
        setTimeout(() => {
          highlight(token.text, token.lang, function(err, code2) {
            if (err) {
              return done(err);
            }
            if (code2 != null && code2 !== token.text) {
              token.text = code2;
              token.escaped = true;
            }
            pending--;
            if (pending === 0) {
              done();
            }
          });
        }, 0);
      }
    });
    if (pending === 0) {
      done();
    }
    return;
  }
  function onError(e3) {
    e3.message += "\nPlease report this to https://github.com/markedjs/marked.";
    if (opt.silent) {
      return "<p>An error occurred:</p><pre>" + escape(e3.message + "", true) + "</pre>";
    }
    throw e3;
  }
  try {
    const tokens = Lexer.lex(src, opt);
    if (opt.walkTokens) {
      if (opt.async) {
        return Promise.all(marked.walkTokens(tokens, opt.walkTokens)).then(() => {
          return Parser.parse(tokens, opt);
        }).catch(onError);
      }
      marked.walkTokens(tokens, opt.walkTokens);
    }
    return Parser.parse(tokens, opt);
  } catch (e3) {
    onError(e3);
  }
}
marked.options = marked.setOptions = function(opt) {
  merge(marked.defaults, opt);
  changeDefaults(marked.defaults);
  return marked;
};
marked.getDefaults = getDefaults;
marked.defaults = defaults2;
marked.use = function(...args) {
  const opts = merge({}, ...args);
  const extensions = marked.defaults.extensions || { renderers: {}, childTokens: {} };
  let hasExtensions;
  args.forEach((pack) => {
    if (pack.extensions) {
      hasExtensions = true;
      pack.extensions.forEach((ext) => {
        if (!ext.name) {
          throw new Error("extension name required");
        }
        if (ext.renderer) {
          const prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null;
          if (prevRenderer) {
            extensions.renderers[ext.name] = function(...args2) {
              let ret = ext.renderer.apply(this, args2);
              if (ret === false) {
                ret = prevRenderer.apply(this, args2);
              }
              return ret;
            };
          } else {
            extensions.renderers[ext.name] = ext.renderer;
          }
        }
        if (ext.tokenizer) {
          if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
            throw new Error("extension level must be 'block' or 'inline'");
          }
          if (extensions[ext.level]) {
            extensions[ext.level].unshift(ext.tokenizer);
          } else {
            extensions[ext.level] = [ext.tokenizer];
          }
          if (ext.start) {
            if (ext.level === "block") {
              if (extensions.startBlock) {
                extensions.startBlock.push(ext.start);
              } else {
                extensions.startBlock = [ext.start];
              }
            } else if (ext.level === "inline") {
              if (extensions.startInline) {
                extensions.startInline.push(ext.start);
              } else {
                extensions.startInline = [ext.start];
              }
            }
          }
        }
        if (ext.childTokens) {
          extensions.childTokens[ext.name] = ext.childTokens;
        }
      });
    }
    if (pack.renderer) {
      const renderer2 = marked.defaults.renderer || new Renderer();
      for (const prop2 in pack.renderer) {
        const prevRenderer = renderer2[prop2];
        renderer2[prop2] = (...args2) => {
          let ret = pack.renderer[prop2].apply(renderer2, args2);
          if (ret === false) {
            ret = prevRenderer.apply(renderer2, args2);
          }
          return ret;
        };
      }
      opts.renderer = renderer2;
    }
    if (pack.tokenizer) {
      const tokenizer = marked.defaults.tokenizer || new Tokenizer();
      for (const prop2 in pack.tokenizer) {
        const prevTokenizer = tokenizer[prop2];
        tokenizer[prop2] = (...args2) => {
          let ret = pack.tokenizer[prop2].apply(tokenizer, args2);
          if (ret === false) {
            ret = prevTokenizer.apply(tokenizer, args2);
          }
          return ret;
        };
      }
      opts.tokenizer = tokenizer;
    }
    if (pack.walkTokens) {
      const walkTokens2 = marked.defaults.walkTokens;
      opts.walkTokens = function(token) {
        let values2 = [];
        values2.push(pack.walkTokens.call(this, token));
        if (walkTokens2) {
          values2 = values2.concat(walkTokens2.call(this, token));
        }
        return values2;
      };
    }
    if (hasExtensions) {
      opts.extensions = extensions;
    }
    marked.setOptions(opts);
  });
};
marked.walkTokens = function(tokens, callback) {
  let values2 = [];
  for (const token of tokens) {
    values2 = values2.concat(callback.call(marked, token));
    switch (token.type) {
      case "table": {
        for (const cell of token.header) {
          values2 = values2.concat(marked.walkTokens(cell.tokens, callback));
        }
        for (const row of token.rows) {
          for (const cell of row) {
            values2 = values2.concat(marked.walkTokens(cell.tokens, callback));
          }
        }
        break;
      }
      case "list": {
        values2 = values2.concat(marked.walkTokens(token.items, callback));
        break;
      }
      default: {
        if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) {
          marked.defaults.extensions.childTokens[token.type].forEach(function(childTokens) {
            values2 = values2.concat(marked.walkTokens(token[childTokens], callback));
          });
        } else if (token.tokens) {
          values2 = values2.concat(marked.walkTokens(token.tokens, callback));
        }
      }
    }
  }
  return values2;
};
marked.parseInline = function(src, opt) {
  if (typeof src === "undefined" || src === null) {
    throw new Error("marked.parseInline(): input parameter is undefined or null");
  }
  if (typeof src !== "string") {
    throw new Error("marked.parseInline(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected");
  }
  opt = merge({}, marked.defaults, opt || {});
  checkSanitizeDeprecation(opt);
  try {
    const tokens = Lexer.lexInline(src, opt);
    if (opt.walkTokens) {
      marked.walkTokens(tokens, opt.walkTokens);
    }
    return Parser.parseInline(tokens, opt);
  } catch (e3) {
    e3.message += "\nPlease report this to https://github.com/markedjs/marked.";
    if (opt.silent) {
      return "<p>An error occurred:</p><pre>" + escape(e3.message + "", true) + "</pre>";
    }
    throw e3;
  }
};
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.TextRenderer = TextRenderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.Tokenizer = Tokenizer;
marked.Slugger = Slugger;
marked.parse = marked;
var options = marked.options;
var setOptions = marked.setOptions;
var use2 = marked.use;
var walkTokens = marked.walkTokens;
var parseInline = marked.parseInline;
var parser = Parser.parse;
var lexer = Lexer.lex;

// public/app/utils/markdown.js
var import_dompurify = __toESM(require_purify());
var CustomMarkedRenderer = class extends marked.Renderer {
  link(...args) {
    const link2 = super.link(...args);
    return link2.replace("<a", '<a target="_blank"');
  }
};
marked.setOptions({
  gfm: true,
  tables: true,
  breaks: true,
  pedantic: false,
  smartLists: true,
  renderer: new CustomMarkedRenderer()
});
function convertMarkdownToHTML(text3, convertReferences = false) {
  if (!text3) {
    return "";
  }
  var d3 = marked(text3);
  var html5 = import_dompurify.default.sanitize(d3, { ADD_ATTR: ["target"] });
  if (convertReferences) {
    return convertReferencesToLinks(html5);
  }
  return html5;
}
function convertMarkdownToPlainText(markdown) {
  return marked(markdown, { renderer: new PlainTextRenderer() });
}
var PlainTextRenderer = class extends marked.Renderer {
  code(code2, infostring, escaped) {
    return "--" + _4("Code") + "--";
  }
  blockquote(quote) {
    return quote;
  }
  html() {
    return "";
  }
  heading(text3, level) {
    return text3 + "\n";
  }
  hr() {
    return "\r\n";
  }
  list(body3, ordered, start) {
    return body3;
  }
  listitem(text3) {
    return text3 + "\n";
  }
  checkbox(checked) {
    return `[${checked ? "x" : " "}]`;
  }
  paragraph(text3) {
    return htmlEscapeToText(text3) + "\r\n";
  }
  table(header, body3) {
    return "--" + _4("Table") + "--";
  }
  tablerow(content2) {
    return "";
  }
  tablecell(content2, flags) {
    return "";
  }
  strong(text3) {
    return text3;
  }
  em(text3) {
    return text3;
  }
  codespan(text3) {
    return text3;
  }
  br() {
    return "\r";
  }
  del(text3) {
    return "";
  }
  link(href, title, text3) {
    return text3;
  }
  image(href, title, text3) {
    return "--" + _4("Image") + "--";
  }
};
function htmlEscapeToText(text3) {
  return text3.replace(/\&\#[0-9]*;|&amp;/g, (escapeCode) => {
    if (escapeCode.match(/amp/)) {
      return "&";
    }
    return String.fromCharCode(escapeCode.match(/[0-9]+/));
  });
}

// public/app/attributes/content.js
attributeTypeRegistry.register("content", {
  title: _lazy("Rich text content"),
  description: _lazy("A long text with support for Markdown"),
  icon: "paragraph",
  important: true,
  groupable: false,
  filterable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-content",
  widgetBreakline: true,
  editorDirective: "attribute-type-content-editor",
  formDirective: "attribute-type-content-form",
  reprComponent: "attribute-repr-content",
  getReprWidgets: $invokeDecorator([
    "$args",
    "dropdown",
    "$sce",
    ($args, dropdown, $sce) => {
      const [, attr, modelAttr, { expanded, expandable }] = $args;
      let widget;
      if (expanded) {
        widget = {
          type: "content",
          value: attr.value
        };
      } else {
        widget = {
          type: "icon",
          value: true,
          tooltip: modelAttr.name,
          options: {
            iconClass: "bi-text-left"
          }
        };
      }
      if (expandable) {
        widget.onDOMLoad = (element2, options2 = {}) => {
          let drop;
          const onClickExpand = (event2) => {
            event2.stopPropagation();
            if (options2.editable && options2.openEditor) {
              options2.openEditor();
            } else {
              const value2 = attr.value;
              if (!value2 || value2 === "") return;
              const valueAsHTML = convertMarkdownToHTML(value2, true).valueOf();
              const embeddedHTML = `<div class="attribute-type-content-editor">
                <div class="read-only-container markdown">${valueAsHTML}</div><div>`;
              drop = dropdown.toggle(drop, $element2.get(0) || $element2.get(0), options2.scope, {
                content: $sce.trustAsHtml(embeddedHTML).valueOf(),
                classes: "drop-theme-arrow attribute-editor-dropdown"
              });
            }
          };
          const $element2 = jquery_default(element2);
          $element2.on("click", onClickExpand);
          return function dispose2() {
            $element2.off("click", onClickExpand);
          };
        };
      }
      return widget;
    }
  ]),
  buildFilterEditorNode(stores, name2, attr) {
    return {
      operators: [
        { label: _4("Contains"), op: "~=" },
        { label: _4("Exactly matches"), op: "=" },
        { label: _4("Is empty"), op: "empty" },
        { label: _4("Is not empty"), op: "not_empty" }
      ],
      options: {
        empty: false,
        not_empty: false
      }
    };
  },
  getFilters(project, attr, append2) {
    return [
      {
        label: _4("Empty"),
        action: () => {
          append2("{" + attr.name + "}=empty");
        }
      },
      {
        label: _4("Not empty"),
        action: () => {
          append2("{" + attr.name + "}!=empty");
        }
      },
      {
        input: true,
        placeholder: _4("Value"),
        submit: (value2) => {
          append2("{" + attr.name + "}~=" + value2);
        },
        resetOnSubmit: true
      }
    ];
  }
});

// public/app/attributes/utils/date.js
var dateRangeRegex = /(?:(?<start>\d{4}-\d{2}-\d{2}(?:(?: |T)\d{2}:\d{2}:\d{2}(?:.\d{1,6})?)?)?(?<separator> -> ))?(?<end>\d{4}-\d{2}-\d{2}(?:(?: |T)\d{2}:\d{2}:\d{2}(?:.\d{1,6})?)?)?/;
function parseDate(modelAttr, value2, momentInstance) {
  if (!value2) return null;
  if (value2[0] === "+") {
    return false;
  }
  momentInstance = momentInstance || moment_default;
  if (value2.indexOf(" ") !== -1 && !modelAttr?.options?.notimezone) {
    return momentInstance.utc(value2).local();
  }
  return momentInstance(value2);
}
function parseDateRange(modelAttr, start, end, momentInstance) {
  start = parseDate(modelAttr, start, momentInstance);
  end = parseDate(modelAttr, end, momentInstance);
  return { start, end };
}
function formatDateRange(modelAttr, start, end, shorter = false) {
  if (!end) return null;
  const today = moment_default();
  const displayYear = !((end?.isSame(today, "year") ?? true) && (start?.isSame(today, "year") ?? true));
  let precision = modelAttr?.options?.precision;
  if (precision === "days" && start && start.isSame(end, "day")) {
    start = null;
  }
  if (!start) {
    return formatDate2(end, "days", shorter, displayYear);
  }
  if (precision === "years" && (!isDateOnEdge(start, "year") || !isDateOnEdge(end, "year"))) {
    precision = "days";
  }
  if (precision === "months" && (!isDateOnEdge(start, "month") || !isDateOnEdge(end, "month"))) {
    precision = "days";
  }
  switch (precision) {
    case "years":
      if (start.isSame(end, "year")) {
        return formatDate2(end, "years", shorter, displayYear);
      }
      return `${formatDate2(start, "years", shorter, displayYear)} - ${formatDate2(end, "years", shorter, displayYear)}`;
    case "months":
      if (start.isSame(end, "month")) {
        return formatDate2(end, "months", shorter, displayYear);
      }
      return `${formatDate2(start, "months", shorter, displayYear)} - ${formatDate2(end, "months", shorter, displayYear)}`;
    default:
      return `${formatDate2(start, "days", shorter, displayYear)} - ${formatDate2(end, "days", shorter, displayYear)}`;
  }
}
function isDateOnEdge(date, periodUnit = "day", precision = "day") {
  return date.isSame(date.clone().startOf(periodUnit), precision) || date.isSame(date.clone().endOf(periodUnit), precision);
}
function formatDate2(date, precision = "days", shorter = false, displayYear = true) {
  if (!date) return "";
  if (precision === "days" && !date.isSame(date.clone().startOf("day")) && !date.isSame(date.clone().endOf("day"))) {
    precision = "days_time";
  }
  switch (precision) {
    case "years":
      return formatDate(date, "YYYY");
    case "months":
      if (shorter) {
        if (!displayYear) {
          return formatDate(date, "MMM");
        } else {
          return formatDate(date, "MMM, YYYY");
        }
      }
      return formatDate(date, "MMMM, YYYY");
    case "weeks":
      return formatDate(date, "GGGG MMMM, YYYY");
    case "days_time":
      if (shorter) {
        if (!displayYear) {
          return formatDate(date, "monthAndDay");
        } else {
          return formatDate(date, "ll");
        }
      }
      return formatDate(date, "lll");
    default:
      if (shorter) {
        if (!displayYear) {
          return formatDate(date, "monthAndDay");
        } else {
          return formatDate(date, "ll");
        }
      }
      return formatDate(date, "LL");
  }
}
function getServerDateFormat(attr, m3, forceTime) {
  if (attr?.options?.precision === "days_time" || forceTime) {
    return "YYYY-MM-DD HH:mm:ss";
  }
  return "YYYY-MM-DD";
}
function formatServerDate(attr, m3, forceTime) {
  if (!m3) {
    return null;
  }
  const format2 = getServerDateFormat(attr, m3, forceTime);
  if (attr && attr.options && format2 !== "YYYY-MM-DD" && !attr.options.notimezone) {
    m3 = m3.clone().utc();
  }
  return m3.format(format2);
}
function formatServerDateRange(attr, start, end) {
  if (!end) {
    return { start: null, end: null };
  }
  switch (attr?.options?.precision) {
    case "years":
      if (start) {
        start.startOf("year");
      } else {
        start = end.clone().startOf("year");
      }
      end.endOf("year");
    case "months":
      if (start) {
        start.startOf("month");
      } else {
        start = end.clone().startOf("month");
      }
      end.endOf("month");
    case "days":
      if (start) {
        if (start.isSame(end, "day")) {
          start = null;
        } else {
          start.startOf("day");
        }
      }
      end.endOf("day");
  }
  return {
    start: formatServerDate(attr, start),
    end: formatServerDate(attr, end)
  };
}
function parseDateFromComputedAttribute(modelAttr, objAttr, { momentInstance, noEndDateResolveTo = "start", noStartDateResolveTo = "end" } = {}) {
  momentInstance = momentInstance || moment_default;
  if (!objAttr || !objAttr.value) {
    return null;
  }
  let start, end, isRange;
  if (modelAttr.type === "date") {
    start = objAttr.value.start || objAttr.value.end;
    end = objAttr.value.end;
  } else if (
    // Computed attribute type (such as formula or lookup)
    // TODO: once we generalise type_hint detection to any computed attributes, we just need to check for type_hint date
    // But right now, lookup attribute type hint is not reliable
    modelAttr.type === "lookup" || modelAttr.type === "formula" && modelAttr.options?.type_hint === "date"
  ) {
    if (!angular.isString(objAttr.value)) return null;
    const match2 = objAttr.value.match(dateRangeRegex);
    if (!match2.groups.end && match2.groups.start) {
      if (noEndDateResolveTo === "start") {
        end = match2.groups.start;
      } else if (noEndDateResolveTo === "today") {
        end = momentInstance().format(getServerDateFormat());
      } else if (noEndDateResolveTo === "hide") {
        return null;
      }
    }
    if (match2.groups.end && !match2.groups.start) {
      if (noStartDateResolveTo === "end") {
        start = match2.groups.end;
      }
    }
    start = start || match2.groups.start;
    end = end || match2.groups.end;
    isRange = match2.groups.separator;
  }
  const allDay = end && end.indexOf(" ") === -1 || start && start.indexOf(" ") === -1;
  const parsed_start = start ? parseDate(modelAttr, start, momentInstance) : null;
  const parsed_end = end ? parseDate(modelAttr, end, momentInstance) : null;
  if (allDay) {
    parsed_end?.endOf("day");
    parsed_start?.startOf("day");
  }
  return {
    start: parsed_start,
    end: parsed_end,
    allDay,
    isRange,
    raw: { start, end }
  };
}

// public/app/attributes/date.js
attributeTypeRegistry.register("date", {
  title: _lazy("Date"),
  description: _lazy("A date"),
  icon: "calendar",
  important: true,
  groupable: false,
  sortable: true,
  filterable: true,
  batchable: true,
  copyable: true,
  widgetDirective: "attribute-type-date",
  editorDirective: "attribute-type-date-editor",
  getReprWidgets(obj, attr, modelAttr) {
    var value2 = attr.value;
    if (value2 && !isObject2(value2)) {
      value2 = { start: null, end: value2 };
    }
    const { start, end } = parseDateRange(modelAttr, value2.start, value2.end);
    value2 = formatDateRange(modelAttr, start, end, true);
    return {
      type: "label",
      value: value2,
      tooltip: modelAttr.name,
      options: {
        icon: "clock-o",
        cssclass: "badge-due-date " + (getDateDiffLabel(end)[0] || "")
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    var dateA = parseDate(modelAttr, attrA.value?.end || attrA.value);
    var dateB = parseDate(modelAttr, attrB.value?.end || attrB.value);
    return dateA.isSame(dateB) ? 0 : dateA.isBefore(dateB) ? -1 : 1;
  },
  buildFilterEditorNode(stores, name2, attr) {
    const options2 = [
      { label: _4("Today"), value: "today" },
      { label: _4("Yesterday"), value: "yesterday" },
      { label: _4("Tomorrow"), value: "tomorrow" },
      "--",
      { menu: ($ctrl) => {
        return {
          datepicker: true,
          resetAfterAction: true,
          hideNoDate: true,
          closeAfterSelect: true,
          select: (date) => $ctrl.setViewValue(moment_default(date).format("YYYY-MM-DD"))
        };
      } }
    ];
    return {
      operators: [
        { label: _4("Is"), op: "=" },
        { label: _4("Is before"), op: "<" },
        { label: _4("Is after"), op: ">" },
        { label: _4("Is empty"), op: "empty" },
        { label: _4("Is not empty"), op: "not_empty" }
      ],
      options: {
        empty: false,
        not_empty: false,
        "=": options2,
        "<": options2,
        ">": options2
      },
      match(node) {
        let m3 = matchAttributeNode(name2, node);
        if (m3) {
          if (m3[1] === "TODAY()") {
            return [m3[0], "today"];
          }
          return m3;
        }
      },
      transform(value2, op) {
        return value2 === "today" ? transformAttributeNode(name2, "today()", op, false) : transformAttributeNode(name2, value2, op);
      }
    };
  },
  getFilters(project, attr, append2) {
    var makeDatepicker = function(op) {
      return [{
        datepicker: true,
        resetAfterAction: true,
        select: (date) => {
          append2("{" + attr.name + "}" + op + '"' + moment_default(date).format("YYYY-MM-DD") + '"');
        }
      }];
    };
    return [
      {
        label: _4("No date"),
        action: () => {
          append2("{" + attr.name + "}=empty");
        }
      },
      {
        label: _4("Today"),
        action: () => {
          append2("{" + attr.name + "}=today()");
        }
      },
      {
        label: _4("Yesterday"),
        action: () => {
          append2("{" + attr.name + "}=yesterday");
        }
      },
      {
        label: _4("Tomorrow"),
        action: () => {
          append2("{" + attr.name + "}=tomorrow");
        }
      },
      {
        label: _4("Past"),
        action: () => {
          append2("{" + attr.name + "}<today()");
        }
      },
      {
        label: _4("Future"),
        action: () => {
          append2("{" + attr.name + "}>today()");
        }
      },
      {
        label: "--"
      },
      {
        label: _4("Exact date"),
        submenu: makeDatepicker("=")
      },
      {
        label: _4("Before..."),
        submenu: makeDatepicker("<")
      },
      {
        label: _4("After..."),
        submenu: makeDatepicker(">")
      }
    ];
  }
});

// public/app/attributes/decorators.js
attributeTypeRegistry.register("separator", {
  title: _lazy("Separator"),
  description: _lazy("Separate group of fields"),
  icon: "minus",
  category: "decoration",
  decorative: true,
  widgetDirective: "attribute-type-separator",
  widgetBreakline: true,
  widgetHideAttributeName: true
});
attributeTypeRegistry.register("statictext", {
  title: _lazy("Static text"),
  description: _lazy(""),
  hidden: true,
  icon: "align-justify",
  decorative: true,
  widgetDirective: "attribute-type-statictext",
  widgetBreakline: true,
  widgetHideAttributeName: true
});
attributeTypeRegistry.register("header", {
  title: _lazy("Header"),
  description: _lazy(""),
  icon: "header",
  category: "decoration",
  decorative: true,
  widgetDirective: "attribute-type-header",
  widgetBreakline: true,
  widgetHideAttributeName: true
});
attributeTypeRegistry.register("spacer", {
  title: _lazy("Empty space"),
  description: _lazy(""),
  icon: "square-o",
  category: "decoration",
  decorative: true,
  widgetDirective: "attribute-type-spacer",
  widgetHideAttributeName: true
});

// public/app/attributes/encrypted.js
attributeTypeRegistry.register("encrypted_text", {
  title: _lazy("Encrypted text field"),
  description: _lazy("A password protected text field which is encrypted client-side using AES256"),
  icon: "lock",
  copyable: true,
  widgetDirective: "attribute-type-encrypted",
  editorDirective: "attribute-type-encrypted-editor",
  availableFor: ["card"],
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "icon",
      value: true,
      tooltip: modelAttr.name,
      options: {
        icon: "lock"
      }
    };
  }
});

// public/app/attributes/files.js
attributeTypeRegistry.register("files", {
  title: _lazy("Files"),
  description: _lazy("Attach files"),
  icon: "files-o",
  important: true,
  groupable: false,
  copyable: true,
  arrayValue: true,
  isFile: true,
  availableFor: ["card", "form"],
  widgetDirective: "attribute-type-files",
  widgetBreakline: true,
  editorDirective: "attribute-type-files-editor",
  editorOptions: {
    async: true
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "counter",
      value: attr.value.length,
      tooltip: modelAttr.name,
      aggregate: "files",
      options: {
        icon: "paperclip"
      }
    };
  },
  popValue(value2, file) {
    if (value2) {
      for (var i3 = 0; i3 < value2.length; i3++) {
        if (value2[i3].id === file.id) {
          value2.splice(i3, 1);
          return;
        }
      }
    }
  }
});

// public/app/attributes/formula.js
attributeTypeRegistry.register("formula", {
  title: _lazy("Formula"),
  description: _lazy("Compute a value based on a formula"),
  icon: "superscript",
  availableFor: ["card"],
  important: true,
  groupable: false,
  filterable: true,
  sortable: true,
  computed: true,
  notConvertible: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-formula-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    overflow: true,
    clearable: false,
    allowEmpty: false,
    valueIsOption: "query",
    editorOpener: true,
    editBtn: _lazy("Edit"),
    init($scope2) {
      $scope2.$watch(() => ($scope2.attribute.options || {})["computing"], (computing) => {
        $scope2.loading = computing;
      });
      $scope2.$watch(() => ($scope2.attribute.options || {})["parse_error"], (error2) => {
        $scope2.hasError = !!error2;
        $scope2.errorMessage = error2;
      });
    },
    formatValue: ["$scope", "$value", function($scope2, $value) {
      if (!$scope2.attribute.options || !$scope2.attribute.options["parse_error"]) {
        $scope2.hasError = typeof $value === "string" && $value.indexOf("[ERROR") === 0;
        $scope2.errorMessage = $value;
      }
      const { start, end, isRange } = parseDateFromComputedAttribute(
        $scope2.attribute,
        { value: $value },
        { noEndDateResolveTo: null, noStartDateResolveTo: null }
      ) || {};
      let value2;
      if (isRange) {
        if (!start && !end) {
          return null;
        }
        const today = moment_default();
        const displayYear = !((end?.isSame(today, "year") ?? true) && (start?.isSame(today, "year") ?? true));
        const endOutput = end ? formatDate2(end, "days", false, displayYear) : "?";
        const startOutput = start ? formatDate2(start, "days", false, displayYear) : "?";
        value2 = end && start && end.isSame(start, "day") ? endOutput : `${startOutput} - ${endOutput}`;
      } else if (end) {
        value2 = formatDate2(end, "days", false, !end.isSame(moment_default(), "year"));
        ;
      }
      if (value2) {
        return value2;
      }
      return $value;
    }]
  },
  getReprWidgets(obj, attr, modelAttr) {
    let value2 = attr.value.toString();
    let options2;
    const { start, end, isRange } = parseDateFromComputedAttribute(
      modelAttr,
      attr,
      { noEndDateResolveTo: null, noStartDateResolveTo: null }
    ) || {};
    if (isRange) {
      if (!start && !end) {
        return null;
      }
      const today = moment_default();
      const displayYear = !((end?.isSame(today, "year") ?? true) && (start?.isSame(today, "year") ?? true));
      const endOutput = end ? formatDate2(end, "days", true, displayYear) : "?";
      const startOutput = start ? formatDate2(start, "days", true, displayYear) : "?";
      value2 = end && start && end.isSame(start, "day") ? endOutput : `${startOutput} - ${endOutput}`;
      options2 = {
        icon: "clock-o",
        cssclass: "badge-due-date " + (end ? getDateDiffLabel(end)[0] || "" : "")
      };
    } else if (end) {
      value2 = formatDate2(end, "days", true, !end.isSame(moment_default(), "year"));
      options2 = {
        icon: "clock-o",
        cssclass: "badge-due-date " + (getDateDiffLabel(end)[0] || "")
      };
    }
    return {
      type: "label",
      value: value2,
      tooltip: modelAttr.name,
      options: options2
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});

// public/app/attributes/group-type.js
attributeTypeRegistry.register("group_type", {
  title: _lazy("Labels"),
  description: _lazy("Tag cards with multiple labels"),
  icon: "tags",
  important: true,
  groupable: true,
  filterable: true,
  sortable: true,
  arrayValue: true,
  noAttributeValue: true,
  canHaveDefaultValue: true,
  availableFor: ["card", "form"],
  widgetDirective: "attribute-type-group-type",
  editorDirective: "attribute-type-group-type-editor",
  formDirective: "attribute-type-group-type-form",
  editorOptions: {
    async: true
  },
  getReprWidgets(obj, attr, modelAttr) {
    const widgets = [];
    for (let group2 of obj.groups) {
      if (cardGroupStore.exists(group2.id) && group2.type_id === modelAttr.group_type_id) {
        group2 = cardGroupStore.get(group2.id);
        var groupType = cardGroupTypeStore.tryGet(group2.type_id);
        if (groupType && !group2.is_archived) {
          widgets.push({
            type: "label",
            value: group2.title,
            tooltip: group2.title + " (" + groupType.singular_name + ")",
            options: {
              bgcolor: group2.color,
              icon: group2.icon || groupType.icon,
              cssclass: group2.is_archived ? "closed" : "",
              groupType
            }
          });
        }
      }
    }
    return widgets;
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    var groupsA = objA.groups.filter((group2) => group2.type_id === modelAttr.group_type_id).map((group2) => (cardGroupStore.tryGet(group2.id) || group2).title);
    var groupsB = objB.groups.filter((group2) => group2.type_id === modelAttr.group_type_id).map((group2) => (cardGroupStore.tryGet(group2.id) || group2).title);
    var groups = angular.copy(groupsA).concat(groupsB.filter((g3) => !groupsA.includes(g3)));
    if (groups.length === 0) {
      return 0;
    }
    if (groupsA.length === 0 && groupsB.length !== 0) {
      return 1;
    }
    if (groupsA.length !== 0 && groupsB.length === 0) {
      return -1;
    }
    groups.sort();
    if (groupsA.indexOf(groups[0]) !== -1 && groupsB.indexOf(groups[0]) !== -1) {
      return 0;
    }
    return groupsA.indexOf(groups[0]) !== -1 ? -1 : 1;
  },
  groupByChoiceFormatter(choice) {
    return [`#{${choice["title"]}}`, choice["title"]];
  },
  formatValueItemToServer(value2) {
    return value2.id;
  },
  popValue(array, value2) {
    if (value2) {
      for (var i3 = 0; i3 < array.length; i3++) {
        if (array[i3].id === value2.id) {
          array.splice(i3, 1);
          return;
        }
      }
    }
  },
  buildFilterEditorNode(stores, name2, attr) {
    return createGroupTypeNode(name2, attr ? attr.group_type_id : null, stores);
  },
  getFilters(project, attr, append2) {
    var items = [];
    var groupType, name2;
    if (project) {
      groupType = cardGroupTypeStore.tryGet(attr.group_type_id);
      if (!groupType) {
        return [];
      }
      name2 = groupType.name;
    } else {
      name2 = attr.name;
    }
    items.push(
      {
        label: _4("None"),
        action: () => {
          append2("not #" + escapeKqlName(name2) + ":*");
        }
      },
      {
        label: _4("Any"),
        action: () => {
          append2("#" + escapeKqlName(name2) + ":*");
        }
      },
      { label: "--" }
    );
    if (project) {
      items.push.apply(items, cardGroupStore.scopedByType(groupType, project.top_level_card).query().map(function(group2) {
        return {
          label: group2.title,
          color: group2.color,
          icon: group2.icon,
          classes: "icon-right",
          action: () => {
            append2("#" + escapeKqlName(name2) + ":" + escapeKqlName(group2.title));
          }
        };
      }));
    }
    return items;
  }
});
attributeTypeRegistry.register("group_type_multiple_choice", {
  alias: "group_type",
  aliasOptions: {
    one_group_per_card: true
  },
  availableFor: ["card", "form"],
  title: _lazy("Multiple choice"),
  description: _lazy("Choose a value from a list of items"),
  icon: "list-ol",
  important: true
});

// public/app/attributes/indicators.js
attributeTypeRegistry.register("indicators", {
  title: _lazy("Indicators"),
  description: _lazy("Add indicator icons to your card"),
  icon: "tags",
  groupable: false,
  arrayValue: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-indicators",
  editorDirective: "attribute-type-indicators-editor",
  editorOptions: {
    async: true
  },
  widgetOptions: {
    items: [
      "anchor",
      "asterisk",
      "ban",
      "bell",
      "birthday-cake",
      "bolt",
      "bomb",
      "bug",
      "bullhorn",
      "check",
      "cloud",
      "cog",
      "exclamation-triangle",
      "flag",
      "flask",
      "gift",
      "globe",
      "heart",
      "info-circle",
      "leaf",
      "life-ring",
      "lock",
      "magic",
      "magnet",
      "paw",
      "phone",
      "plug",
      "recycle",
      "question-circle",
      "rocket",
      "rss",
      "retweet",
      "shield",
      "shopping-cart",
      "star",
      "suitcase",
      "trophy",
      "umbrella",
      "unlock",
      "wrench",
      "pie-chart",
      "line-chart",
      "euro",
      "dollar",
      "pause",
      "play",
      "check-square-o",
      "times"
    ]
  },
  getReprWidgets(obj, attr) {
    return attr.value.map((indicator) => {
      if (!Array.isArray(indicator)) {
        indicator = [indicator, null];
      }
      return {
        type: "icon",
        value: true,
        options: {
          icon: indicator[0],
          color: indicator[1]
        }
      };
    });
  },
  popValue(array, value2) {
    for (var i3 = 0; i3 < array.length; i3++) {
      if (array[i3][0] === value2) {
        array.splice(i3, 1);
        return;
      }
    }
  }
});

// public/app/attributes/labels.js
attributeTypeRegistry.register("labels", {
  title: _lazy("Labels"),
  description: _lazy("List of text labels"),
  icon: "tags",
  hidden: true,
  groupable: false,
  arrayValue: true,
  widgetDirective: "attribute-type-labels",
  getReprWidgets(obj, attr) {
    return attr.value.map((lbl) => {
      return {
        type: "label",
        value: lbl[0],
        tooltip: lbl[0],
        options: {
          bgcolor: lbl[1]
        }
      };
    });
  }
});

// public/app/attributes/likes.js
attributeTypeRegistry.register("likes", {
  title: _lazy("Like/dislike button"),
  description: _lazy("A button where members choose between like or dislike"),
  icon: "thumbs-up",
  groupable: false,
  sortable: true,
  notConvertible: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-likes",
  getReprWidgets(obj, attr, modelAttr) {
    if (attr.value.total === 0) {
      return [];
    }
    return {
      type: "counter",
      value: attr.value.points,
      tooltip: modelAttr.name,
      aggregate: "likes",
      options: {
        icon: attr.value.points >= 0 ? "thumbs-up" : "thumbs-down"
      }
    };
  },
  formatLocalValue(value2, current) {
    var o3 = {
      "total": Math.abs(value2),
      "points": value2,
      "likes": [],
      "dislikes": []
    };
    if (value2 > 0) {
      o3["likes"].push(currentUser);
    } else if (value2 < 0) {
      o3["dislikes"].push(currentUser);
    }
    return o3;
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrB.value.points, attrA.value.points);
  }
});

// public/app/attributes/location.js
attributeTypeRegistry.register("location", {
  title: _lazy("Location"),
  description: _lazy("An address displayed on a map"),
  icon: "map-marker",
  groupable: false,
  filterable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-location",
  widgetBreakline: true,
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  // Convert dict value to string for editor
  getEditorValue(value2) {
    if (!value2) return "";
    if (typeof value2 === "string") return value2;
    return value2.address || "";
  },
  // Convert string from editor to dict for saving
  processEditorValue(value2) {
    if (!value2) return null;
    return value2;
  },
  getReprWidgets(obj, attr, modelAttr) {
    const address = typeof attr.value === "string" ? attr.value : attr.value?.address || "";
    return {
      type: "label",
      value: address,
      tooltip: modelAttr.name,
      options: {
        icon: "map-marker"
      }
    };
  },
  getFilters: defaultAttributeFilters
});

// public/app/attributes/lookup.js
attributeTypeRegistry.register("lookup", {
  title: _lazy("Lookup"),
  description: _lazy("Lookup related card field values through relationships"),
  icon: "bi-link-45deg",
  groupable: false,
  filterable: true,
  sortable: true,
  copyable: true,
  computed: true,
  widgetDirective: "attribute-type-input",
  widgetOptions: {
    readonly: true,
    formatValue: ["$scope", "$value", function($scope2, $value) {
      const { start, end, isRange } = parseDateFromComputedAttribute(
        $scope2.attribute,
        { value: $value },
        { noEndDateResolveTo: null, noStartDateResolveTo: null }
      ) || {};
      let value2;
      if (isRange) {
        if (!start && !end) {
          return null;
        }
        const today = moment_default();
        const displayYear = !((end?.isSame(today, "year") ?? true) && (start?.isSame(today, "year") ?? true));
        const endOutput = end ? formatDate2(end, "days", false, displayYear) : "?";
        const startOutput = start ? formatDate2(start, "days", false, displayYear) : "?";
        value2 = end && start && end.isSame(start, "day") ? endOutput : `${startOutput} - ${endOutput}`;
      } else if (end) {
        value2 = formatDate2(end, "days", false, !end.isSame(moment_default(), "year"));
      }
      if (value2) {
        return value2;
      }
      return $value;
    }]
  },
  getReprWidgets(obj, attr, modelAttr) {
    let value2 = attr.value.toString();
    let options2;
    const { start, end, isRange } = parseDateFromComputedAttribute(
      modelAttr,
      attr,
      { noEndDateResolveTo: null, noStartDateResolveTo: null }
    ) || {};
    if (isRange) {
      if (!start && !end) {
        return null;
      }
      const today = moment_default();
      const displayYear = !((end?.isSame(today, "year") ?? true) && (start?.isSame(today, "year") ?? true));
      const endOutput = end ? formatDate2(end, "days", true, displayYear) : "?";
      const startOutput = start ? formatDate2(start, "days", true, displayYear) : "?";
      value2 = end && start && end.isSame(start, "day") ? endOutput : `${startOutput} - ${endOutput}`;
      options2 = {
        icon: "clock-o",
        cssclass: "badge-due-date " + (end ? getDateDiffLabel(end)[0] || "" : "")
      };
    } else if (end) {
      value2 = formatDate2(end, "days", true, !end.isSame(moment_default(), "year"));
      options2 = {
        icon: "clock-o",
        cssclass: "badge-due-date " + (getDateDiffLabel(end)[0] || "")
      };
    }
    return {
      type: "label",
      value: value2,
      tooltip: modelAttr.name,
      options: options2
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});

// public/app/attributes/members.js
attributeTypeRegistry.register("members", {
  title: _lazy("Members"),
  description: _lazy("List of members"),
  icon: "users",
  important: true,
  groupable: true,
  filterable: true,
  batchable: true,
  copyable: true,
  arrayValue: true,
  widgetDirective: "attribute-type-members",
  formDirective: "attribute-type-members",
  editorDirective: "attribute-type-members-editor",
  editorOptions: {
    async: true
  },
  getReprWidgets(obj, attr, modelAttr) {
    return attr.value.map((user) => {
      return {
        type: "avatar",
        value: userAvatarUrl(user),
        tooltip: user.display_name + " (" + modelAttr.name + ")",
        aggregate: "members"
      };
    });
  },
  groupByChoiceFormatter(choice) {
    return [`@${choice["username"]}`, choice["display_name"]];
  },
  fillCardGroupByStore(card, model, modelAttr, store2) {
    const memberStore = projectMemberStore.scopedByProject(projectStore.getForCard(card));
    const _refresh = debounce2(() => {
      store2.transaction(() => {
        store2.clear();
        let q = {};
        if (modelAttr?.options?.roles && modelAttr.options.roles.length) {
          q["role"] = query_exports.objMatch({ id: query_exports.any(modelAttr.options.roles.map((r3) => r3.id)) });
        }
        memberStore.query(q, { sortBy: "user.display_name" }).forEach((member) => {
          const group2 = createDynamicGroupForAttribute(
            store2,
            card,
            model,
            modelAttr,
            member.user.id,
            member.user.display_name,
            true
          );
          store2.update(group2, { avatar: userAvatarUrl(member.user) });
        });
      });
    }, 500);
    return memberStore.subscribe(["inserted", "updated", "removed"], _refresh, true);
  },
  equals(attr, value2) {
    return (attr.value || []).some((member) => {
      return ["display_name", "username", "id"].some((propKey) => member[propKey] === value2);
    });
  },
  isGroupByStoreAppendable(modelAttr) {
    return true;
  },
  formatValueItemToServer(value2) {
    return value2.id ? value2.id : value2;
  },
  popValue(array, value2) {
    if (value2) {
      for (var i3 = 0; i3 < array.length; i3++) {
        if (array[i3] === value2.id || isObject2(array[i3]) && array[i3].id === value2.id) {
          array.splice(i3, 1);
          return;
        }
      }
    }
  },
  buildFilterEditorNode(stores, name2, attr) {
    let node = {
      operators: [
        { label: _4("Contains at least one person"), op: "not_empty" },
        { label: _4("Includes"), op: "in" },
        { label: _4("Has no one"), op: "empty" }
      ],
      options: {
        empty: false,
        not_empty: false,
        in: []
      },
      transformEscapeValue: false
    };
    if (stores["projectMember"]) {
      for (const member of stores["projectMember"].query({}, { sortBy: "user.display_name" })) {
        node.options.in.push({
          label: member.user.display_name,
          value: "@" + escapeKqlName(member.user.username),
          category: _4("Members")
        });
      }
    }
    if (stores["role"]) {
      for (const role of stores["role"].query({}, { sortBy: "name" })) {
        node.options.in.push({
          label: role.name,
          value: "@@" + escapeKqlName(role.name),
          category: _4("Roles")
        });
      }
    }
    return node;
  },
  getFilters(project, attr, append2) {
    var items = [
      {
        label: _4("No one"),
        action: () => {
          append2("{" + attr.name + "}=empty");
        }
      },
      {
        label: "@me",
        action: () => {
          append2("@me in {" + attr.name + "}");
        }
      }
    ];
    if (project) {
      items.push(
        { label: "--" },
        { subheader: _4("Members") }
      );
      for (const member of projectMemberStore.scopedByProject(project).query({}, { sortBy: "user.display_name" })) {
        items.push({
          label: member.user.display_name,
          action: () => {
            append2("@" + escapeKqlName(member.user.username) + " in {" + attr.name + "}");
          }
        });
      }
      const org2 = orgStore.tryGetForProject(project);
      const roles = org2 ? roleStore.scopedByOrg(org2).query({}, { sortBy: "name" }) : [];
      if (roles.length) {
        items.push(
          { label: "--" },
          { subheader: _4("Roles") }
        );
        for (const role of roles) {
          items.push({
            label: role.name,
            action: () => {
              append2("@@" + escapeKqlName(role.name) + " in {" + attr.name + "}");
            }
          });
        }
      }
    }
    return items;
  }
});

// public/app/attributes/number.js
attributeTypeRegistry.register("number", {
  title: _lazy("Number"),
  description: _lazy("Any number"),
  icon: "pencil-square-o",
  important: true,
  groupable: false,
  sortable: true,
  filterable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    inputType: "number",
    inputAttrs: {
      "step": "any"
    },
    inputPlaceholder: _lazy("Enter number")
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "counter",
      value: attr.value,
      tooltip: modelAttr.name
    };
  },
  aggregates: {
    sum(values2) {
      return Math.round((values2.reduce((accu, value2) => accu + value2, 0) + Number.EPSILON) * 100) / 100;
    },
    min(values2) {
      return Math.min(values2);
    },
    max(values2) {
      return Math.max(values2);
    }
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters(project, attr, append2) {
    const makeSubmenu = (op) => {
      return [
        {
          input: true,
          placeholder: _4("Enter number"),
          submit: (value2) => {
            append2("{" + attr.name + "}" + op + value2);
          },
          resetOnSubmit: true
        }
      ];
    };
    return [
      {
        label: _4("No value"),
        action: () => {
          append2("{" + attr.name + "}=empty");
        }
      },
      {
        label: _4("Equals"),
        submenu: makeSubmenu("=")
      },
      {
        label: _4("Less than"),
        submenu: makeSubmenu("<")
      },
      {
        label: _4("Less than or equal"),
        submenu: makeSubmenu("<=")
      },
      {
        label: _4("Greater than"),
        submenu: makeSubmenu(">")
      },
      {
        label: _4("Greater than or equal"),
        submenu: makeSubmenu(">=")
      }
    ];
  },
  buildFilterEditorNode(stores, name2, attr) {
    return {
      operators: [
        { label: _4("Equals to"), op: "=" },
        { label: _4("Different from"), op: "!=" },
        { label: _4("Greater than"), op: ">" },
        { label: _4("Greater or equal than"), op: ">=" },
        { label: _4("Less than"), op: "<" },
        { label: _4("Less or equal than"), op: "<=" },
        { label: _4("Is empty"), op: "empty" },
        { label: _4("Is not empty"), op: "not_empty" }
      ],
      transformEscapeValue: false
    };
  }
});

// public/app/attributes/percentage.js
attributeTypeRegistry.register("percentage", {
  title: _4("Percentage"),
  description: _4("Display a percentage as a progress bar. Update manually or through automation rules"),
  icon: "percent",
  widgetDirective: "attribute-type-percentage",
  getReprWidgets(obj, attr, modelAttr) {
    return [{
      type: "progress",
      value: attr.value,
      tooltip: `${attr.value}% (${modelAttr.name})`
    }];
  },
  aggregates: {
    sum(values2) {
      return Math.round((values2.reduce((accu, value2) => accu + value2, 0) + Number.EPSILON) * 100) / 100;
    },
    min(values2) {
      return Math.min(values2);
    },
    max(values2) {
      return Math.max(values2);
    }
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp(attrA.value, attrB.value);
  },
  getFilters(project, attr, append2) {
    const makeSubmenu = (op) => {
      return [
        {
          input: true,
          placeholder: _4("Enter number"),
          submit: (value2) => {
            append2("{" + attr.name + "}" + op + value2);
          },
          resetOnSubmit: true
        }
      ];
    };
    return [
      {
        label: _4("No value"),
        action: () => {
          append2("{" + attr.name + "}=empty");
        }
      },
      {
        label: _4("Equals"),
        submenu: makeSubmenu("=")
      },
      {
        label: _4("Less than"),
        submenu: makeSubmenu("<")
      },
      {
        label: _4("Less than or equal"),
        submenu: makeSubmenu("<=")
      },
      {
        label: _4("Greater than"),
        submenu: makeSubmenu(">")
      },
      {
        label: _4("Greater than or equal"),
        submenu: makeSubmenu(">=")
      }
    ];
  },
  buildFilterEditorNode(stores, name2, attr) {
    return {
      operators: [
        { label: _4("Equals to"), op: "=" },
        { label: _4("Different from"), op: "!=" },
        { label: _4("Greater than"), op: ">" },
        { label: _4("Greater or equal than"), op: ">=" },
        { label: _4("Less than"), op: "<" },
        { label: _4("Less or equal than"), op: "<=" },
        { label: _4("Is empty"), op: "empty" },
        { label: _4("Is not empty"), op: "not_empty" }
      ],
      transformEscapeValue: false
    };
  }
});

// public/app/attributes/progress.js
attributeTypeRegistry.register("progress", {
  title: _4("Card progress"),
  description: _4("Display the card's progress based on child cards or related cards"),
  icon: "percent",
  hidden: true,
  widgetDirective: "attribute-type-progress",
  getReprWidgets(obj, attr, modelAttr) {
    return [{
      type: "progress",
      value: attr.value,
      tooltip: `${attr.value}% (${modelAttr.name})`
    }];
  },
  aggregates: {
    sum(values2) {
      return Math.round((values2.reduce((accu, value2) => accu + value2, 0) + Number.EPSILON) * 100) / 100;
    },
    min(values2) {
      return Math.min(values2);
    },
    max(values2) {
      return Math.max(values2);
    }
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp(attrA.value, attrB.value);
  },
  getFilters(project, attr, append2) {
    const makeSubmenu = (op) => {
      return [
        {
          input: true,
          placeholder: _4("Enter number"),
          submit: (value2) => {
            append2("{" + attr.name + "}" + op + value2);
          },
          resetOnSubmit: true
        }
      ];
    };
    return [
      {
        label: _4("No value"),
        action: () => {
          append2("{" + attr.name + "}=empty");
        }
      },
      {
        label: _4("Equals"),
        submenu: makeSubmenu("=")
      },
      {
        label: _4("Less than"),
        submenu: makeSubmenu("<")
      },
      {
        label: _4("Less than or equal"),
        submenu: makeSubmenu("<=")
      },
      {
        label: _4("Greater than"),
        submenu: makeSubmenu(">")
      },
      {
        label: _4("Greater than or equal"),
        submenu: makeSubmenu(">=")
      }
    ];
  },
  buildFilterEditorNode(project, name2, attr) {
    return {
      operators: [
        { label: _4("Equals to"), op: "=" },
        { label: _4("Different from"), op: "!=" },
        { label: _4("Greater than"), op: ">" },
        { label: _4("Greater or equal than"), op: ">=" },
        { label: _4("Less than"), op: "<" },
        { label: _4("Less or equal than"), op: "<=" },
        { label: _4("Is empty"), op: "empty" },
        { label: _4("Is not empty"), op: "not_empty" }
      ],
      transformEscapeValue: false
    };
  }
});

// public/app/attributes/project.js
attributeTypeRegistry.register("__project__", {
  title: _lazy("Workspace"),
  hidden: true,
  noAttributeValue: true,
  getReprWidgets(obj, objAttr, attr) {
    const project = projectStore.tryGet(obj.project_id);
    if (project) {
      return {
        type: "label",
        value: project.title,
        options: {
          bgcolor: project.color,
          cssclass: project.is_archived ? "closed" : ""
        }
      };
    }
  }
});

// public/app/attributes/relationships.js
attributeTypeRegistry.register("relationships", {
  title: _lazy("Relationships"),
  description: _lazy("Relationships between cards"),
  icon: "link",
  // category: 'relationships',
  important: true,
  groupable: true,
  copyable: true,
  arrayValue: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-relationships",
  widgetBreakline: true,
  widgetOptions: {
    async: true,
    multi: true,
    onSelect(attributeGroup, attribute2, obj, value2, choice, refreshValue) {
      return attributeGroup.appendObjAttribute(obj, attribute2, { id: choice[0] });
    }
  },
  editorOpener: $invokeDecorator(["$args", "dropdown", ($args, dropdown) => {
    const [target, editorScope] = $args;
    if (editorScope.obj && editorScope.obj.project_id) {
      editorScope.project = projectStore.tryGet(editorScope.obj.project_id);
    }
    if (editorScope.project && editorScope.project.top_level_card) {
      editorScope.board = editorScope.project.top_level_card;
    } else {
      editorScope.board = editorScope.obj;
    }
    editorScope.card = editorScope.obj;
    editorScope.onDone = () => dropdown.close(drop);
    const dropHtml = `<div>
      <attribute-type-relationships-editor
        project="project"
        value="value"
        attribute-group="attributeGroup"
        attribute="attribute"
        card="card"
        board="board"
        on-done="onDone()"
      />
    </div>`;
    const drop = dropdown.openCompile(target, dropHtml, editorScope, {
      classes: "attribute-type-relationships-editor-drop drop-theme-menu",
      tetherOptions: {
        target: "body",
        attachment: "middle center",
        targetAttachment: "middle center",
        targetOffset: "-35% -18%",
        constraints: [
          {
            to: "window",
            attachment: "together",
            pin: true
          }
        ]
      }
    });
  }]),
  groupByChoiceFormatter(choice) {
    return [choice.id, `${choice.title} (#${choice.ref})`];
  },
  getReprWidgets(obj, attr, modelAttr) {
    const widgets = [];
    for (let card of attr.value) {
      widgets.push({
        type: "label",
        value: card.title,
        tooltip: modelAttr.name + ": " + card.title,
        onDOMLoad: (element2, options2 = {}) => {
          function onClick(event2) {
            event2.stopPropagation();
            ngApp.$injector.get("cardModal").load(card.id);
          }
          $(element2).on("click", onClick);
          return function dispose2() {
            return $(element2).off("click", onClick);
          };
        },
        keepDefaultReprListeners: true,
        options: {
          icon: "link",
          clickable: true
        }
      });
    }
    return widgets;
  },
  formatValueItemToServer(value2, attr) {
    return { card: value2.id, direction: value2.direction, attachment: value2.attachment };
  },
  popValue(array, value2) {
    for (var i3 = 0; i3 < array.length; i3++) {
      if (array[i3].id === value2) {
        array.splice(i3, 1);
        return;
      }
    }
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    const relsA = (attrA.value || []).map((rel) => rel.title).sort((a3, b3) => cmp2(a3, b3));
    const relsB = (attrB.value || []).map((rel) => rel.title).sort((a3, b3) => cmp2(a3, b3));
    if (relsA.length === 0 && relsB.length === 0) {
      return 0;
    }
    if (relsA.length === 0 && relsB.length !== 0) {
      return 1;
    }
    if (relsA.length !== 0 && relsB.length === 0) {
      return -1;
    }
    return cmp2(relsA[0], relsB[0]);
  },
  fillCardGroupByStore(card, model, modelAttr, store2) {
    const project = projectStore.getForCard(card);
    const relatedCards = /* @__PURE__ */ new Map();
    for (const c3 of cardStore.scopedByProject(project).query()) {
      const attr = c3.attributes?.find((a3) => a3.id === modelAttr.id);
      if (!attr) continue;
      for (const rel of attr.value) {
        relatedCards.set(rel.id, rel.title);
      }
    }
    store2.transaction(() => {
      store2.clear();
      for (const [id, title] of relatedCards.entries()) {
        const group2 = createDynamicGroupForAttribute(store2, card, model, modelAttr, id, title, true);
        store2.update(group2, {
          onTitleClick: ["cardModal", (cardModal) => {
            cardModal.open(cardStore.get(id));
          }]
        });
      }
    });
  },
  getUngroupedCardStoreFilters: function(card, model, modelAttr, store2) {
    return { attributes: query_exports.not(query_exports.arrayMatch((a3) => a3.id === modelAttr.id)) };
  },
  equals(attr, value2) {
    return attr.value && attr.value.some((card) => card.title === value2 || card.id === value2);
  }
});

// public/app/attributes/remote.js
attributeTypeRegistry.register("remote_choice", {
  title: _lazy("Multiple choice from external data source"),
  description: _lazy("Select a value from a list of choices provided by a GET request to an URL"),
  icon: "list-ol",
  category: "remote",
  groupable: true,
  availableFor: ["card", "form"],
  widgetDirective: "attribute-type-select",
  editorDirective: "attribute-type-select-editor",
  getWidgetOptions(modelAttr) {
    return {
      valueIsAlwayArray: true,
      multi: !!modelAttr.options.multi
    };
  },
  getReprWidgets(obj, attr, modelAttr) {
    return attr.value.map((v3) => {
      return {
        type: "label",
        value: v3[1],
        tooltip: modelAttr.name
      };
    });
  },
  formatValueToServer(value2, modelAttr) {
    if (modelAttr.options.multi) {
      return value2.map(this.formatValueItemToServer);
    }
    return this.formatValueItemToServer(value2);
  },
  formatValueItemToServer(value2, modelAttr) {
    return value2[0];
  },
  fillCardGroupByStore(card, model, modelAttr, store2) {
    const project = projectStore.getForCard(card);
    const attrGroup = new ModelAttributeGroup(project, model, cardModelStore.getExtendedModelAttributes(model, project));
    getSelectChoices(attrGroup, modelAttr, card).then((items) => {
      for (let item of items) {
        createDynamicGroupForAttribute(
          store2,
          card,
          model,
          modelAttr,
          item[0],
          item[1],
          !!modelAttr.options.multi,
          false,
          (value2, attrValue) => attrValue.find((item2) => item2[0] === value2)
        );
      }
    });
  },
  isGroupByStoreAppendable(modelAttr) {
    return !!modelAttr.options.multi;
  }
});
attributeTypeRegistry.register("remote_action_btn", {
  title: _lazy("Remote Action Button"),
  description: _lazy("Perform a POST request to a URL and show the output"),
  icon: "bolt",
  category: "remote",
  decorative: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-remote-action-btn"
});
attributeTypeRegistry.register("remote_value", {
  title: _lazy("Value from external source"),
  description: _lazy("The value of the attribute comes from a GET request to an URL"),
  icon: "plug",
  category: "remote",
  statelessAsync: true,
  notConvertible: true,
  availableFor: ["card"],
  widgetDirective: "attribute-type-remote-value",
  getReprWidgets(obj, attr, modelAttr) {
    const isDict = attr && attr.value && typeof attr.value.data === "object" && !angular.isArray(attr.value.data);
    const isList = attr && attr.value && typeof attr.value.data === "object" && angular.isArray(attr.value.data);
    if (isDict || isList) {
      return {
        type: "icon",
        value: true,
        tooltip: modelAttr.name,
        options: {
          icon: "table"
        }
      };
    }
    return {
      type: "label",
      value: attr.value.data,
      tooltip: modelAttr.name
    };
  }
});

// public/app/attributes/size.js
var SIZES = [
  ["S", "S", "#B1E696"],
  ["M", "M", "#92dc6d"],
  ["L", "L", "#74d244"],
  ["XL", "XL", "#5bb72c"]
];
attributeTypeRegistry.register("size", {
  title: _lazy("Size"),
  description: _lazy("Choose between: S, M, L, XL"),
  icon: "tachometer",
  groupable: true,
  sortable: true,
  filterable: true,
  batchable: true,
  copyable: true,
  widgetDirective: "attribute-type-select",
  editorDirective: "attribute-type-select-editor",
  editorOptions: {
    async: true
  },
  widgetOptions: {
    useItemsAsValue: true,
    items: SIZES
  },
  getColor(size4) {
    return SIZES.find((item) => item[0] === size4)?.[2];
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: attr.value,
      tooltip: modelAttr.name,
      options: {
        bgcolor: this.getColor(attr.value),
        color: "#ffffff"
      }
    };
  },
  formatValueItemToServer(value2) {
    return Array.isArray(value2) && value2.length > 0 ? value2[0] : value2;
  },
  fillCardGroupByStore(card, model, modelAttr, store2) {
    for (let item of SIZES) {
      createDynamicGroupForAttribute(store2, card, model, modelAttr, item[0]);
    }
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    var sizes = SIZES.map((i3) => i3[0]);
    var vA = sizes.indexOf(attrA.value);
    var vB = sizes.indexOf(attrB.value);
    return cmp2(vA, vB);
  },
  buildFilterEditorNode(stores, name2, attr) {
    const options2 = SIZES.map((item) => ({ label: item[0], value: item[0] }));
    return {
      operators: [
        { label: _4("Is"), op: "=" },
        { label: _4("Is greater or equal than"), op: ">=" },
        { label: _4("Is empty"), op: "empty" },
        { label: _4("Is not empty"), op: "not_empty" }
      ],
      options: {
        empty: false,
        not_empty: false,
        "=": options2,
        ">=": options2
      }
    };
  },
  getFilters(project, attr, append2) {
    return [{
      label: _4("Not set"),
      action: () => {
        append2("{" + attr.name + "}=empty");
      }
    }].concat(SIZES.map((item) => {
      return {
        label: item[0],
        action: () => {
          append2("{" + attr.name + "}=" + item[0]);
        }
      };
    }));
  }
});

// public/app/attributes/state.js
attributeTypeRegistry.register("__state__", {
  title: _lazy("State"),
  hidden: true,
  noAttributeValue: true,
  widgetDirective: "attribute-type-state",
  editorDirective: "attribute-type-state-editor",
  editorOptions: {
    async: true
  },
  getReprWidgets(obj) {
    const state = cardStateStore.getForCard(obj);
    return {
      type: "label",
      value: state.label,
      options: {
        icon: state.icon
      }
    };
  }
});

// public/app/attributes/text.js
attributeTypeRegistry.register("text", {
  title: _lazy("Text"),
  description: _lazy("A short text entry"),
  icon: "pencil-square-o",
  important: true,
  groupable: false,
  filterable: true,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    overflow: true,
    color: true
  },
  getReprWidgets(obj, attr, modelAttr) {
    var e3 = extractColorFromText2(attr.value);
    return {
      type: "label",
      value: e3 ? e3[0] : attr.value,
      tooltip: modelAttr.name,
      options: {
        bgcolor: e3 ? e3[1] : null
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});
attributeTypeRegistry.register("email", {
  title: _lazy("Email"),
  description: _lazy("An email address"),
  icon: "envelope",
  groupable: false,
  filterable: true,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    inputType: "email",
    inputPlaceholder: _lazy("Enter email"),
    actionIcon: "fa-envelope",
    actionTooltip: _lazy("Write email"),
    action($scope2) {
      window.open("mailto:" + $scope2.value);
    }
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: attr.value,
      tooltip: modelAttr.name,
      options: {
        icon: "envelope"
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});
attributeTypeRegistry.register("url", {
  title: _lazy("Link"),
  description: _lazy("A link to a website"),
  icon: "external-link",
  groupable: false,
  filterable: true,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    inputPlaceholder: _lazy("Enter a link"),
    action($scope2) {
      window.open(Array.isArray($scope2.value) ? $scope2.value[1] : $scope2.value);
    }
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: Array.isArray(attr.value) ? attr.value[0] : attr.value,
      tooltip: modelAttr.name,
      onDOMLoad: (element2, options2 = {}) => {
        if (!options2.editable) return;
        function onClick(event2) {
          event2.stopPropagation();
          window.open(Array.isArray(attr.value) ? attr.value[1] : attr.value);
        }
        jquery_default(element2).on("click", onClick);
        return function dispose2() {
          return jquery_default(element2).off("click", onClick);
        };
      },
      options: {
        icon: "external-link",
        clickable: true
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});
attributeTypeRegistry.register("phone", {
  title: _lazy("Phone"),
  description: _lazy("A phone number"),
  icon: "phone",
  groupable: false,
  filterable: true,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    inputType: "tel",
    inputPlaceholder: _lazy("Enter phone number")
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: attr.value,
      tooltip: modelAttr.name,
      options: {
        icon: "phone"
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});
attributeTypeRegistry.register("skype_username", {
  title: _lazy("Skype username"),
  description: _lazy("A skype username"),
  icon: "skype",
  hidden: true,
  groupable: false,
  filterable: true,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    actionIcon: "fa-skype",
    actionTooltip: _lazy("Call on Skype"),
    inputPlaceholder: _lazy("Enter skype username"),
    action($scope2) {
      window.open("skype:" + $scope2.value + "?call");
    }
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: attr.value,
      tooltip: modelAttr.name,
      options: {
        icon: "skype"
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});
attributeTypeRegistry.register("iframe", {
  title: _lazy("iFrame"),
  description: _lazy("Embed a page based on a URL"),
  icon: "window-maximize",
  important: false,
  groupable: false,
  filterable: true,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetBreakline: true,
  widgetDirective: "attribute-type-iframe",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    inputPlaceholder: _lazy("Embed a page based on a URL")
  },
  getReprWidgets(obj, attr, modelAttr, options2 = {}) {
    const { expanded } = options2;
    if (expanded) {
      return {
        type: "label",
        value: attr.value,
        tooltip: modelAttr.name
      };
    }
    return {
      type: "icon",
      value: true,
      tooltip: attr.value,
      options: {
        icon: "window-maximize"
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    return cmp2(attrA.value, attrB.value);
  },
  getFilters: defaultAttributeFilters
});

// public/app/attributes/time.js
attributeTypeRegistry.register("time", {
  title: _lazy("Time"),
  description: _lazy("A time"),
  icon: "clock-o",
  important: true,
  groupable: false,
  sortable: true,
  batchable: true,
  copyable: true,
  canHaveDefaultValue: true,
  widgetDirective: "attribute-type-input",
  editorDirective: "attribute-type-input-editor",
  formDirective: "attribute-type-input-form",
  widgetOptions: {
    inputPlaceholder: _lazy("00:00:00")
  },
  getReprWidgets(obj, attr, modelAttr) {
    return {
      type: "label",
      value: attr.value,
      tooltip: modelAttr.name,
      options: {
        icon: "clock-o"
      }
    };
  },
  compare(objA, attrA, objB, attrB, modelAttr) {
    var mA = moment_default.duration(attrA.value);
    var mB = moment_default.duration(attrB.value);
    return cmp2(mA.asSeconds(), mB.asSeconds());
  },
  getFilters: defaultAttributeFilters,
  aggregates: {
    sum(values2) {
      return formatAggregate(timesToInts(values2).reduce((accu, value2) => accu + value2, 0));
    },
    min(values2) {
      return formatAggregate(Math.min(timesToInts(values2)));
    },
    max(values2) {
      return formatAggregate(Math.max(timesToInts(values2)));
    }
  }
});
function timesToInts(values2) {
  return values2.map((v3) => moment_default.duration(v3).asMilliseconds());
}
function formatAggregate(out) {
  var d3 = moment_default.duration(out);
  var total = d3.asSeconds();
  var hours = (total - d3.seconds() - d3.minutes() * 60) / 3600;
  var minutes = d3.minutes() < 10 ? "0" + d3.minutes() : d3.minutes();
  var seconds = d3.seconds() < 10 ? "0" + d3.seconds() : d3.seconds();
  return hours + ":" + minutes + ":" + seconds;
}

// public/app/stores/utils/model.js
function createAttributeGroup(card, attributeFilters, sort = true) {
  const model = cardModelStore.getCardModel(card);
  const project = projectStore.tryGetForCard(card, true);
  return new ModelAttributeGroup(project, model, cardModelStore.getCardAvailableAttributes(card, attributeFilters, sort));
}
function getCardAttribute(card, attr) {
  return createAttributeGroup(card, void 0, false).getObjAttribute(card, attr);
}
function getCardAttributes(card, attrs2, withModelAttribute = false) {
  const attrGroup = createAttributeGroup(card, void 0, false);
  const out = [];
  for (const modelAttr of attrGroup) {
    let objAttr = attrGroup.getObjAttribute(card, modelAttr);
    if (objAttr) {
      for (const attr of attrs2) {
        let id = attr;
        if (typeof attr !== "number" && typeof attr !== "string") {
          id = attr.id || attr.name;
        }
        if (objAttr.id == id || objAttr.name == id) {
          out.push(withModelAttribute ? [objAttr, modelAttr] : objAttr);
        }
      }
    }
  }
  return out;
}
function getCardCompositeModel(card, attributeFilters) {
  const model = cardModelStore.getCardModel(card);
  const project = projectStore.tryGetForCard(card, true);
  return {
    model,
    card_color: cardModelStore.getExtendedModelProp(model, project, "card_color"),
    indicator: cardModelStore.getExtendedModelProp(model, project, "indicator"),
    attributes: createAttributeGroup(card, attributeFilters)
  };
}

// public/app/apps/cards/common/utils.ts
function getScopedModelStore(project, cardStore2) {
  if (project) {
    return cardModelStore.scopedByEnabled(project);
  } else if (cardStore2) {
    return cardModelStore.scopedByCards(cardStore2.query());
  }
}
function getScopedGroupTypeStore(project, cardStore2, withAttributes = false) {
  if (project) {
    return cardGroupTypeStore.scopedByEnabled(project, withAttributes);
  } else if (cardStore2) {
    return cardGroupTypeStore.scopedByCards(cardStore2.query(), withAttributes);
  }
}
function getScopedGroupStore(board, cardStore2, groupType, includeArchived = false) {
  let groupStore;
  const groupStoreScopeFilters = {
    is_archived: (v3) => includeArchived ? true : !v3
  };
  if (board) {
    groupStore = (groupType ? cardGroupStore.scopedByType(groupType, board) : cardGroupStore.scopedByAvailableForChildren(board)).scoped(groupStoreScopeFilters);
  } else if (cardStore2) {
    groupStore = cardGroupStore.scopedByCards(cardStore2.query(), groupType).scoped(groupStoreScopeFilters);
  }
  return groupStore;
}
function getSortableAttributes(project, cardStore2, withGroupTypes) {
  const sortChoices = [];
  const modelStore = getScopedModelStore(project, cardStore2);
  const attrChoiceMapper = (attr) => ({
    label: attr.name,
    value: attr.name.toLowerCase(),
    id: attr.id
  });
  if (modelStore) {
    sortChoices.push(
      ...(modelStore.getSortableAttributes().sort() || []).map(attrChoiceMapper)
    );
  }
  if (withGroupTypes) {
    const groupTypeStore = getScopedGroupTypeStore(project, cardStore2);
    if (groupTypeStore) {
      sortChoices.push(
        ...(groupTypeStore.asAttributes().sort() || []).map(attrChoiceMapper)
      );
    }
  }
  return sortChoices;
}
function isProjectFilteredOnGroupBy(groupBy2, project, filter4) {
  if (!project || !groupBy2 || !filter4) return false;
  if (!groupBy2.getGroupType()) return false;
  const matches3 = filter4.match(
    /#(((\{[^}]+\})|([a-z\u00C0-\u017F0-9_]+)):((\{[^}]+\})|([a-z\u00C0-\u017F0-9_]+)))/gi
  );
  if (!matches3 || !matches3.length) return false;
  if (filter4.match(/(^|\s)not\s/gi)) return false;
  for (let i3 = 0; i3 < matches3.length; i3++) {
    if (matches3[i3].indexOf(":") !== -1) {
      const typeName2 = unescapeKqlName(matches3[i3].substr(1).split(":")[0]);
      const type = cardGroupTypeStore.queryByName(project, typeName2, true)?.[0];
      return groupBy2.getGroupType().id === type?.id;
    }
  }
  return false;
}
function cardMatchesFilterResult(card, matchingCardIndex) {
  if (!Array.isArray(matchingCardIndex)) return true;
  return matchingCardIndex.includes(card.id);
}
var specialFieldLabels = /* @__PURE__ */ new Map([
  ["__ref__", _lazy("Reference")],
  ["__comments__", _lazy("Number of comments")],
  ["__children__", _lazy("Number of child cards")],
  ["__cover__", _lazy("Image cover")],
  ["__project__", _lazy("Project")],
  ["__state__", _lazy("State")]
]);
function getAvailableAttrs(project, cardStore2, options2) {
  const availableAttrs = /* @__PURE__ */ new Map();
  const {
    specialFields = [],
    stripAttrsHiddenByDefault: _stripAttrsHiddenByDefault = false,
    withGroupType = true,
    attrFilters
  } = options2;
  for (const attrName of specialFields) {
    const attr = {
      type: attrName,
      id: attrName,
      name: attrName,
      label: specialFieldLabels.get(attrName),
      container: "",
      is_dynamic: true
    };
    addToAvailableAttrs(availableAttrs, attr);
  }
  if (withGroupType) {
    const groupTypeAttrs = getScopedGroupTypeStore(project, cardStore2).asAttributes().sort((a3, b3) => localeSort(a3.name, b3.name, getCurrentLocale()));
    for (const attr of groupTypeAttrs) {
      addToAvailableAttrs(availableAttrs, attr);
    }
  }
  const modelAttrs = getScopedModelStore(project, cardStore2).getAttributesFromModels(attrFilters, true).filter(
    ([attr, model]) => !attributeTypeRegistry.get(attr.type)?.decorative
  ).sort((a3, b3) => localeSort(a3[0].name, b3[0].name, getCurrentLocale()));
  for (const [attr, model] of modelAttrs) {
    addToAvailableAttrs(availableAttrs, attr, model);
  }
  return _stripAttrsHiddenByDefault ? stripAttrsHiddenByDefault(availableAttrs) : availableAttrs;
}
function getAvailableAttrsByName(project, cardStore2, names) {
  const availableAttrs = /* @__PURE__ */ new Map();
  const modelAttrs = getScopedModelStore(
    project,
    cardStore2
  ).getAttributesFromModels({ name: (name2) => names.includes(name2) }, true);
  for (const [attr, model] of modelAttrs) {
    addToAvailableAttrs(availableAttrs, attr, model);
  }
  return availableAttrs;
}
function getAvailableAttrsOfType(project, cardStore2, type = null, options2 = {}, typeHint = "date") {
  if (type === null) {
    return getAvailableAttrs(project, cardStore2, options2);
  }
  const {
    withComputed = true,
    specialFields,
    stripAttrsHiddenByDefault: stripAttrsHiddenByDefault2
  } = options2;
  const attrFilters = withComputed ? (modelAttr) => {
    return (Array.isArray(type) ? type.includes(modelAttr.type) : modelAttr.type === type) || modelAttr.is_computed && // TODO: once lookup will get a correct type_hint, remove this
    (modelAttr.type === "lookup" || modelAttr.type === "formula" && modelAttr.options?.type_hint === typeHint);
  } : Array.isArray(type) ? query_exports.any(type) : { type };
  return getAvailableAttrs(project, cardStore2, {
    specialFields,
    stripAttrsHiddenByDefault: stripAttrsHiddenByDefault2,
    withGroupType: false,
    attrFilters
  });
}
function addToAvailableAttrs(availableAttrs, attr, model = {}) {
  if (availableAttrs.has(attr.name)) {
    const a3 = availableAttrs.get(attr.name);
    a3.push(attr);
    if (model?.id !== a3.model?.id) {
      delete a3.model;
    }
  } else {
    availableAttrs.set(
      attr.name,
      new NamedAttributeGroup([attr], attr.name, attr.label || attr.name, model)
    );
  }
}
function stripAttrsHiddenByDefault(availableAttributes) {
  return filterMap(
    availableAttributes,
    (attrGroup) => attrGroup.visibleByDefault
  );
}
function availablesEquals(availables = /* @__PURE__ */ new Map(), others = /* @__PURE__ */ new Map()) {
  if (availables.size !== others.size) {
    return false;
  }
  for (const [name2, attrGroup] of availables) {
    if (!others.has(name2) || !others.get(name2).equals(attrGroup)) {
      return false;
    }
  }
  for (const [name2, attrGroup] of others) {
    if (!availables.has(name2) || !availables.get(name2).equals(attrGroup)) {
      return false;
    }
  }
  return true;
}
function areAttributesAvailableForCard(card, attrs2) {
  return !!getCardAvailableAttributes(card, attrs2).length;
}
function getCardAvailableAttributes(card, attrs2) {
  const realCard = cardStore.isMirror(card) ? card.broken_link ? null : cardStore.tryGet(card.link.id) : card;
  if (!realCard) return [];
  const availableAttributesForCard = [];
  for (const [key2, attrGroup] of attrs2) {
    availableAttributesForCard.push(
      ...attrGroup.getCardAvailableAttributes(realCard)
    );
  }
  return availableAttributesForCard;
}
function getCardAvailableAttributesAsMap(card, attrs2) {
  const realCard = cardStore.isMirror(card) ? card.broken_link ? null : cardStore.tryGet(card.link.id) : card;
  if (!realCard) return /* @__PURE__ */ new Map();
  const availableAttributesForCard = /* @__PURE__ */ new Map();
  for (const [attrGroupName, attrGroup] of attrs2) {
    const attrs3 = attrGroup.getCardAvailableAttributes(realCard);
    if (attrs3?.length) {
      availableAttributesForCard.set(attrGroupName, attrs3);
    }
  }
  return availableAttributesForCard;
}
function findEditableAttribute(attrs2, project) {
  for (const [attrName, namedAttrGroup] of attrs2) {
    const attr = namedAttrGroup.findEditableAttribute(project);
    if (attr) return attr;
  }
  return null;
}
function isUngroupedVisible(groupBy2, isAppModeOptionEnabled) {
  return !groupBy2 || groupBy2 && groupBy2.isNothing() || // always show if groupBy Nothing
  isAppModeOptionEnabled && groupBy2 && groupBy2.getUngroupedCardsStore() && groupBy2.getUngroupedCardsStore().count() > 0 || groupBy2 && !groupBy2.isNothing() && groupBy2.getGroupStore().count() === 0;
}
function getCardsAttributeAggregations(cards, project) {
  if (!cards || cards.length === 0) return [];
  const modelIds = uniq(cards.map((card) => card.model_id)).filter(Boolean).concat(project ? cardModelStore.getProjectModel(project).id : []);
  const aggFunc = "sum";
  const modelAttributes = cardModelStore.scoped({ id: query_exports.any(modelIds) }).getAggregatableAttributes().filter((modelAttr) => {
    const attrType = attributeTypeRegistry.get(modelAttr.type);
    return attrType && typeof attrType.aggregates[aggFunc] !== "undefined";
  });
  const aggregates = /* @__PURE__ */ new Map();
  for (const modelAttr of modelAttributes) {
    const values2 = cards.map((card) => {
      const attr = getCardAttribute(card, modelAttr);
      if (attr) {
        return attr.value;
      }
    }).filter((v3) => v3 !== void 0 && v3 !== null);
    const attrType = attributeTypeRegistry.get(modelAttr.type);
    const sum = attrType.aggregates[aggFunc](values2);
    if (aggregates.has(modelAttr.name)) {
      aggregates.get(modelAttr.name).value += sum;
    } else {
      aggregates.set(modelAttr.name, {
        name: modelAttr.name,
        type: attrType.name,
        value: sum
      });
    }
  }
  return Array.from(aggregates.values());
}
function activateViewScroll($el, appClass, handleClass, verticalScrollEnabled) {
  let cachedMousePosition = { x: 0, y: 0 };
  let maxScrollLeft;
  let maxScrollTop;
  let $viewport;
  let dragging;
  let canScrollVertically;
  const end = () => {
    dragging = false;
    jquery_default("body").removeClass("noSelect");
    jquery_default(document).off("mousemove", drag);
    jquery_default(document).off("mouseup", end);
  };
  const drag = (event2) => {
    const mousePosition = {
      x: event2.pageX,
      y: event2.pageY
    };
    const delta = {
      x: mousePosition.x - cachedMousePosition.x,
      y: mousePosition.y - cachedMousePosition.y
    };
    delta.x = -delta.x;
    delta.y = -delta.y;
    cachedMousePosition = mousePosition;
    const scrollLeft = $viewport.scrollLeft();
    const scrollTop = $viewport.scrollTop();
    if (delta.x > 0 && scrollLeft < maxScrollLeft || delta.x < 0 && scrollLeft > 0) {
      $viewport.scrollLeft(scrollLeft + delta.x);
    }
    if (canScrollVertically && (delta.y > 0 && scrollTop < maxScrollTop || delta.y < 0 && scrollTop > 0)) {
      $viewport.scrollTop(scrollTop + delta.y);
    }
  };
  $el.on("mousedown", handleClass, function(event2) {
    if (event2.target !== this) {
      return;
    }
    $viewport = appClass ? $el.find(appClass) : $el;
    const viewportClientWidth = $viewport[0].clientWidth;
    const viewportClientHeight = $viewport[0].clientHeight;
    maxScrollLeft = $viewport[0].scrollWidth - viewportClientWidth;
    maxScrollTop = $viewport[0].scrollHeight - viewportClientHeight;
    canScrollVertically = isFunction_default(verticalScrollEnabled) ? verticalScrollEnabled() : verticalScrollEnabled;
    if (maxScrollLeft > 0 && event2.clientY < $viewport.offset().top + viewportClientHeight || canScrollVertically && maxScrollTop > 0 && event2.clientX < $viewport.offset().left + viewportClientWidth) {
      if (dragging) {
        end();
      }
      dragging = true;
      cachedMousePosition = {
        x: event2.pageX,
        y: event2.pageY
      };
      jquery_default("body").addClass("noSelect");
      jquery_default(document).on("mousemove", drag);
      jquery_default(document).on("mouseup", end);
    }
  });
}
function setSortBy(options2, value2, reverse = false) {
  const newModeOptions = { ...options2 || {} };
  if (value2) {
    newModeOptions["sort_by"] = { value: value2, reverse };
  } else {
    newModeOptions["sort_by"] = null;
  }
  if (newModeOptions["sort_by_overrides"]) {
    newModeOptions["sort_by_overrides"] = null;
  }
  return newModeOptions;
}
function getSortBy(options2, forced = false) {
  const value2 = options2["sort_by"] || options2["order_by"];
  if (forced || !isConnected()) {
    return value2 || { value: "ref", reverse: false };
  }
  return value2;
}
function canFreeSort(project, groupBy2, options2) {
  return !!groupBy2 && !!groupBy2[1].isNothing() && // no multi dimension
  !!project && !options2?.include_descendants;
}

// public/app/apps/cards/common/attributes-visibility.ts
var menuSectionLabels = /* @__PURE__ */ new Map([
  ["fields", _lazy("Fields")],
  ["contexts", _lazy("Contexts")],
  ["others", _lazy("Others")]
]);
var CHILDREN_ATTRS_VISIBILITY_OPTIONS = [
  {
    name: "Show all",
    value: null
  },
  {
    name: "Show nothing",
    value: "none"
  },
  {
    name: "Same as parent",
    value: "selected"
  }
];
function keepExistingVisibleAttrNames(visibleAttrNames, availableAttributes) {
  if (visibleAttrNames === void 0) {
    return void 0;
  }
  return Array.from(availableAttributes.keys()).filter((name2) => visibleAttrNames.includes(name2)).sort((a3, b3) => visibleAttrNames.indexOf(a3) - visibleAttrNames.indexOf(b3));
}
function toggleAttrVisibility(attrName, visibleAttrNames, availableAttrs, onChange) {
  const newVisibleAttrNames = Array.from(visibleAttrNames);
  if (visibleAttrNames.includes(attrName)) {
    newVisibleAttrNames.splice(visibleAttrNames.indexOf(attrName), 1);
  } else {
    newVisibleAttrNames.push(attrName);
  }
  const newAllAttrsVisible = getAllAttrsVisible(
    newVisibleAttrNames,
    availableAttrs
  );
  onChange?.(newVisibleAttrNames, newAllAttrsVisible);
}
function getAllAttrsVisible(visibleAttrNames, availableAttrs) {
  const visibleByDefaultAttrs = stripAttrsHiddenByDefault(availableAttrs);
  const haveAttrsHiddenByDefault = Array.from(availableAttrs).some(
    ([, { visibleByDefault }]) => !visibleByDefault
  );
  if (visibleAttrNames.length === availableAttrs.size) {
    if (haveAttrsHiddenByDefault) {
      return "+default_hidden";
    } else {
      return true;
    }
  } else if (visibleAttrNames.length === visibleByDefaultAttrs.size && visibleAttrNames.every((name2) => visibleByDefaultAttrs.has(name2))) {
    return true;
  }
  return false;
}
function groupAvailablesByMenuSection(availableAttrs, flatten4 = false) {
  return groupBy(
    availableAttrs,
    (attrGroup) => attrGroup.menuSection,
    Array.from(menuSectionLabels.keys()),
    flatten4
  );
}
function getVisibleAttrNames(visibleAttrNamesFromConfig, allAttrsVisible, availableAttributes) {
  const availableAttrsOrderedByMenuSection = groupAvailablesByMenuSection(
    availableAttributes,
    true
  );
  let visibleAttrNames = keepExistingVisibleAttrNames(
    visibleAttrNamesFromConfig,
    availableAttributes
  );
  if (visibleAttrNames === void 0) {
    if (allAttrsVisible === "+default_hidden") {
      visibleAttrNames = Array.from(availableAttrsOrderedByMenuSection.keys());
    } else {
      visibleAttrNames = Array.from(
        stripAttrsHiddenByDefault(availableAttrsOrderedByMenuSection).keys()
      );
    }
  } else {
    if (allAttrsVisible === true) {
      visibleAttrNames = Array.from(
        reorderMap(
          stripAttrsHiddenByDefault(availableAttrsOrderedByMenuSection),
          visibleAttrNames
        ).keys()
      );
    } else if (allAttrsVisible === "+default_hidden") {
      visibleAttrNames = Array.from(
        reorderMap(availableAttrsOrderedByMenuSection, visibleAttrNames).keys()
      );
    }
  }
  return visibleAttrNames;
}
function toggleAll(visibleAttrNames, availableAttrs, onChange) {
  if (visibleAttrNames.length === availableAttrs.size) {
    onChange?.([], false);
  } else {
    const newVisibleAttrNames = Array.from(
      reorderMap(
        groupAvailablesByMenuSection(availableAttrs, true),
        visibleAttrNames
      ).keys()
    );
    onChange?.(newVisibleAttrNames, "+default_hidden");
  }
}
function createMenuItem(attrName, attrGroup, visibleAttrNames, availableAttrs, onChange) {
  return {
    checkbox: true,
    icon: attrGroup.icon,
    color: attrGroup.fromDifferentTypes ? "orange" : void 0,
    label: attrGroup.label,
    small: attrGroup.model?.base_model_id ? void 0 : attrGroup.model?.name,
    help: attrGroup.length > 1 ? _4("{nb} fields under this name", { nb: attrGroup.length }).concat(
      attrGroup.fromDifferentTypes ? ` (${_4("with different types")})` : ""
    ) : void 0,
    filterable: true,
    filterPredicate: (filter4) => attrGroup.label.toLowerCase().indexOf(filter4.toLowerCase()) >= 0,
    value: () => visibleAttrNames.includes(attrName),
    toggle: () => toggleAttrVisibility(
      attrName,
      visibleAttrNames,
      availableAttrs,
      onChange
    )
  };
}
function getAttrsVisibilityMenuItems(project, cardStore2, appOptions, options2, onChange) {
  const allAttrsVisible = appOptions?.all_attrs_visible;
  const availableAttrs = getAvailableAttrs(project, cardStore2, {
    specialFields: options2?.specialFields,
    stripAttrsHiddenByDefault: options2?.hideAttrsHiddenByDefault
  });
  const visibleAttrNames = getVisibleAttrNames(
    options2?.visibles || appOptions?.visible_attributes,
    allAttrsVisible,
    availableAttrs
  );
  const items = [];
  for (const [section, groupedAvailables] of groupAvailablesByMenuSection(
    availableAttrs
  )) {
    items.push({ subheader: menuSectionLabels.get(section) });
    for (const [attrName, attrGroup] of groupedAvailables) {
      items.push(
        createMenuItem(
          attrName,
          attrGroup,
          visibleAttrNames,
          availableAttrs,
          onChange
        )
      );
    }
  }
  items.push({
    label: _4("Toggle all"),
    noCloseAfterAction: true,
    action: () => toggleAll(visibleAttrNames, availableAttrs, onChange)
  });
  if (options2.showChildrenVisibilityMenu) {
    items.push({ label: "--" });
    items.push({ subheader: _4("Sub-card's fields visibility") });
    const selected = CHILDREN_ATTRS_VISIBILITY_OPTIONS.find((opt) => opt.value === appOptions?.children_visible_attributes);
    items.push({
      selectbox: true,
      select: (selectedOption) => {
        onChange(void 0, void 0, selectedOption.value);
      },
      selectOptions: CHILDREN_ATTRS_VISIBILITY_OPTIONS,
      defaultValue: selected === void 0 ? CHILDREN_ATTRS_VISIBILITY_OPTIONS[0] : selected,
      optionsLabelProperty: "name",
      noCloseAfterAction: true
    });
  }
  return items;
}
function getAttrsVisibilityMenuWatcher(project, store2, appOptions) {
  const appOptionsGetter = typeof appOptions === "function" ? appOptions : () => appOptions;
  return (cb2, scope) => {
    return offMany([
      getScopedModelStore(project, store2).$watchAll(scope, cb2, false),
      scope.$watchCollection(
        () => appOptionsGetter()?.visible_attributes || [],
        (n4, o3) => {
          if (n4.length !== o3.length || n4.some((attr, idx) => attr !== o3[idx])) {
            cb2();
          }
        }
      ),
      scope.$watchGroup(
        [
          appOptionsGetter()?.visible_attributes,
          appOptionsGetter()?.all_attrs_visible,
          appOptionsGetter()?.children_visible_attributes
        ],
        (n4, o3) => {
          if (n4 === o3) return;
          cb2();
        }
      )
    ]);
  };
}
function getAttrsVisibilityMenu(project, cardStore2, appOptions, options2, onChange) {
  return {
    config: () => () => getAttrsVisibilityMenuItems(
      project,
      cardStore2,
      appOptions,
      options2,
      onChange
    ),
    options: {
      watch: getAttrsVisibilityMenuWatcher(project, cardStore2, appOptions)
    }
  };
}
function getAttrVisibilityFilterObject(visibleAttrNames, hideAttrsHiddenByDefault) {
  const visibleByDefaultFilterObj = {
    type: (type) => attributeTypeRegistry.get(type)?.visibleByDefault !== false
  };
  if (!visibleAttrNames) {
    return visibleByDefaultFilterObj;
  }
  let filterObj = {
    name: (name2) => visibleAttrNames.includes(name2)
  };
  if (hideAttrsHiddenByDefault) {
    Object.assign(filterObj, visibleByDefaultFilterObj);
  }
  return filterObj;
}
function flattenMaps(maps) {
  const flattenedMap = /* @__PURE__ */ new Map();
  for (const [, map5] of maps) {
    for (const [key2, value2] of map5) {
      flattenedMap.set(key2, value2);
    }
  }
  return flattenedMap;
}
function groupBy(map5, groupValueGetter, order2, flatten4 = true) {
  let groupedMap = /* @__PURE__ */ new Map();
  for (const [key2, value2] of map5) {
    const groupValue = groupValueGetter(value2, key2);
    if (groupedMap.has(groupValue)) {
      groupedMap.get(groupValue).set(key2, value2);
    } else {
      groupedMap.set(groupValue, /* @__PURE__ */ new Map([[key2, value2]]));
    }
  }
  if (order2) groupedMap = reorderMap(groupedMap, order2);
  if (flatten4) groupedMap = flattenMaps(groupedMap);
  return groupedMap;
}

// public/app/apps/cards/kanban/index.js
cardsAppRegistry.register("kanban", {
  component: "cards-app-kanban",
  title: _lazy("Kanban"),
  description: _lazy("A visual way to manage your projects and workflows"),
  icon: "kfi-kanban",
  groupable: true,
  groupableTwice: true,
  useDefaultGroupByOnCreateView: true,
  filterable: true,
  searchable: true,
  sortable: true,
  freeSort: true,
  menu: (store2, board, groupBy2, options2, onChange) => {
    const project = board ? projectStore.tryGetForCard(board) : null;
    const attrVisibilityMenuOptions = {
      specialFields: ["__ref__", "__comments__", "__children__", "__cover__"],
      // Hide attributes with type.visibleByDefault === false, while we don't find a good UX for this
      hideAttrsHiddenByDefault: true,
      showChildrenVisibilityMenu: true
    };
    function onChangeAttrsVisibility(visibleAttrNames = options2.visible_attributes, allAttrsVisible = options2.all_attrs_visible, childrenVisibleAttrs = options2?.children_visible_attributes || null) {
      return onChange({
        visible_attributes: visibleAttrNames,
        all_attrs_visible: allAttrsVisible,
        children_visible_attributes: childrenVisibleAttrs
      });
    }
    return {
      config: [
        {
          label: _4("Displayed fields"),
          icon: "eye-slash",
          submenu: () => () => getAttrsVisibilityMenuItems(
            project,
            store2,
            options2,
            attrVisibilityMenuOptions,
            onChangeAttrsVisibility
          ),
          options: { watch: getAttrsVisibilityMenuWatcher(project, store2, options2) }
        },
        {
          label: _4("Display density"),
          icon: "bi-reception-4",
          submenu: [
            {
              checkbox: true,
              switch: false,
              label: _4("Normal"),
              value: () => !(options2 || {}).displayDensity,
              toggle: () => onChange({ displayDensity: null })
            },
            { desc: _4("A good balance between space and information density") },
            {
              checkbox: true,
              switch: false,
              label: _4("Compact"),
              value: () => (options2 || {}).displayDensity === "compact",
              toggle: () => onChange({ displayDensity: "compact" })
            },
            { desc: _4("A dense layout to see more cards at once") },
            {
              checkbox: true,
              switch: false,
              label: _4("Large"),
              value: () => (options2 || {}).displayDensity === "large",
              toggle: () => onChange({ displayDensity: "large" })
            },
            { desc: _4("A lot of space for greater readability") }
          ]
        },
        {
          label: _4("Columns and rows colors"),
          icon: "bi-palette-fill",
          submenu: [
            {
              checkbox: true,
              switch: false,
              label: _4("Colorize columns"),
              value: () => !(options2 || {}).color_rows,
              toggle: () => onChange({ color_rows: !(options2 || {}).color_rows })
            },
            {
              checkbox: true,
              switch: false,
              label: _4("Colorize rows"),
              value: () => (options2 || {}).color_rows,
              toggle: () => onChange({ color_rows: !(options2 || {}).color_rows })
            }
          ]
        },
        { label: "--" },
        { subheader: _4("Visibility of cards") },
        {
          checkbox: true,
          label: _4("Ungrouped"),
          offline: true,
          mobile: true,
          value: () => !!(options2 || {}).showUngroupedCards,
          toggle: () => onChange({ showUngroupedCards: !(options2 || {}).showUngroupedCards })
        },
        ...getCommonModeOptions(options2, (changes) => onChange(changes)),
        { label: "--" },
        { subheader: _4("More") },
        {
          checkbox: true,
          label: _4("Expand columns to fill screen"),
          warning: isFirefox() ? _4("Experimental on Firefox") : null,
          offline: true,
          mobile: false,
          value: () => !!(options2 || {}).stretched,
          toggle: () => onChange({ stretched: !(options2 || {}).stretched })
        },
        {
          checkbox: true,
          label: _4("Adapt swimlanes height to content"),
          offline: true,
          mobile: false,
          enabled: () => !groupBy2[1].isNothing(),
          value: () => !(options2 || {}).swimlanes_fixed_height,
          toggle: () => onChange({ swimlanes_fixed_height: !(options2 || {}).swimlanes_fixed_height })
        },
        {
          checkbox: true,
          label: _4("Strike done cards"),
          offline: true,
          mobile: true,
          value: () => !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0,
          // Default to TRUE
          toggle: () => onChange({ strikeDoneCards: !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0 ? false : void 0 })
        },
        {
          checkbox: true,
          label: _4("Show progress"),
          offline: true,
          mobile: false,
          value: () => !!(options2 || {}).showProgress,
          toggle: () => onChange({ showProgress: !(options2 || {}).showProgress })
        },
        {
          checkbox: true,
          label: _4("Hide empty groups"),
          offline: false,
          mobile: true,
          value: () => !!(options2 || {}).hideEmptyGroups,
          toggle: () => onChange({ hideEmptyGroups: !(options2 || {}).hideEmptyGroups })
        },
        {
          label: _4("Maximize / minimize"),
          submenu: [
            {
              label: _4("Minimize all columns"),
              offline: true,
              mobile: true,
              action: () => {
                $broadcast("minimizeAllGroups");
              }
            },
            {
              label: _4("Maximize all columns"),
              offline: true,
              mobile: true,
              action: () => {
                $broadcast("maximizeAllGroups");
              }
            },
            {
              label: _4("Maximize all cards"),
              public: true,
              mobile: true,
              action: () => {
                $broadcast("maximizeAllCards");
              }
            },
            {
              label: _4("Minimize all cards"),
              public: true,
              mobile: true,
              action: () => {
                $broadcast("minimizeAllCards");
              }
            }
          ]
        },
        ...project ? [getFullScreenOption()] : [],
        ...getActionsOptions(options2, (changes) => onChange(changes), project)
      ]
    };
  }
});

// public/app/apps/cards/table/index.js
cardsAppRegistry.register("table", {
  component: "cards-app-table",
  title: _lazy("Table"),
  description: _lazy("A spreadsheet-like view to easily manage data"),
  icon: "table",
  filterable: true,
  groupable: true,
  searchable: true,
  sortable: true,
  freeSort: true,
  menu: (store2, board, groupBy2, options2, onChange) => {
    const project = board ? projectStore.tryGetForCard(board) : null;
    const specialFields = !board ? ["__project__", "__state__"] : [];
    const attrVisibilityMenuOptions = { specialFields };
    return { config: [
      {
        label: _4("Visible columns"),
        icon: "eye-slash",
        submenu: () => () => getAttrsVisibilityMenuItems(
          project,
          store2,
          options2,
          attrVisibilityMenuOptions,
          (visibleAttrNames, allAttrsVisible) => onChange({
            visible_attributes: visibleAttrNames,
            all_attrs_visible: allAttrsVisible
          })
        ),
        options: { watch: getAttrsVisibilityMenuWatcher(project, store2, options2) }
      },
      {
        label: _4("Borders & rows"),
        icon: "bi-border-outer",
        submenu: [
          { label: _4("Borders") },
          {
            checkbox: true,
            offline: true,
            mobile: true,
            label: _4("Show the vertical borders"),
            value: () => !(options2 || {}).hideVerticalBorders,
            toggle: () => onChange({ hideVerticalBorders: !(options2 || {}).hideVerticalBorders })
          },
          {
            checkbox: true,
            offline: true,
            mobile: true,
            label: _4("Show the horizontal borders"),
            value: () => !(options2 || {}).hideHorizontalBorders,
            toggle: () => onChange({ hideHorizontalBorders: !(options2 || {}).hideHorizontalBorders })
          },
          { label: "--" },
          { label: _4("Rows") },
          { desc: _4("Row height") },
          {
            checkbox: true,
            switch: false,
            offline: true,
            mobile: true,
            label: _4("Normal"),
            value: () => !(options2 || {}).rowHeight,
            toggle: () => onChange({ rowHeight: null })
          },
          {
            checkbox: true,
            switch: false,
            offline: true,
            mobile: true,
            label: _4("Compact"),
            value: () => (options2 || {}).rowHeight === "compact",
            toggle: () => onChange({ rowHeight: "compact" })
          },
          {
            checkbox: true,
            switch: false,
            offline: true,
            mobile: true,
            label: _4("Large"),
            value: () => (options2 || {}).rowHeight === "large",
            toggle: () => onChange({ rowHeight: "large" })
          },
          { label: " " },
          { desc: _4("Striped rows") },
          {
            checkbox: true,
            offline: true,
            mobile: true,
            label: _4("Alternate the background color of every second row"),
            value: () => !!(options2 || {}).stripedRows,
            toggle: () => onChange({ stripedRows: !(options2 || {}).stripedRows })
          }
        ]
      },
      { label: "--" },
      { subheader: _4("Visibility of cards") },
      {
        checkbox: true,
        label: _4("Ungrouped"),
        offline: true,
        mobile: true,
        value: () => !!(options2 || {}).showUngroupedCards,
        toggle: () => onChange({ showUngroupedCards: !(options2 || {}).showUngroupedCards })
      },
      ...getCommonModeOptions(options2, (changes) => onChange(changes)),
      { label: "--" },
      { subheader: _4("More") },
      {
        checkbox: true,
        label: _4("Strike done cards"),
        offline: true,
        mobile: true,
        value: () => !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0,
        // Default to TRUE
        toggle: () => onChange({ strikeDoneCards: !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0 ? false : void 0 })
      },
      {
        checkbox: true,
        label: _4("Hide empty groups"),
        offline: false,
        mobile: true,
        value: () => !!(options2 || {}).hideEmptyGroups,
        toggle: () => onChange({ hideEmptyGroups: !(options2 || {}).hideEmptyGroups })
      },
      {
        label: _4("Maximize / minimize"),
        enabled: () => !groupBy2[0].isNothing(),
        submenu: [
          {
            label: _4("Minimize all tables"),
            offline: true,
            mobile: true,
            action: () => {
              $broadcast("minimizeAllGroups");
            }
          },
          {
            label: _4("Maximize all tables"),
            offline: true,
            mobile: true,
            action: () => {
              $broadcast("maximizeAllGroups");
            }
          }
        ]
      },
      ...project ? [getFullScreenOption()] : [],
      ...getActionsOptions(options2, (changes) => onChange(changes), project)
    ] };
  }
});

// public/app/apps/cards/checklist/index.js
cardsAppRegistry.register("list", {
  component: "cards-app-checklist",
  title: _lazy("List"),
  description: _lazy("The easiest way to manage to-do lists"),
  icon: "kfi-checklist",
  groupable: true,
  filterable: true,
  searchable: true,
  sortable: true,
  freeSort: true,
  menu: (store2, board, groupBy2, options2, onChange) => {
    const project = board ? projectStore.tryGetForCard(board) : null;
    const attrVisibilityMenuOptions = {
      specialFields: ["__ref__", "__comments__", "__children__", "__cover__"],
      // Hide attributes with type.visibleByDefault === false, while we don't find a good UX for this
      hideAttrsHiddenByDefault: true,
      showChildrenVisibilityMenu: true
    };
    function onChangeAttrsVisibility(visibleAttrNames = options2.visible_attributes, allAttrsVisible = options2.all_attrs_visible, childrenVisibleAttrs = options2?.children_visible_attributes || null) {
      return onChange({
        visible_attributes: visibleAttrNames,
        all_attrs_visible: allAttrsVisible,
        children_visible_attributes: childrenVisibleAttrs
      });
    }
    return {
      config: [
        {
          label: _4("Displayed fields"),
          icon: "eye-slash",
          submenu: () => () => getAttrsVisibilityMenuItems(
            project,
            store2,
            options2,
            attrVisibilityMenuOptions,
            onChangeAttrsVisibility
          ),
          options: { watch: getAttrsVisibilityMenuWatcher(project, store2, options2) }
        },
        { label: "--" },
        { subheader: _4("Visibility of cards") },
        {
          checkbox: true,
          label: _4("Ungrouped"),
          offline: true,
          mobile: true,
          value: () => !!(options2 || {}).showUngroupedCards,
          toggle: () => onChange({ showUngroupedCards: !(options2 || {}).showUngroupedCards })
        },
        ...getCommonModeOptions(options2, (changes) => onChange(changes)),
        { label: "--" },
        { subheader: _4("More") },
        {
          checkbox: true,
          label: _4("Strike done cards"),
          offline: true,
          mobile: true,
          value: () => !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0,
          // Default to TRUE
          toggle: () => onChange({ strikeDoneCards: !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0 ? false : void 0 })
        },
        {
          checkbox: true,
          label: _4("Show progress"),
          offline: true,
          mobile: false,
          value: () => !!(options2 || {}).showProgress,
          toggle: () => onChange({ showProgress: !(options2 || {}).showProgress })
        },
        {
          checkbox: true,
          label: _4("Hide empty groups"),
          offline: false,
          mobile: true,
          value: () => !!(options2 || {}).hideEmptyGroups,
          toggle: () => onChange({ hideEmptyGroups: !(options2 || {}).hideEmptyGroups })
        },
        {
          label: _4("Maximize / minimize"),
          submenu: [
            {
              label: _4("Minimize all checklists"),
              offline: true,
              mobile: true,
              action: () => {
                $broadcast("minimizeAllGroups");
              },
              enabled: () => !groupBy2[0].isNothing()
            },
            {
              label: _4("Maximize all checklists"),
              offline: true,
              mobile: true,
              action: () => {
                $broadcast("maximizeAllGroups");
              },
              enabled: () => !groupBy2[0].isNothing()
            },
            {
              label: _4("Maximize all cards"),
              public: true,
              mobile: true,
              action: () => {
                $broadcast("maximizeAllCards");
              }
            },
            {
              label: _4("Minimize all cards"),
              public: true,
              mobile: true,
              action: () => {
                $broadcast("minimizeAllCards");
              }
            }
          ]
        },
        ...project ? [getFullScreenOption()] : [],
        ...getActionsOptions(options2, (changes) => onChange(changes), project)
      ]
    };
  }
});

// public/app/apps/cards/calendar/index.js
cardsAppRegistry.register("calendar", {
  component: "cards-app-calendar",
  title: _lazy("Calendar"),
  description: _lazy("Visualize cards on a classic calendar"),
  icon: "calendar",
  color: "#036351",
  filterable: true,
  needsField: "date",
  needsFieldMultiple: true,
  menu: (store2, board, groupBy2, options2 = {}, onChange) => {
    return { config: () => () => {
      const project = board ? projectStore.tryGetForCard(board) : null;
      return [
        ...getCommonModeOptions(options2, (changes) => onChange(changes)),
        { label: "--" },
        {
          checkbox: true,
          label: _4("Strike done cards"),
          offline: true,
          mobile: true,
          value: () => !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0,
          // Default to TRUE
          toggle: () => onChange({ strikeDoneCards: !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0 ? false : void 0 })
        },
        {
          checkbox: true,
          label: _4("Show week numbers"),
          offline: true,
          mobile: true,
          value: () => !!options2?.weekNumbers,
          toggle: () => onChange({ weekNumbers: !options2?.weekNumbers })
        },
        {
          label: _4("iCalendar feed"),
          icon: "link",
          enabled: () => !project.is_public,
          offline: false,
          action: () => {
            $invoke(["cardICalendarModal", (cardICalendarModal) => cardICalendarModal.open({ id: board.id })]);
          }
        },
        ...project ? [getFullScreenOption()] : [],
        ...getActionsOptions(options2, (changes) => onChange(changes), project)
      ];
    } };
  }
});

// public/app/ui/utils/dom-to-canvas.js
var import_html2canvas = __toESM(require_html2canvas());
function exportElementToImage(title, selector) {
  const element2 = document.querySelector(selector);
  if (element2) {
    (0, import_html2canvas.default)(element2, {
      allowTaint: true,
      useCORS: true,
      logging: true,
      scale: 2
    }).then((canvas) => {
      canvas.toBlob((blob) => {
        const url2 = URL.createObjectURL(blob);
        const a3 = document.createElement("a");
        a3.href = url2;
        a3.download = `${title}.png`;
        document.body.appendChild(a3);
        a3.click();
        document.body.removeChild(a3);
        URL.revokeObjectURL(url2);
      });
    }).catch((error2) => {
      console.error("Error capturing selector content:", error2);
    });
  } else {
    console.error("Element " + selector + " not found");
  }
}

// public/app/apps/cards/timeline/dom-to-canvas-helpers.js
var helpers = {};
helpers.backgroundColor = "#f8f8f8";
helpers.setSize = function(element2, canvas) {
  var $viewportElement = jquery_default(element2).find(".timeline-viewport");
  var $sidebarElement = jquery_default(element2).find(".timeline-sidebar");
  var $containerElement = jquery_default(element2).find(".timeline-container");
  var width = $containerElement.width() + ($sidebarElement.hasClass("ng-hide") ? 0 : $sidebarElement.width());
  var height = $viewportElement.height() + 18;
  canvas.height = height;
  canvas.width = width;
  return canvas;
};
helpers.convert = function(element2, canvas) {
  var $viewportElement = jquery_default(element2).find(".timeline-viewport");
  var $sidebarElement = jquery_default(element2).find(".timeline-sidebar");
  var $containerElement = jquery_default(element2).find(".timeline-container");
  var containerScrollLeft = $containerElement.scrollLeft();
  var ctx = canvas.getContext("2d");
  ctx.save();
  ctx.fillStyle = helpers.backgroundColor;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.restore();
  var hasSidebar = !$sidebarElement.hasClass("ng-hide");
  drawBackground($containerElement, ctx, { x: hasSidebar ? 300 : 0, y: 18 });
  var groupTopPos = $viewportElement.find(".timeline-content").get(0).offsetTop + 50;
  $viewportElement.find("cards-app-timeline-group:not(.ng-hide)").each(function() {
    drawTimelineGroup(jquery_default(this), ctx, { x: (hasSidebar ? 300 : 0) - containerScrollLeft, y: groupTopPos }, !hasSidebar, containerScrollLeft);
    groupTopPos += jquery_default(this).outerHeight(true);
  });
  if (hasSidebar) {
    ctx.save();
    ctx.shadowOffsetX = 1;
    ctx.shadowOffsetY = 0;
    ctx.shadowBlur = 4;
    ctx.shadowColor = "rgba(0, 0, 0, 0.05)";
    ctx.strokeStyle = "#e2e2e2";
    ctx.beginPath();
    ctx.moveTo(299.5, 0);
    ctx.lineTo(299.5, canvas.height);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
    ctx.save();
    ctx.fillStyle = helpers.backgroundColor;
    ctx.fillRect(0, 0, 299, canvas.height);
    ctx.restore();
    var sidebarGroupTopPos = $sidebarElement.find(".timeline-sidebar-container").get(0).offsetTop + 18;
    $sidebarElement.find("cards-app-timeline-sidebar-group:not(.ng-hide)").each(function() {
      drawSidebarGroup(jquery_default(this), ctx, { x: 0, y: sidebarGroupTopPos });
      sidebarGroupTopPos += jquery_default(this).outerHeight(true);
    });
  }
  return canvas;
};
function drawBackground($element2, ctx, pos) {
  var font = $element2.css("font-family");
  var minSpanWidth = $element2.find(".timeline-background > :first-child").width();
  var accuLeftPos = pos.x + minSpanWidth;
  var topPos = pos.y + 32;
  var startingDayIndex = Math.floor($element2.scrollLeft() / minSpanWidth);
  var currentOffsetLeft;
  ctx.save();
  ctx.strokeStyle = "#efefef";
  ctx.fillStyle = "#f2f2f2";
  ctx.beginPath();
  $element2.find(".timeline-background > span").filter(function(index2) {
    return index2 >= startingDayIndex;
  }).each(function(index2) {
    if (jquery_default(this).hasClass("with-separator")) {
      ctx.moveTo(accuLeftPos - 0.5, topPos);
      ctx.lineTo(accuLeftPos - 0.5, ctx.canvas.height);
    }
    if (jquery_default(this).hasClass("current")) {
      currentOffsetLeft = accuLeftPos - minSpanWidth;
    }
    if (this.style && this.style.backgroundColor) {
      ctx.fillRect(accuLeftPos - minSpanWidth, topPos - 22, minSpanWidth - 1, ctx.canvas.height);
    }
    accuLeftPos += minSpanWidth;
  });
  ctx.closePath();
  ctx.stroke();
  ctx.restore();
  var currentElement = $element2.find(".timeline-background > span.current");
  if (currentElement.length) {
    ctx.save();
    ctx.strokeStyle = "#337ab7";
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(currentOffsetLeft + minSpanWidth / 2, topPos);
    ctx.lineTo(currentOffsetLeft + minSpanWidth / 2, ctx.canvas.height);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
  drawDays($element2, ctx, pos);
  ctx.save();
  accuLeftPos = pos.x;
  ctx.font = "18px " + font;
  ctx.fillStyle = "#555555";
  $element2.find(".timeline-background > span").filter(function(index2) {
    return index2 >= startingDayIndex;
  }).each(function(index2) {
    if (jquery_default(this).children(".month-name").length) {
      var dayLabel = jquery_default(this).children(".month-name").get(0).innerText;
      ctx.fillText(dayLabel, accuLeftPos + 2, pos.y + 6);
    }
    accuLeftPos += minSpanWidth;
  });
  ctx.restore();
}
function drawDays($element2, ctx, pos) {
  var font = $element2.css("font-family");
  var minSpanWidth = $element2.find(".timeline-background > :first-child").width();
  var startingDayIndex = Math.floor($element2.scrollLeft() / minSpanWidth);
  var accuLeftPos = pos.x;
  var topPos = pos.y;
  var dateOffset = {
    x: 14,
    y: 10
  };
  ctx.save();
  ctx.font = "11px " + font;
  $element2.find(".timeline-dates > span").filter(function(index2) {
    return index2 >= startingDayIndex;
  }).each(function(index2) {
    var dateElement = jquery_default(this);
    var dayLabel = dateElement.children().get(0).innerText;
    if (dateElement.hasClass("current")) {
      var dateBackgroundColor = dateElement.children().css("background-color");
      ctx.save();
      ctx.beginPath();
      ctx.fillStyle = dateBackgroundColor;
      canvasRadius(ctx, accuLeftPos + 1, topPos + 10, minSpanWidth - 2, 22, 2);
      ctx.fill();
      ctx.closePath();
      ctx.restore();
    }
    ctx.save();
    var dateColor = dateElement.children().css("color");
    ctx.fillStyle = dateColor;
    if (minSpanWidth <= 20 && dateElement.hasClass("current")) {
      ctx.fillText(dayLabel, accuLeftPos, topPos + 25);
    } else {
      ctx.textAlign = "center";
      ctx.fillText(dayLabel, accuLeftPos + Math.round(minSpanWidth / 2), topPos + 25);
    }
    ctx.restore();
    accuLeftPos += minSpanWidth;
  });
  ctx.restore();
}
function drawSidebarGroup($element2, ctx, pos) {
  var font = $element2.css("font-family");
  var title = $element2.find(".cardlist-title > div > span").get(0).innerText;
  var color = $element2.find(".cardlist-title > div > span").css("color");
  var groupBgColor = $element2.find(".cardlist-title > div > span").css("background-color");
  var $contentElement = $element2.find("cardlist-content:not(.ng-hide)");
  ctx.save();
  ctx.fillStyle = groupBgColor;
  ctx.font = "14px " + font;
  var width = ctx.measureText(title).width >= 275 ? 275 : parseInt(ctx.measureText(title).width, 10);
  ctx.fillRect(pos.x + 9, pos.y + 7 + 1, 3 + width + 3, 2 + 20 + 2);
  ctx.restore();
  ctx.save();
  ctx.font = "14px " + font;
  ctx.fillStyle = color;
  ctx.fillText(fittingString(ctx, title, 275), pos.x + 12, pos.y + 9 + 17);
  ctx.restore();
  if ($element2.find(".cardlist-cards > .card-tile").length) {
    ctx.save();
    ctx.strokeStyle = "#dddddd";
    ctx.beginPath();
    ctx.moveTo(pos.x, parseInt(pos.y + $element2.find("cardlist-header").outerHeight(), 10) - 0.5);
    ctx.lineTo(pos.x + 300, parseInt(pos.y + $element2.find("cardlist-header").outerHeight(), 10) - 0.5);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
  if ($contentElement.length) {
    var cardTopPos = pos.y + $contentElement.get(0).offsetTop;
    $element2.find(".cardlist-cards > .card-tile").each(function() {
      drawSidebarCard(jquery_default(this), ctx, { x: pos.x + 0, y: cardTopPos });
      cardTopPos += jquery_default(this).outerHeight(true);
    });
    ctx.save();
    ctx.strokeStyle = "#dddddd";
    ctx.beginPath();
    ctx.moveTo(pos.x, parseInt(pos.y + $contentElement.outerHeight(), 10) - 0.5);
    ctx.lineTo(pos.x + 299, parseInt(pos.y + $contentElement.outerHeight(), 10) - 0.5);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
}
function drawCardBackground(ctx, fillStyle, left, top2, width, height, radius) {
  ctx.save();
  ctx.fillStyle = fillStyle;
  if (radius) {
    ctx.beginPath();
    canvasRadius(ctx, left, top2, width, height, radius);
    ctx.closePath();
    ctx.fill();
  } else {
    ctx.fillRect(left, top2, width, height);
  }
  ctx.restore();
}
function drawSidebarCard($element2, ctx, pos) {
  var $innerElement = $element2.find("> .card-tile-inner");
  var $childrenListElement = $element2.find("> .card-tile-children-list");
  var $titleElement = $innerElement.find(".card-tile-content > .title");
  var $refElement = $innerElement.find(".card-tile-content > .ref");
  var $modelIndicatorElement = $innerElement.find(".card-tile-content > .model-indicator");
  var $stateIndicatorElement = $innerElement.find(".card-tile-content > .state-indicator");
  var $childrenIndicatorElement = $innerElement.find(".card-tile-content > .card-tile-children");
  var hasModelIndicator = $modelIndicatorElement.length;
  var hasStateIndicator = $stateIndicatorElement.length;
  var hasChildrenIndicator = $childrenIndicatorElement.length;
  var refWidth = $refElement.outerWidth(true);
  var modelIndicatorWidth = 0;
  var stateIndicatorWidth = 0;
  var childrenIndicatorWidth = 0;
  if (hasModelIndicator) {
    modelIndicatorWidth = $modelIndicatorElement.outerWidth(true);
  }
  if (hasStateIndicator) {
    stateIndicatorWidth = $stateIndicatorElement.outerWidth(true);
  }
  if (hasChildrenIndicator) {
    childrenIndicatorWidth = $childrenIndicatorElement.outerWidth(true);
  }
  var font = $element2.css("font-family");
  var contentWidth = 299 - pos.x;
  var contentPaddingLeft = 7;
  var contentBaseline = pos.y + (pos.x ? 19 : 23);
  var contentFontSize = pos.x ? 12 : 14;
  var titlePaddingLeft = 5;
  var titleColor = $titleElement.css("color");
  var titleFontSize = contentFontSize;
  var titleText = $element2.find(".card-tile-content > .title").get(0).innerText;
  var titleMaxWidth = contentWidth - contentPaddingLeft - refWidth - childrenIndicatorWidth - modelIndicatorWidth - stateIndicatorWidth - titlePaddingLeft;
  var titlePosLeft = pos.x + contentPaddingLeft + modelIndicatorWidth + titlePaddingLeft;
  var bgColor = $innerElement.css("background-color");
  drawCardBackground(ctx, bgColor || "#ffffff", pos.x, pos.y, contentWidth, parseInt($innerElement.outerHeight(), 10));
  var imgUrl = $innerElement.css("background-image");
  if (imgUrl && imgUrl !== "none") {
    var img = new Image();
    img.src = imgUrl.slice(5, -2);
    drawCardBackground(ctx, ctx.createPattern(img, "repeat"), pos.x, pos.y, contentWidth, parseInt($innerElement.outerHeight(), 10));
  }
  if (hasModelIndicator) {
    var modelIndicatorText = getFontAwesomeCode($modelIndicatorElement);
    var modelIndicatorColor = $modelIndicatorElement.css("color");
    var modelIndicatorFontSize = contentFontSize;
    var modelIndicatorPaddingLeft = 5;
    var modelIndicatorPosLeft = pos.x + contentPaddingLeft + modelIndicatorPaddingLeft;
    ctx.save();
    ctx.font = modelIndicatorFontSize + "px FontAwesome";
    ctx.fillStyle = modelIndicatorColor;
    ctx.fillText(modelIndicatorText, modelIndicatorPosLeft, contentBaseline);
    ctx.restore();
  }
  ctx.save();
  ctx.font = titleFontSize + "px " + font;
  var titleMeasuredWidth = parseInt(ctx.measureText(titleText).width, 10);
  var titleWidth = titleMeasuredWidth >= titleMaxWidth ? titleMaxWidth : titleMeasuredWidth;
  ctx.fillStyle = titleColor;
  ctx.fillText(fittingString(ctx, titleText, titleMaxWidth), titlePosLeft, contentBaseline);
  ctx.restore();
  if ($element2.hasClass("finished")) {
    lineThroughText(ctx, titleWidth, { x: titlePosLeft, y: contentBaseline }, titleFontSize, titleColor);
  }
  if (hasChildrenIndicator) {
    var $childrenIndicatorIconElement = $childrenIndicatorElement.children().eq(0);
    var $childrenIndicatorTextElement = $childrenIndicatorElement.children().eq(1);
    var $childrenIndicatorCaretElement = $childrenIndicatorElement.children().eq(2).children().eq($childrenIndicatorElement.hasClass("is-opened") ? 1 : 0);
    var childrenIndicatorColor = $childrenIndicatorElement.css("color");
    var childrenIndicatorBackgroundColor = $childrenIndicatorElement.css("background-color");
    var childrenIndicatorFontSize = 12;
    var childrenIndicatorMarginRight = 4;
    var childrenIndicatorPaddingLeftRight = 4;
    var childrenIndicatorPaddingTopBottom = 4;
    var childrenIndicatorHeight = $childrenIndicatorElement.outerHeight();
    var childrenIndicatorPosLeft = pos.x + contentWidth - refWidth - stateIndicatorWidth - childrenIndicatorWidth;
    var childrenIndicatorPosTop = pos.y + $childrenIndicatorElement.get(0).offsetTop;
    var childrenIndicatorBaseline = childrenIndicatorHeight - childrenIndicatorPaddingTopBottom;
    ctx.save();
    ctx.translate(childrenIndicatorPosLeft, childrenIndicatorPosTop);
    ctx.save();
    ctx.beginPath();
    ctx.fillStyle = childrenIndicatorBackgroundColor;
    canvasRadius(ctx, 0, 0, childrenIndicatorWidth - childrenIndicatorMarginRight, childrenIndicatorHeight, 2);
    ctx.fill();
    ctx.closePath();
    ctx.restore();
    ctx.save();
    ctx.font = childrenIndicatorFontSize + "px FontAwesome";
    ctx.fillStyle = childrenIndicatorColor;
    ctx.fillText(getFontAwesomeCode($childrenIndicatorIconElement), childrenIndicatorPaddingLeftRight, childrenIndicatorBaseline);
    ctx.restore();
    ctx.save();
    ctx.font = childrenIndicatorFontSize + "px " + font;
    ctx.fillStyle = childrenIndicatorColor;
    ctx.fillText($childrenIndicatorTextElement.get(0).innerText, childrenIndicatorPaddingLeftRight + $childrenIndicatorIconElement.outerWidth() + 3, childrenIndicatorBaseline);
    ctx.restore();
    if ($childrenIndicatorCaretElement.length) {
      ctx.save();
      ctx.font = childrenIndicatorFontSize + "px FontAwesome";
      ctx.fillStyle = childrenIndicatorColor;
      ctx.textAlign = "right";
      ctx.fillText(getFontAwesomeCode($childrenIndicatorCaretElement), childrenIndicatorWidth - childrenIndicatorMarginRight - childrenIndicatorPaddingLeftRight, childrenIndicatorBaseline);
      ctx.restore();
    }
    ctx.restore();
  }
  if (hasStateIndicator) {
    var stateIndicatorText = getFontAwesomeCode($stateIndicatorElement);
    var stateIndicatorColor = $stateIndicatorElement.css("color");
    var stateIndicatorFontSize = 12;
    var stateIndicatorPosLeft = pos.x + contentWidth - refWidth - stateIndicatorWidth;
    ctx.save();
    ctx.font = stateIndicatorFontSize + "px FontAwesome";
    ctx.fillStyle = stateIndicatorColor;
    ctx.fillText(stateIndicatorText, stateIndicatorPosLeft, contentBaseline);
    ctx.restore();
  }
  var refText = $refElement.get(0).innerText;
  var refColor = $refElement.css("color");
  var refFontSize = 11;
  var refPaddingRight = 6;
  var refPosRight = pos.x + contentWidth - refPaddingRight;
  ctx.save();
  ctx.font = refFontSize + "px " + font;
  ctx.textAlign = "right";
  ctx.fillStyle = refColor;
  ctx.fillText(refText, refPosRight, contentBaseline);
  ctx.restore();
  var cardBottomWidth = $element2.css("border-bottom-width");
  if (cardBottomWidth && cardBottomWidth !== "0px") {
    ctx.save();
    ctx.strokeStyle = "#dddddd";
    ctx.beginPath();
    ctx.moveTo(pos.x, parseInt(pos.y + $element2.outerHeight(), 10) - 0.5);
    ctx.lineTo(pos.x + contentWidth, parseInt(pos.y + $element2.outerHeight(), 10) - 0.5);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
  if ($childrenListElement.length) {
    ctx.save();
    ctx.strokeStyle = "#dddddd";
    ctx.beginPath();
    ctx.moveTo(pos.x, parseInt(pos.y + $innerElement.outerHeight(), 10) - 0.5);
    ctx.lineTo(pos.x + contentWidth, parseInt(pos.y + $innerElement.outerHeight(), 10) - 0.5);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
  if (pos.x) {
    ctx.save();
    ctx.strokeStyle = "#dddddd";
    ctx.beginPath();
    ctx.moveTo(pos.x - 0.5, pos.y);
    ctx.lineTo(pos.x - 0.5, pos.y + parseInt($innerElement.outerHeight(), 10));
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
  if (!$element2.hasClass("has-daterange") || $element2.hasClass("finished")) {
    drawCardBackground(ctx, "rgba(255,255,255,0.7)", pos.x, pos.y, contentWidth, parseInt($innerElement.outerHeight(), 10));
  }
  if ($childrenListElement.length) {
    var cardTopPos = pos.y + $childrenListElement.get(0).offsetTop;
    $childrenListElement.find("> .card-tile").each(function() {
      drawSidebarCard(jquery_default(this), ctx, { x: pos.x + 16, y: cardTopPos });
      cardTopPos += jquery_default(this).outerHeight(true);
    });
  }
}
function drawTimelineGroup($element2, ctx, pos, isCompact, scrolledDistance) {
  scrolledDistance = scrolledDistance || 0;
  var font = $element2.css("font-family");
  var $contentElement = $element2.find(".timeline-group-content:not(.ng-hide)");
  if (isCompact) {
    ctx.save();
    var title = $element2.find(".cardlist-title > div > span").get(0).innerText;
    ctx.font = "14px " + font;
    ctx.fillStyle = "#555555";
    ctx.fillText(title, pos.x + scrolledDistance + 12, pos.y + 9 + 17);
    ctx.restore();
  }
  if ($contentElement.length) {
    var cardTopPos = pos.y + $contentElement.get(0).offsetTop;
    $contentElement.find("> cards-app-timeline-card").each(function() {
      var topPos;
      if (isCompact) {
        var transformedTopPos = getTransformedTopPos(this);
        if (transformedTopPos === false) {
          return;
        }
        topPos = cardTopPos + transformedTopPos;
      } else {
        topPos = cardTopPos;
        cardTopPos += jquery_default(this).outerHeight(true);
      }
      drawTimelineCard(jquery_default(this), ctx, { x: pos.x + 0, y: topPos }, isCompact);
    });
  }
}
function drawTimelineCardChildrenBackground($bgElement, ctx, pos) {
  var $innerElement = $bgElement.find(".cards-app-timeline-cards-background-inner");
  var $topBorderElement = $bgElement.find(".cards-app-timeline-card-global-date-range-object");
  var left = $bgElement.get(0).offsetLeft;
  var top2 = $bgElement.get(0).offsetTop;
  var width = $bgElement.get(0).offsetWidth;
  var height = $bgElement.get(0).offsetHeight;
  var triangleTopBorderSize = 14;
  var backgroundColor = $innerElement.css("background-color");
  var borderColor = $innerElement.css("border-left-color");
  var topBorderColor = $topBorderElement.hasClass("faded") ? borderColor : $topBorderElement.css("border-top-color");
  if (!$innerElement.hasClass("ng-hide")) {
    ctx.save();
    ctx.fillStyle = backgroundColor;
    ctx.fillRect(pos.x + left, pos.y + top2, width, height);
    ctx.restore();
    ctx.save();
    ctx.lineWidth = 1;
    ctx.strokeStyle = borderColor;
    ctx.beginPath();
    canvasRadius(ctx, pos.x + left, pos.y + top2, width, height, 0);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
  }
  ctx.save();
  ctx.lineWidth = 4;
  ctx.strokeStyle = topBorderColor;
  ctx.beginPath();
  ctx.moveTo(pos.x + left, pos.y + top2);
  ctx.lineTo(pos.x + left + width, pos.y + top2);
  ctx.closePath();
  ctx.stroke();
  ctx.restore();
  ctx.save();
  ctx.lineWidth = 1;
  ctx.fillStyle = topBorderColor;
  ctx.beginPath();
  ctx.moveTo(pos.x + left, pos.y + top2 - triangleTopBorderSize / 2);
  ctx.lineTo(pos.x + left + triangleTopBorderSize, pos.y + top2);
  ctx.lineTo(pos.x + left, pos.y + top2 + triangleTopBorderSize / 2);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
  ctx.save();
  ctx.lineWidth = 1;
  ctx.fillStyle = topBorderColor;
  ctx.beginPath();
  ctx.moveTo(pos.x + left + width, pos.y + top2 - triangleTopBorderSize / 2);
  ctx.lineTo(pos.x + left + width - triangleTopBorderSize, pos.y + top2);
  ctx.lineTo(pos.x + left + width, pos.y + top2 + triangleTopBorderSize / 2);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
}
function drawTimelineCard($element2, ctx, pos, isCompact, isChild) {
  var $contentElement = $element2.find("> .timeline-object > .timeline-object-container > .cards-app-timeline-card-container");
  var $childrenListElement = $element2.find("> .cards-app-timeline-card-children-list");
  var $titleElement = $contentElement.find(".cards-app-timeline-card-title");
  var $refElement = $contentElement.find(".cards-app-timeline-card-ref");
  var $modelIndicatorElement = $contentElement.find(".model-indicator:not(.ng-hide)");
  var $stateIndicatorElement = $contentElement.find(".state-indicator:not(.ng-hide)");
  var $childrenIndicatorElement = $contentElement.find(".card-tile-children:not(.ng-hide)");
  var hasModelIndicator = $modelIndicatorElement.length;
  var hasStateIndicator = $stateIndicatorElement.length;
  var hasChildrenIndicator = $childrenIndicatorElement.length;
  var refWidth = $refElement.outerWidth(true);
  var titleWidth = $titleElement.outerWidth(true);
  var modelIndicatorWidth = 0;
  var stateIndicatorWidth = 0;
  var childrenIndicatorWidth = 0;
  if (hasModelIndicator) {
    modelIndicatorWidth = $modelIndicatorElement.outerWidth(true);
  }
  if (hasStateIndicator) {
    stateIndicatorWidth = $stateIndicatorElement.outerWidth(true);
  }
  if (hasChildrenIndicator) {
    childrenIndicatorWidth = $childrenIndicatorElement.outerWidth(true);
  }
  var font = $element2.css("font-family");
  var contentPosLeft = pos.x + $element2.find("> .timeline-object > .timeline-object-container").get(0).offsetLeft + $contentElement.get(0).offsetLeft;
  var contentPosTop = pos.y + (isChild ? 2 : 4);
  var contentWidth = $contentElement.get(0).offsetWidth;
  var contentHeight = isChild ? 23 : 30;
  var contentBorderRadius = 2;
  var contentBaseline = isChild ? 15 : 20;
  var contentFontSize = isChild ? 12 : 14;
  if ($childrenListElement.find("> .cards-app-timeline-card-children-list-container").length) {
    drawTimelineCardChildrenBackground($childrenListElement.find("> .cards-app-timeline-cards-background"), ctx, { x: pos.x, y: pos.y + $element2.find("> .timeline-object").outerHeight() });
    var cardTopPos = pos.y + $childrenListElement.get(0).offsetTop;
    $childrenListElement.find("> .cards-app-timeline-card-children-list-container > cards-app-timeline-card").each(function() {
      var topPos;
      if (isCompact) {
        var transformedTopPos = getTransformedTopPos(this);
        if (transformedTopPos === false) {
          return;
        }
        topPos = cardTopPos + transformedTopPos;
      } else {
        topPos = cardTopPos;
        cardTopPos += jquery_default(this).outerHeight(true);
      }
      drawTimelineCard(jquery_default(this), ctx, { x: pos.x, y: topPos }, isCompact, true);
    });
  }
  if (!contentWidth) {
    return;
  }
  var displayRef = true;
  var displayStateIndicator = true;
  var displayModelIndicator = true;
  var displayTitle = true;
  var displayChildrenIndicator = true;
  if (isCompact) {
    if (refWidth + stateIndicatorWidth + modelIndicatorWidth + titleWidth + childrenIndicatorWidth > contentWidth) {
      displayChildrenIndicator = false;
    }
    if (refWidth + stateIndicatorWidth + modelIndicatorWidth + 10 > contentWidth) {
      displayTitle = false;
    }
    if (refWidth + stateIndicatorWidth + modelIndicatorWidth > contentWidth) {
      displayModelIndicator = false;
    }
    if (refWidth + stateIndicatorWidth > contentWidth) {
      displayStateIndicator = true;
    }
    if (refWidth < 10) {
      displayRef = false;
    }
  }
  ctx.save();
  ctx.translate(contentPosLeft, contentPosTop);
  var colors = $contentElement.css(["border-left-color", "color", "background-color", "background-image"]);
  var borderColor = colors["border-left-color"];
  var color = colors.color;
  var backgroundColor = colors["background-color"];
  var backgroundImage = colors["background-image"];
  drawCardBackground(ctx, backgroundColor, 0, 0, contentWidth - 2, contentHeight, contentBorderRadius);
  var imgUrl = backgroundImage;
  if (imgUrl && imgUrl !== "none") {
    var img = new Image();
    img.src = imgUrl.slice(5, -2);
    drawCardBackground(ctx, ctx.createPattern(img, "repeat"), 0, 0, contentWidth - 2, contentHeight, contentBorderRadius);
  }
  ctx.save();
  ctx.lineWidth = 1;
  ctx.strokeStyle = borderColor;
  ctx.beginPath();
  canvasRadius(ctx, 0, 0, contentWidth - 2, contentHeight, contentBorderRadius);
  ctx.stroke();
  ctx.closePath();
  ctx.restore();
  if (displayRef) {
    var refText = $refElement.get(0).innerText;
    var refPaddingLeftRight = 6;
    var refColor = $refElement.css("color");
    ctx.save();
    ctx.font = "11px " + font;
    ctx.fillStyle = refColor;
    if (isCompact && contentWidth <= 30) {
      ctx.textAlign = "center";
      ctx.fillText(refText, Math.round((contentWidth - 2) / 2), contentBaseline);
    } else {
      ctx.fillText(refText, refPaddingLeftRight, contentBaseline);
    }
    ctx.restore();
  }
  if (hasStateIndicator && displayStateIndicator) {
    var stateIndicatorText = getFontAwesomeCode($stateIndicatorElement);
    var stateIndicatorColor = $stateIndicatorElement.css("color");
    var stateIndicatorFontSize = 12;
    var stateIndicatorPosLeft = refWidth;
    ctx.save();
    ctx.font = stateIndicatorFontSize + "px FontAwesome";
    ctx.fillStyle = stateIndicatorColor;
    ctx.fillText(stateIndicatorText, stateIndicatorPosLeft, contentBaseline);
    ctx.restore();
  }
  if (hasModelIndicator && displayModelIndicator) {
    var modelIndicatorText = getFontAwesomeCode($modelIndicatorElement);
    var modelIndicatorColor = $modelIndicatorElement.css("color");
    var modelIndicatorFontSize = contentFontSize;
    var modelIndicatorPosLeft = refWidth + stateIndicatorWidth;
    ctx.save();
    ctx.font = modelIndicatorFontSize + "px FontAwesome";
    ctx.fillStyle = modelIndicatorColor;
    ctx.fillText(modelIndicatorText, modelIndicatorPosLeft, contentBaseline);
    ctx.restore();
  }
  if (displayTitle) {
    var titleFontSize = contentFontSize;
    var titlePaddingRight = 6;
    var titlePosLeft = refWidth + stateIndicatorWidth + modelIndicatorWidth;
    var titleText = $titleElement.get(0).innerText;
    ctx.save();
    ctx.font = titleFontSize + "px " + font;
    titleText = isCompact ? fittingString(ctx, titleText, contentWidth - titlePosLeft) : titleText;
    var titleTextWidth = ctx.measureText(titleText).width;
    ctx.fillStyle = color;
    ctx.fillText(titleText, titlePosLeft, contentBaseline);
    if ($contentElement.hasClass("finished")) {
      lineThroughText(ctx, titleTextWidth, { x: titlePosLeft, y: contentBaseline }, titleFontSize, color);
    }
    ctx.restore();
  }
  if (hasChildrenIndicator && displayChildrenIndicator) {
    var $childrenIndicatorTextElement = $childrenIndicatorElement.children().eq(0);
    var $childrenIndicatorCaretElement = $childrenIndicatorElement.children().eq(1).children().eq($childrenIndicatorElement.hasClass("is-opened") ? 1 : 0);
    var childrenIndicatorColor = $childrenIndicatorElement.css("color");
    var childrenIndicatorBackgroundColor = $childrenIndicatorElement.css("background-color");
    var childrenIndicatorFontSize = 12;
    var childrenIndicatorPaddingLeftRight = 4;
    var childrenIndicatorPaddingTopBottom = isChild ? 3 : 4;
    var childrenIndicatorHeight = $childrenIndicatorElement.outerHeight();
    var childrenIndicatorPosLeft = refWidth + stateIndicatorWidth + modelIndicatorWidth + titleWidth;
    var childrenIndicatorPosTop = $childrenIndicatorElement.get(0).offsetTop;
    var childrenIndicatorBaseline = childrenIndicatorHeight - childrenIndicatorPaddingTopBottom;
    ctx.save();
    ctx.translate(childrenIndicatorPosLeft, childrenIndicatorPosTop);
    ctx.save();
    ctx.beginPath();
    ctx.fillStyle = childrenIndicatorBackgroundColor;
    canvasRadius(ctx, 0, 0, childrenIndicatorWidth, childrenIndicatorHeight, 2);
    ctx.fill();
    ctx.closePath();
    ctx.restore();
    ctx.save();
    ctx.font = childrenIndicatorFontSize + "px " + font;
    ctx.fillStyle = childrenIndicatorColor;
    ctx.fillText($childrenIndicatorTextElement.get(0).innerText, childrenIndicatorPaddingLeftRight, childrenIndicatorBaseline);
    ctx.restore();
    if ($childrenIndicatorCaretElement.length) {
      ctx.save();
      ctx.font = childrenIndicatorFontSize + "px FontAwesome";
      ctx.fillStyle = childrenIndicatorColor;
      ctx.textAlign = "right";
      ctx.fillText(getFontAwesomeCode($childrenIndicatorCaretElement), childrenIndicatorWidth - childrenIndicatorPaddingLeftRight, childrenIndicatorBaseline);
      ctx.restore();
    }
    ctx.restore();
  }
  if ($contentElement.hasClass("finished")) {
    drawCardBackground(ctx, "rgba(255,255,255,0.7)", 0, 0, contentWidth - 2, contentHeight, contentBorderRadius);
  }
  ctx.restore();
}
function fittingString(ctx, str, maxWidth) {
  var width = ctx.measureText(str).width;
  var ellipsis2 = "\u2026";
  var ellipsisWidth = ctx.measureText(ellipsis2).width;
  if (width <= maxWidth || width <= ellipsisWidth) {
    return str;
  } else {
    var len = str.length;
    while (width >= maxWidth - ellipsisWidth && len-- > 0) {
      str = str.substring(0, len);
      width = ctx.measureText(str).width;
    }
    return str + ellipsis2;
  }
}
function getTransformedTopPos(objectEl) {
  var match2 = objectEl.style.transform.match(/translate3d\((-?[0-9]+)(?:px)?, ?(-?[0-9]+)(?:px)?, ?(-?[0-9]+)(?:px)?\)/);
  if (match2 === null || match2.length < 2) {
    return false;
  }
  return match2[2] ? parseInt(match2[2], 10) : 0;
}
function lineThroughText(ctx, textWidth, textPos, textSize, lineThroughColor) {
  ctx.save();
  ctx.strokeStyle = lineThroughColor;
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(textPos.x - 2, textPos.y - parseInt(textSize / 4, 10) - 0.5);
  ctx.lineTo(textPos.x + textWidth + 2, textPos.y - parseInt(textSize / 4, 10) - 0.5);
  ctx.closePath();
  ctx.stroke();
  ctx.restore();
}
function canvasRadius(ctx, x3, y3, width, height, radius) {
  var right = x3 + width, bottom = y3 + height;
  ctx.moveTo(x3 + radius, y3);
  ctx.lineTo(right - radius, y3);
  ctx.quadraticCurveTo(right, y3, right, y3 + radius);
  ctx.lineTo(right, bottom - radius);
  ctx.quadraticCurveTo(right, bottom, right - radius, bottom);
  ctx.lineTo(x3 + radius, bottom);
  ctx.quadraticCurveTo(x3, bottom, x3, bottom - radius);
  ctx.lineTo(x3, y3 + radius);
  ctx.quadraticCurveTo(x3, y3, x3 + radius, y3);
}
function getFontAwesomeCode($element2) {
  return window.getComputedStyle($element2.get(0), ":before").content.replace(/"/g, "");
}

// public/app/apps/cards/timeline/index.js
cardsAppRegistry.register("timeline", {
  component: "cards-app-timeline",
  navComponent: "cards-app-nav-timeline",
  title: _lazy("Timeline"),
  description: _lazy("Visualize your cards on a timeline"),
  icon: "kfi-timeline",
  filterable: true,
  groupable: true,
  sortable: true,
  mobileReadOnly: true,
  needsField: "date",
  // convertToImage: (title) => {
  //   const canvas = createCanvasFromElement(angular.element('.cards-app-timeline-content').get(0), domToCanvasHelpers);
  //   downloadCanvasAsImage(canvas, title);
  // },
  menu: (store2, board, groupBy2, options2 = {}, onChange) => {
    const project = board ? projectStore.tryGetForCard(board) : null;
    return { config: () => () => [
      { label: "--" },
      { subheader: _4("Visibility of cards") },
      {
        checkbox: true,
        label: _4("Ungrouped"),
        offline: true,
        mobile: true,
        value: () => !!(options2 || {}).showUngroupedCards,
        toggle: () => onChange({ showUngroupedCards: !(options2 || {}).showUngroupedCards })
      },
      ...getCommonModeOptions(options2, (changes) => onChange(changes)),
      { label: "--" },
      { subheader: _4("More") },
      {
        checkbox: true,
        label: _4("Strike done cards"),
        offline: true,
        mobile: true,
        value: () => !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0,
        // Default to TRUE
        toggle: () => onChange({ strikeDoneCards: !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0 ? false : void 0 })
      },
      {
        checkbox: true,
        label: _4("Hide empty groups"),
        offline: false,
        mobile: true,
        value: () => !!(options2 || {}).hideEmptyGroups,
        toggle: () => onChange({ hideEmptyGroups: !(options2 || {}).hideEmptyGroups })
      },
      {
        label: _4("iCalendar feed"),
        icon: "link",
        public: false,
        offline: false,
        action: () => $invoke(["cardICalendarModal", (cardICalendarModal) => cardICalendarModal.open({ id: board.id })]),
        enabled: () => !!board
      },
      {
        label: _4("Maximize / minimize"),
        submenu: [
          {
            label: _4("Minimize all sections"),
            offline: true,
            mobile: true,
            action: () => {
              $broadcast("minimizeAllGroups");
            },
            enabled: () => !groupBy2[0].isNothing()
          },
          {
            label: _4("Maximize all sections"),
            offline: true,
            mobile: true,
            action: () => {
              $broadcast("maximizeAllGroups");
            },
            enabled: () => !groupBy2[0].isNothing()
          },
          {
            label: _4("Maximize all cards"),
            public: true,
            mobile: true,
            action: () => {
              $broadcast("maximizeAllCards");
            }
          },
          {
            label: _4("Minimize all cards"),
            public: true,
            mobile: true,
            action: () => {
              $broadcast("minimizeAllCards");
            }
          }
        ]
      },
      ...project ? [getFullScreenOption()] : [],
      ...getActionsOptions(options2, (changes) => onChange(changes), project)
    ] };
  }
});

// public/app/apps/cards/timeline/utils.js
function isDateRangesEqual(firstDateRange, secondDateRange) {
  if (!firstDateRange && !secondDateRange) return true;
  if (firstDateRange && secondDateRange && firstDateRange.start.isSame(secondDateRange.start, "day") && firstDateRange.end.isSame(secondDateRange.end, "day")) {
    return true;
  }
  return false;
}
function getMinMaxFromDateRanges(dateRanges) {
  dateRanges = (dateRanges || []).filter(function(dateRange) {
    return !!dateRange;
  });
  if (!dateRanges.length) return null;
  return dateRanges.reduce(function(accu, dateRange) {
    if (accu.start === null) {
      accu.start = dateRange.start;
    } else {
      accu.start = moment_default.min(accu.start, dateRange.start);
    }
    if (accu.end === null) {
      accu.end = dateRange.end;
    } else {
      accu.end = moment_default.max(accu.end, dateRange.end);
    }
    return accu;
  }, {
    start: null,
    end: null
  });
}
function extractCardDateRangeFromAttribute(card, attr, options2) {
  var cardDateAttr = getCardAttribute(card, attr);
  const { start, end } = parseDateFromComputedAttribute(attr, cardDateAttr, options2) || {};
  if (!start && !end) return null;
  return { start, end };
}
function _convertCardToTimelineObject(card, attr, includeArchived, dateRangeOnly) {
  var realCard = cardStore.isValidMirror(card) ? cardStore.get(card.link.id) : card;
  var dateRange = extractCardDateRangeFromAttribute(realCard, attr);
  var descendantsDateRange = null;
  var globalDateRange = null;
  if (!dateRangeOnly) {
    if (realCard.nb_children) {
      var allCardDescendants = cardStore.scopedByProject({ id: realCard.project_id }).scoped({
        is_archived: function(v3) {
          return includeArchived || !v3;
        }
      }).query(function(c3) {
        return cardStore.isCardDescendantOf(c3, realCard) && // filters mirror link if it is not loaded in cardStore
        (!cardStore.isValidMirror(c3) || cardStore.exists(c3.link.id));
      });
      descendantsDateRange = getMinMaxFromDateRanges(allCardDescendants.map(function(descendantCard) {
        var realDescendantCard = cardStore.isValidMirror(descendantCard) ? cardStore.get(descendantCard.link.id) : descendantCard;
        return extractCardDateRangeFromAttribute(realDescendantCard, attr);
      }));
    }
    globalDateRange = getMinMaxFromDateRanges([descendantsDateRange, dateRange]);
  }
  return {
    id: "card_" + card.id,
    _card: card,
    parent_id: card.parent_id,
    dateRange,
    descendantsDateRange,
    globalDateRange
  };
}
function convertCardsToTimelineObjects(cards, activeDateAttribute, includeArchived) {
  return (cards || []).filter((card) => areAttributesAvailableForCard(card, activeDateAttribute)).map((card) => {
    var attr = getCardAvailableAttributes(card, activeDateAttribute)[0];
    return _convertCardToTimelineObject(card, attr, includeArchived);
  });
}

// public/app/stores/utils/BaseStore.ts
var StorePropMarker = Symbol("__kantree_store_property");
var StorePropInitialValue = Symbol(
  "__kantree_store_initial_value"
);
var StoreEffectMarker = Symbol("__kantree_store_effect");
var StoreEffectCallback = Symbol(
  "__kantree_store_effect_callback"
);
var StoreEffectOptions = Symbol(
  "__kantree_store_effect_options"
);
function prop(initialValue) {
  return {
    [StorePropMarker]: true,
    [StorePropInitialValue]: initialValue
  };
}
function effect(callbackOrOn, callback, options2) {
  return {
    [StoreEffectMarker]: true,
    [StoreEffectCallback]: [callbackOrOn, callback].filter(Boolean),
    [StoreEffectOptions]: options2
  };
}
function hasOnInit(store2) {
  return "onInit" in store2;
}
var isStoreProp = (prop2) => typeof prop2 === "object" && prop2?.[StorePropMarker] === true;
var isStoreEffect = (prop2) => typeof prop2 === "object" && prop2?.[StoreEffectMarker] === true;
var StoreMetaSymbol = Symbol("__kantree_store_meta");
var StoreAccessorsDefinedSymbol = Symbol(
  "__kantree_store_accessors_defined"
);
function getOrCreateMeta(instance) {
  const ctor2 = instance.constructor;
  let meta2 = Object.prototype.hasOwnProperty.call(
    ctor2,
    StoreMetaSymbol
  ) ? ctor2[StoreMetaSymbol] : void 0;
  if (!meta2) {
    const propKeys = [];
    const effectKeys = [];
    const defaultInit = {};
    for (const key2 in instance) {
      if (!Object.prototype.hasOwnProperty.call(instance, key2)) continue;
      const val = instance[key2];
      if (isStoreProp(val)) {
        propKeys.push(key2);
        defaultInit[key2] = val[StorePropInitialValue];
      }
      if (isStoreEffect(val)) effectKeys.push(key2);
    }
    if (!Object.prototype.hasOwnProperty.call(ctor2, StoreAccessorsDefinedSymbol)) {
      const descriptors = {};
      for (let i3 = 0; i3 < propKeys.length; i3++) {
        const key2 = propKeys[i3];
        descriptors[key2] = {
          get() {
            return this.state[key2];
          },
          set(value2) {
            const self2 = this;
            if (isStoreProp(value2)) {
              Object.defineProperty(self2, key2, {
                value: value2,
                writable: true,
                enumerable: true,
                configurable: true
              });
              return;
            }
            this.setState(key2, value2);
          },
          enumerable: false,
          configurable: true
        };
      }
      Object.defineProperties(ctor2.prototype, descriptors);
      Object.defineProperty(ctor2, StoreAccessorsDefinedSymbol, {
        value: true,
        enumerable: false,
        writable: false,
        configurable: false
      });
    }
    meta2 = { propKeys, effectKeys, defaultInit };
    Object.defineProperty(ctor2, StoreMetaSymbol, {
      value: meta2,
      enumerable: false,
      writable: false,
      configurable: false
    });
  }
  return meta2;
}
var BaseStore = class {
  init(initialValue) {
    runWithOwner(this.owner ?? getOwner(), () => {
      this.setupStoreAndProps(initialValue);
      this.setupEffects();
      if (hasOnInit(this)) {
        this.onInit();
      }
    });
    return this;
  }
  setupStoreAndProps(initialValue) {
    const { defaultInit, propKeys } = getOrCreateMeta(this);
    const initObj = initialValue ? Object.assign({}, defaultInit, initialValue) : { ...defaultInit };
    [this.state, this.setState] = createStore(initObj);
    for (let i3 = 0; i3 < propKeys.length; i3++) {
      const key2 = propKeys[i3];
      if (Object.prototype.hasOwnProperty.call(this, key2)) {
        if (!delete this[key2]) {
          Object.defineProperty(this, key2, {
            get: () => this.state[key2],
            set: (value2) => this.setState(key2, value2),
            enumerable: false,
            configurable: true
          });
        }
      }
    }
  }
  setupEffects() {
    const { effectKeys } = getOrCreateMeta(this);
    for (const key2 of effectKeys) {
      const val = this[key2];
      const effects = val[StoreEffectCallback];
      const opts = val[StoreEffectOptions];
      const cbs = effects.map(
        (callback) => typeof callback === "string" ? this[callback] : callback
      );
      if (cbs.length === 1) {
        createEffect((...args) => cbs[0].call(this, ...args));
      } else if (cbs.length === 2) {
        createEffect(
          on(cbs[0].bind(this), cbs[1].bind(this), opts)
        );
      }
    }
  }
  update(data2) {
    if (typeof data2 === "function") {
      this.setState(produce(data2));
    } else {
      this.setState(produce((draft) => Object.assign(draft, data2)));
    }
  }
  getState() {
    return this.state;
  }
  static create(initialValue, owner) {
    const instance = new this();
    instance.owner = owner;
    return instance.init(initialValue);
  }
};

// public/app/ui/base/selectable/Selectable.ts
var SelectableState = class {
  constructor() {
    this.selection = [];
  }
};
function createSelectable() {
  class Selectable extends createStoreMixin(SelectableState) {
    constructor() {
      super();
    }
    isSelected(item) {
      return this.selection.includes(item);
    }
    select(...items) {
      this.setState("selection", (list2) => [
        ...list2,
        ...items.filter((i3) => !this.isSelected(i3))
      ]);
    }
    unselect(...items) {
      this.setState(
        "selection",
        (list2) => list2.filter((i3) => !items.includes(i3))
      );
    }
    toggle(...items) {
      batch(() => {
        items.forEach((i3) => {
          if (this.isSelected(i3)) {
            this.unselect(i3);
          } else {
            this.select(i3);
          }
        });
      });
    }
    unselectAll() {
      this.setState("selection", []);
    }
  }
  return new Selectable();
}

// public/app/ui/base/selectable/context.tsx
var SelectableContext = createContext();
function SelectableProvider(props2) {
  return createComponent(SelectableContext.Provider, {
    get value() {
      return props2.selectable;
    },
    get children() {
      return props2.children;
    }
  });
}
function createSpecificSelectable() {
  const Context = createContext();
  const useSelectable = () => useContext(Context);
  const Provider = (props2) => createComponent(Context.Provider, {
    get value() {
      return props2.selectable;
    },
    get children() {
      return props2.children;
    }
  });
  return {
    useSelectable,
    Provider,
    createSelectable
  };
}

// public/app/ui/timeline/selectables.ts
var {
  Provider: SelectPeriodProvider,
  createSelectable: createPeriodSelectable,
  useSelectable: usePeriodSelectable
} = createSpecificSelectable();
var {
  Provider: SelectRelationProvider,
  createSelectable: createRelationSelectable,
  useSelectable: useRelationSelectable
} = createSpecificSelectable();

// public/app/ui/timeline/timeline-utils/date.ts
var precisionToTimeUnit = {
  days_time: "hour" /* HOUR */,
  days: "day" /* DAY */,
  weeks: "week" /* WEEK */,
  months: "month" /* MONTH */,
  years: "year" /* YEAR */
};
var DEFAULT_PERIOD = {
  start: moment_default().subtract(15, "days"),
  end: moment_default().add(10, "days")
};
function isWeekend(date) {
  const day = date.getDay();
  return day === 0 || day === 6;
}
function isFirstDay(date) {
  return date.getDate() === 1;
}
function isLastDayOfMonth(date) {
  const nextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1, 12);
  return date.getDate() === addDays(nextMonth, -1).getDate();
}
function getWeekNumber(date) {
  return moment_default(date).isoWeek();
}
function sameDate(date1, date2) {
  return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate();
}
function isFirstDayOfWeek(date, firstDayOfWeek = 1) {
  return date.getDay() === firstDayOfWeek;
}
function isToday(date) {
  const today = /* @__PURE__ */ new Date();
  return sameDate(date, today);
}
function getDaysInPeriod(startDate, endDate) {
  const dates = [];
  let currentDate = new Date(startDate.getTime());
  while (currentDate <= endDate) {
    dates.push(new Date(currentDate.getTime()));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
}
function getNbDaysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
function getPositionInPeriod(date, periodStart, useEdgeDate) {
  let _date = moment_default(date);
  if (useEdgeDate) {
    _date[useEdgeDate]("day");
  }
  const diff = _date.diff(moment_default(periodStart).startOf("day"), "days");
  return diff + 1;
}
function addMinutes(date, minutes) {
  return moment_default(date).add(minutes, "minutes").toDate();
}
function addDays(date, days) {
  return moment_default(date).add(days, "days").toDate();
}
function compareDates(date1, date2, precision) {
  switch (precision) {
    case "year":
      const year1 = date1.getFullYear();
      const year2 = date2.getFullYear();
      return year1 > year2 ? 1 : year1 < year2 ? -1 : 0;
    case "month":
      const yearComparison = compareDates(date1, date2, "year");
      if (yearComparison !== 0) return yearComparison;
      const month1 = date1.getMonth();
      const month2 = date2.getMonth();
      return month1 > month2 ? 1 : month1 < month2 ? -1 : 0;
    case "date":
      const monthComparison = compareDates(date1, date2, "month");
      if (monthComparison !== 0) return monthComparison;
      const day1 = date1.getDate();
      const day2 = date2.getDate();
      return day1 > day2 ? 1 : day1 < day2 ? -1 : 0;
    default:
      return date1 > date2 ? 1 : date1 < date2 ? -1 : 0;
  }
}
function formatPeriodToString(period) {
  if (!period) return null;
  return {
    start: moment_default.isMoment(period.start) ? period.start.format() : period.start,
    end: moment_default.isMoment(period.end) ? period.end.format() : period.end
  };
}

// public/app/ui/timeline/timeline-utils/item-period.ts
function computeTranslation(translation2, columnWidth, visibleDays, minutesBreakpoint, allDay = false) {
  if (allDay || visibleDays > minutesBreakpoint) {
    let adjustedValue = Math.floor(translation2 / columnWidth) * columnWidth;
    const remainder = translation2 - adjustedValue;
    if (Math.abs(remainder) > columnWidth / 2) {
      adjustedValue += (remainder < 0 ? -1 : 1) * columnWidth;
    }
    translation2 = adjustedValue;
  }
  return translation2;
}
function computeMinutes(translation2, minuteWidth) {
  return translation2 / minuteWidth;
}
function computeDays(translation2, minuteWidth) {
  return Math.round(translation2 / minuteWidth / (24 * 60));
}
function useMinuteWidth() {
  const timelineStore = useTimelineStore();
  return createMemo(() => calculateMinuteWidth(timelineStore.columnWidth));
}
function shiftDate(ref, minutes, stepUnit) {
  let date = moment_default(ref).toDate();
  const days = Math.trunc(Math.round(minutes) / (24 * 60));
  switch (stepUnit) {
    case "hour" /* HOUR */:
      const hours = Math.floor(minutes / 60);
      date = moment_default(ref).add(hours, "hours").toDate();
      break;
    case "day" /* DAY */:
      date = moment_default(ref).add(days, "days").toDate();
      break;
    case "week" /* WEEK */:
      const weekThreshold = 7 / 2;
      let week = 0;
      if (Math.abs(days) >= weekThreshold) {
        const target = moment_default(ref).add(days, "days");
        week = Math.round(target.diff(moment_default(ref), "weeks", true));
      }
      date = moment_default(ref).add(week, "weeks").toDate();
      break;
    case "month" /* MONTH */:
      const monthThreshold = 15;
      let month = 0;
      if (Math.abs(days) >= monthThreshold) {
        const target = moment_default(ref).add(days, "days");
        month = Math.round(target.diff(moment_default(ref), "months", true));
      }
      date = moment_default(ref).add(month, "months").toDate();
      break;
    case "year" /* YEAR */:
      const yearThreshold = 365 / 2;
      let year = 0;
      if (Math.abs(days) >= yearThreshold) {
        const target = moment_default(ref).add(days, "days");
        year = Math.round(target.diff(moment_default(ref), "years", true));
      }
      date = moment_default(ref).add(year, "years").toDate();
      break;
    default:
      date = moment_default(ref).add(minutes, "minutes").toDate();
  }
  return date;
}

// public/app/ui/timeline/timeline-utils/node-ref.ts
var daysRef = /* @__PURE__ */ new Map();
var dayNodesRef = /* @__PURE__ */ new WeakMap();
var dateToDaysRefKey = (date) => {
  const year = date.getFullYear().toString();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
};
var registerDayNode = (date, node) => {
  const key2 = dateToDaysRefKey(date);
  daysRef.set(key2, date);
  dayNodesRef.set(date, node);
};
var getDayNode = (date) => {
  if (!date) return void 0;
  const strKey = dateToDaysRefKey(date);
  if (daysRef.has(strKey)) {
    const key2 = daysRef.get(strKey);
    return dayNodesRef.get(key2);
  }
  return void 0;
};
var unregisterDayNode = (date) => {
  daysRef.delete(dateToDaysRefKey(date));
};

// public/app/ui/timeline/timeline-utils/misc.ts
function calculatePadding(start, end, columnWidth, visibleDays, minutesBreakpoint, allDay = false) {
  let left = 0;
  let right = 0;
  if (allDay || visibleDays > minutesBreakpoint) return { left, right };
  const minutesPerPixel = 24 * 60 / columnWidth;
  if (start) {
    const dayStart = new Date(
      start.getFullYear(),
      start.getMonth(),
      start.getDate()
    );
    const padStart = start.getTime() - dayStart.getTime();
    const padStartM = Math.floor(padStart / 1e3 / 60);
    left = Math.max(0, Math.floor(padStartM / minutesPerPixel));
  }
  if (end) {
    const dayEnd = new Date(
      end.getFullYear(),
      end.getMonth(),
      end.getDate(),
      23,
      59
    );
    const padEnd = dayEnd.getTime() - end.getTime();
    const padEndM = Math.floor(padEnd / 1e3 / 60);
    right = Math.max(0, Math.floor(padEndM / minutesPerPixel));
  }
  return { left, right };
}
function calculateMinuteWidth(dayWidth) {
  return dayWidth / (24 * 60);
}
function customExp(x3) {
  return Math.pow(1.75, x3) - 1;
}
var MAX_ZOOM = 365;
var MIN_ZOOM = 1;
function accelerateNumberOnWheelEvent(currentNumber, event2) {
  const delta = Math.sign(event2.deltaY);
  const acceleration = Math.abs(event2.deltaY) > 102 ? 5 : 1;
  const normalizedDelta = Math.abs(event2.deltaY) / 100;
  const exponent = customExp(normalizedDelta);
  const newNumber = Math.round(currentNumber + delta * acceleration * exponent);
  return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, newNumber));
}

// public/app/ui/timeline/timeline-utils/item-new.ts
function getNewItemDate(event2, timeline) {
  const newDate = new Date(timeline.period.start);
  const minuteWidth = calculateMinuteWidth(timeline.columnWidth);
  if (timeline.visibleDays > timeline.minutesBreakpoint) {
    return addDays(newDate, computeDays(event2.offsetX, minuteWidth));
  } else {
    return addMinutes(newDate, computeMinutes(event2.offsetX, minuteWidth));
  }
}

// public/app/ui/timeline/timeline-utils/item-relation.ts
function swapDirection(direction) {
  switch (direction) {
    case "out" /* Out */:
      return "in" /* In */;
    case "in" /* In */:
      return "out" /* Out */;
    case "both" /* Both */:
      return "both" /* Both */;
    case "none" /* None */:
      return "none" /* None */;
  }
}
function setupTimelineItemRelation() {
  const relationShip = useRelationShip();
  return {
    handleTimelineRelations: (payload, selectable) => {
      const relations = {
        added: [],
        removed: []
      };
      const addOrRemove = (relation) => {
        if (relationShip.hasRelation(relation.id)) {
          relations.removed.push(relation);
        } else {
          relations.added.push(relation);
        }
      };
      const useSelection2 = selectable?.selection.length > 0;
      let dropTargets = [];
      let dragTargets = [];
      if (useSelection2) {
        const isPayloadToSelected = selectable?.selection.includes(payload.to);
        dropTargets = isPayloadToSelected ? selectable?.selection : [payload.to];
        dragTargets = isPayloadToSelected ? [payload.from] : selectable?.selection;
      } else {
        dropTargets = [payload.to];
        dragTargets = [payload.from];
      }
      dragTargets.forEach((dragTarget) => {
        dropTargets.forEach((dropTarget) => {
          addOrRemove(
            createRelation(
              relationShip,
              dragTarget.parent,
              dropTarget.parent,
              payload.attachment,
              "in" /* In */
            )
          );
        });
      });
      return relations;
    }
  };
}

// public/app/ui/timeline/timeline-utils/item-selection.ts
function getSelectionOrPeriod(item, selectable) {
  let selection = [item];
  if (selectable?.isSelected(item)) {
    selection = selectable?.selection ?? [];
  }
  return selection;
}
function useSelection() {
  const period = useTimelinePeriod();
  const selectable = usePeriodSelectable();
  return () => getSelectionOrPeriod(period, selectable);
}

// node_modules/@solid-primitives/intersection-observer/dist/index.js
function observe(el2, instance) {
  if (DEV && el2 instanceof HTMLElement && el2.style.display === "contents") {
    console.warn(
      `[@solid-primitives/intersection-observer] IntersectionObserver is not able to observe elements with 'display: "contents"' style:`,
      el2
    );
  }
  instance.observe(el2);
}
function createVisibilityObserver(options2, setter) {
  if (isServer) {
    return () => () => false;
  }
  const callbacks2 = /* @__PURE__ */ new WeakMap();
  const io = new IntersectionObserver((entries2, instance) => {
    for (const entry of entries2)
      callbacks2.get(entry.target)?.(entry, instance);
  }, options2);
  onCleanup(() => io.disconnect());
  function removeEntry(el2) {
    io.unobserve(el2);
    callbacks2.delete(el2);
  }
  function addEntry(el2, callback) {
    observe(el2, io);
    callbacks2.set(el2, callback);
  }
  const getCallback = setter ? (get7, set4) => {
    const setterRef = access(setter);
    return (entry) => set4(setterRef(entry, { visible: untrack(get7) }));
  } : (_5, set4) => (entry) => set4(entry.isIntersecting);
  return (element2) => {
    const [isVisible, setVisible] = createSignal(options2?.initialValue ?? false);
    const callback = getCallback(isVisible, setVisible);
    let prevEl;
    if (!(element2 instanceof Element)) {
      createEffect(() => {
        const el2 = element2();
        if (el2 === prevEl)
          return;
        if (prevEl)
          removeEntry(prevEl);
        if (el2)
          addEntry(el2, callback);
        prevEl = el2;
      });
    } else
      addEntry(element2, callback);
    onCleanup(() => prevEl && removeEntry(prevEl));
    return isVisible;
  };
}

// public/app/ui/timeline/timeline-utils/item-visibility.ts
function useItemVisibility(elt, displayAllItems) {
  const item = useTimelineItem();
  const useVisibilityObserver = createVisibilityObserver({
    initialValue: true
  });
  const visible = useVisibilityObserver(elt);
  createEffect(
    on(
      () => [visible(), displayAllItems()],
      ([isVisible, displayAll]) => {
        item.visible = displayAll || isVisible;
      }
    )
  );
  onCleanup(() => item.visible = false);
}

// public/app/ui/timeline/timeline-utils/period-stacking.ts
function computePeriodsStackLevels(periods) {
  if (periods.length === 0) {
    return -1;
  }
  if (periods.length === 1) {
    periods[0].stackLevel = 0;
    return 0;
  }
  const validPeriods = periods.filter((p4) => p4.start && p4.end);
  const invalidPeriods = periods.filter((p4) => !p4.start || !p4.end);
  invalidPeriods.forEach((p4) => {
    p4.stackLevel = 0;
  });
  if (validPeriods.length === 0) {
    return 0;
  }
  const sorted = [...validPeriods].sort((a3, b3) => {
    const startDiff = a3.start.getTime() - b3.start.getTime();
    if (startDiff !== 0) return startDiff;
    return a3.end.getTime() - b3.end.getTime();
  });
  const levelEndTimes = [];
  let maxLevel = 0;
  for (const period of sorted) {
    const periodStart = period.start.getTime();
    let assignedLevel = -1;
    for (let level = 0; level < levelEndTimes.length; level++) {
      if (levelEndTimes[level] <= periodStart) {
        assignedLevel = level;
        break;
      }
    }
    if (assignedLevel === -1) {
      assignedLevel = levelEndTimes.length;
      levelEndTimes.push(0);
    }
    period.stackLevel = assignedLevel;
    levelEndTimes[assignedLevel] = period.end.getTime();
    maxLevel = Math.max(maxLevel, assignedLevel);
  }
  return maxLevel;
}
function getStackRowCount(maxStackLevel) {
  return Math.max(1, maxStackLevel + 1);
}

// public/app/ui/timeline/timeline-utils/relation.ts
function checkPeriodsSelection(periods, selectable) {
  return periods.some((period) => selectable?.isSelected(period));
}
function checkRelationSelection(relation, relationSelectable) {
  return relationSelectable?.isSelected(relation);
}
function checkItem(item) {
  return item.periods.some((p4) => p4.resizing) || item.periods.some((p4) => p4.moving);
}

// public/app/ui/timeline/timeline-utils/relation-path/utils.ts
var MARKER_SIZE = 18;
var MARKER_OFFSET = MARKER_SIZE + MARKER_SIZE * 0.25;
var ARROW_SAFE_AREA = MARKER_OFFSET * 2;

// public/app/ui/timeline/timeline-utils/relation-path/line.ts
function buildStartToEndPath(start, end) {
  const points = [start];
  const middleY = start.y + (end.y - start.y) / 2;
  const midEndX = end.x + MARKER_OFFSET;
  const diff = midEndX - start.x;
  const addPoint = (x3, y3) => points.push({ x: x3, y: y3 });
  if (diff < 0) {
    const midStartX = Math.min(midEndX, start.x - MARKER_OFFSET);
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midStartX, end.y);
  } else {
    const midStartX = start.x - MARKER_OFFSET;
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midEndX, middleY);
    addPoint(midEndX, end.y);
  }
  points.push(end);
  return points;
}
function buildEndToEndPath(start, end) {
  const midX = Math.max(start.x + MARKER_OFFSET, end.x + MARKER_OFFSET);
  const points = [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
  return points;
}
function buildStartToStartPath(start, end) {
  const midX = Math.min(start.x - MARKER_OFFSET, end.x - MARKER_OFFSET);
  const points = [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
  return points;
}
function buildEndToStartPath(start, end) {
  const points = [start];
  const middleY = start.y + (end.y - start.y) / 2;
  const midEndX = end.x - MARKER_OFFSET;
  const diff = midEndX - start.x;
  const addPoint = (x3, y3) => points.push({ x: x3, y: y3 });
  if (diff > 0) {
    const midStartX = Math.min(start.x + MARKER_OFFSET, midEndX);
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midStartX, end.y);
  } else {
    const midStartX = start.x + MARKER_OFFSET;
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midEndX, middleY);
    addPoint(midEndX, end.y);
  }
  points.push(end);
  return points;
}
var pathBuilders = {
  ["start_end" /* START_TO_END */]: buildStartToEndPath,
  ["end_end" /* END_TO_END */]: buildEndToEndPath,
  ["start_start" /* START_TO_START */]: buildStartToStartPath,
  ["end_start" /* END_TO_START */]: buildEndToStartPath
};

// public/app/ui/timeline/timeline-utils/tree.ts
function getTimelineItem(groups, path) {
  const group2 = groups[path[0]];
  if (!group2) return void 0;
  const subpath = path.slice(1);
  if (subpath.length === 0) return void 0;
  return group2.findPath(subpath);
}
function walkTree(item, callback) {
  const stopWalking = callback(item);
  if (stopWalking) return stopWalking;
  if (item.children.length > 0) {
    for (const child of item.children) {
      const stopWalking2 = walkTree(child, callback);
      if (stopWalking2) return stopWalking2;
    }
  }
  return false;
}
function getClosestParent(start, end) {
  const startPath = start.path;
  const endPath = end.path;
  const parentPath = getClosestParentPath(startPath, endPath);
  if (!parentPath) return false;
  return start.getRoot().findPath(parentPath.slice(1));
}
function getClosestParentPath(start, end) {
  if (start[0] !== end[0]) return false;
  const minLength = Math.min(start.length, end.length);
  const parentPath = [];
  let i3 = 0;
  while (i3 < minLength - 1 && start[i3] === end[i3]) {
    parentPath.push(start[i3]);
    i3++;
  }
  return parentPath.length === 0 ? false : parentPath;
}
function isBefore(path, target) {
  const pathStr = path.join("");
  const targetStr = target.join("");
  return pathStr < targetStr;
}
function isBetween(path, start, end) {
  return isBefore(start, path) && isBefore(path, end);
}

// public/app/ui/timeline/stores/timeline.tsx
var DEFAULT_VISIBLE_DAY_BREAKPOINT = 120;
var DEFAULT_VISIBLE_DAY_LABEL_BREAKPOINT = 64;
var DEFAULT_VISIBLE_WEEK_DAY_BREAKPOINT = 20;
var TimelineStore = class extends BaseStore {
  visibleDays = prop(7);
  daysCount = prop(0);
  initialized = prop(false);
  period = prop();
  initialPeriod = prop();
  nbRows = prop(0);
  scrollLeft = prop();
  scrollTop = prop();
  scrollLeftPercent = prop();
  applyScrollLeftPercent = prop(false);
  snapScrollBehavior = prop();
  todayVisible = prop();
  todayRef = prop();
  firstDayRef = prop();
  lastDayRef = prop();
  viewport = prop();
  container = prop();
  hoveredDay = prop();
  dragging = prop();
  minutesBreakpoint = prop(7);
  visibleDayLabelBreakpoint = prop(DEFAULT_VISIBLE_DAY_LABEL_BREAKPOINT);
  visibleDayBreakpoint = prop(DEFAULT_VISIBLE_DAY_BREAKPOINT);
  visibleWeekDayBreakpoint = prop(DEFAULT_VISIBLE_WEEK_DAY_BREAKPOINT);
  displayRelations = prop();
  displayWeekNumber = prop();
  headerHeight = prop(48);
  pointer = prop({
    offsetX: 0,
    offsetY: 0,
    x: 0,
    y: 0
  });
  itemsMoving = prop();
  itemsResizing = prop();
  creatingRelation = prop();
  dragOverNewPeriod = prop();
  dragOverNewPeriodData = prop();
  sidebarWidth = prop(300);
  viewportWidth = prop(0);
  today = /* @__PURE__ */ new Date();
  isTodayInPeriod() {
    const start = this.initialPeriod?.start;
    const end = this.initialPeriod?.end;
    return start && end ? this.today >= start && this.today <= end : false;
  }
  isTodayBeforePeriod() {
    const start = this.initialPeriod?.start;
    return !this.isTodayInPeriod() && start ? this.today < start : false;
  }
  isTodayAfterPeriod() {
    const end = this.initialPeriod?.end;
    return !this.isTodayInPeriod() && end ? this.today > end : false;
  }
  todayPosition() {
    const start = this.period?.start;
    if (!this.isTodayInPeriod() || !start) return 1;
    return getPositionInPeriod(this.today, start);
  }
  displayWeekDay() {
    return this.visibleDays > (this.visibleWeekDayBreakpoint ?? DEFAULT_VISIBLE_WEEK_DAY_BREAKPOINT);
  }
  displayDayLabel() {
    return this.visibleDays < (this.visibleDayLabelBreakpoint ?? DEFAULT_VISIBLE_DAY_LABEL_BREAKPOINT);
  }
  displayDays() {
    return this.visibleDays < (this.visibleDayBreakpoint ?? DEFAULT_VISIBLE_DAY_BREAKPOINT);
  }
  setDragOverNewPeriod(data2) {
    this.dragOverNewPeriodData = data2;
  }
  // Compute the column width based on the container width and the number of visible days.
  get columnWidth() {
    return this.computedColumnWidth();
  }
  getLeftOffsetRelativeToViewport(element2) {
    const viewport = this.viewport;
    if (!viewport) return 0;
    let left = 0;
    let current = element2;
    while (current && current !== viewport) {
      left += current.offsetLeft;
      current = current.offsetParent;
    }
    return Math.abs(left);
  }
  getTopOffsetRelativeToViewport(element2) {
    const viewport = this.viewport;
    if (!viewport) return 0;
    let top2 = 0;
    let current = element2;
    while (current && current !== viewport) {
      top2 += current.offsetTop;
      current = current.offsetParent;
    }
    return Math.abs(top2);
  }
  onInit() {
    this.days = createMemo(() => {
      return this.period ? getDaysInPeriod(this.period.start, this.period.end) : [];
    });
    this.daysLength = createMemo(() => this.days().length);
    this.computedColumnWidth = createMemo(() => {
      const visibleDays = this.visibleDays;
      const sidebarWidth = this.sidebarWidth;
      const viewportWidth = this.viewportWidth;
      if (visibleDays && viewportWidth) {
        return (viewportWidth - sidebarWidth) / visibleDays;
      }
      return 0;
    });
  }
};
var TimelineContext = createContext({});
var useTimelineStore = () => {
  return useContext(TimelineContext);
};
var TimelineProvider = TimelineContext.Provider;

// public/app/ui/timeline/stores/item.tsx
var getEarliestPeriod = (prev, current) => {
  if (!prev) return current;
  if (!current) return prev;
  if (current.start && (!prev.start || prev.start.getTime() > current.start.getTime())) {
    return current;
  }
  return prev;
};
var getLatestPeriod = (prev, current) => {
  if (!prev) return current;
  if (!current) return prev;
  if (current.end && (!prev.end || prev.end.getTime() < current.end.getTime())) {
    return current;
  }
  return prev;
};
var TimelineItemStore2 = class extends BaseStore {
  id = prop();
  index = prop();
  parent = prop();
  children = prop([]);
  relations = prop([]);
  visible = prop(true);
  visibleChild = prop(true);
  position = prop(0);
  deletingDates = prop();
  isRoot = prop(false);
  wrapperRef = prop();
  wrapperWidth = prop();
  wrapperHeight = prop();
  periods = prop([]);
  title = prop();
  groupHeight = prop();
  hovered = prop(false);
  /** Cached max stack level for this item's periods */
  _maxStackLevel = prop(0);
  periodSelectable = usePeriodSelectable();
  relationSelectable = useRelationSelectable();
  timeline = useTimelineStore();
  get path() {
    return [...this.parent?.path ?? [], this.index];
  }
  get resizing() {
    return this.periods.some((period) => period.resizing);
  }
  get moving() {
    return this.periods.some((period) => period.moving);
  }
  get hasPeriodSelected() {
    return this.periods.some((period) => period.selected);
  }
  get count() {
    return this.children.length;
  }
  get deepCount() {
    if (this.children.length === 0) return 1;
    return this.children.reduce((count, child) => count + child.deepCount, 1);
  }
  get isHovered() {
    return this.hovered && !this.moving && !this.resizing && !this.timeline.itemsMoving && !this.timeline.itemsResizing || this.moving || this.resizing;
  }
  /**
   * Returns the number of rows needed to display all stacked periods.
   * This is used to set the height of the timeline row.
   */
  get stackedRowCount() {
    return getStackRowCount(this._maxStackLevel);
  }
  /**
   * Computes stack levels for all periods in this item.
   * Periods that overlap will be assigned different stack levels.
   * Should be called whenever periods are added/removed or their dates change.
   */
  computeStackLevels() {
    this._maxStackLevel = computePeriodsStackLevels(this.periods);
  }
  addChild(store2, index2) {
    if (index2 !== void 0) {
      const newChildren = [...this.children];
      newChildren.splice(index2, 0, store2);
      this.children = newChildren;
    } else {
      this.children = [...this.children, store2];
    }
  }
  sortChildren() {
    const children2 = [...this.children];
    children2.sort((a3, b3) => a3.position - b3.position);
    this.children = children2;
  }
  removeChild(store2) {
    this.children = this.children.filter((child) => child !== store2);
  }
  registerPeriod(store2) {
    if (!this.periods.includes(store2)) {
      this.periods = [...this.periods, store2];
    }
  }
  unregisterPeriod(store2) {
    this.periods = this.periods.filter((period) => period !== store2);
  }
  unregisterOldPeriods(newPeriodIds) {
    this.periods = this.periods.filter((period) => newPeriodIds.includes(period.id));
  }
  unregisterPeriods() {
    this.periods = [];
  }
  get creatingRelation() {
    return this.periods.some((period) => period.creatingRelation);
  }
  find(itemOrId) {
    if (typeof itemOrId === "number" || typeof itemOrId === "string") {
      if (this.id === itemOrId) return this;
    } else {
      if (this === itemOrId) return this;
    }
    for (const child of this.children) {
      const found2 = child.find(itemOrId);
      if (found2) return found2;
    }
    return void 0;
  }
  findPath(path) {
    if (path.length === 0) return this;
    const child = this.children[path[0]];
    if (!child) return void 0;
    return child.findPath(path.slice(1));
  }
  earliestPeriod(useChildrenPeriods = true) {
    if (useChildrenPeriods && this.children.length > 0) {
      return this.children.reduce((prev, child) => {
        const childPeriod = child.earliestPeriod();
        return getEarliestPeriod(prev, childPeriod);
      }, void 0);
    }
    return this.periods.reduce(getEarliestPeriod, void 0);
  }
  latestPeriod(useChildrenPeriods = true, excludeMilestones = false) {
    if (useChildrenPeriods && this.children.length > 0) {
      return this.children.reduce((prev, child) => {
        const childPeriod = child.latestPeriod(useChildrenPeriods, excludeMilestones);
        return getLatestPeriod(prev, childPeriod);
      }, void 0);
    }
    return this.periods.filter((p4) => excludeMilestones && !p4.isMilestone || !excludeMilestones).reduce(getLatestPeriod, void 0);
  }
  latestPeriods(useChildrenPeriods = true) {
    let result2 = [];
    if (useChildrenPeriods && this.children.length > 0) {
      for (const child of this.children) {
        const latests = child.latestPeriods();
        if (latests.length === 0) continue;
        if (result2.length === 0) result2 = latests;
        else {
          const latest = latests[0];
          const diff = compareDates(result2[0].end, latest.end);
          if (diff < 0) {
            result2 = latests;
          } else if (diff === 0) {
            result2.push(latest);
          }
        }
      }
      return result2.filter(Boolean);
    }
    return [this.latestPeriod(false, true)].filter(Boolean);
  }
  /**
   * @returns The earliest start date of the item and its children.
   */
  start() {
    const period = this.earliestPeriod();
    return period?.start;
  }
  /**
   * @returns The latest end date of the item and its children.
   */
  end() {
    const period = this.latestPeriod();
    return period?.end;
  }
  getBranchVisibility() {
    if (!this.parent) {
      return this.visibleChild;
    }
    return this.parent.visibleChild && this.parent.getBranchVisibility();
  }
  getRoot() {
    if (this.isRoot) {
      return this;
    }
    return this.parent.getRoot();
  }
  hoverise() {
    if (!this.timeline.dragging) {
      this.hovered = true;
    }
  }
  unhoverise() {
    this.hovered = false;
  }
  scrollTo() {
    const container = this.timeline.container;
    if (!container) return;
    const item = this.wrapperRef;
    if (!item) return;
    container.scrollTo({
      behavior: "smooth",
      left: item.offsetLeft - container.offsetWidth / 2 + item.offsetWidth / 2
    });
  }
};
var ItemContext = createContext();
function useTimelineItem() {
  return useContext(ItemContext);
}
var TimelineItemProvider = (props2) => {
  return createComponent(ItemContext.Provider, {
    get value() {
      return props2.store;
    },
    get children() {
      return props2.children;
    }
  });
};

// public/app/ui/timeline/stores/option.tsx
var DisplayCardTitle = /* @__PURE__ */ function(DisplayCardTitle2) {
  DisplayCardTitle2["NONE"] = "none";
  DisplayCardTitle2["AFTER"] = "after";
  DisplayCardTitle2["INSIDE"] = "inside";
  return DisplayCardTitle2;
}({});
var DisplayPeriodTitle = /* @__PURE__ */ function(DisplayPeriodTitle2) {
  DisplayPeriodTitle2["NONE"] = "none";
  DisplayPeriodTitle2["INSIDE"] = "inside";
  return DisplayPeriodTitle2;
}({});
var DisplayDensity = /* @__PURE__ */ function(DisplayDensity2) {
  DisplayDensity2["COMPACT"] = "compact";
  DisplayDensity2["LARGE"] = "large";
  DisplayDensity2[DisplayDensity2["NORMAL"] = null] = "NORMAL";
  return DisplayDensity2;
}({});
var OptionState = class {
  filter = null;
  group_by = [];
  include_archived = false;
  include_descendants = false;
  showUngroupedCards = true;
  enableSideDisplay = false;
  displayCriticalPath = false;
  strikeDoneCards = true;
  hideEmptyGroups = false;
  displayAllItems = false;
  period = formatPeriodToString(DEFAULT_PERIOD);
  displayCardTitle = DisplayCardTitle.NONE;
  displayPeriodTitle = DisplayPeriodTitle.NONE;
  // planning specific options
  relationship = null;
  dateField = null;
  constructor(initialData) {
    Object.assign(this, initialData);
  }
};
var OptionStore = class extends createStoreMixin(OptionState) {
  constructor(initialData) {
    super(initialData);
    this.resetState = new OptionState(initialData);
  }
  updateOptions(updates) {
    if (this.resetState.name !== updates.name) {
      this.resetState = new OptionState(updates);
    }
    const updateKeys = Object.keys(updates);
    const allKeys2 = Object.keys(this.state);
    this.setState(produce((draft) => {
      allKeys2.filter((k2) => !updateKeys.includes(k2)).forEach((k2) => {
        draft[k2] = this.resetState[k2];
      });
      Object.keys(updates).forEach((key2) => {
        const value2 = updates[key2];
        if (JSON.stringify(this[key2]) !== JSON.stringify(value2)) {
          draft[key2] = value2;
        }
      });
    }));
  }
  toggleDisplayAllItems(force) {
    this.setState("displayAllItems", force ?? !this.state.displayAllItems);
  }
  getSortByValue() {
    const sortBy3 = getSortBy(this.state, true);
    return sortBy3?.reverse ? `-${sortBy3.value}` : sortBy3?.value;
  }
};
var OptionContext = createContext();

// public/app/ui/timeline/stores/period.tsx
var TimelinePeriodStore4 = class extends BaseStore {
  id = prop();
  name = prop();
  parent = prop();
  start = prop();
  tmpStart = prop();
  end = prop();
  tmpEnd = prop();
  left = prop(0);
  right = prop(0);
  gridColumnStart = prop(-1);
  gridColumnEnd = prop(-1);
  elt = prop();
  eltWidth = prop(0);
  eltHeight = prop(0);
  deletingDates = prop(false);
  moving = prop(false);
  resizing = prop(false);
  creatingRelation = prop(false);
  dragover = prop(false);
  invalidDrop = prop(false);
  color = prop("");
  isMilestone = prop(false);
  progress = prop(0);
  allDay = prop(false);
  isRange = prop(false);
  movable = prop(false);
  resizable = prop(false);
  relationAllowed = prop(false);
  stepUnit = prop("day" /* DAY */);
  /** Stack level for overlapping periods (0 = no stacking, 1+ = stacked below) */
  stackLevel = prop(0);
  periodSelectable = usePeriodSelectable();
  get selected() {
    return this.periodSelectable.isSelected(this);
  }
  gridColumn() {
    let colStart = this.gridColumnStart;
    colStart = colStart > -1 ? colStart : 1;
    let colEnd = this.gridColumnEnd;
    colEnd = colEnd > -1 ? colEnd + 1 : 1;
    return `${colStart} / ${colEnd}`;
  }
};
var TimelinePeriodContext = createContext();
function useTimelinePeriod() {
  return useContext(TimelinePeriodContext);
}
var TimelinePeriodProvider = (props2) => {
  return createComponent(TimelinePeriodContext.Provider, {
    get value() {
      return props2.value;
    },
    get children() {
      return props2.children;
    }
  });
};

// public/app/ui/timeline/timeline-utils/relation-path/line2.ts
function getStartPoint(data2, attachment) {
  switch (attachment) {
    case "start_end" /* START_TO_END */:
    case "start_start" /* START_TO_START */:
      return { x: data2.x, y: data2.y + data2.height / 2 };
    case "end_end" /* END_TO_END */:
    case "end_start" /* END_TO_START */:
      return { x: data2.x + data2.width, y: data2.y + data2.height / 2 };
    default:
      throw new Error("Invalid attachment type");
  }
}
function getEndPoint(data2, attachment) {
  switch (attachment) {
    case "start_end" /* START_TO_END */:
    case "end_end" /* END_TO_END */:
      return { x: data2.x + data2.width, y: data2.y + data2.height / 2 };
    case "end_start" /* END_TO_START */:
    case "start_start" /* START_TO_START */:
      return { x: data2.x, y: data2.y + data2.height / 2 };
    default:
      throw new Error("Invalid attachment type");
  }
}
function buildStartToEndPath2(start, end) {
  const points = [start];
  const middleY = start.y + (end.y - start.y) / 2;
  const midEndX = end.x + MARKER_OFFSET;
  const diff = midEndX - start.x;
  const addPoint = (x3, y3) => points.push({ x: x3, y: y3 });
  if (diff < 0) {
    const midStartX = Math.min(midEndX, start.x - MARKER_OFFSET);
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midStartX, end.y);
  } else {
    const midStartX = start.x - MARKER_OFFSET;
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midEndX, middleY);
    addPoint(midEndX, end.y);
  }
  points.push(end);
  return points;
}
function buildEndToEndPath2(start, end) {
  const midX = Math.max(start.x + MARKER_OFFSET, end.x + MARKER_OFFSET);
  const points = [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
  return points;
}
function buildStartToStartPath2(start, end) {
  const midX = Math.min(start.x - MARKER_OFFSET, end.x - MARKER_OFFSET);
  const points = [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
  return points;
}
function buildEndToStartPath2(start, end) {
  const points = [start];
  const middleY = start.y + (end.y - start.y) / 2;
  const midEndX = end.x - MARKER_OFFSET;
  const diff = midEndX - start.x;
  const addPoint = (x3, y3) => points.push({ x: x3, y: y3 });
  if (diff > 0) {
    const midStartX = Math.min(start.x + MARKER_OFFSET, midEndX);
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midStartX, end.y);
  } else {
    const midStartX = start.x + MARKER_OFFSET;
    addPoint(midStartX, start.y);
    addPoint(midStartX, middleY);
    addPoint(midEndX, middleY);
    addPoint(midEndX, end.y);
  }
  points.push(end);
  return points;
}
var pathBuilders2 = {
  ["start_end" /* START_TO_END */]: buildStartToEndPath2,
  ["end_end" /* END_TO_END */]: buildEndToEndPath2,
  ["start_start" /* START_TO_START */]: buildStartToStartPath2,
  ["end_start" /* END_TO_START */]: buildEndToStartPath2
};
function buildLinePath(type, data2, startVisible = true, endVisible = true) {
  const start = getStartPoint(data2.start, type);
  const end = getEndPoint(data2.end, type);
  const points = pathBuilders2[type](start, end);
  const _start = points[0];
  const _end = points[points.length - 1];
  switch (type) {
    case "end_start" /* END_TO_START */:
      if (!startVisible) {
        return [points[points.length - 2], _end];
      } else if (!endVisible) {
        return [_start, points[1]];
      }
      break;
    case "start_end" /* START_TO_END */:
      if (!startVisible) {
        return [points[points.length - 2], _end];
      } else if (!endVisible) {
        return [_start, points[1]];
      }
      break;
    case "start_start" /* START_TO_START */:
      if (!startVisible) {
        _start.x = points[1].x;
        _start.y = _end.y;
        return [_start, points[2], _end];
      } else if (!endVisible) {
        _end.x = points[1].x;
        _end.y = _start.y;
        return [_start, points[1], _end];
      }
      break;
    case "end_end" /* END_TO_END */:
      if (!startVisible) {
        _start.x = points[1].x;
        _start.y = _end.y;
        return [_start, points[2], _end];
      } else if (!endVisible) {
        _end.x = points[1].x;
        _end.y = _start.y;
        return [_start, points[1], _end];
      }
      break;
  }
  return points;
}
function buildLinePathFromPoints(points) {
  if (points.length < 2) return "";
  const linePath = points.reduce(
    (path, point) => path + ` ${point.x} ${point.y} L`,
    "M"
  );
  return linePath.endsWith("L") ? linePath.slice(0, -1) : linePath;
}

// public/app/ui/timeline/draw/arrow.tsx
var _tmpl$20 = /* @__PURE__ */ template(`<svg><path class="timeline-relation-path-interactive-area"></path><path class="timeline-relation-path"></path></svg>`, 6);
var _tmpl$211 = /* @__PURE__ */ template(`<svg><path class="timeline-relation-marker"></path></svg>`, 4, true);
var MARKER_MATRIX = {
  ["start_end" /* START_TO_END */]: {
    ["out" /* Out */]: {
      dir: "left",
      pos: "end"
    },
    ["in" /* In */]: {
      dir: "right",
      pos: "end"
    }
  },
  ["end_start" /* END_TO_START */]: {
    ["out" /* Out */]: {
      dir: "right",
      pos: "end"
    },
    ["in" /* In */]: {
      dir: "left",
      pos: "start"
    }
  },
  ["start_start" /* START_TO_START */]: {
    ["out" /* Out */]: {
      dir: "right",
      pos: "end"
    },
    ["in" /* In */]: {
      dir: "right",
      pos: "start"
    }
  },
  ["end_end" /* END_TO_END */]: {
    ["out" /* Out */]: {
      dir: "left",
      pos: "end"
    },
    ["in" /* In */]: {
      dir: "left",
      pos: "start"
    }
  }
};
function _getX(s3, e3) {
  return s3.x < e3.x ? s3.x : e3.x;
}
function _getY(s3, e3) {
  return s3.y < e3.y ? s3.y : e3.y;
}
function _getHeight(s3, e3) {
  return s3.y < e3.y ? e3.y - s3.y + e3.height : s3.y > e3.y ? s3.y - e3.y + s3.height : Math.max(s3.height, e3.height);
}
function _getWidth(s3, e3) {
  const sl = s3.x, sr = s3.x + s3.width;
  const el2 = e3.x, er = e3.x + e3.width;
  if (sl === el2) return Math.max(s3.width, e3.width);
  if (sl < el2) {
    return sr > er ? s3.width : er - sl;
  } else if (sl > el2) {
    return sr > er ? sr - el2 : e3.width;
  }
}
function Arrow(props2) {
  const isVisible = () => {
    const s3 = props2.start();
    const e3 = props2.end();
    const sv = s3?.parent?.visible && s3?.parent?.getBranchVisibility();
    const ev = e3?.parent?.visible && e3?.parent?.getBranchVisibility();
    return !(!sv && !ev);
  };
  return createComponent(Show, {
    get when() {
      return isVisible();
    },
    get children() {
      return createComponent(_Arrow, props2);
    }
  });
}
function _Arrow(props2) {
  const bounds = getBounds(props2.start, props2.end, () => props2.relation.attachment);
  const points = getPoints(() => bounds, () => props2.relation);
  const markers = getMarkers(() => bounds, () => points(), () => props2.relation);
  const path = () => buildLinePathFromPoints(points());
  return (() => {
    const _el$ = _tmpl$20.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
    _el$2.$$contextmenu = (e3) => {
      props2.onContextMenu?.(e3, props2.relation);
    };
    _el$2.$$click = (e3) => {
      props2.onClick?.(e3, props2.relation);
    };
    insert(_el$, createComponent(For, {
      each: markers,
      children: (marker) => createComponent(Marker, marker)
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = bounds.x, _v$2 = bounds.y, _v$3 = bounds.width, _v$4 = bounds.height, _v$5 = path(), _v$6 = !!props2.relation.highlighted, _v$7 = !!["both" /* Both */, "in" /* In */].includes(props2.relation.direction), _v$8 = !!["both" /* Both */, "out" /* Out */].includes(props2.relation.direction), _v$9 = !!(!props2.relation.start.visible || !props2.relation.end.visible), _v$10 = props2.relation.color ?? "var(--timeline-relation-color)", _v$11 = props2.relation.id, _v$12 = path();
      _v$ !== _p$._v$ && setAttribute(_el$, "x", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && setAttribute(_el$, "y", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && setAttribute(_el$, "width", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && setAttribute(_el$, "height", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && setAttribute(_el$2, "d", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$3.classList.toggle("highlighted", _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$3.classList.toggle("referencing", _p$._v$7 = _v$7);
      _v$8 !== _p$._v$8 && _el$3.classList.toggle("referenced", _p$._v$8 = _v$8);
      _v$9 !== _p$._v$9 && _el$3.classList.toggle("cut", _p$._v$9 = _v$9);
      _v$10 !== _p$._v$10 && _el$3.style.setProperty("--_timeline-relation-color", _p$._v$10 = _v$10);
      _v$11 !== _p$._v$11 && setAttribute(_el$3, "data-id", _p$._v$11 = _v$11);
      _v$12 !== _p$._v$12 && setAttribute(_el$3, "d", _p$._v$12 = _v$12);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0,
      _v$6: void 0,
      _v$7: void 0,
      _v$8: void 0,
      _v$9: void 0,
      _v$10: void 0,
      _v$11: void 0,
      _v$12: void 0
    });
    return _el$;
  })();
}
function Marker(props2) {
  const dValue = createMemo(() => {
    const x3 = props2.point.x;
    const y3 = props2.point.y;
    const endX = x3 + MARKER_SIZE * (props2.dir === "left" ? 1 : -1);
    const offset = MARKER_SIZE / 4 * (props2.dir === "left" ? -1 : 1);
    const points = [{
      x: x3,
      y: y3
    }, {
      x: endX + offset,
      y: y3 - 7
    }, {
      x: endX,
      y: y3
    }, {
      x: endX + offset,
      y: y3 + 7
    }];
    return buildLinePathFromPoints(points);
  });
  return (() => {
    const _el$4 = _tmpl$211.cloneNode(true);
    createRenderEffect((_p$) => {
      const _v$13 = dValue(), _v$14 = props2.relation.color ?? "var(--timeline-relation-color)";
      _v$13 !== _p$._v$13 && setAttribute(_el$4, "d", _p$._v$13 = _v$13);
      _v$14 !== _p$._v$14 && _el$4.style.setProperty("--_timeline-relation-marker-color", _p$._v$14 = _v$14);
      return _p$;
    }, {
      _v$13: void 0,
      _v$14: void 0
    });
    return _el$4;
  })();
}
function createBounds(startDate, endDate, elt, timeline) {
  const startDayNode = getDayNode(startDate);
  const endDayNode = getDayNode(endDate);
  return {
    x: timeline.getLeftOffsetRelativeToViewport(startDayNode),
    y: timeline.getTopOffsetRelativeToViewport(elt),
    width: (endDayNode?.offsetLeft ?? 0) - (startDayNode?.offsetLeft ?? 0) + (endDayNode?.offsetWidth ?? 0),
    height: elt?.offsetHeight ?? 0
  };
}
function computeBounds(start, end, timeline, attachment) {
  const ps = start;
  const pe = end;
  let s3 = ps && ps.elt ? createBounds(ps.tmpStart ?? ps.start, ps.tmpEnd ?? ps.end, ps.elt, timeline) : null;
  let e3 = pe && pe.elt ? createBounds(pe.tmpStart ?? pe.start, pe.tmpEnd ?? pe.end, pe.elt, timeline) : null;
  if (!s3 && e3) {
    s3 = e3;
  } else if (!e3 && s3) {
    e3 = s3;
  } else if (!s3 && !e3) {
    return null;
  }
  const bounds = {
    x: _getX(s3, e3),
    y: _getY(s3, e3),
    width: _getWidth(s3, e3),
    height: _getHeight(s3, e3),
    start: s3,
    end: e3
  };
  switch (attachment) {
    case "start_end" /* START_TO_END */:
    case "end_start" /* END_TO_START */:
      bounds.x -= ARROW_SAFE_AREA;
      bounds.width += ARROW_SAFE_AREA * 2;
      break;
    case "start_start" /* START_TO_START */:
      bounds.x -= ARROW_SAFE_AREA;
      bounds.width += ARROW_SAFE_AREA;
      break;
    case "end_end" /* END_TO_END */:
      bounds.width += ARROW_SAFE_AREA;
      break;
  }
  return bounds;
}
function getBounds(start, end, attachment) {
  const timeline = useTimelineStore();
  const relationShip = useRelationShip();
  const [bounds, setBounds] = createStore({
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    start: {},
    end: {}
  });
  const updateBounds = () => {
    const computedBounds = computeBounds(start(), end(), timeline, attachment());
    if (!computedBounds) return;
    setBounds(computedBounds);
  };
  createEffect(on(() => {
    const ps = start();
    const pe = end();
    return [!!ps, !!ps?.tmpStart, !!ps?.tmpEnd, ps?.parent.visible, ps?.parent.getBranchVisibility(), !!pe, !!pe?.tmpStart, !!pe?.tmpEnd, pe?.parent.visible, pe?.parent.getBranchVisibility(), !!attachment(), !!relationShip.dirty, timeline.headerHeight > 0, !!timeline.firstDayRef, timeline.columnWidth > 0];
  }, () => {
    updateBounds();
    setTimeout(() => {
      updateBounds();
    });
  }));
  return bounds;
}
function boundsEqual(prev, next2) {
  return prev.x === next2.x && prev.y === next2.y && prev.width === next2.width && prev.height === next2.height;
}
function validateBounds(bounds) {
  return bounds.width > 0 && bounds.height > 0;
}
function getPoints(bounds, relation) {
  const [state, setState] = createStore({
    points: [],
    sv: false,
    ev: false
  });
  const attachment = () => relation().attachment;
  const start = createMemo(() => {
    const x3 = Math.abs(bounds().x - bounds().start.x);
    const y3 = Math.abs(bounds().y - bounds().start.y);
    const width = bounds().start.width;
    const height = bounds().start.height;
    return {
      x: x3,
      y: y3,
      width,
      height
    };
  }, null, {
    equals: boundsEqual
  });
  const end = createMemo(() => {
    const x3 = Math.abs(bounds().x - bounds().end.x);
    const y3 = Math.abs(bounds().y - bounds().end.y);
    const width = bounds().end.width;
    const height = bounds().end.height;
    return {
      x: x3,
      y: y3,
      width,
      height
    };
  }, null, {
    equals: boundsEqual
  });
  const _sv = () => relation().start.visible;
  const _ev = () => relation().end.visible;
  const delay = 100;
  const startVisible = createDebounce(() => setState("sv", _sv()), delay);
  const endVisible = createDebounce(() => setState("ev", _ev()), delay);
  createEffect(on(() => _sv(), () => {
    startVisible.clear();
    startVisible();
  }));
  createEffect(on(() => _ev(), () => {
    endVisible.clear();
    endVisible();
  }));
  createEffect(on(() => [attachment(), start(), end(), state.sv, state.ev], ([attach, start2, end2, sv, ev]) => {
    if (!validateBounds(start2) || !validateBounds(end2)) {
      setState("points", []);
      return;
    }
    const data2 = {
      start: start2,
      end: end2
    };
    const pts = buildLinePath(attach, data2, sv, ev);
    setState("points", pts);
  }));
  return () => state.points;
}
function getMarkers(bounds, points, relation) {
  const [markers, setMarkers] = createStore([]);
  const direction = () => relation().direction;
  const attachment = () => relation().attachment;
  const startWidth = () => bounds().start.width;
  const endWidth = () => bounds().end.width;
  createEffect(on(() => [direction(), attachment(), points(), startWidth(), endWidth()], ([dir, type, pts, startW, endW]) => {
    const newMarkers = [];
    if (dir === "none" /* None */ || pts.length < 2 || pts[0].y === pts[pts.length - 1].y) {
      setMarkers([]);
      return;
    }
    const result2 = MARKER_MATRIX[type][dir];
    let point = result2?.pos === "end" ? pts[pts.length - 1] : pts[0];
    point = JSON.parse(JSON.stringify(point));
    newMarkers.push({
      point,
      dir: result2?.dir ?? "left",
      relation: relation()
    });
    setMarkers(newMarkers);
  }));
  return markers;
}
delegateEvents(["click", "contextmenu"]);

// public/app/ui/timeline/draw/layer.tsx
var _tmpl$21 = /* @__PURE__ */ template(`<svg width="100%" height="100%" aria-hidden="true"></svg>`, 2);
var LocalLayerContext = createContext();
var Layer = (props2) => {
  let ref;
  const [theme2, rest2] = splitProps(props2, ["class"]);
  const [state, setState] = createStore({
    size: {
      width: 0,
      height: 0
    }
  });
  createResizeObserver(() => ref, (size4) => setState("size", size4));
  const viewBox = () => `0 0 ${state.size.width} ${state.size.height}`;
  return createComponent(LocalLayerContext.Provider, {
    value: state,
    get children() {
      const _el$ = _tmpl$21.cloneNode(true);
      const _ref$ = ref;
      typeof _ref$ === "function" ? use(_ref$, _el$) : ref = _el$;
      insert(_el$, () => rest2.children);
      createRenderEffect((_p$) => {
        const _v$ = viewBox(), _v$2 = classNames("timeline-layer", theme2.class);
        _v$ !== _p$._v$ && setAttribute(_el$, "viewBox", _p$._v$ = _v$);
        _v$2 !== _p$._v$2 && setAttribute(_el$, "class", _p$._v$2 = _v$2);
        return _p$;
      }, {
        _v$: void 0,
        _v$2: void 0
      });
      return _el$;
    }
  });
};

// public/app/ui/timeline/draw/free-line-layer.tsx
var _tmpl$30 = /* @__PURE__ */ template(`<svg><path class="timeline-free-line-path"></path></svg>`, 4, true);
var FreeLineContext = createContext({
  draw: () => {
  },
  update: () => {
  },
  clear: () => {
  }
});
function useFreeLine() {
  return useContext(FreeLineContext);
}
var FreeLineProvider = (props2) => {
  const [state, setState] = createStore({
    start: {
      x: 0,
      y: 0
    },
    end: {
      x: 0,
      y: 0
    }
  });
  const draw = (start, end) => {
    setState({
      start,
      end
    });
  };
  const clear = () => {
    setState({
      start: {
        x: 0,
        y: 0
      },
      end: {
        x: 0,
        y: 0
      }
    });
  };
  return createComponent(FreeLineContext.Provider, {
    value: {
      draw,
      clear,
      update: setState
    },
    get children() {
      return [createMemo(() => props2.children), createComponent(FreeLineLayer, {
        get start() {
          return state.start;
        },
        get end() {
          return state.end;
        }
      })];
    }
  });
};
var FreeLineLayer = (props2) => {
  let pathRef;
  const timelineStore = useTimelineStore();
  const d3 = () => {
    const viewport = timelineStore.viewport;
    const mx = props2.start.x;
    const my = props2.start.y;
    const lx = props2.end.x;
    const ly = props2.end.y;
    if (!pathRef || !viewport) return "";
    if (mx === 0 || my === 0 || lx === 0 || ly === 0) return "";
    return `M ${mx} ${my} L ${lx} ${ly}`;
  };
  return createComponent(Layer, {
    "class": "timeline-free-line-layer",
    get children() {
      const _el$ = _tmpl$30.cloneNode(true);
      const _ref$ = pathRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : pathRef = _el$;
      createRenderEffect(() => setAttribute(_el$, "d", d3()));
      return _el$;
    }
  });
};

// public/app/ui/timeline/draw/relation-ship-layer.tsx
var RelationShipLayer = (props2) => {
  const store2 = useRelationShip();
  const timeline = useTimelineStore();
  const relationSelectable = useRelationSelectable();
  const keyboardState2 = useKeyboard();
  const highlighted = () => store2.relations.filter((relation) => relation.highlighted);
  const onRelationClick = (e3, relation) => {
    if (keyboardState2?.Control) {
      relationSelectable?.toggle(relation);
    } else {
      batch(() => {
        relationSelectable?.unselectAll();
        relationSelectable?.select(relation);
      });
    }
    props2.onRelationClick?.(e3, relation);
  };
  const onRelationContextMenu = (e3, relation) => {
    props2.onRelationContextMenu?.(e3, relation);
  };
  createShortcut(["delete"], () => {
    if (relationSelectable?.selection.length > 0) {
      props2.onRemoveRelations?.(relationSelectable?.selection);
    }
  }, {
    requireReset: true
  });
  const [initialized, setInitialized] = createSignal(false);
  createEffect(on(() => timeline.initialized, (initialized2, prev) => {
    if (initialized2 && !prev) {
      setInitialized(true);
    }
  }));
  return createComponent(Show, {
    get when() {
      return initialized();
    },
    get children() {
      return createComponent(Layer, {
        "class": "timeline-relations-layer",
        get children() {
          return [createComponent(For, {
            get each() {
              return store2.relations;
            },
            children: (relation) => createComponent(Dynamic, {
              get component() {
                return props2.relationComponent ?? Arrow;
              },
              relation,
              onClick: onRelationClick,
              onContextMenu: onRelationContextMenu
            })
          }), createComponent(For, {
            get each() {
              return highlighted();
            },
            children: (relation) => createComponent(Dynamic, {
              get component() {
                return props2.relationComponent ?? Arrow;
              },
              relation,
              onClick: onRelationClick,
              onContextMenu: onRelationContextMenu
            })
          })];
        }
      });
    }
  });
};

// public/app/ui/timeline/stores/relation.tsx
var RelationShip2 = class extends BaseStore {
  id = prop();
  start = prop();
  end = prop();
  attachment = prop();
  direction = prop();
  color = prop();
  isSimple = prop(false);
  periodSelectable = usePeriodSelectable();
  relationSelectable = useRelationSelectable();
  get highlighted() {
    return checkRelationSelection(this, this.relationSelectable) || checkPeriodsSelection(this.start.periods, this.periodSelectable) || checkPeriodsSelection(this.end.periods, this.periodSelectable) || checkItem(this.start) || checkItem(this.end);
  }
};
function createRelation(relationsStore, from2, to, attachment, direction, color) {
  const id = `${from2.id}.${to.id}`;
  if (relationsStore.hasRelation(id)) {
    return relationsStore.getRelation(id);
  }
  return RelationShip2.create({
    id,
    start: from2,
    end: to,
    attachment,
    direction,
    color
  });
}
var RelationShipStore = class extends BaseStore {
  relations = prop([]);
  dirty = prop(false);
  relationsMap = /* @__PURE__ */ new Map();
  add(relation) {
    if (this.hasRelation(relation.id)) return;
    this.relations = [...this.relations, relation];
    this.relationsMap.set(relation.id, relation);
  }
  remove(relation) {
    this.relations = this.relations.filter((r3) => r3.id !== relation.id);
    this.relationsMap.delete(relation.id);
  }
  hasRelation(id) {
    return this.relationsMap.has(id);
  }
  getRelation(id) {
    return this.relationsMap.get(id);
  }
  findFromIdRelations(id) {
    return this.relations.filter((r3) => r3.start.id === id);
  }
  findToIdRelations(id) {
    return this.relations.filter((r3) => r3.end.id === id);
  }
  addOrRemove(relation) {
    if (this.hasRelation(relation.id)) {
      this.remove(relation);
    } else {
      this.add(relation);
    }
  }
  clear(fromId) {
    const relationsToRemove = this.relations.filter((r3) => (r3.isSimple ? r3.start.id : r3.end.id) === fromId);
    batch(() => {
      relationsToRemove.forEach((r3) => this.remove(r3));
    });
  }
  clearAll() {
    this.relations = [];
    this.relationsMap.clear();
  }
};
var RelationShipContext = createContext();
function useRelationShip() {
  return useContext(RelationShipContext);
}
var RelationShipProvider = (props2) => {
  const store2 = RelationShipStore.create();
  onCleanup(() => {
    store2.clearAll();
  });
  return createComponent(RelationShipContext.Provider, {
    value: store2,
    get children() {
      return props2.children;
    }
  });
};
function RelationShipLayerWrapper(props2) {
  const selectable = createSelectable();
  return createComponent(SelectableProvider, {
    selectable,
    get children() {
      return createComponent(RelationShipLayer, {
        get onRelationClick() {
          return props2.onRelationClick;
        },
        get onRemoveRelations() {
          return props2.onRemoveRelations;
        },
        get onRelationContextMenu() {
          return props2.onRelationContextMenu;
        },
        get relationComponent() {
          return props2.relationComponent;
        }
      });
    }
  });
}

// public/app/ui/timeline/components/grid.tsx
var _tmpl$31 = /* @__PURE__ */ template(`<div></div>`, 2);
var TimelineGrid = (props2) => {
  let ref;
  const [local, theme2, container] = splitProps(props2, ["children", "ref"], ["style"]);
  const timelineStore = useTimelineStore();
  const themeStyle = createMemo(() => ({
    ...theme2.style ?? {},
    "grid-template-columns": `repeat(${timelineStore.daysLength()}, var(--timeline-column-size-px))`
  }));
  const onRef = (elt) => {
    ref = elt;
    props2.ref?.(ref);
  };
  return (() => {
    const _el$ = _tmpl$31.cloneNode(true);
    use(onRef, _el$);
    spread(_el$, mergeProps(container, {
      get style() {
        return themeStyle();
      }
    }), false, true);
    insert(_el$, () => local.children);
    return _el$;
  })();
};

// public/app/ui/timeline/components/columns.tsx
var _tmpl$36 = /* @__PURE__ */ template(`<div class="timeline-columns-wrapper"></div>`, 2);
var _tmpl$212 = /* @__PURE__ */ template(`<div class="timeline-column"></div>`, 2);
var TimelineColumns = (props2) => {
  const timelineStore = useTimelineStore();
  return (() => {
    const _el$ = _tmpl$36.cloneNode(true);
    insert(_el$, createComponent(TimelineGrid, {
      "class": "timeline-columns",
      get children() {
        return createComponent(For, {
          get each() {
            return timelineStore.days();
          },
          children: (day, index2) => createComponent(TimelineColumn, {
            day,
            get index() {
              return index2();
            }
          })
        });
      }
    }));
    return _el$;
  })();
};
var TimelineColumn = (props2) => {
  const timelineStore = useTimelineStore();
  return (() => {
    const _el$2 = _tmpl$212.cloneNode(true);
    _el$2.style.setProperty("grid-row-start", "1");
    createRenderEffect((_p$) => {
      const _v$ = !!isToday(props2.day), _v$2 = !!isLastDayOfMonth(props2.day), _v$3 = !!isWeekend(props2.day), _v$4 = !timelineStore.displayDays(), _v$5 = !!timelineStore.displayDayLabel(), _v$6 = `${props2.index + 1} / ${props2.index + 2}`, _v$7 = `span ${timelineStore.nbRows + 2}`;
      _v$ !== _p$._v$ && _el$2.classList.toggle("today", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$2.classList.toggle("last-of-month", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$2.classList.toggle("weekend", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$2.classList.toggle("reduced", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$2.classList.toggle("display-day-labels", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$2.style.setProperty("grid-column", _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$2.style.setProperty("grid-row-end", _p$._v$7 = _v$7);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0,
      _v$6: void 0,
      _v$7: void 0
    });
    return _el$2;
  })();
};

// public/app/ui/timeline/components/today-controls.tsx
var _tmpl$37 = /* @__PURE__ */ template(`<div class="timeline-header-today-control"><div class="today-control-wrapper end"></div></div>`, 4);
var _tmpl$213 = /* @__PURE__ */ template(`<div class="timeline-header-today-control"><div class="today-control-wrapper start"></div></div>`, 4);
var TodayControls = (props2) => {
  const timelineStore = useTimelineStore();
  const scrollToToday = () => {
    const column = getDayNode(/* @__PURE__ */ new Date());
    if (column) {
      column.scrollIntoView({
        inline: "center",
        behavior: "smooth",
        block: "nearest"
      });
    } else {
      const year = timelineStore.today.getFullYear();
      const month = timelineStore.today.getMonth();
      if (timelineStore.isTodayAfterPeriod()) {
        const lastDayOfCurrentMonth = new Date(year, month + 1, 0);
        timelineStore.setState("period", "end", lastDayOfCurrentMonth);
      } else {
        const firstDayOfCurrentMonth = new Date(year, month, 1);
        timelineStore.setState("period", "start", firstDayOfCurrentMonth);
      }
      setTimeout(() => {
        scrollToToday();
      });
    }
  };
  return [createComponent(Presence, {
    exitBeforeEnter: true,
    get children() {
      return createComponent(Show, {
        get when() {
          return timelineStore.isTodayAfterPeriod();
        },
        get children() {
          const _el$ = _tmpl$37.cloneNode(true), _el$2 = _el$.firstChild;
          insert(_el$2, createComponent(Motion.button, {
            initial: {
              opacity: 0,
              scale: 0.6
            },
            animate: {
              opacity: 1,
              scale: 1
            },
            exit: {
              opacity: 0,
              scale: 0.6
            },
            tabindex: "-1",
            transition: {
              duration: 0.3
            },
            "class": "today-control-button right",
            onClick: () => {
              scrollToToday();
            },
            children: "Aujourd'hui >"
          }));
          createRenderEffect((_p$) => {
            const _v$ = `${props2.row}`, _v$2 = `1 / ${timelineStore.isTodayAfterPeriod() ? -1 : timelineStore.todayPosition() + 1}`;
            _v$ !== _p$._v$ && _el$.style.setProperty("grid-row-start", _p$._v$ = _v$);
            _v$2 !== _p$._v$2 && _el$.style.setProperty("grid-column", _p$._v$2 = _v$2);
            return _p$;
          }, {
            _v$: void 0,
            _v$2: void 0
          });
          return _el$;
        }
      });
    }
  }), createComponent(Presence, {
    exitBeforeEnter: true,
    get children() {
      return createComponent(Show, {
        get when() {
          return timelineStore.isTodayBeforePeriod();
        },
        get children() {
          const _el$3 = _tmpl$213.cloneNode(true), _el$4 = _el$3.firstChild;
          insert(_el$4, createComponent(Motion.button, {
            initial: {
              opacity: 0,
              scale: 0.6
            },
            animate: {
              opacity: 1,
              scale: 1
            },
            exit: {
              opacity: 0,
              scale: 0.6
            },
            transition: {
              duration: 0.3
            },
            tabindex: "-1",
            "class": "today-control-button left",
            onClick: () => {
              scrollToToday();
            },
            children: "< Aujourd'hui"
          }));
          createRenderEffect((_p$) => {
            const _v$3 = `${props2.row}`, _v$4 = `${timelineStore.isTodayBeforePeriod() ? 1 : timelineStore.todayPosition() + 2} / -1`;
            _v$3 !== _p$._v$3 && _el$3.style.setProperty("grid-row-start", _p$._v$3 = _v$3);
            _v$4 !== _p$._v$4 && _el$3.style.setProperty("grid-column", _p$._v$4 = _v$4);
            return _p$;
          }, {
            _v$3: void 0,
            _v$4: void 0
          });
          return _el$3;
        }
      });
    }
  })];
};
var today_controls_default = TodayControls;

// public/app/ui/timeline/components/header.tsx
var _tmpl$38 = /* @__PURE__ */ template(`<div class="timeline-header_month"><div class="timeline-header_month-content"></div></div>`, 4);
var _tmpl$214 = /* @__PURE__ */ template(`<div class="timeline-header_week"><div class="timeline-header_week-content"></div></div>`, 4);
var _tmpl$39 = /* @__PURE__ */ template(`<div class="timeline-header_day"><div class="timeline-header_day-content"></div></div>`, 4);
var TimelineHeader = () => {
  let ref;
  const timelineStore = useTimelineStore();
  const [headerHeight, setHeaderHeight] = createSignal(72);
  createResizeObserver(() => ref, (size4) => {
    setHeaderHeight(size4.height);
  });
  const heightTolerance = 2;
  createEffect(on(() => headerHeight(), (height, prevHeight) => {
    if (height <= prevHeight - heightTolerance || height >= prevHeight + heightTolerance) {
      timelineStore.headerHeight = height;
      timelineStore.container.style.setProperty("--timeline-header-height", `${height}px`);
    }
  }));
  return createComponent(TimelineGrid, {
    ref: (elt) => ref = elt,
    "class": "timeline-header",
    get children() {
      return [createComponent(For, {
        get each() {
          return timelineStore.days();
        },
        children: (day, _index) => {
          const index2 = _index();
          return [createComponent(Show, {
            get when() {
              return isFirstDay(day);
            },
            get children() {
              return createComponent(HeaderMonth, {
                day,
                index: index2
              });
            }
          }), createComponent(Show, {
            get when() {
              return timelineStore.displayWeekNumber && timelineStore.visibleDays <= 120;
            },
            get children() {
              return createComponent(Show, {
                get when() {
                  return isFirstDayOfWeek(day);
                },
                get children() {
                  return createComponent(HeaderWeek, {
                    day,
                    index: index2
                  });
                }
              });
            }
          }), createComponent(HeaderDay, {
            day,
            index: index2
          })];
        }
      }), createComponent(Show, {
        get when() {
          return timelineStore.columnWidth > 20;
        },
        get children() {
          return createComponent(today_controls_default, {
            get row() {
              return timelineStore.displayWeekNumber ? 3 : 2;
            }
          });
        }
      })];
    }
  });
};
function HeaderMonth(props2) {
  const gridColumn = createMemo(() => {
    const day = props2.day;
    const index2 = props2.index;
    return `${index2 + 1} / ${index2 + getNbDaysInMonth(day.getFullYear(), day.getMonth()) + 1}`;
  });
  const label = createMemo(() => {
    const day = props2.day;
    return `${day.toLocaleString("default", {
      month: "short"
    })} ${day.getFullYear()}`;
  });
  return (() => {
    const _el$ = _tmpl$38.cloneNode(true), _el$2 = _el$.firstChild;
    _el$.style.setProperty("grid-row", "1");
    insert(_el$2, label);
    createRenderEffect(() => _el$.style.setProperty("grid-column", gridColumn()));
    return _el$;
  })();
}
function HeaderWeek(props2) {
  const gridColumn = createMemo(() => {
    const index2 = props2.index;
    return `${index2 + 1} / ${index2 + 8}`;
  });
  const label = createMemo(() => {
    const day = props2.day;
    return `${getWeekNumber(day)}`;
  });
  return (() => {
    const _el$3 = _tmpl$214.cloneNode(true), _el$4 = _el$3.firstChild;
    _el$3.style.setProperty("grid-row", "2");
    insert(_el$4, label);
    createRenderEffect(() => _el$3.style.setProperty("grid-column", gridColumn()));
    return _el$3;
  })();
}
var HeaderDay = (props2) => {
  let ref;
  const timelineStore = useTimelineStore();
  const isToday2 = createMemo(() => isToday(props2.day));
  const isLastDay = createMemo(() => sameDate(props2.day, timelineStore.period.end));
  const _isLastDayOfMonth = createMemo(() => isLastDayOfMonth(props2.day));
  const _isWeekend = createMemo(() => isWeekend(props2.day));
  const label = createMemo(() => {
    const day = props2.day;
    return day.toLocaleString("default", {
      day: "numeric",
      ...timelineStore.displayWeekDay() ? {} : {
        weekday: "short"
      }
    });
  });
  const hiddenDay = createMemo(() => {
    return !timelineStore.displayDays() || timelineStore.columnWidth < 20 || _isLastDayOfMonth() && timelineStore.visibleDays > 120;
  });
  onMount(() => {
    registerDayNode(props2.day, ref);
    if (isToday2()) {
      timelineStore.todayRef = ref;
    }
    if (props2.index === 0) {
      timelineStore.firstDayRef = ref;
    }
    if (isLastDay()) {
      timelineStore.lastDayRef = ref;
    }
  });
  onCleanup(() => {
    unregisterDayNode(props2.day);
  });
  return (() => {
    const _el$5 = _tmpl$39.cloneNode(true), _el$6 = _el$5.firstChild;
    const _ref$ = ref;
    typeof _ref$ === "function" ? use(_ref$, _el$5) : ref = _el$5;
    insert(_el$6, label);
    createRenderEffect((_p$) => {
      const _v$ = !!isToday2(), _v$2 = !!_isLastDayOfMonth(), _v$3 = !!_isWeekend(), _v$4 = !!hiddenDay(), _v$5 = !!timelineStore.displayDayLabel(), _v$6 = hiddenDay() ? 0 : 1, _v$7 = `${props2.index + 1} / ${props2.index + 2}`, _v$8 = timelineStore.displayWeekNumber ? 3 : 2;
      _v$ !== _p$._v$ && _el$5.classList.toggle("today", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$5.classList.toggle("last-of-month", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$5.classList.toggle("weekend", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$5.classList.toggle("day-hidden", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$5.classList.toggle("display-day-labels", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$5.style.setProperty("opacity", _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$5.style.setProperty("grid-column", _p$._v$7 = _v$7);
      _v$8 !== _p$._v$8 && _el$5.style.setProperty("grid-row", _p$._v$8 = _v$8);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0,
      _v$6: void 0,
      _v$7: void 0,
      _v$8: void 0
    });
    return _el$5;
  })();
};

// public/app/ui/timeline/components/period.tsx
var _tmpl$40 = /* @__PURE__ */ template(`<div aria-hidden="true" class="timeline-period-tooltip-anchor start"></div>`, 2);
var _tmpl$215 = /* @__PURE__ */ template(`<div aria-hidden="true" class="timeline-period-tooltip-anchor end"></div>`, 2);
var _tmpl$310 = /* @__PURE__ */ template(`<div class="timeline-period-content"></div>`, 2);
var _tmpl$45 = /* @__PURE__ */ template(`<div></div>`, 2);
var _tmpl$53 = /* @__PURE__ */ template(`<div class="timeline-period-creator-hint"><span></span></div>`, 4);
var _tmpl$63 = /* @__PURE__ */ template(`<div class="timeline-period"><div class="timeline-period-content"></div></div>`, 4);
var _tmpl$73 = /* @__PURE__ */ template(`<button class="timeline-period-resizer" tabindex="-1" aria-hidden="true"></button>`, 2);
var _tmpl$83 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$92 = /* @__PURE__ */ template(`<div class="timeline-highlighted-period"><div></div></div>`, 4);
var TimelinePeriod = (props2) => {
  const [theme2, internal, rest2] = splitProps(props2, ["class", "classList", "style"], ["store"]);
  const store2 = internal.store ?? TimelinePeriodStore4.create();
  const timelineStore = useTimelineStore();
  const item = useTimelineItem();
  const selectable = usePeriodSelectable();
  onMount(() => {
    if (item) {
      store2.parent = item;
    }
  });
  createResizeObserver(() => store2.elt, (size4) => {
    store2.update({
      eltWidth: size4.width,
      eltHeight: size4.height
    });
  });
  createEffect(() => {
    const parentVisibility = item.parent ? item.parent.visible : true;
    const isVisible = parentVisibility || item.visible;
    const start = store2.start;
    const end = store2.end;
    const periodStart = timelineStore.period?.start;
    const computeGridCols = !!(isVisible && start && end && periodStart);
    const gridColStart = computeGridCols ? getPositionInPeriod(start, periodStart, "startOf") : void 0;
    const gridColEnd = computeGridCols ? getPositionInPeriod(end, periodStart, "endOf") : void 0;
    store2.update({
      gridColumnStart: gridColStart,
      gridColumnEnd: gridColEnd
    });
  });
  createEffect(() => {
    const isVisible = item.visible;
    const columnWidth = timelineStore.columnWidth;
    const visibleDays = timelineStore.visibleDays;
    const minutesBreakpoint = timelineStore.minutesBreakpoint;
    const start = store2.start;
    const end = store2.end;
    if (isVisible && start && end) {
      const {
        left,
        right
      } = calculatePadding(start, end, columnWidth, visibleDays, minutesBreakpoint, store2.allDay);
      store2.update({
        left,
        right
      });
    }
  });
  const onRef = (ref) => {
    if (props2.ref && typeof props2.ref === "function") {
      props2.ref(ref);
    }
    store2.elt = ref;
  };
  const displayContent = () => props2.displayAllItems || item.visible && store2.start && store2.end && compareDates(store2.start, timelineStore.period?.start) > 0 || store2.start && store2.end && store2.creatingRelation;
  const tooltipStartContent = () => {
    if (!store2.allDay && timelineStore.visibleDays <= timelineStore.minutesBreakpoint || timelineStore.minutesBreakpoint < 3) {
      return (store2.tmpStart ?? store2.start).toLocaleDateString();
    }
    return (store2.tmpStart ?? store2.start).toLocaleString();
  };
  const tooltipEndContent = () => {
    if (!store2.allDay && timelineStore.visibleDays <= timelineStore.minutesBreakpoint || timelineStore.minutesBreakpoint < 3) {
      return (store2.tmpEnd ?? store2.end).toLocaleDateString();
    }
    return (store2.tmpEnd ?? store2.end).toLocaleString();
  };
  onCleanup(() => {
    store2.elt = void 0;
  });
  return createComponent(TimelinePeriodProvider, {
    value: store2,
    get children() {
      const _el$ = _tmpl$45.cloneNode(true);
      use(onRef, _el$);
      spread(_el$, mergeProps({
        get ["class"]() {
          return classNames("timeline-period", theme2.class);
        },
        get classList() {
          return {
            selected: selectable?.isSelected(store2),
            deletingDates: store2.deletingDates,
            moving: store2.moving,
            resizing: store2.resizing,
            "creating-relation": store2.creatingRelation,
            stacked: store2.stackLevel > 0,
            ...theme2.classList ?? {}
          };
        },
        get style() {
          return {
            "grid-row": 1,
            "grid-column": store2.gridColumn(),
            "--stack-level": store2.stackLevel,
            ...theme2.style ?? {}
          };
        }
      }, rest2), false, true);
      insert(_el$, createComponent(Show, {
        get when() {
          return displayContent();
        },
        get children() {
          const _el$2 = _tmpl$310.cloneNode(true);
          insert(_el$2, createComponent(Show, {
            get when() {
              return (store2.moving || store2.resizing) && store2.tmpStart;
            },
            get children() {
              return createComponent(Tooltip, {
                show: true,
                get label() {
                  return tooltipStartContent();
                },
                get mount() {
                  return timelineStore.viewport?.querySelector(".timeline");
                },
                placement: "top-end",
                showArrow: false,
                get children() {
                  return _tmpl$40.cloneNode(true);
                }
              });
            }
          }), null);
          insert(_el$2, () => props2.children, null);
          insert(_el$2, createComponent(Show, {
            get when() {
              return (store2.moving || store2.resizing) && store2.tmpEnd && !store2.isMilestone;
            },
            get children() {
              return createComponent(Tooltip, {
                show: true,
                get label() {
                  return tooltipEndContent();
                },
                get mount() {
                  return timelineStore.viewport?.querySelector(".timeline");
                },
                placement: "top-start",
                showArrow: false,
                get children() {
                  return _tmpl$215.cloneNode(true);
                }
              });
            }
          }), null);
          createRenderEffect((_p$) => {
            const _v$ = !!store2.isMilestone, _v$2 = `${store2.left}px`, _v$3 = `${store2.right}px`;
            _v$ !== _p$._v$ && _el$2.classList.toggle("milestone", _p$._v$ = _v$);
            _v$2 !== _p$._v$2 && _el$2.style.setProperty("left", _p$._v$2 = _v$2);
            _v$3 !== _p$._v$3 && _el$2.style.setProperty("right", _p$._v$3 = _v$3);
            return _p$;
          }, {
            _v$: void 0,
            _v$2: void 0,
            _v$3: void 0
          });
          return _el$2;
        }
      }));
      return _el$;
    }
  });
};
var PeriodCreator = (props2) => {
  let periodRef;
  let gridRef;
  const keyboard = useKeyboard();
  const timelineStore = useTimelineStore();
  const newPeriod = props2.newPeriod ?? TimelinePeriodStore4.create({
    isRange: true
  });
  const minuteWidth = useMinuteWidth();
  const [initialDate, setInitialDate] = createSignal();
  const [mouseDown, setMouseDown] = createSignal(false);
  const [didDrag, setDidDrag] = createSignal(false);
  let cachedGridLeft = null;
  const [dragPreview, setDragPreview] = createSignal(null);
  const finalizeCreation = () => {
    if (newPeriod.start && newPeriod.end) {
      props2.onPeriodCreated?.(periodRef, newPeriod);
    }
  };
  const computeOffsetX = (clientX, state) => {
    if (!gridRef) return 0;
    if (cachedGridLeft === null) {
      cachedGridLeft = gridRef.getBoundingClientRect().left;
    }
    const scrollOffset = state?.autoScrollOffset?.x ?? 0;
    return clientX - (cachedGridLeft - scrollOffset);
  };
  const computePixelLeft = (date) => {
    const dayIndex = getPositionInPeriod(date, timelineStore.period.start, "startOf") - 1;
    return dayIndex * timelineStore.columnWidth;
  };
  const computePixelWidth = (start, end) => {
    const startDayIndex = getPositionInPeriod(start, timelineStore.period.start, "startOf");
    const endDayIndex = getPositionInPeriod(end, timelineStore.period.start, "endOf");
    const nbDays = endDayIndex - startDayIndex + 1;
    return nbDays * timelineStore.columnWidth;
  };
  const onDragStart = (e3) => {
    const minutes = computeMinutes(e3.offsetX, minuteWidth());
    let mStartDate = moment_default(timelineStore.period.start).add(minutes, "minutes").startOf(newPeriod.stepUnit);
    const startDate = mStartDate.toDate();
    setInitialDate(startDate);
    const endDate = moment_default(startDate).endOf(newPeriod.stepUnit).toDate();
    const left = computePixelLeft(startDate);
    const width = computePixelWidth(startDate, endDate);
    setDragPreview({
      left,
      width
    });
    newPeriod.start = startDate;
    newPeriod.end = endDate;
  };
  const onDrag = (e3, state) => {
    if (!didDrag()) setDidDrag(true);
    const offsetX = state?.x != null ? computeOffsetX(state.x, state) : e3.offsetX;
    const minutes = computeMinutes(offsetX, minuteWidth());
    const initialStartDate = initialDate();
    if (!initialStartDate) return;
    let startDate;
    let endDate;
    if (!newPeriod.isRange) {
      const mDate = moment_default(timelineStore.period.start).add(minutes, "minutes").startOf(newPeriod.stepUnit);
      startDate = mDate.toDate();
      endDate = moment_default(startDate).endOf(newPeriod.stepUnit).toDate();
    } else {
      let mEndDate = moment_default(timelineStore.period.start).add(minutes, "minutes").endOf(newPeriod.stepUnit);
      const dragEndDate = mEndDate.toDate();
      if (dragEndDate.getTime() < initialStartDate.getTime()) {
        startDate = dragEndDate;
        endDate = initialStartDate;
      } else {
        startDate = initialStartDate;
        endDate = dragEndDate;
      }
    }
    const left = computePixelLeft(startDate);
    const width = computePixelWidth(startDate, endDate);
    setDragPreview({
      left,
      width
    });
  };
  const onDragEnd = (e3, state) => {
    const preview = dragPreview();
    if (preview) {
      const offsetX = state?.x != null ? computeOffsetX(state.x, state) : e3.offsetX;
      const minutes = computeMinutes(offsetX, minuteWidth());
      const initialStartDate = initialDate();
      if (initialStartDate) {
        let startDate;
        let endDate;
        if (!newPeriod.isRange) {
          const mDate = moment_default(timelineStore.period.start).add(minutes, "minutes").startOf(newPeriod.stepUnit);
          startDate = mDate.toDate();
          endDate = moment_default(startDate).endOf(newPeriod.stepUnit).toDate();
        } else {
          let mEndDate = moment_default(timelineStore.period.start).add(minutes, "minutes").endOf(newPeriod.stepUnit);
          const dragEndDate = mEndDate.toDate();
          if (dragEndDate.getTime() < initialStartDate.getTime()) {
            startDate = dragEndDate;
            endDate = initialStartDate;
          } else {
            startDate = initialStartDate;
            endDate = dragEndDate;
          }
        }
        newPeriod.update({
          start: startDate,
          end: endDate
        });
      }
    }
    setDragPreview(null);
    queueMicrotask(() => {
      finalizeCreation();
    });
    setMouseDown(false);
    setDidDrag(false);
    cachedGridLeft = null;
  };
  return createComponent(TimelineGrid, {
    ref: (ref) => {
      gridRef = ref;
      draggable(ref, () => ({
        disable: () => !keyboard.Control,
        container: () => timelineStore.viewport,
        draggingCursor: "ew-resize",
        // onDragStart,
        onDrag,
        onDragEnd,
        autoScroll: {
          x: true,
          y: false
        },
        autoScrollSpeed: 15,
        autoScrollZone: 60,
        autoScrollAcceleration: true,
        autoScrollZoneOffset: {
          left: timelineStore.sidebarWidth
        }
      }));
    },
    onMouseDown: (e3) => {
      if (e3.ctrlKey) {
        if (gridRef) {
          cachedGridLeft = gridRef.getBoundingClientRect().left;
        }
        setMouseDown(true);
        setDidDrag(false);
        onDragStart(e3, null);
      }
    },
    onMouseUp: (e3) => {
      if (mouseDown() && !didDrag() && e3.ctrlKey) {
        setDragPreview(null);
        queueMicrotask(() => {
          finalizeCreation();
        });
      }
      setMouseDown(false);
      setDidDrag(false);
    },
    "class": "timeline-period-creator",
    get classList() {
      return {
        draggable: keyboard.Control
      };
    },
    style: {
      display: "grid",
      "grid-row": "1",
      "grid-column": "1 / -1"
    },
    get children() {
      return [createComponent(Show, {
        get when() {
          return dragPreview();
        },
        children: (preview) => (() => {
          const _el$7 = _tmpl$63.cloneNode(true), _el$8 = _el$7.firstChild;
          _el$7.style.setProperty("position", "absolute");
          _el$7.style.setProperty("grid-row", "1");
          _el$7.style.setProperty("pointer-events", "none");
          _el$8.style.setProperty("left", "0");
          _el$8.style.setProperty("right", "0");
          createRenderEffect((_p$) => {
            const _v$4 = `${preview().left}px`, _v$5 = `${preview().width}px`;
            _v$4 !== _p$._v$4 && _el$7.style.setProperty("left", _p$._v$4 = _v$4);
            _v$5 !== _p$._v$5 && _el$7.style.setProperty("width", _p$._v$5 = _v$5);
            return _p$;
          }, {
            _v$4: void 0,
            _v$5: void 0
          });
          return _el$7;
        })()
      }), createComponent(Show, {
        get when() {
          return !dragPreview() && newPeriod.start && newPeriod.end;
        },
        get children() {
          return createComponent(TimelinePeriod, {
            store: newPeriod,
            style: {
              "pointer-events": "none"
            },
            ref: (ref) => periodRef = ref
          });
        }
      }), createComponent(Show, {
        get when() {
          return !dragPreview() && (!newPeriod.start || !newPeriod.end);
        },
        get children() {
          const _el$5 = _tmpl$53.cloneNode(true), _el$6 = _el$5.firstChild;
          insert(_el$6, (() => {
            const _c$ = createMemo(() => !!newPeriod.isRange);
            return () => _c$() ? _4("Ctrl + click and drag on an empty space to create new period") : _4("Ctrl + click on an empty space to create new period");
          })());
          return _el$5;
        }
      })];
    }
  });
};
var TimelinePeriodMoveHandler = (props2) => {
  const timelineStore = useTimelineStore();
  const period = useTimelinePeriod();
  const selection = useSelection();
  const minuteWidth = useMinuteWidth();
  const [theme2, rest2] = splitProps(props2, ["class"]);
  const [initial2, setInitial] = createStore({
    left: 0,
    right: 0,
    periodDurations: /* @__PURE__ */ new Map()
  });
  const onDragStart = () => {
    const durations = /* @__PURE__ */ new Map();
    selection().forEach((selectedPeriod) => {
      const start = selectedPeriod.isRange ? selectedPeriod.start : selectedPeriod.end;
      const end = selectedPeriod.end;
      if (start && end) {
        const unit = period.stepUnit;
        const duration = moment_default(end).diff(moment_default(start), unit);
        durations.set(selectedPeriod, {
          value: duration,
          unit
        });
      }
    });
    setInitial({
      left: period.left ?? 0,
      right: period.right ?? 0,
      periodDurations: durations
    });
    period.moving = true;
    timelineStore.itemsMoving = true;
  };
  const onDrag = (drag) => {
    const translation2 = computeTranslation(drag.sx - drag.x, timelineStore.columnWidth, timelineStore.visibleDays, timelineStore.minutesBreakpoint, period.allDay);
    const left = initial2.left + translation2 * -1;
    const right = initial2.right + translation2;
    const _minuteWidth = minuteWidth();
    const minutes = computeMinutes(translation2 * -1, _minuteWidth);
    selection().forEach((selectedPeriod) => {
      selectedPeriod.update((draft) => {
        const isNotRange = !draft.isRange;
        const isMilestone = draft.isMilestone;
        const isNotRangeOrMilestone = isNotRange || isMilestone;
        const start = isNotRangeOrMilestone ? draft.end : draft.start;
        let newStart = shiftDate(start, minutes, period.stepUnit);
        newStart = moment_default(newStart).startOf(period.stepUnit).toDate();
        const savedDuration = initial2.periodDurations.get(selectedPeriod);
        let newEnd;
        if (savedDuration && !isMilestone) {
          newEnd = moment_default(newStart).add(savedDuration.value, savedDuration.unit).endOf(period.stepUnit).toDate();
        } else {
          newEnd = shiftDate(draft.end, minutes, period.stepUnit);
          newEnd = moment_default(newEnd).endOf(period.stepUnit).toDate();
        }
        const leftDiff = Math.abs(moment_default(start).startOf(period.stepUnit).diff(newStart, "minutes"));
        const rightDiff = Math.abs(moment_default(draft.end).endOf(period.stepUnit).diff(newEnd, "minutes"));
        draft.left = initial2.left + leftDiff * _minuteWidth * (left > 0 ? 1 : -1);
        draft.right = initial2.right + rightDiff * _minuteWidth * (right > 0 ? 1 : -1);
        draft.tmpStart = newStart;
        draft.tmpEnd = newEnd;
      });
    });
  };
  const onDragEnd = () => {
    const translation2 = period.left - initial2.left;
    const minutes = computeMinutes(translation2, minuteWidth());
    const days = computeDays(translation2, minuteWidth());
    const data2 = selection().map((selectedPeriod) => {
      return {
        item: selectedPeriod.parent,
        period: selectedPeriod,
        original: {
          start: selectedPeriod.start,
          end: selectedPeriod.end
        },
        days,
        minutes,
        start: selectedPeriod.tmpStart ?? selectedPeriod.start,
        end: selectedPeriod.tmpEnd ?? selectedPeriod.end
      };
    });
    if (props2.onPeriodsMoved) {
      props2.onPeriodsMoved(data2);
    }
    if (props2.onPeriodMoved) {
      data2.forEach((payload) => {
        props2.onPeriodMoved(payload);
      });
    }
    period.update({
      moving: false
      // Don't reset tmp values to avoid flickering.
      // tmpStart: undefined,
      // tmpEnd: undefined,
    });
    setTimeout(() => {
      timelineStore.itemsMoving = false;
    });
  };
  return (() => {
    const _el$9 = _tmpl$45.cloneNode(true);
    use(draggable, _el$9, () => ({
      disable: () => !props2.enable,
      container: () => timelineStore.viewport,
      draggingCursor: "grabbing",
      onDragStart,
      onDrag: (_5, drag) => onDrag(drag),
      onDragEnd,
      autoScroll: {
        x: true,
        y: false
      },
      autoScrollSpeed: 15,
      autoScrollZone: 60,
      autoScrollAcceleration: true,
      autoScrollZoneOffset: {
        left: timelineStore.sidebarWidth
      }
    }));
    spread(_el$9, mergeProps({
      get ["class"]() {
        return classNames("timeline-period-move-handler", theme2.class);
      }
    }, rest2), false, true);
    insert(_el$9, () => props2.children);
    return _el$9;
  })();
};
var TimelinePeriodResizer = (props2) => {
  const timelineStore = useTimelineStore();
  const period = useTimelinePeriod();
  const selection = useSelection();
  const minuteWidth = useMinuteWidth();
  const [initial2, setInitial] = createStore({
    left: 0,
    right: 0
  });
  const propName = () => props2.start ? "left" : "right";
  const getMinutesAndDaysPayload = (translation2, value2) => {
    const originalValue = initial2[propName()];
    const sign = (props2.start ? 1 : -1) * (value2 < originalValue ? -1 : 1);
    const minutes = sign * Math.abs(computeMinutes(translation2, minuteWidth()));
    const days = sign * Math.abs(computeDays(translation2, minuteWidth()));
    return {
      minutes,
      days
    };
  };
  const onDragStart = () => {
    setInitial({
      left: period.left ?? 0,
      right: period.right ?? 0
    });
    period.resizing = true;
    timelineStore.itemsResizing = true;
  };
  const onDrag = (drag) => {
    const translation2 = drag.sx - drag.x;
    const value2 = computeTranslation(props2.start ? initial2.left + translation2 * -1 : initial2.right + translation2, timelineStore.columnWidth, timelineStore.visibleDays, timelineStore.minutesBreakpoint, period.allDay);
    const {
      minutes,
      days
    } = getMinutesAndDaysPayload(translation2, value2);
    const dateProp = props2.start ? "start" : "end";
    const _minuteWidth = minuteWidth();
    const _propName = propName();
    selection().forEach((selectedPeriod) => {
      const newDate = shiftDate(selectedPeriod[dateProp], minutes, period.stepUnit);
      const start = dateProp === "start" ? newDate : selectedPeriod.start;
      const end = dateProp === "end" ? newDate : selectedPeriod.end;
      selectedPeriod.update((draft) => {
        const diff = Math.abs(moment_default(draft[dateProp]).diff(dateProp === "start" ? start : end, "minutes"));
        draft[_propName] = initial2[_propName] + diff * _minuteWidth * (value2 > 0 ? 1 : -1);
        if (selectedPeriod === period) {
          if (props2.start) {
            draft.tmpStart = newDate;
          } else if (props2.end) {
            draft.tmpEnd = newDate;
          }
        }
        if (start > end || end < start) {
          draft.deletingDates = true;
        } else {
          draft.deletingDates = false;
        }
      });
    });
  };
  const onDragEnd = () => {
    const value2 = period[propName()];
    const originalValue = initial2[propName()];
    const translation2 = value2 - originalValue;
    const {
      minutes,
      days
    } = getMinutesAndDaysPayload(translation2, value2);
    selection().forEach((selectedPeriod) => {
      props2.onPeriodResized?.({
        item: selectedPeriod.parent,
        period: selectedPeriod,
        original: {
          start: selectedPeriod.start,
          end: selectedPeriod.end
        },
        days,
        minutes,
        start: selectedPeriod.tmpStart,
        end: selectedPeriod.tmpEnd
      });
    });
    period.update({
      resizing: false,
      tmpStart: void 0,
      tmpEnd: void 0
    });
    setTimeout(() => {
      timelineStore.itemsResizing = false;
    });
  };
  return (() => {
    const _el$10 = _tmpl$73.cloneNode(true);
    use(draggable, _el$10, () => ({
      container: () => timelineStore.viewport,
      draggingCursor: "ew-resize",
      onDragStart,
      onDrag: (_5, drag) => onDrag(drag),
      onDragEnd,
      autoScroll: {
        x: true,
        y: false
      },
      autoScrollSpeed: 15,
      autoScrollZone: 60,
      autoScrollAcceleration: true,
      autoScrollZoneOffset: {
        left: timelineStore.sidebarWidth
      }
    }));
    insert(_el$10, createComponent(Show, {
      get when() {
        return props2.children;
      },
      get fallback() {
        return (() => {
          const _el$11 = _tmpl$83.cloneNode(true);
          createRenderEffect(() => _el$11.innerHTML = props2.start ? "&lt;" : "&gt;");
          return _el$11;
        })();
      },
      get children() {
        return props2.children;
      }
    }));
    createRenderEffect((_p$) => {
      const _v$6 = !!(props2.start || !props2.end), _v$7 = !!props2.end;
      _v$6 !== _p$._v$6 && _el$10.classList.toggle("start", _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$10.classList.toggle("end", _p$._v$7 = _v$7);
      return _p$;
    }, {
      _v$6: void 0,
      _v$7: void 0
    });
    return _el$10;
  })();
};
var TimelineHighlightedPeriod = () => {
  const timelineStore = useTimelineStore();
  const period = TimelinePeriodStore4.create();
  createEffect(() => {
    const data2 = timelineStore.dragOverNewPeriodData;
    if (data2 && data2 !== "") {
      const {
        start,
        end
      } = JSON.parse(data2);
      if (start && end) {
        period.update({
          start: new Date(start),
          end: new Date(end)
        });
      }
    }
  });
  createEffect(() => {
    const start = period.start;
    const end = period.end;
    const periodStart = timelineStore.period?.start;
    const computeGridCols = !!(start && end && periodStart);
    if (computeGridCols) {
      const gridColStart = getPositionInPeriod(start, periodStart);
      const gridColEnd = getPositionInPeriod(end, periodStart);
      period.update({
        gridColumnStart: gridColStart,
        gridColumnEnd: gridColEnd
      });
    }
  });
  createEffect(() => {
    const columnWidth = timelineStore.columnWidth;
    const visibleDays = timelineStore.visibleDays;
    const minutesBreakpoint = timelineStore.minutesBreakpoint;
    const start = period.start;
    const end = period.end;
    if (start && end) {
      period.update((draft) => {
        const {
          left,
          right
        } = calculatePadding(start, end, columnWidth, visibleDays, minutesBreakpoint);
        draft.left = left;
        draft.right = right;
      });
    }
  });
  const gridColumn = () => {
    const value2 = period.gridColumn();
    if (value2 === "1 / -1") return "1 / 1";
    return value2;
  };
  return createComponent(Show, {
    get when() {
      return timelineStore.dragOverNewPeriod;
    },
    get children() {
      const _el$12 = _tmpl$92.cloneNode(true), _el$13 = _el$12.firstChild;
      createRenderEffect((_p$) => {
        const _v$8 = gridColumn(), _v$9 = `1 / ${timelineStore.nbRows + 2}`, _v$10 = `${period.left}px`, _v$11 = `${period.right}px`;
        _v$8 !== _p$._v$8 && _el$12.style.setProperty("grid-column", _p$._v$8 = _v$8);
        _v$9 !== _p$._v$9 && _el$12.style.setProperty("grid-row", _p$._v$9 = _v$9);
        _v$10 !== _p$._v$10 && _el$13.style.setProperty("left", _p$._v$10 = _v$10);
        _v$11 !== _p$._v$11 && _el$13.style.setProperty("right", _p$._v$11 = _v$11);
        return _p$;
      }, {
        _v$8: void 0,
        _v$9: void 0,
        _v$10: void 0,
        _v$11: void 0
      });
      return _el$12;
    }
  });
};

// public/app/ui/utils/drag-image.ts
var dragImage = document.createElement("img");
dragImage.style.position = "absolute";
dragImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NgAAIAAAUAAR4f7BQAAAAASUVORK5CYII=";
document.body.appendChild(dragImage);

// public/app/ui/timeline/components/relation-creator.tsx
var _tmpl$41 = /* @__PURE__ */ template(`<div aria-hidden="true" class="timeline-relation-creator"><span class="sr-only">+</span></div>`, 4);
var PointsStore = class extends BaseStore {
  start = prop(void 0);
  end = prop(void 0);
};
var TimelineRelationCreator = (props2) => {
  let ref;
  const timelineStore = useTimelineStore();
  const item = useTimelineItem();
  const freeLineApi = useFreeLine();
  const period = useTimelinePeriod();
  const [dragover, setDragover] = createSignal(false);
  const pointStore = PointsStore.create();
  createEventListener(() => ref, "dragstart", (e3) => {
    e3.dataTransfer?.setDragImage(dragImage, 0, 0);
    const target = e3.target;
    const point = {
      x: timelineStore.getLeftOffsetRelativeToViewport(target) + 4,
      y: timelineStore.getTopOffsetRelativeToViewport(target) + 4
    };
    freeLineApi.clear();
    pointStore.start = {
      x: point.x,
      y: point.y
    };
    pointStore.end = {
      x: point.x,
      y: point.y
    };
    e3.dataTransfer?.setData("timeline/create-relation", JSON.stringify({
      swap: props2.swap ?? false,
      path: item.path,
      attachment: props2.start ? "start" : "end"
    }));
    freeLineApi.draw(pointStore.start, pointStore.end);
    setTimeout(() => {
      period.creatingRelation = true;
      timelineStore.creatingRelation = true;
    });
  });
  createEventListener(() => ref, "drag", (e3) => {
    const prevX = pointStore.end.x;
    const prevY = pointStore.end.y;
    let x3 = timelineStore.pointer.offsetX;
    let y3 = timelineStore.pointer.offsetY;
    if (Math.abs(x3 - prevX) > prevX / 2) {
      x3 = prevX;
    }
    if (Math.abs(y3 - prevY) > prevY / 2) {
      y3 = prevY;
    }
    pointStore.setState("end", {
      x: x3,
      y: y3
    });
  });
  createEventListener(() => ref, "dragend", () => {
    period.creatingRelation = false;
    timelineStore.creatingRelation = false;
    freeLineApi.clear();
  });
  createEventListener(() => period.creatingRelation ? null : ref, "dragover", (e3) => {
    e3.preventDefault();
  });
  createEventListener(() => period.creatingRelation ? null : ref, "dragenter", (e3) => {
    e3.preventDefault();
    setDragover(true);
    if (!period.creatingRelation && timelineStore.creatingRelation) {
      freeLineApi.update("end", {
        x: timelineStore.getLeftOffsetRelativeToViewport(ref) + 4,
        y: timelineStore.getTopOffsetRelativeToViewport(ref) + 4
      });
    }
  });
  createEventListener(() => period.creatingRelation ? null : ref, "dragleave", (e3) => {
    e3.preventDefault();
    setDragover(false);
  });
  createEventListener(() => period.creatingRelation ? null : ref, "drop", (e3) => {
    e3.preventDefault();
    props2.onDrop(e3);
    setDragover(false);
  });
  return (() => {
    const _el$ = _tmpl$41.cloneNode(true);
    const _ref$ = ref;
    typeof _ref$ === "function" ? use(_ref$, _el$) : ref = _el$;
    setAttribute(_el$, "draggable", true);
    createRenderEffect((_p$) => {
      const _v$ = !!dragover(), _v$2 = !!props2.start, _v$3 = !!props2.end;
      _v$ !== _p$._v$ && _el$.classList.toggle("dragover", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$.classList.toggle("start", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$.classList.toggle("end", _p$._v$3 = _v$3);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0
    });
    return _el$;
  })();
};

// public/app/ui/timeline/components/row.tsx
var CSSGridRowOffset = 1;
var TimelineRow = (props2) => {
  let rowRef;
  const [local, theme2, rest2] = splitProps(props2, ["children", "rowOffset", "row", "displayAllItems"], ["class", "classList", "style"]);
  const item = useTimelineItem();
  useItemVisibility(() => rowRef, () => local.displayAllItems);
  const onRef = (ref) => {
    rowRef = ref;
    if (props2.ref) {
      props2.ref(rowRef);
    }
  };
  const row = createMemo(() => (local.row !== void 0 ? local.row : item.position) + CSSGridRowOffset + (local.rowOffset ?? 0));
  const gridStyle = createMemo(() => {
    return {
      "grid-row": row(),
      "grid-column": `1 / -1`
    };
  });
  return createComponent(TimelineGrid, mergeProps({
    ref: onRef
  }, rest2, {
    get ["class"]() {
      return classNames("timeline-row", theme2.class);
    },
    get classList() {
      return {
        ...theme2.classList ?? {}
      };
    },
    get style() {
      return {
        ...theme2.style ?? {},
        ...gridStyle()
      };
    },
    get children() {
      return local.children;
    }
  }));
};

// public/app/ui/timeline/components/timeline.tsx
var _tmpl$46 = /* @__PURE__ */ template(`<div class="timeline"></div>`, 2);
var SCROLL_END_EVENT = "k:scrollend";
var Timeline = (props2) => {
  let containerRef;
  const timelineStore = useTimelineStore();
  const keyboardState2 = useKeyboard();
  const spaceBarPressed = useSpacebar({
    preventDefault: false
  });
  const useVisibilityObserver = createVisibilityObserver();
  const todayVisible = useVisibilityObserver(() => timelineStore.todayRef);
  const firstDayVisible = useVisibilityObserver(() => timelineStore.firstDayRef);
  const lastDayVisible = useVisibilityObserver(() => timelineStore.lastDayRef);
  const shouldLoadFutureDays = createMemo(() => timelineStore.initialized && lastDayVisible());
  const shouldLoadPastDays = createMemo(() => timelineStore.initialized && firstDayVisible());
  createEffect(() => {
    containerRef?.style.setProperty("--timeline-column-visible-days", `${timelineStore.visibleDays}`);
  });
  createEffect(() => {
    containerRef?.style.setProperty("--timeline-sidebar-width", `${timelineStore.sidebarWidth}px`);
  });
  createResizeObserver(() => containerRef?.closest(".timeline-wrapper"), (size4) => {
    timelineStore.viewportWidth = size4.width;
  });
  onMount(() => {
    timelineStore.container = containerRef;
  });
  let animationFrameId;
  createEffect((prev) => {
    const columnWidth = timelineStore.columnWidth;
    const vp = timelineStore.viewport;
    const scrollLeftPercent = timelineStore.scrollLeftPercent;
    if (vp && timelineStore.initialized && prev && timelineStore.columnWidth !== prev && scrollLeftPercent != null && timelineStore.applyScrollLeftPercent) {
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
      animationFrameId = requestAnimationFrame(() => {
        vp.scrollLeft = scrollLeftPercent * (vp.scrollWidth - vp.clientWidth);
        timelineStore.applyScrollLeftPercent = false;
      });
    }
    return columnWidth;
  });
  createEffect(() => timelineStore.setState("todayVisible", todayVisible()));
  createEffect((prev) => {
    const loadMore = shouldLoadPastDays();
    const date = timelineStore.period?.start;
    if (prev !== loadMore && loadMore && date) {
      timelineStore.setState("period", "start", addDays(date, timelineStore.visibleDays * -1));
      requestAnimationFrame(() => {
        getDayNode(date)?.scrollIntoView({
          inline: "start",
          block: "nearest"
        });
      });
    }
    return loadMore;
  });
  createEffect((prev) => {
    const loadMore = shouldLoadFutureDays();
    if (prev !== loadMore && loadMore) {
      timelineStore.setState("period", "end", addDays(timelineStore.period.end, timelineStore.visibleDays));
    }
    return loadMore;
  });
  const onSimpleBarInit = (instance) => {
    const viewport = instance.getScrollElement();
    timelineStore.setState("viewport", viewport);
  };
  createEventListener(() => timelineStore.container, "dragover", (e3) => {
    if (e3.dataTransfer?.getData("timeline/drop-period") !== "") {
      e3.preventDefault();
    }
    timelineStore.setState(produce((s3) => {
      s3.pointer.x = e3.x;
      s3.pointer.offsetX = e3.offsetX;
      s3.pointer.y = e3.y;
      s3.pointer.offsetY = e3.offsetY;
    }));
  });
  const dragging = useDragToScroll(() => timelineStore.viewport, () => ({
    useSpacebar: true
  }));
  createEffect(on(() => dragging(), (dragging2) => {
    timelineStore.setState("dragging", dragging2);
  }));
  const scrollEnd = createDebounce(() => {
    timelineStore.viewport?.dispatchEvent(new Event(SCROLL_END_EVENT));
  }, 500);
  createEventListener(() => timelineStore.viewport, ["scroll"], () => {
    const viewport = timelineStore.viewport;
    timelineStore.setState(produce((s3) => {
      s3.scrollLeft = viewport.scrollLeft;
      s3.scrollTop = viewport.scrollTop;
    }));
    scrollEnd.clear();
    scrollEnd();
  }, {
    passive: true
  });
  createEventListener(() => timelineStore.initialized ? timelineStore.viewport : null, "wheel", (e3) => {
    const viewport = timelineStore.viewport;
    if (e3.ctrlKey) {
      e3.preventDefault();
      if (!viewport) return;
      const scrollPercentBeforeZoom = viewport.scrollLeft / (viewport.scrollWidth - viewport.clientWidth);
      timelineStore.setState(produce((s3) => {
        s3.scrollLeftPercent = scrollPercentBeforeZoom;
        s3.visibleDays = accelerateNumberOnWheelEvent(s3.visibleDays, e3);
        s3.applyScrollLeftPercent = true;
      }));
    }
  }, {
    passive: false
  });
  return createComponent(ScrollContainer, {
    "class": "timeline-wrapper scroll-container-native",
    get classList() {
      return {
        "spacebar-pressed": spaceBarPressed(),
        "density-compact": props2?.displayDensity === DisplayDensity.COMPACT,
        "density-large": props2?.displayDensity === DisplayDensity.LARGE
      };
    },
    native: true,
    onInitialized: onSimpleBarInit,
    get children() {
      const _el$ = _tmpl$46.cloneNode(true);
      const _ref$ = containerRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : containerRef = _el$;
      insert(_el$, createComponent(TimelineColumns, {}), null);
      insert(_el$, createComponent(TimelineHeader, {}), null);
      insert(_el$, () => props2.children, null);
      insert(_el$, createComponent(TimelineHighlightedPeriod, {}), null);
      createRenderEffect((_p$) => {
        const _v$ = !!dragging(), _v$2 = !!timelineStore.itemsMoving, _v$3 = !!timelineStore.itemsResizing, _v$4 = !!timelineStore.creatingRelation, _v$5 = !!(keyboardState2.Control || keyboardState2.Shift);
        _v$ !== _p$._v$ && _el$.classList.toggle("dragging", _p$._v$ = _v$);
        _v$2 !== _p$._v$2 && _el$.classList.toggle("items-moving", _p$._v$2 = _v$2);
        _v$3 !== _p$._v$3 && _el$.classList.toggle("items-resizing", _p$._v$3 = _v$3);
        _v$4 !== _p$._v$4 && _el$.classList.toggle("creating-relation", _p$._v$4 = _v$4);
        _v$5 !== _p$._v$5 && _el$.classList.toggle("hold-key-modifier", _p$._v$5 = _v$5);
        return _p$;
      }, {
        _v$: void 0,
        _v$2: void 0,
        _v$3: void 0,
        _v$4: void 0,
        _v$5: void 0
      });
      return _el$;
    }
  });
};

// public/app/apps/cards/common/providers/AppOptionsProvider.tsx
var AppOptions = class extends BaseStore {
  name = prop(void 0);
  mode = prop(void 0);
  include_archived = prop(false);
  include_descendants = prop(false);
  showUngroupedCards = prop(true);
  filter = prop(null);
  sort_by = prop(void 0);
  group_by = prop([]);
  hideEmptyGroups = prop(false);
  displayAllItems = prop(false);
  strikeDoneCards = prop(true);
  get sortBy() {
    const sortBy3 = getSortBy({
      sort_by: this.sort_by
    });
    return sortBy3?.reverse ? `-${sortBy3.value}` : sortBy3?.value;
  }
  onInit() {
    this.initialData = unwrap(this.getState());
  }
  updateOptions(updates) {
    if (this.initialData?.name !== updates.name) {
      this.initialData = unwrap(updates);
    }
    const updateKeys = Object.keys(updates);
    const allKeys2 = Object.keys(this.getState());
    this.setState(produce((draft) => {
      allKeys2.forEach((key2) => {
        if (updateKeys.includes(key2)) {
          draft[key2] = updates[key2];
        } else if (this.initialData && key2 in this.initialData) {
          draft[key2] = this.initialData[key2];
        }
      });
    }));
  }
  toggleDisplayAllItems(force) {
    this.displayAllItems = force ?? !this.displayAllItems;
  }
};
var AppOptionsContext = createContext();
function useAppOptions() {
  return useContext(AppOptionsContext);
}
function AppOptionsProvider(props2) {
  return createComponent(AppOptionsContext.Provider, {
    get value() {
      return props2.store;
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/stores/providers/card.tsx
var CardStoreContext = createContext();
function useCardStore() {
  return useContext(CardStoreContext);
}
function CardStoreProvider(props2) {
  return createComponent(CardStoreContext.Provider, {
    get value() {
      return props2.store;
    },
    get children() {
      return props2.children;
    }
  });
}
var BoardContext = createContext();
function useBoard() {
  return useContext(BoardContext);
}
function BoardProvider(props2) {
  return createComponent(BoardContext.Provider, {
    get value() {
      return props2.board;
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/stores/providers/project.tsx
var ProjectContext = createContext();
function useProject() {
  return useContext(ProjectContext);
}
var ProjectProvider = (props2) => {
  const getProject = createMemo(() => {
    return props2.project ?? (props2.board ? projectStore.tryGetForCard(props2.board) : null);
  });
  return createComponent(ProjectContext.Provider, {
    value: getProject,
    get children() {
      return props2.children;
    }
  });
};

// public/app/apps/cards/common/providers/ScopedGroupTypeStoreProvider.tsx
var ScopedGroupTypeStoreContext = createContext();
function useScopedGroupTypeStore() {
  return useContext(ScopedGroupTypeStoreContext);
}
function ScopedGroupTypeStoreProvider(props2) {
  const project = useProject();
  const cardStore2 = useCardStore();
  const modelStore = createMemo(() => getScopedGroupTypeStore(project(), cardStore2));
  return createComponent(ScopedGroupTypeStoreContext.Provider, {
    value: modelStore,
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/providers/ScopedModelStoreProvider.tsx
var ScopedModelStoreContext = createContext();
function useScopedModelStore() {
  return useContext(ScopedModelStoreContext);
}
function ScopedModelStoreProvider(props2) {
  const project = useProject();
  const cardStore2 = useCardStore();
  const modelStore = createMemo(() => getScopedModelStore(project(), cardStore2));
  return createComponent(ScopedModelStoreContext.Provider, {
    value: modelStore,
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/providers/AvailableAttributesProvider.tsx
var AvailableAttributesContext = createContext();
function AvailableAttributesProvider(props2) {
  const scopedModelStore = useScopedModelStore();
  const _models = createMemo(() => {
    const modelStore = scopedModelStore();
    return untrack(() => modelStore.react({}, {}));
  });
  const models = createMemo(() => _models()());
  const attributes = createMemo(() => {
    const attrs2 = models().flatMap((m3) => m3.attributes);
    return attrs2;
  });
  const owner = getOwner();
  const cachedMemos = /* @__PURE__ */ new Map();
  function getMemo(key2, compute) {
    return untrack(() => {
      const hit = cachedMemos.get(key2);
      if (hit) return hit;
      const memo = runWithOwner(owner, () => createMemo(compute));
      cachedMemos.set(key2, memo);
      return memo;
    });
  }
  function trackAttributesByKey(key2, computeForKey) {
    return runWithOwner(owner, () => createMemo(() => {
      const k2 = key2();
      return getMemo(k2, () => computeForKey(k2))();
    }));
  }
  return createComponent(AvailableAttributesContext.Provider, {
    value: {
      attributes,
      owner,
      cachedMemos,
      trackAttributesByKey
    },
    get children() {
      return props2.children;
    }
  });
}
function useAvailableAttributes() {
  return useContext(AvailableAttributesContext);
}
function useAvailableAttributesOfType(type, typeHint, withComputed) {
  const _type = () => typeof type === "function" ? type() : type;
  const _typeHint = () => typeof typeHint === "function" ? typeHint() : typeHint;
  const _withComputed = () => typeof withComputed === "function" ? withComputed() : withComputed;
  const _key = () => {
    const __type = _type();
    const types2 = Array.isArray(__type) ? __type : [__type];
    const hint = _typeHint();
    const computed = _withComputed();
    let k2 = types2.join(",");
    if (hint) k2 += `-${hint}`;
    if (computed) k2 += `-${computed}`;
    return k2;
  };
  return useAvailableAttrs(() => {
    const type2 = _type();
    const typeHint2 = _typeHint() || "date";
    const withComputed2 = _withComputed() ?? true;
    const specialFields = [];
    const stripAttrsHiddenByDefault2 = false;
    const attrFilters = withComputed2 ? (modelAttr) => {
      return (Array.isArray(type2) ? type2.includes(modelAttr.type) : modelAttr.type === type2) || modelAttr.is_computed && // TODO: once lookup will get a correct type_hint, remove this
      (modelAttr.type === "lookup" || modelAttr.type === "formula" && modelAttr.options?.type_hint === typeHint2);
    } : Array.isArray(type2) ? query_exports.any(type2) : {
      type: type2
    };
    return {
      specialFields,
      stripAttrsHiddenByDefault: stripAttrsHiddenByDefault2,
      withGroupType: false,
      attrFilters,
      __key: _key()
    };
  });
}
function useAvailableAttrs(options2) {
  const scopedGroupTypeStore = useScopedGroupTypeStore();
  const context = useAvailableAttributes();
  const opt = () => {
    const {
      specialFields = [],
      stripAttrsHiddenByDefault: _stripAttrsHiddenByDefault = false,
      withGroupType = true,
      attrFilters,
      __key
    } = options2 && (typeof options2 === "function" ? options2() : options2) || {};
    return {
      specialFields,
      stripAttrsHiddenByDefault: _stripAttrsHiddenByDefault,
      withGroupType,
      attrFilters,
      __key
    };
  };
  const attrs2 = () => {
    const attributes = context.attributes();
    const {
      attrFilters
    } = opt();
    const out = [];
    for (const attr of attributes) {
      if (!attrFilters || query_exports.matchObject(attr, attrFilters)) {
        out.push(attr);
      }
    }
    return out;
  };
  const modelAttrs = () => {
    return attrs2().filter((attr) => !attributeTypeRegistry.get(attr.type)?.decorative).sort((a3, b3) => localeSort(a3.name, b3.name, getCurrentLocale()));
  };
  const groupTypeAttrs = () => {
    const groupTypeStore = scopedGroupTypeStore();
    const {
      withGroupType
    } = opt();
    return withGroupType ? groupTypeStore.asAttributes().sort((a3, b3) => localeSort(a3.name, b3.name, getCurrentLocale())) : [];
  };
  const compute = () => {
    const {
      specialFields,
      stripAttrsHiddenByDefault: _stripAttrsHiddenByDefault
    } = opt();
    const attrs3 = modelAttrs();
    const gAttrs = groupTypeAttrs();
    const availableAttrs = /* @__PURE__ */ new Map();
    for (const attrName of specialFields) {
      const attr = {
        type: attrName,
        id: attrName,
        name: attrName,
        label: specialFieldLabels.get(attrName),
        container: "",
        is_dynamic: true
      };
      addToAvailableAttrs(availableAttrs, attr);
    }
    for (const attr of gAttrs) {
      addToAvailableAttrs(availableAttrs, attr);
    }
    for (const attr of attrs3) {
      addToAvailableAttrs(availableAttrs, attr);
    }
    const results2 = _stripAttrsHiddenByDefault ? stripAttrsHiddenByDefault(availableAttrs) : availableAttrs;
    return results2;
  };
  return context.trackAttributesByKey(() => opt().__key, compute);
}

// public/app/stores/utils/card.ts
function defaultCardCompareFunc(a3, b3, reverse = false) {
  return compare2(a3?.title, b3?.title, false, reverse) || compare2(a3?.created_at, b3?.created_at, false, reverse) || 0;
}
function getCardCompareFunc(sortBy3, opts) {
  opts = opts || {};
  let reverse = sortBy3?.reverse || false;
  let prop2 = sortBy3?.value;
  if (["ref", "nb_children", "title", "created_at", "-updated_at"].includes(prop2)) {
    if (prop2.charAt(0) === "-") {
      reverse = true;
      prop2 = prop2.substr(1);
    }
    return function(a3, b3) {
      return compare2(a3[prop2], b3[prop2], false, reverse) || defaultCardCompareFunc(a3, b3, reverse);
    };
  }
  if (prop2 === "state") {
    const states = opts.states || cardStateStore.getBuiltinStates().map((s3) => s3.id);
    return function(a3, b3) {
      return compare2(states.indexOf(a3.state), states.indexOf(b3.state), false, reverse) || defaultCardCompareFunc(a3, b3, reverse);
    };
  }
  let attrGroup;
  if (opts.attrGroup) {
    attrGroup = opts.attrGroup;
  } else if (opts.modelStore) {
    const attrs2 = opts.modelStore.getSortableAttributes();
    if (opts.groupTypeStore) {
      attrs2.push(...opts.groupTypeStore.asAttributes());
    }
    attrGroup = new AttributeGroup(attrs2);
  } else {
    const attrs2 = cardModelStore.getSortableAttributes();
    attrs2.push(...cardGroupTypeStore.asAttributes());
    attrGroup = new AttributeGroup(attrs2);
  }
  const attr = attrGroup.get(prop2);
  if (attr) {
    return attrGroup.makeComparisonFunc(attr, reverse);
  }
  return (a3, b3) => defaultCardCompareFunc(a3, b3, reverse);
}
function sortCardQuery(queryResults, sortBy3, ungroupedPosition, options2) {
  if (sortBy3) {
    return queryResults.sort(getCardCompareFunc(sortBy3, options2));
  }
  if (ungroupedPosition) {
    return sortBy2(queryResults, "position", true, defaultCardCompareFunc);
  }
  return sortBy2(
    queryResults,
    "meta:position",
    true,
    defaultCardCompareFunc
  );
}
function cardHasAttrValue(card, value2, attrId) {
  return card.attributes.some((cardAttr) => {
    if (cardAttr.id !== attrId) return false;
    let attrType = attributeTypeRegistry.get(cardAttr.type);
    if (attrType && isFunction_default(attrType.equals)) {
      return attrType.equals(cardAttr, value2);
    }
    if (Array.isArray(cardAttr.value)) {
      return cardAttr.value.some(
        (attrValue) => equals(attrValue, value2) || attrValue.id === value2
      );
    }
    return cardAttr.value === value2;
  });
}
function cardHasGroupFromGroupType(card, groupType) {
  return card.groups.some((cardGroup) => groupType.id === cardGroup.type_id);
}

// public/app/apps/cards/common/providers/CardCompareFunctionProvider.tsx
var CardCompareFunctionContext = createContext();
function useCardCompareFunction() {
  return useContext(CardCompareFunctionContext);
}
function CardCompareFunctionProvider(props2) {
  const project = useProject();
  const options2 = useAppOptions();
  const compareFunction = createMemo(() => {
    const _project = project();
    const modelStore = getScopedModelStore(_project, cardStore);
    const groupTypeStore = getScopedGroupTypeStore(_project, cardStore);
    return getCardCompareFunc(options2.sort_by, {
      modelStore,
      groupTypeStore
    });
  });
  return createComponent(CardCompareFunctionContext.Provider, {
    value: compareFunction,
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/providers/ViewsProvider.tsx
var ViewsContext = createContext(void 0);
function useViews() {
  return useContext(ViewsContext);
}
function ViewsProvider(props2) {
  const project = useProject();
  const _views = createMemo(() => {
    const store2 = viewStore.scopedByProject(project());
    return untrack(() => store2.react({}, {}));
  });
  const views = createMemo(() => _views()());
  return createComponent(ViewsContext.Provider, {
    value: views,
    get children() {
      return props2.children;
    }
  });
}

// public/app/ui/base/Stepper.tsx
var _tmpl$47 = /* @__PURE__ */ template(`<div class="stepper"></div>`, 2);
var _tmpl$216 = /* @__PURE__ */ template(`<div class="stepper-step"></div>`, 2);
var stepperContext = createContext();
var StepperState = class extends BaseStore {
  current = prop(0);
  steps = prop([]);
  canNext() {
    return this.current < this.steps.length - 1;
  }
  canPrevious() {
    return this.current > 0;
  }
  next() {
    this.current = Math.min(this.current + 1, this.steps.length - 1);
  }
  previous() {
    this.current = Math.max(this.current - 1, 0);
  }
  goTo(index2) {
    this.current = index2;
  }
  registerStep(step2) {
    if (this.steps.length === 0) {
      this.steps = [step2];
    } else {
      const prevIndex = this.steps.findIndex((s3) => s3.ref.nextElementSibling === step2.ref);
      const tmp = [...this.steps];
      tmp.splice(prevIndex + 1, 0, step2);
      this.steps = tmp;
    }
  }
  unregisterStep(step2) {
    this.steps = this.steps.filter((s3) => s3.ref !== step2.ref);
    this.current = Math.max(0, this.current - 1);
  }
  getCurrentStep() {
    return this.steps[this.current];
  }
  findIndexByRef(ref) {
    return this.steps.findIndex((s3) => s3.ref === ref);
  }
};
function useStepper() {
  return useContext(stepperContext);
}
function Stepper(props2) {
  const state = props2.state || StepperState.create();
  let timeoutRef;
  createEffect((previous) => {
    const currentStep = state.getCurrentStep();
    let behavior = "instant";
    if (previous) {
      behavior = previous[0] !== void 0 ? "smooth" : "instant";
      if (previous[0] === currentStep && previous[1]?.length !== state.steps.length) {
        behavior = "instant";
      }
    }
    if (timeoutRef) {
      clearTimeout(timeoutRef);
    }
    timeoutRef = setTimeout(() => {
      state.steps.filter((s3) => s3 !== currentStep).forEach((s3) => {
        s3.ref.setAttribute("inert", "");
      });
      currentStep?.ref.removeAttribute("inert");
      currentStep?.ref.scrollIntoView({
        behavior
      });
    });
    return [currentStep, [...state.steps]];
  });
  return createComponent(stepperContext.Provider, {
    value: state,
    get children() {
      return createComponent(Show, {
        get when() {
          return props2.asChild === true;
        },
        get fallback() {
          return (() => {
            const _el$ = _tmpl$47.cloneNode(true);
            insert(_el$, () => props2.children);
            return _el$;
          })();
        },
        get children() {
          return props2.children({
            class: "stepper"
          });
        }
      });
    }
  });
}
function registerStep(element2) {
  const state = useStepper();
  onMount(() => {
    const ref = element2();
    if (ref) {
      state?.registerStep({
        ref
      });
    }
  });
  onCleanup(() => {
    const ref = element2();
    if (ref) {
      state?.unregisterStep({
        ref
      });
    }
  });
}
function Step(props2) {
  let _ref;
  const setRef = (ref) => {
    _ref = ref;
  };
  registerStep(() => _ref);
  return createComponent(Show, {
    get when() {
      return props2.asChild === true;
    },
    get fallback() {
      return (() => {
        const _el$2 = _tmpl$216.cloneNode(true);
        use(setRef, _el$2);
        insert(_el$2, () => props2.children);
        return _el$2;
      })();
    },
    get children() {
      return props2.children({
        class: "stepper-step"
      }, setRef);
    }
  });
}

// public/app/apps/cards/common/models.ts
function useModels() {
  const project = useProject();
  const models = cardModelStore.scopedByEnabled(project, true, true).react({}, {});
  return models;
}
function useDefaultModel() {
  const project = useProject();
  return createMemo(() => cardModelStore.tryGetProjectModel(project()));
}
function useModelApi() {
  const project = useProject();
  return {
    createAttribute: (model, attribute2, position) => {
      return createAttribute(project(), model, attribute2, position);
    }
  };
}

// public/app/ui/base/form/BaseForm.tsx
var _tmpl$48 = /* @__PURE__ */ template(`<form novalidate></form>`, 2);
var FormFieldMarker = Symbol("__kantree_form_field");
var FormFieldArrayMarker = Symbol("__kantree_form_field_array");
var FieldValidateMarker = Symbol("__kantree_field_validate");
var FieldValidateOnMarker = Symbol("__kantree_field_validate_on");
function isFormFieldState(field2) {
  return typeof field2 === "object" && !!field2 && field2[FormFieldMarker] === true;
}
function isFormFieldArrayState(field2) {
  return typeof field2 === "object" && !!field2 && field2[FormFieldArrayMarker] === true;
}
function isNestedFormFieldState(field2) {
  return typeof field2 === "object" && !!field2 && !field2[FormFieldMarker] && !field2[FormFieldArrayMarker];
}
var touchedFieldStateProp = Symbol("baseform:touched");
var dirtyFieldStateProp = Symbol("baseform:dirty");
var errorFieldStateProp = Symbol("baseform:error");
var FieldStatePropSymbols = {
  touched: touchedFieldStateProp,
  dirty: dirtyFieldStateProp,
  error: errorFieldStateProp
};
function field(options2) {
  return {
    [FormFieldMarker]: true,
    [FieldValidateMarker]: options2?.validate,
    [FieldValidateOnMarker]: options2?.validateOn ?? "change",
    value: void 0
  };
}
function nestedField(config3) {
  return config3;
}
function fields(config3) {
  return {
    ...config3,
    [FormFieldArrayMarker]: true
  };
}
var formContext = createContext();
function useForm() {
  return useContext(formContext);
}
var fieldContext = createContext();
function useField() {
  const contextValue = useContext(fieldContext);
  if (!contextValue) throw new Error("useField must be used inside a child of a Field provider (or a component that wraps it)");
  return contextValue;
}
var BaseForm = class {
  static create(initialValue) {
    const instance = new this();
    return instance.init(initialValue);
  }
  init(initialValue) {
    this.setupForm(initialValue);
    return this;
  }
  setupForm(initialValue) {
    [this.state, this.setState] = createStore(this.userValueToStateValue(initialValue));
  }
  userValueToStateValue(userValue, stateProps) {
    const state = {};
    for (const [key2, value2] of Object.entries(userValue)) {
      if (Array.isArray(value2)) {
        if (state[key2] === void 0) {
          state[key2] = [];
          state[key2][FormFieldArrayMarker] = true;
          state[key2][FieldStatePropSymbols.touched] = stateProps?.touched ?? false;
          state[key2][FieldStatePropSymbols.dirty] = stateProps?.dirty ?? false;
        }
        for (const val of value2) {
          state[key2].push(this.userValueToStateValue(val));
        }
      } else if (typeof value2 === "object" && value2 !== null) {
        state[key2] = {
          ...this.userValueToStateValue(value2),
          [FieldStatePropSymbols.touched]: stateProps?.touched ?? false,
          [FieldStatePropSymbols.dirty]: stateProps?.dirty ?? false
        };
      } else {
        state[key2] = {
          [FormFieldMarker]: true,
          value: value2,
          [FieldStatePropSymbols.dirty]: stateProps?.dirty ?? false,
          [FieldStatePropSymbols.touched]: stateProps?.touched ?? false,
          [FieldStatePropSymbols.error]: stateProps?.error ?? null
        };
      }
    }
    return state;
  }
  _stateToValues(state) {
    if (isFormFieldState(state)) return state.value;
    const [isArray3, isNested] = [isFormFieldArrayState(state), isNestedFormFieldState(state)];
    const values2 = isArray3 ? [] : {};
    if (isArray3 || isNested) {
      for (const [key2, value2] of Object.entries(state)) {
        values2[key2] = this._stateToValues(value2);
      }
    }
    return values2;
  }
  get values() {
    return this._stateToValues(this.state);
  }
  get errors() {
    let errors3 = {};
    this.walk(this.state, (field2, p4) => {
      const error2 = field2[FieldStatePropSymbols.error];
      if (error2) errors3[p4] = JSON.parse(JSON.stringify(error2));
    });
    return errors3;
  }
  get Form() {
    const _self$ = this;
    return (props2) => createComponent(formContext.Provider, {
      value: _self$,
      get children() {
        return createComponent(Form, props2);
      }
    });
  }
  _walk(node, cb2, path = "") {
    const [isFieldState, isArrayState, isNestedState] = [isFormFieldState(node), isFormFieldArrayState(node), isNestedFormFieldState(node)];
    if (isFieldState || isArrayState || isNestedState) cb2(node, path);
    if (isArrayState || isNestedState) {
      for (const [key2, value2] of Object.entries(node)) {
        const _path = `${path !== "" ? `${path}.` : ""}${key2}`;
        this._walk(value2, cb2, _path);
      }
    }
  }
  walk(state, cb2, path = "") {
    this._walk(state, cb2, path);
  }
  get touched() {
    let touched = false;
    this.walk(this.state, (field2) => {
      const _touched = field2[FieldStatePropSymbols.touched];
      if (_touched && !touched) touched = true;
    });
    return touched;
  }
  get dirty() {
    let dirty = false;
    this.walk(this.state, (field2) => {
      const _dirty = field2[FieldStatePropSymbols.dirty];
      if (_dirty && !dirty) dirty = true;
    });
    return dirty;
  }
  createFieldProvider(dynamicPath) {
    return (props2) => {
      const valuePath = createMemo(() => {
        if (!dynamicPath.includes("[number]")) return dynamicPath;
        const nbs = [...props2.indexes];
        return dynamicPath.replace(/\[number\]/g, () => `.${nbs.shift()}`);
      });
      const fieldPath = createMemo(() => {
        return dynamicPath.replace(/\[number\]/g, "");
      });
      const state = () => this.get(valuePath());
      const config3 = () => this.getField(fieldPath());
      return createComponent(fieldContext.Provider, {
        value: {
          get valuePath() {
            return valuePath();
          },
          get state() {
            return state();
          },
          get config() {
            return config3();
          }
        },
        get children() {
          return props2.children;
        }
      });
    };
  }
  updateField(path, value2, options2) {
    this.setState(produce((draft) => {
      const field2 = this.get(path, draft);
      if (field2) {
        field2.value = value2;
        field2[FieldStatePropSymbols.touched] = options2?.touched ?? true;
        field2[FieldStatePropSymbols.dirty] = options2?.dirty ?? true;
        field2[FieldStatePropSymbols.error] = options2?.error ?? null;
      }
    }));
  }
  clearField(path, options2) {
    this.setState(produce((draft) => {
      const field2 = this.get(path, draft);
      if (!isFormFieldArrayState(field2)) {
        throw new Error(`Field "${path}" is not an array`);
      }
      field2.length = 0;
      field2[FieldStatePropSymbols.touched] = options2?.touched ?? true;
      field2[FieldStatePropSymbols.dirty] = options2?.dirty ?? true;
      field2[FieldStatePropSymbols.error] = options2?.error ?? null;
    }));
  }
  insertField(path, valueToAdd, options2) {
    this.setState(produce((draft) => {
      const field2 = this.get(path, draft);
      if (!isFormFieldArrayState(field2)) {
        throw new Error(`Field "${path}" is not an array`);
      }
      field2.push(this.userValueToStateValue(valueToAdd, options2));
      field2[FieldStatePropSymbols.touched] = options2?.touched ?? true;
      field2[FieldStatePropSymbols.dirty] = options2?.dirty ?? true;
      field2[FieldStatePropSymbols.error] = options2?.error ?? null;
    }));
  }
  removeField(path) {
    this.setState(produce((draft) => {
      const lastIndex = Number(path.split(".").pop());
      const parentPath = path.split(".").slice(0, -1).join(".");
      const parentKey = path.split(".").slice(-2, -1)[0];
      const grandParentPath = parentPath.split(".").slice(0, -1).join(".");
      const gpField = this.get(grandParentPath, draft) ?? draft;
      if (!isFormFieldArrayState(gpField[parentKey])) {
        throw new Error(`MetaField "${path}" is not an array`);
      }
      gpField[parentKey] = gpField[parentKey].filter((_5, i3) => i3 !== lastIndex);
      gpField[parentKey][FormFieldArrayMarker] = true;
      gpField[parentKey][FieldStatePropSymbols.touched] = true;
      gpField[parentKey][FieldStatePropSymbols.dirty] = true;
    }));
  }
  get(path, src) {
    return path.split(".").reduce((acc, key2) => {
      if (acc === void 0) {
        return void 0;
      }
      return acc[key2];
    }, src ?? this.state);
  }
  has(path, src) {
    return !!this.get(path, src);
  }
  getField(path) {
    return path.split(".").reduce((acc, key2) => {
      if (acc === void 0) {
        return void 0;
      }
      return acc[key2];
    }, this);
  }
  isTouched(path) {
    const field2 = this.get(path);
    if (field2) {
      if (isFormFieldState(field2)) {
        return field2[FieldStatePropSymbols.touched];
      } else if (isFormFieldArrayState(field2)) {
        return field2[FieldStatePropSymbols.touched] || field2.some((_5, i3) => this.isTouched(`${path}.${i3}`));
      } else {
        let touched = false;
        this.walk(field2, (f3) => {
          const _touched = f3[FieldStatePropSymbols.touched];
          if (_touched) touched = true;
        });
        return touched;
      }
    }
    console.error(`Field "${path}" does not exist`);
    return false;
  }
  isDirty(path) {
    const field2 = this.get(path);
    if (field2) {
      if (isFormFieldState(field2)) {
        return field2[FieldStatePropSymbols.dirty];
      } else if (isFormFieldArrayState(field2)) {
        return field2[FieldStatePropSymbols.dirty] || field2.some((_5, i3) => this.isDirty(`${path}.${i3}`));
      } else {
        let dirty = false;
        this.walk(field2, (f3) => {
          const _dirty = f3[FieldStatePropSymbols.dirty];
          if (_dirty) dirty = true;
        });
        return dirty;
      }
    }
    console.error(`Field "${path}" does not exist`);
    return false;
  }
  markAs(path, props2) {
    const updateProps = (field2) => {
      field2[FieldStatePropSymbols.touched] = props2.touched ?? true;
      field2[FieldStatePropSymbols.dirty] = props2.dirty ?? true;
      if (props2.error !== void 0) field2[FieldStatePropSymbols.error] = props2.error;
    };
    const updateField = (field2) => {
      const [isFState, isFAState, isNState] = [isFormFieldState(field2), isFormFieldArrayState(field2), isNestedFormFieldState(field2)];
      if (isFState || isFAState || isNState) updateProps(field2);
      if (isFAState || isNState) this.walk(field2, (f3) => updateProps(f3));
    };
    this.setState(produce((draft) => {
      const field2 = this.get(path, draft);
      if (field2) {
        updateField(field2);
      }
    }));
  }
  hasErrors() {
    let hasError = false;
    this.walk(this.state, (field2) => {
      const error2 = field2[FieldStatePropSymbols.error];
      if (error2) hasError = true;
    });
    return hasError;
  }
};
function Form(props2) {
  const [local, rest2] = splitProps(props2, ["onSubmit"]);
  const onSubmit = (e3) => {
    e3.preventDefault();
    local.onSubmit?.();
  };
  return (() => {
    const _el$ = _tmpl$48.cloneNode(true);
    _el$.addEventListener("submit", onSubmit);
    spread(_el$, rest2, false, false);
    return _el$;
  })();
}

// node_modules/@modular-forms/solid/dist/esm/index.js
function createSignal2(value2) {
  const [get7, set4] = createSignal(value2);
  return {
    get: get7,
    set: set4
  };
}
function createFormStore({
  initialValues = {},
  validateOn = "submit",
  revalidateOn = "input",
  validate: validate3
} = {}) {
  const fieldNames = createSignal2([]);
  const fieldArrayNames = createSignal2([]);
  const element2 = createSignal2();
  const submitCount = createSignal2(0);
  const submitting = createSignal2(false);
  const submitted = createSignal2(false);
  const validating = createSignal2(false);
  const touched = createSignal2(false);
  const dirty = createSignal2(false);
  const invalid2 = createSignal2(false);
  const response = createSignal2({});
  return {
    internal: {
      // Props
      initialValues,
      validate: validate3,
      validateOn,
      revalidateOn,
      // Signals
      fieldNames,
      fieldArrayNames,
      element: element2,
      submitCount,
      submitting,
      submitted,
      validating,
      touched,
      dirty,
      invalid: invalid2,
      response,
      // Stores
      fields: {},
      fieldArrays: {},
      // Other
      validators: /* @__PURE__ */ new Set()
    },
    get element() {
      return element2.get();
    },
    get submitCount() {
      return submitCount.get();
    },
    get submitting() {
      return submitting.get();
    },
    get submitted() {
      return submitted.get();
    },
    get validating() {
      return validating.get();
    },
    get touched() {
      return touched.get();
    },
    get dirty() {
      return dirty.get();
    },
    get invalid() {
      return invalid2.get();
    },
    get response() {
      return response.get();
    }
  };
}
function createForm(options2) {
  const form = createFormStore(options2);
  return [form, {
    Form: (props2) => Form2(mergeProps({
      of: form
    }, props2)),
    Field: (props2) => Field(
      // eslint-disable-next-line solid/reactivity
      mergeProps({
        of: form
      }, props2)
    ),
    FieldArray: (props2) => FieldArray(mergeProps({
      of: form
    }, props2))
  }];
}
function getElementInput(element2, field2, type) {
  const {
    checked,
    files,
    options: options2,
    value: value2,
    valueAsDate,
    valueAsNumber
  } = element2;
  return untrack(() => !type || type === "string" ? value2 : type === "string[]" ? options2 ? [...options2].filter((e3) => e3.selected && !e3.disabled).map((e3) => e3.value) : checked ? [...field2.value.get() || [], value2] : (field2.value.get() || []).filter((v3) => v3 !== value2) : type === "number" ? valueAsNumber : type === "boolean" ? checked : type === "File" && files ? files[0] : type === "File[]" && files ? [...files] : type === "Date" && valueAsDate ? valueAsDate : field2.value.get());
}
function getFieldAndArrayStores(form) {
  return [...Object.values(form.internal.fields), ...Object.values(form.internal.fieldArrays)];
}
function getFieldArrayStore(form, name2) {
  return form.internal.fieldArrays[name2];
}
function getPathIndex(name2, path) {
  return +path.replace(`${name2}.`, "").split(".")[0];
}
function removeInvalidNames(form, names) {
  getFieldArrayNames(form, false).forEach((fieldArrayName) => {
    const lastIndex = untrack(getFieldArrayStore(form, fieldArrayName).items.get).length - 1;
    names.filter((name2) => name2.startsWith(`${fieldArrayName}.`) && getPathIndex(fieldArrayName, name2) > lastIndex).forEach((name2) => {
      names.splice(names.indexOf(name2), 1);
    });
  });
}
function getFieldArrayNames(form, shouldValid = true) {
  const fieldArrayNames = [...untrack(form.internal.fieldArrayNames.get)];
  if (shouldValid) {
    removeInvalidNames(form, fieldArrayNames);
  }
  return fieldArrayNames;
}
function getFieldNames(form, shouldValid = true) {
  const fieldNames = [...untrack(form.internal.fieldNames.get)];
  if (shouldValid) {
    removeInvalidNames(form, fieldNames);
  }
  return fieldNames;
}
function getFieldStore(form, name2) {
  return form.internal.fields[name2];
}
function getFilteredNames(form, arg2, shouldValid) {
  return untrack(() => {
    const allFieldNames = getFieldNames(form, shouldValid);
    const allFieldArrayNames = getFieldArrayNames(form, shouldValid);
    if (typeof arg2 === "string" || Array.isArray(arg2)) {
      return (typeof arg2 === "string" ? [arg2] : arg2).reduce((tuple, name2) => {
        const [fieldNames, fieldArrayNames] = tuple;
        if (allFieldArrayNames.includes(name2)) {
          allFieldArrayNames.forEach((fieldArrayName) => {
            if (fieldArrayName.startsWith(name2)) {
              fieldArrayNames.add(fieldArrayName);
            }
          });
          allFieldNames.forEach((fieldName) => {
            if (fieldName.startsWith(name2)) {
              fieldNames.add(fieldName);
            }
          });
        } else {
          fieldNames.add(name2);
        }
        return tuple;
      }, [/* @__PURE__ */ new Set(), /* @__PURE__ */ new Set()]).map((set4) => [...set4]);
    }
    return [allFieldNames, allFieldArrayNames];
  });
}
function getOptions4(arg1, arg2) {
  return (typeof arg1 !== "string" && !Array.isArray(arg1) ? arg1 : arg2) || {};
}
function getPathValue(path, object2) {
  return path.split(".").reduce((value2, key2) => value2?.[key2], object2);
}
var counter2 = 0;
function getUniqueId() {
  return counter2++;
}
function isFieldDirty(startValue, currentValue) {
  const toValue = (item) => item instanceof Blob ? item.size : item;
  return Array.isArray(startValue) && Array.isArray(currentValue) ? startValue.map(toValue).join() !== currentValue.map(toValue).join() : startValue instanceof Date && currentValue instanceof Date ? startValue.getTime() !== currentValue.getTime() : Number.isNaN(startValue) && Number.isNaN(currentValue) ? false : startValue !== currentValue;
}
function updateFormDirty(form, dirty) {
  untrack(() => form.internal.dirty.set(dirty || getFieldAndArrayStores(form).some((fieldOrFieldArray) => fieldOrFieldArray.active.get() && fieldOrFieldArray.dirty.get())));
}
function updateFieldDirty(form, field2) {
  untrack(() => {
    const dirty = isFieldDirty(field2.startValue.get(), field2.value.get());
    if (dirty !== field2.dirty.get()) {
      batch(() => {
        field2.dirty.set(dirty);
        updateFormDirty(form, dirty);
      });
    }
  });
}
function validateIfRequired(form, fieldOrFieldArray, name2, {
  on: modes,
  shouldFocus = false
}) {
  untrack(() => {
    if (modes.includes((form.internal.validateOn === "submit" ? form.internal.submitted.get() : fieldOrFieldArray.error.get()) ? form.internal.revalidateOn : form.internal.validateOn)) {
      validate(form, name2, {
        shouldFocus
      });
    }
  });
}
function handleFieldEvent(form, field2, name2, event2, validationModes, inputValue) {
  batch(() => {
    field2.value.set((prevValue) => field2.transform.reduce((current, transformation) => transformation(current, event2), inputValue ?? prevValue));
    field2.touched.set(true);
    form.internal.touched.set(true);
    updateFieldDirty(form, field2);
    validateIfRequired(form, field2, name2, {
      on: validationModes
    });
  });
}
function initializeFieldArrayStore(form, name2) {
  if (!getFieldArrayStore(form, name2)) {
    const initial2 = getPathValue(name2, form.internal.initialValues)?.map(() => getUniqueId()) || [];
    const initialItems = createSignal2(initial2);
    const startItems = createSignal2(initial2);
    const items = createSignal2(initial2);
    const error2 = createSignal2("");
    const active = createSignal2(false);
    const touched = createSignal2(false);
    const dirty = createSignal2(false);
    form.internal.fieldArrays[name2] = {
      // Signals
      initialItems,
      startItems,
      items,
      error: error2,
      active,
      touched,
      dirty,
      // Other
      validate: [],
      consumers: /* @__PURE__ */ new Set()
    };
    form.internal.fieldArrayNames.set((names) => [...names, name2]);
  }
  return getFieldArrayStore(form, name2);
}
function initializeFieldStore(form, name2) {
  if (!getFieldStore(form, name2)) {
    const initial2 = getPathValue(name2, form.internal.initialValues);
    const elements = createSignal2([]);
    const initialValue = createSignal2(initial2);
    const startValue = createSignal2(initial2);
    const value2 = createSignal2(initial2);
    const error2 = createSignal2("");
    const active = createSignal2(false);
    const touched = createSignal2(false);
    const dirty = createSignal2(false);
    form.internal.fields[name2] = {
      // Signals
      elements,
      initialValue,
      startValue,
      value: value2,
      error: error2,
      active,
      touched,
      dirty,
      // Other
      validate: [],
      transform: [],
      consumers: /* @__PURE__ */ new Set()
    };
    form.internal.fieldNames.set((names) => [...names, name2]);
  }
  return getFieldStore(form, name2);
}
function setErrorResponse(form, formErrors, {
  shouldActive = true
}) {
  const message = Object.entries(formErrors).reduce((errors3, [name2, error2]) => {
    if ([getFieldStore(form, name2), getFieldArrayStore(form, name2)].every((fieldOrFieldArray) => !fieldOrFieldArray || shouldActive && !untrack(fieldOrFieldArray.active.get))) {
      errors3.push(error2);
    }
    return errors3;
  }, []).join(" ");
  if (message) {
    form.internal.response.set({
      status: "error",
      message
    });
  }
}
function updateFormInvalid(form, invalid2) {
  untrack(() => {
    form.internal.invalid.set(invalid2 || getFieldAndArrayStores(form).some((fieldOrFieldArray) => fieldOrFieldArray.active.get() && fieldOrFieldArray.error.get()));
  });
}
function updateFormState(form) {
  let touched = false, dirty = false, invalid2 = false;
  untrack(() => {
    for (const fieldOrFieldArray of getFieldAndArrayStores(form)) {
      if (fieldOrFieldArray.active.get()) {
        if (fieldOrFieldArray.touched.get()) {
          touched = true;
        }
        if (fieldOrFieldArray.dirty.get()) {
          dirty = true;
        }
        if (fieldOrFieldArray.error.get()) {
          invalid2 = true;
        }
      }
      if (touched && dirty && invalid2) {
        break;
      }
    }
  });
  batch(() => {
    form.internal.touched.set(touched);
    form.internal.dirty.set(dirty);
    form.internal.invalid.set(invalid2);
  });
}
function focus(form, name2) {
  untrack(() => getFieldStore(form, name2)?.elements.get()[0]?.focus());
}
function setError(form, name2, error2, {
  shouldActive = true,
  shouldTouched = false,
  shouldDirty = false,
  shouldFocus = !!error2
} = {}) {
  batch(() => {
    untrack(() => {
      for (const fieldOrFieldArray of [getFieldStore(form, name2), getFieldArrayStore(form, name2)]) {
        if (fieldOrFieldArray && (!shouldActive || fieldOrFieldArray.active.get()) && (!shouldTouched || fieldOrFieldArray.touched.get()) && (!shouldDirty || fieldOrFieldArray.dirty.get())) {
          fieldOrFieldArray.error.set(error2);
          if (error2 && "value" in fieldOrFieldArray && shouldFocus) {
            focus(form, name2);
          }
        }
      }
    });
    updateFormInvalid(form, !!error2);
  });
}
function getValue(form, name2, {
  shouldActive = true,
  shouldTouched = false,
  shouldDirty = false,
  shouldValid = false
} = {}) {
  const field2 = initializeFieldStore(form, name2);
  if ((!shouldActive || field2.active.get()) && (!shouldTouched || field2.touched.get()) && (!shouldDirty || field2.dirty.get()) && (!shouldValid || !field2.error.get())) {
    return field2.value.get();
  }
  return void 0;
}
function getValues(form, arg2, arg3) {
  const [fieldNames, fieldArrayNames] = getFilteredNames(form, arg2);
  const {
    shouldActive = true,
    shouldTouched = false,
    shouldDirty = false,
    shouldValid = false
  } = getOptions4(arg2, arg3);
  if (typeof arg2 !== "string" && !Array.isArray(arg2)) {
    form.internal.fieldNames.get();
  } else {
    fieldArrayNames.forEach((fieldArrayName) => getFieldArrayStore(form, fieldArrayName).items.get());
  }
  return fieldNames.reduce((values2, name2) => {
    const field2 = getFieldStore(form, name2);
    if ((!shouldActive || field2.active.get()) && (!shouldTouched || field2.touched.get()) && (!shouldDirty || field2.dirty.get()) && (!shouldValid || !field2.error.get())) {
      (typeof arg2 === "string" ? name2.replace(`${arg2}.`, "") : name2).split(".").reduce((object2, key2, index2, keys5) => object2[key2] = index2 === keys5.length - 1 ? (
        // If it is last key, add value
        field2.value.get()
      ) : (
        // Otherwise return object or array
        typeof object2[key2] === "object" && object2[key2] || (isNaN(+keys5[index2 + 1]) ? {} : [])
      ), values2);
    }
    return values2;
  }, typeof arg2 === "string" ? [] : {});
}
function reset2(form, arg2, arg3) {
  const [fieldNames, fieldArrayNames] = getFilteredNames(form, arg2, false);
  const resetSingleField = typeof arg2 === "string" && fieldNames.length === 1;
  const resetEntireForm = !resetSingleField && !Array.isArray(arg2);
  const options2 = getOptions4(arg2, arg3);
  const {
    initialValue,
    initialValues,
    keepResponse = false,
    keepSubmitCount = false,
    keepSubmitted = false,
    keepValues = false,
    keepDirtyValues = false,
    keepItems = false,
    keepDirtyItems = false,
    keepErrors = false,
    keepTouched = false,
    keepDirty = false
  } = options2;
  batch(() => untrack(() => {
    fieldNames.forEach((name2) => {
      const field2 = getFieldStore(form, name2);
      if (resetSingleField ? "initialValue" in options2 : initialValues) {
        field2.initialValue.set(() => resetSingleField ? initialValue : getPathValue(name2, initialValues));
      }
      const keepDirtyValue = keepDirtyValues && field2.dirty.get();
      if (!keepValues && !keepDirtyValue) {
        field2.startValue.set(field2.initialValue.get);
        field2.value.set(field2.initialValue.get);
        field2.elements.get().forEach((element2) => {
          if (element2.type === "file") {
            element2.value = "";
          }
        });
      }
      if (!keepTouched) {
        field2.touched.set(false);
      }
      if (!keepDirty && !keepValues && !keepDirtyValue) {
        field2.dirty.set(false);
      }
      if (!keepErrors) {
        field2.error.set("");
      }
    });
    fieldArrayNames.forEach((name2) => {
      const fieldArray = getFieldArrayStore(form, name2);
      const keepCurrentDirtyItems = keepDirtyItems && fieldArray.dirty.get();
      if (!keepItems && !keepCurrentDirtyItems) {
        if (initialValues) {
          fieldArray.initialItems.set(getPathValue(name2, initialValues)?.map(() => getUniqueId()) || []);
        }
        fieldArray.startItems.set([...fieldArray.initialItems.get()]);
        fieldArray.items.set([...fieldArray.initialItems.get()]);
      }
      if (!keepTouched) {
        fieldArray.touched.set(false);
      }
      if (!keepDirty && !keepItems && !keepCurrentDirtyItems) {
        fieldArray.dirty.set(false);
      }
      if (!keepErrors) {
        fieldArray.error.set("");
      }
    });
    if (resetEntireForm) {
      if (!keepResponse) {
        form.internal.response.set({});
      }
      if (!keepSubmitCount) {
        form.internal.submitCount.set(0);
      }
      if (!keepSubmitted) {
        form.internal.submitted.set(false);
      }
    }
    updateFormState(form);
  }));
}
function setResponse(form, response, {
  duration
} = {}) {
  form.internal.response.set(response);
  if (duration) {
    setTimeout(() => {
      if (untrack(form.internal.response.get) === response) {
        form.internal.response.set({});
      }
    }, duration);
  }
}
function setValue(form, name2, value2, {
  shouldTouched = true,
  shouldDirty = true,
  shouldValidate = true,
  shouldFocus = true
} = {}) {
  batch(() => {
    const field2 = initializeFieldStore(form, name2);
    field2.value.set(() => value2);
    if (shouldTouched) {
      field2.touched.set(true);
      form.internal.touched.set(true);
    }
    if (shouldDirty) {
      updateFieldDirty(form, field2);
    }
    if (shouldValidate) {
      validateIfRequired(form, field2, name2, {
        on: ["touched", "input"],
        shouldFocus
      });
    }
  });
}
async function validate(form, arg2, arg3) {
  const [fieldNames, fieldArrayNames] = getFilteredNames(form, arg2);
  const {
    shouldActive = true,
    shouldFocus = true
  } = getOptions4(arg2, arg3);
  const validator = getUniqueId();
  form.internal.validators.add(validator);
  form.internal.validating.set(true);
  const formErrors = form.internal.validate ? await form.internal.validate(untrack(() => getValues(form, {
    shouldActive
  }))) : {};
  let valid2 = typeof arg2 !== "string" && !Array.isArray(arg2) ? !Object.keys(formErrors).length : true;
  const [errorFields] = await Promise.all([
    // Validate each field in list
    Promise.all(fieldNames.map(async (name2) => {
      const field2 = getFieldStore(form, name2);
      if (!shouldActive || untrack(field2.active.get)) {
        let localError;
        for (const validation of field2.validate) {
          localError = await validation(untrack(field2.value.get));
          if (localError) {
            break;
          }
        }
        const fieldError = localError || formErrors[name2] || "";
        if (fieldError) {
          valid2 = false;
        }
        field2.error.set(fieldError);
        return fieldError ? name2 : null;
      }
    })),
    // Validate each field array in list
    Promise.all(fieldArrayNames.map(async (name2) => {
      const fieldArray = getFieldArrayStore(form, name2);
      if (!shouldActive || untrack(fieldArray.active.get)) {
        let localError = "";
        for (const validation of fieldArray.validate) {
          localError = await validation(untrack(fieldArray.items.get));
          if (localError) {
            break;
          }
        }
        const fieldArrayError = localError || formErrors[name2] || "";
        if (fieldArrayError) {
          valid2 = false;
        }
        fieldArray.error.set(fieldArrayError);
      }
    }))
  ]);
  batch(() => {
    setErrorResponse(form, formErrors, {
      shouldActive
    });
    if (shouldFocus) {
      const name2 = errorFields.find((name3) => name3);
      if (name2) {
        focus(form, name2);
      }
    }
    updateFormInvalid(form, !valid2);
    form.internal.validators.delete(validator);
    if (!form.internal.validators.size) {
      form.internal.validating.set(false);
    }
  });
  return valid2;
}
function setValues(form, arg2, arg3, arg4) {
  const isFieldArray = typeof arg2 === "string";
  const values2 = isFieldArray ? arg3 : arg2;
  const options2 = (isFieldArray ? arg4 : arg3) || {};
  const {
    shouldTouched = true,
    shouldDirty = true,
    shouldValidate = true,
    shouldFocus = true
  } = options2;
  const names = isFieldArray ? [arg2] : [];
  batch(() => {
    const setFieldArrayItems = (name2, value2) => {
      const fieldArray = initializeFieldArrayStore(form, name2);
      fieldArray.items.set(value2.map(() => getUniqueId()));
      if (shouldTouched) {
        fieldArray.touched.set(true);
        form.internal.touched.set(true);
      }
      if (shouldDirty) {
        fieldArray.dirty.set(true);
        form.internal.dirty.set(true);
      }
    };
    const setNestedValues = (data2, prevPath) => Object.entries(data2).forEach(([path, value2]) => {
      const compoundPath = prevPath ? `${prevPath}.${path}` : path;
      if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) {
        setValue(form, compoundPath, value2, {
          ...options2,
          shouldValidate: false
        });
        names.push(compoundPath);
      }
      if (Array.isArray(value2)) {
        setFieldArrayItems(compoundPath, value2);
      }
      if (value2 && typeof value2 === "object") {
        setNestedValues(value2, compoundPath);
      }
    });
    if (isFieldArray) {
      setFieldArrayItems(arg2, arg3);
    }
    setNestedValues(values2, isFieldArray ? arg2 : void 0);
    if (shouldValidate && ["touched", "input"].includes(form.internal.validateOn === "submit" && form.submitted ? form.internal.revalidateOn : form.internal.validateOn)) {
      validate(form, names, {
        shouldFocus
      });
    }
  });
}
function createLifecycle({
  of: form,
  name: name2,
  getStore,
  validate: validate3,
  transform,
  keepActive = false,
  keepState = true
}) {
  createEffect(() => {
    const store2 = getStore();
    store2.validate = validate3 ? Array.isArray(validate3) ? validate3 : [validate3] : [];
    if ("transform" in store2) {
      store2.transform = transform ? Array.isArray(transform) ? transform : [transform] : [];
    }
    const consumer = getUniqueId();
    store2.consumers.add(consumer);
    if (!untrack(store2.active.get)) {
      batch(() => {
        store2.active.set(true);
        updateFormState(form);
      });
    }
    onCleanup(() => setTimeout(() => {
      store2.consumers.delete(consumer);
      batch(() => {
        if (!keepActive && !store2.consumers.size) {
          store2.active.set(false);
          if (!keepState) {
            reset2(form, name2);
          } else {
            updateFormState(form);
          }
        }
      });
      if ("elements" in store2) {
        store2.elements.set((elements) => elements.filter((element2) => element2.isConnected));
      }
    }));
  });
}
function Field(props2) {
  const getField = createMemo(() => initializeFieldStore(props2.of, props2.name));
  createLifecycle(mergeProps({
    getStore: getField
  }, props2));
  return createMemo(() => props2.children({
    get name() {
      return props2.name;
    },
    get value() {
      return getField().value.get();
    },
    get error() {
      return getField().error.get();
    },
    get active() {
      return getField().active.get();
    },
    get touched() {
      return getField().touched.get();
    },
    get dirty() {
      return getField().dirty.get();
    }
  }, {
    get name() {
      return props2.name;
    },
    get autofocus() {
      return !!getField().error.get();
    },
    ref(element2) {
      getField().elements.set((elements) => [...elements, element2]);
      createEffect(() => {
        if (element2.type !== "radio" && getField().startValue.get() === void 0 && untrack(getField().value.get) === void 0) {
          const input = getElementInput(element2, getField(), props2.type);
          getField().startValue.set(() => input);
          getField().value.set(() => input);
        }
      });
    },
    onInput(event2) {
      handleFieldEvent(props2.of, getField(), props2.name, event2, ["touched", "input"], getElementInput(event2.currentTarget, getField(), props2.type));
    },
    onChange(event2) {
      handleFieldEvent(props2.of, getField(), props2.name, event2, ["change"]);
    },
    onBlur(event2) {
      handleFieldEvent(props2.of, getField(), props2.name, event2, ["touched", "blur"]);
    }
  }));
}
function FieldArray(props2) {
  const getFieldArray = createMemo(() => initializeFieldArrayStore(props2.of, props2.name));
  createLifecycle(mergeProps({
    getStore: getFieldArray
  }, props2));
  return createMemo(() => props2.children({
    get name() {
      return props2.name;
    },
    get items() {
      return getFieldArray().items.get();
    },
    get error() {
      return getFieldArray().error.get();
    },
    get active() {
      return getFieldArray().active.get();
    },
    get touched() {
      return getFieldArray().touched.get();
    },
    get dirty() {
      return getFieldArray().dirty.get();
    }
  }));
}
var FormError = class extends Error {
  name = "FormError";
  /**
   * Creates an explicit form error with useful information for the user.
   *
   * @param message The error message.
   * @param errors The field errors.
   */
  /**
   * Creates an explicit form error with useful information for the user.
   *
   * @param errors The field errors.
   */
  constructor(arg1, arg2) {
    super(typeof arg1 === "string" ? arg1 : "");
    this.errors = typeof arg1 === "string" ? arg2 || {} : arg1;
  }
};
var _tmpl$49 = /* @__PURE__ */ template(`<form novalidate>`);
function Form2(props2) {
  const [, options2, other] = splitProps(props2, ["of"], ["keepResponse", "shouldActive", "shouldTouched", "shouldDirty", "shouldFocus"]);
  return (() => {
    const _el$ = _tmpl$49();
    const _ref$ = props2.of.internal.element.set;
    typeof _ref$ === "function" ? use(_ref$, _el$) : props2.of.internal.element.set = _el$;
    spread(_el$, mergeProps(other, {
      "onSubmit": async (event2) => {
        event2.preventDefault();
        const {
          of: form,
          onSubmit,
          responseDuration: duration
        } = props2;
        batch(() => {
          if (!options2.keepResponse) {
            form.internal.response.set({});
          }
          form.internal.submitCount.set((count) => count + 1);
          form.internal.submitted.set(true);
          form.internal.submitting.set(true);
        });
        try {
          if (await validate(form, options2)) {
            await onSubmit(getValues(form, options2), event2);
          }
        } catch (error2) {
          batch(() => {
            if (error2 instanceof FormError) {
              Object.entries(error2.errors).forEach(([name2, error3]) => {
                if (error3) {
                  setError(form, name2, error3, {
                    ...options2,
                    shouldFocus: false
                  });
                }
              });
            }
            if (!(error2 instanceof FormError) || error2.message) {
              setResponse(form, {
                status: "error",
                message: error2?.message || "An unknown error has occurred."
              }, {
                duration
              });
            }
          });
        } finally {
          form.internal.submitting.set(false);
        }
      }
    }), false, false);
    return _el$;
  })();
}
function email(error2) {
  return (value2) => value2 && !/^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(value2) ? error2 : "";
}
function required(error2) {
  return (value2) => !value2 && value2 !== 0 || Array.isArray(value2) && !value2.length ? error2 : "";
}
function url(error2) {
  return (value2) => {
    try {
      value2 && new URL(value2);
      return "";
    } catch (_5) {
      return error2;
    }
  };
}

// public/app/ui/base/forms/label.tsx
var _tmpl$50 = /* @__PURE__ */ template(`<label></label>`, 2);
function InputLabel(props2) {
  props2 = mergeProps({
    checkLabel: false
  }, props2);
  const [local, others] = splitProps(props2, ["for", "children", "class", "classList", "checkLabel"]);
  return (() => {
    const _el$ = _tmpl$50.cloneNode(true);
    spread(_el$, mergeProps({
      get ["class"]() {
        return local.checkLabel ? "form-check-label" : "form-label";
      },
      get classList() {
        return {
          ...local.classList,
          [local.class]: !!local.class
        };
      },
      get ["for"]() {
        return local.for;
      }
    }, others), false, true);
    insert(_el$, () => local.children);
    return _el$;
  })();
}

// public/app/ui/base/forms/intputs/check-input.tsx
var _tmpl$51 = /* @__PURE__ */ template(`<div class="form-check"><input class="form-check-input" type="checkbox" role="switch"></div>`, 3);
function CheckInput(props2) {
  const [local, component, others] = splitProps(props2, ["id", "name", "label", "checked", "labelClass", "containerClass", "type", "value"], ["children"]);
  return (() => {
    const _el$ = _tmpl$51.cloneNode(true), _el$2 = _el$.firstChild;
    spread(_el$2, mergeProps({
      get id() {
        return local.id ?? local.name;
      },
      get checked() {
        return local.checked ?? local.value;
      }
    }, others), false, false);
    insert(_el$, createComponent(Show, {
      get when() {
        return local.label || component.children;
      },
      get children() {
        return createComponent(InputLabel, {
          checkLabel: true,
          get ["for"]() {
            return local.id;
          },
          get ["class"]() {
            return local.labelClass;
          },
          get children() {
            return local.label || component.children;
          }
        });
      }
    }), null);
    createRenderEffect((_$p) => classList(_el$, {
      [local.containerClass]: !!local.containerClass
    }, _$p));
    return _el$;
  })();
}

// public/app/config/color-palette.ts
var DEFAULT_COLOR_PALETTE = [
  "#efa9a9",
  "#f9e09a",
  "#c8f4db",
  "#b6daf1",
  "#d2c9e8",
  "#6a708a",
  "#E6E6EA",
  "#F4F4F8"
];
var defaultColorPalette = createMemo(() => {
  return serverConfig.default_color_palette || DEFAULT_COLOR_PALETTE;
});
var prettyMenuColorPickerPalette = createMemo(() => {
  return defaultColorPalette().slice(0, 4);
});

// public/app/ui/base/forms/intputs/color-input.tsx
var _tmpl$54 = /* @__PURE__ */ template(`<span class="sr-only"></span>`, 2);
var _tmpl$217 = /* @__PURE__ */ template(`<button type="button" class="form-color-dropdown-trigger"></button>`, 2);
var _tmpl$311 = /* @__PURE__ */ template(`<div class="form-color-dropdown-content"></div>`, 2);
var _tmpl$410 = /* @__PURE__ */ template(`<div class="form-color"></div>`, 2);
function ColorInput(props2) {
  const [local, component, others] = splitProps(props2, ["id", "name", "label", "labelClass", "containerClass", "type", "value", "allowCardColor"], ["onColorChange"]);
  const FALL_BACK_COLOR = "#fafafa";
  const [lastColor, setLastColor] = createSignal(null);
  const onChange = (color) => {
    const newLastColor = local.value ?? FALL_BACK_COLOR;
    setLastColor(newLastColor);
    component.onColorChange?.(color);
  };
  return (() => {
    const _el$ = _tmpl$410.cloneNode(true);
    insert(_el$, createComponent(Dropdown, {
      get children() {
        return [createComponent(DropdownTrigger, {
          get children() {
            const _el$2 = _tmpl$217.cloneNode(true);
            insert(_el$2, createComponent(Show, {
              get when() {
                return local.label;
              },
              get children() {
                const _el$3 = _tmpl$54.cloneNode(true);
                insert(_el$3, () => local.label);
                return _el$3;
              }
            }));
            createRenderEffect((_p$) => {
              const _v$ = !!(props2.allowCardColor && local.value === null), _v$2 = local.value ? `${local.value}` : "transparent";
              _v$ !== _p$._v$ && _el$2.classList.toggle("use-card-color", _p$._v$ = _v$);
              _v$2 !== _p$._v$2 && _el$2.style.setProperty("background", _p$._v$2 = _v$2);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0
            });
            return _el$2;
          }
        }), createComponent(DropdownContent, {
          get children() {
            const _el$4 = _tmpl$311.cloneNode(true);
            insert(_el$4, createComponent(Show, {
              get when() {
                return local.allowCardColor;
              },
              get children() {
                return createComponent(CheckInput, {
                  containerClass: "form-switch",
                  get name() {
                    return local.name + "-use-card-color";
                  },
                  get id() {
                    return local.name + "-use-card-color";
                  },
                  get label() {
                    return _4("Use card color");
                  },
                  get checked() {
                    return local.value === null;
                  },
                  onChange: (e3) => {
                    onChange(e3.target.checked ? null : lastColor() ?? FALL_BACK_COLOR);
                  }
                });
              }
            }), null);
            insert(_el$4, createComponent(ColorPicker2, {
              get initialColor() {
                return local.value;
              },
              defaultColorPalette,
              get disabled() {
                return local.value === null;
              },
              onChange
            }), null);
            return _el$4;
          }
        })];
      }
    }));
    createRenderEffect((_$p) => classList(_el$, {
      [local.containerClass]: !!local.containerClass
    }, _$p));
    return _el$;
  })();
}

// virtual-ns:clipboard
var clipboard_default = window.ClipboardJS;

// public/app/ui/base/forms/intputs/copyable-readonly-input.tsx
var _tmpl$55 = /* @__PURE__ */ template(`<div class="input-group"><input id="copyable-readonly-input" class="form-control" type="text" readonly></div>`, 3);
function CopyableReadonlyInput(props2) {
  props2 = mergeProps({
    focus: true
  }, props2);
  const [local, others] = splitProps(props2, ["value", "inputClass", "containerClass", "focus"]);
  let input, clip2;
  onMount(() => {
    if (local.focus) {
      input.select();
      input.focus();
    }
    clip2 = new clipboard_default("#copyable-readonly-input-btn");
  });
  onCleanup(() => {
    clip2.destroy();
  });
  return (() => {
    const _el$ = _tmpl$55.cloneNode(true), _el$2 = _el$.firstChild;
    const _ref$ = input;
    typeof _ref$ === "function" ? use(_ref$, _el$2) : input = _el$2;
    spread(_el$2, mergeProps({
      get value() {
        return local.value;
      },
      get classList() {
        return {
          [local.inputClass]: local.inputClass
        };
      }
    }, others), false, false);
    insert(_el$, createComponent(IconButton, {
      "class": "btn-ghost",
      id: "copyable-readonly-input-btn",
      "data-clipboard-target": "#copyable-readonly-input",
      icon: "files-o"
    }), null);
    createRenderEffect((_$p) => classList(_el$, {
      [local.containerClass]: local.containerClass
    }, _$p));
    return _el$;
  })();
}

// public/app/ui/base/forms/intputs/text-input.tsx
var _tmpl$56 = /* @__PURE__ */ template(`<input class="form-control">`, 1);
function TextInput(props2) {
  const [local, others] = splitProps(mergeProps({
    onInput: (e3) => props2.onValue?.(e3.target.value)
  }, props2), ["class", "classList", "value", "required", "disabled"]);
  return (() => {
    const _el$ = _tmpl$56.cloneNode(true);
    spread(_el$, mergeProps({
      get classList() {
        return {
          ...local.classList,
          [local.class]: !!local.class
        };
      },
      get value() {
        return local.value || "";
      },
      get required() {
        return local.required;
      },
      get disabled() {
        return local.disabled;
      }
    }, others), false, false);
    return _el$;
  })();
}

// public/app/ui/base/forms/intputs/file-input.tsx
var FileInputButton = (props2) => {
  const [local, others] = splitProps(props2, ["label", "btnClass", "onChangeFn"]);
  let fileRef;
  return [createComponent(Button, mergeProps({
    onClick: () => fileRef.click(),
    get label() {
      return local.label;
    },
    get ["class"]() {
      return local.btnClass;
    }
  }, others)), createComponent(TextInput, {
    type: "file",
    ref(r$) {
      const _ref$ = fileRef;
      typeof _ref$ === "function" ? _ref$(r$) : fileRef = r$;
    },
    get onChange() {
      return local.onChangeFn;
    },
    style: "display: none"
  })];
};

// public/app/ui/base/forms/intputs/textarea-input.tsx
var _tmpl$57 = /* @__PURE__ */ template(`<textarea class="form-control"></textarea>`, 2);
function TextAreaInput(props2) {
  const [local, others] = splitProps(props2, ["class", "classList", "value"]);
  return (() => {
    const _el$ = _tmpl$57.cloneNode(true);
    spread(_el$, mergeProps({
      get classList() {
        return {
          ...local.classList,
          [local.class]: !!local.class
        };
      },
      get value() {
        return local.value || "";
      }
    }, others), false, false);
    return _el$;
  })();
}

// public/app/ui/base/form/BaseFormOld.tsx
var FormPropMarker = Symbol("__kantree_form_property");
var FormNestedPropMarker = Symbol("__kantree_form_nested_property");

// public/app/ui/base/StateMachine.tsx
var StateMachine = class extends BaseStore {
  current = prop();
  transitions = prop([]);
  error = prop(null);
  canTransitionTo(state) {
    const transitions = this.transitions.filter((t3) => "from" in t3 && t3.from === this.current);
    for (const transition of transitions) {
      const result2 = transition.action(state);
      if (!!result2) {
        return false;
      }
    }
    return true;
  }
  async transitionTo(state) {
    const transitions = this.transitions.filter((t3) => "to" in t3 && t3.to === state);
    if (transitions.length > 0) {
      let error2 = null;
      transitions.forEach(async (transition) => {
        if (!error2) {
          const result2 = await transition.action(this.current);
          if (result2 !== void 0) {
            error2 = result2;
          }
        }
      });
      this.error = error2;
      if (!error2) {
        this.current = state;
      }
    } else {
      const error2 = {
        no_transition: `No transition found for (${this.current}->${state})`
      };
      this.error = error2;
      console.error(error2.no_transition);
    }
  }
};
var stateMachineContext = createContext();
function StateMachineProvider(props2) {
  return createComponent(stateMachineContext.Provider, {
    get value() {
      return props2.value;
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/ui/base/context-menu.tsx
var _tmpl$58 = /* @__PURE__ */ template(`<section class="context-menu"></section>`, 2);
var ContextMenuStore = class extends BaseStore {
  isOpen = prop(false);
  x = prop(0);
  y = prop(0);
};
var ContextMenuContext = createContext();
function useContextMenu() {
  return useContext(ContextMenuContext);
}
function createContextMenu(initialValue, owner) {
  const store2 = ContextMenuStore.create(initialValue, owner);
  return {
    store: store2,
    ContextMenuProvider: (props2) => createComponent(ContextMenuContext.Provider, mergeProps({
      value: store2
    }, props2))
  };
}
function ContextMenu(props2) {
  let ref;
  const store2 = useContextMenu();
  useClickOutside({
    element: () => ref,
    handler: (event2) => {
      props2.onClickOutside?.(event2);
    }
  });
  const getVirtualRef = () => ({
    getBoundingClientRect() {
      const x3 = store2.x ?? 0;
      const y3 = store2.y ?? 0;
      return {
        width: 0,
        height: 0,
        x: x3,
        y: y3,
        top: y3,
        left: x3,
        right: x3,
        bottom: y3
      };
    }
  });
  const updatePosition = async () => {
    if (!ref) return;
    const middleware = [O2(props2.offset ?? 8), b(), E({
      padding: 8
    }), k({
      apply({
        availableWidth,
        availableHeight,
        elements
      }) {
        Object.assign(elements.floating.style, {
          maxWidth: `${availableWidth}px`,
          maxHeight: `${availableHeight}px`
        });
      }
    })];
    const {
      x: x3,
      y: y3
    } = await V(getVirtualRef(), ref, {
      placement: props2.placement ?? "bottom-start",
      middleware
    });
    Object.assign(ref.style, {
      left: `${Math.round(x3)}px`,
      top: `${Math.round(y3)}px`
    });
    ref.style.visibility = "visible";
  };
  let cleanupAutoUpdate;
  createEffect(on(() => store2.isOpen, (opened) => {
    if (!ref) return;
    if (opened) {
      updatePosition();
      cleanupAutoUpdate = z(getVirtualRef(), ref, updatePosition);
    } else {
      if (cleanupAutoUpdate) {
        cleanupAutoUpdate();
        cleanupAutoUpdate = void 0;
      }
    }
  }));
  createEffect(on(() => [store2.x, store2.y], () => {
    if (store2.isOpen) updatePosition();
  }));
  onCleanup(() => {
    if (cleanupAutoUpdate) cleanupAutoUpdate();
  });
  return createComponent(Portal, {
    get children() {
      const _el$ = _tmpl$58.cloneNode(true);
      const _ref$ = ref;
      typeof _ref$ === "function" ? use(_ref$, _el$) : ref = _el$;
      _el$.style.setProperty("position", "absolute");
      _el$.style.setProperty("visibility", "hidden");
      insert(_el$, () => props2.children);
      return _el$;
    }
  });
}

// public/app/apps/cards/common/timeline/GanttConfigProvider.tsx
var ganttConfigContext = createContext();
function GanttConfigProvider(props2) {
  const project = useProject();
  const [local, others] = splitProps(props2, ["config"]);
  const config3 = () => local.config ?? project().gantt_config;
  const [state, setState] = createStore({
    get apply_gantt_constraints() {
      return config3().apply_gantt_constraints;
    },
    configurations: []
  });
  createEffect(on(() => {
    const conf = config3();
    const fieldNames = conf.configurations.flatMap((c3) => [c3.date.name, ...c3.secondary_dates.map((s3) => s3.name), c3.relationship?.name].filter(Boolean));
    const attrGroupMap = getAvailableAttrsByName(project(), null, fieldNames);
    return conf.configurations.map((c3) => {
      const modelsByField = [c3.date.name, ...c3.secondary_dates.map((s3) => s3.name)].reduce((acc, fieldName) => {
        if (!attrGroupMap.has(fieldName)) return acc;
        acc[fieldName] = attrGroupMap.get(fieldName).getModels();
        return acc;
      }, {});
      return {
        ...c3,
        date: {
          ...c3.date,
          editable: !!attrGroupMap.get(c3.date.name)?.findEditableAttribute(project())
        },
        secondary_dates: c3.secondary_dates.map((s3) => ({
          ...s3,
          editable: !!attrGroupMap.get(s3.name)?.findEditableAttribute(project())
        })),
        relationship: c3.relationship && {
          ...c3.relationship,
          editable: !!attrGroupMap.get(c3.relationship.name)?.findEditableAttribute(project())
        },
        models: modelsByField
      };
    });
  }, (extendedConfigs) => {
    setState(produce((draft) => {
      draft.configurations = extendedConfigs;
    }));
  }));
  return createComponent(ganttConfigContext.Provider, mergeProps({
    value: state
  }, others));
}
function useGanttConfig() {
  return useContext(ganttConfigContext);
}
function getGanttConfig(model) {
  const config3 = useGanttConfig();
  return createMemo(() => {
    const m3 = typeof model === "function" ? model() : model;
    return config3 ? buildGanttConfig(config3, m3) : void 0;
  });
}
function buildGanttConfig(config3, model) {
  return getGanttConfigForModel(config3, model);
}
function getGanttConfigForModel(config3, model) {
  const baseConfig = config3.configurations[0];
  const configForModel = config3.configurations.find((c3) => c3.model === model);
  if (configForModel) {
    const mergedConfig = {
      ...baseConfig,
      ...configForModel,
      relationship: baseConfig.relationship
    };
    return mergedConfig;
  }
  return baseConfig;
}

// public/app/apps/cards/common/timeline/timeline-utils/item-card-relation.ts
function setupTimelineItemCardRelation(itemStore) {
  const timelineView = useTimelineViewContext();
  const relationShip = useRelationShip();
  const store2 = itemStore ?? useTimelineItem();
  const groups = useTimelineGroups();
  const options2 = useAppOptions();
  const updateRelations = (dependencyConfigs) => {
    const currentRelations = relationShip.findToIdRelations(store2.card.id);
    if (currentRelations.length === 0 && dependencyConfigs.length === 0) return;
    const relationToRemove = currentRelations.filter((relation) => {
      const [fromId] = relation.id.split(".");
      return !dependencyConfigs.find((config3) => {
        const { dependency } = config3;
        return dependency.id == fromId;
      });
    });
    const relationToAdd = dependencyConfigs.filter((config3) => {
      const { dependency } = config3;
      return !currentRelations.find((relation) => {
        const [fromId, toId] = relation.id.split(".");
        return dependency.id == fromId && toId == store2.card.id;
      });
    });
    const relationToUpdate = currentRelations.filter((relation) => {
      return !relationToRemove.includes(relation);
    });
    batch(() => {
      relationToRemove.forEach((relation) => {
        relationShip.remove(relation);
        store2.relations = store2.relations.filter((r3) => r3.id !== relation.id);
      });
      relationToAdd.forEach(({ dependency, color }) => {
        const targetId = dependency.id;
        if (targetId !== void 0) {
          const targetStore = groups?.().reduce(
            (acc, store3) => acc ?? store3.find(targetId),
            void 0
          );
          if (targetStore) {
            const type = dependency.attachment;
            let direction = swapDirection(dependency.direction);
            const from2 = targetStore;
            const to = store2;
            const relation = createRelation(
              relationShip,
              from2,
              to,
              type,
              direction,
              color
            );
            if (!relationShip.hasRelation(relation.id)) {
              relationShip.add(relation);
              from2.relations = [...from2.relations, relation];
            }
          }
        }
      });
      relationToUpdate.forEach((relation) => {
        const config3 = dependencyConfigs.find((config4) => {
          const { dependency } = config4;
          const [fromId, toId] = relation.id.split(".");
          return dependency.id == fromId && toId == store2.card.id;
        });
        if (config3) {
          relation.color = config3.color || relation.color;
        }
      });
    });
  };
  createEffect(on(() => store2.dependencyConfig(), updateRelations));
  createEffect(
    on(
      () => [
        options2.sort_by?.reverse,
        options2.sort_by?.value,
        timelineView.matchingCardIds()
      ],
      () => {
        updateRelations(store2.dependencyConfig());
      },
      { defer: true }
    )
  );
}
function useRelationshipApi() {
  const project = useProject();
  const relationShipsAttrs = useAvailableAttributesOfType("relationships");
  return {
    add: async (relation, ganttConfig) => {
      await addRelation(relation, relationShipsAttrs(), project(), ganttConfig);
    },
    remove: async (relation, ganttConfig) => {
      await removeRelation(
        relation,
        relationShipsAttrs(),
        project(),
        ganttConfig
      );
    }
  };
}
function addRelation(relation, relationShipsAttrs, project, ganttConfig) {
  const start = relation.start;
  const end = relation.end;
  const relationshipFieldName = ganttConfig.relationship.name;
  const attr = relationShipsAttrs.get(relationshipFieldName)[0];
  const model = cardModelStore.getAttributeOwner(attr);
  const attrGrp = new ModelAttributeGroup(project, model, [attr]);
  return attrGrp.appendObjAttribute(start.card, attr, {
    id: end.card.id,
    direction: relation.direction,
    attachment: relation.attachment
  }).catch(autoCatchAsRequestErrorDialog([400]));
}
function removeRelation(relation, relationShipsAttrs, project, ganttConfig) {
  const start = relation.end;
  const end = relation.start;
  const relationshipFieldName = ganttConfig.relationship.name;
  const attr = relationShipsAttrs.get(relationshipFieldName)[0];
  const model = cardModelStore.getAttributeOwner(attr);
  const attrGrp = new ModelAttributeGroup(project, model, [attr]);
  return attrGrp.popObjAttribute(start.card, attr, end.card).catch(autoCatchAsRequestErrorDialog([400]));
}

// public/app/apps/cards/common/timeline/PlanningConfigProvider.tsx
var PlanningConfigContext = createContext(void 0);
function usePlanningConfig() {
  return useContext(PlanningConfigContext);
}
function PlanningConfigProvider(props2) {
  const project = useProject();
  const options2 = useAppOptions();
  const relationAttrGroupMap = createMemo(() => {
    if (!options2?.relationship) return void 0;
    return getAvailableAttrsByName(project(), null, [options2?.relationship]);
  });
  const relationshipEditable = createMemo(() => {
    const attrGroupMap = relationAttrGroupMap();
    if (!attrGroupMap || !options2?.relationship) return false;
    return !!attrGroupMap.get(options2.relationship)?.findEditableAttribute(project());
  });
  const dateAttrGroupMap = createMemo(() => {
    if (!options2?.dateField) return void 0;
    return getAvailableAttrsByName(project(), null, [options2?.dateField]);
  });
  const dateFieldEditable = createMemo(() => {
    const attrGroupMap = dateAttrGroupMap();
    if (!attrGroupMap || !options2?.dateField) return false;
    return !!attrGroupMap.get(options2.dateField)?.findEditableAttribute(project());
  });
  return createComponent(PlanningConfigContext.Provider, {
    get value() {
      return {
        dateField: options2?.dateField,
        dateFieldEditable: dateFieldEditable(),
        relationship: options2?.relationship,
        relationshipEditable: relationshipEditable(),
        relationAttrGroupMap,
        dateAttrGroupMap,
        getReferencedCards: (card) => {
          if (options2?.relationship) {
            const attrGroup = relationAttrGroupMap();
            if (attrGroup) {
              const relationCardAttr = attrGroup.get(options2.relationship).getObjAttribute(card, options2.relationship);
              const cards = relationCardAttr?.value?.map((attrValue) => {
                return cardStore.tryGet(attrValue.id);
              }).filter(Boolean);
              return cards || [];
            }
          }
          return [];
        }
      };
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/timeline/timeline-utils/item-period.ts
function setupGanttItemPeriod(itemStore) {
  const ganttConfig = getGanttConfig(() => itemStore.card.model_id);
  const store2 = itemStore ?? useTimelineItem();
  const findMaxProgressOrPercentage = useProgress(store2);
  const progress2 = createMemo(() => findMaxProgressOrPercentage());
  const configs = () => {
    const config3 = ganttConfig();
    const items = [config3.date, ...config3.secondary_dates];
    const attrNamesMap = /* @__PURE__ */ new Map();
    for (const cardAttrWithModelAttr of getCardAttributes(
      itemStore.card,
      items.map((c3) => c3.name),
      true
    )) {
      attrNamesMap.set(cardAttrWithModelAttr[1].name, cardAttrWithModelAttr);
    }
    const result2 = [];
    const progressValue = progress2();
    for (const c3 of items) {
      const cardAttrWithModelAttr = attrNamesMap.get(c3.name);
      if (!cardAttrWithModelAttr) continue;
      const dateAttr = cardAttrWithModelAttr[0];
      const modelAttr = cardAttrWithModelAttr[1];
      const dateRange = parseDateFromComputedAttribute(modelAttr, dateAttr);
      const color = c3.color !== null ? c3.color : cardModelStore.tryGet(itemStore.card?.model_id)?.card_color ?? "#fafafa";
      const isComputed = attributeTypeRegistry.get(dateAttr.type)?.computed || modelAttr?.is_computed;
      const isMilestone = c3.type === "milestone" /* Milestone */;
      const isMainPeriod = c3.name === config3.date.name;
      let start = dateRange?.start?.toDate() ?? void 0;
      const end = dateRange?.end?.toDate() ?? void 0;
      if (isMilestone && start !== end) {
        start = end;
      }
      const isRange = modelAttr.options?.daterange ?? false;
      result2.push({
        id: dateAttr.id,
        name: c3.name,
        color,
        isMilestone,
        isRange,
        allDay: dateRange?.allDay ?? false,
        start,
        end,
        progress: progressValue,
        movable: c3.editable && !isComputed,
        resizable: modelAttr.options?.daterange && c3.editable && !isMilestone && !isComputed,
        relationAllowed: config3.relationship?.editable && isMainPeriod,
        stepUnit: precisionToTimeUnit[modelAttr?.options.precision] || "day" /* DAY */
      });
    }
    return result2;
  };
  setupPeriod(store2, configs);
}
function setupPlanningItemPeriod(itemStore) {
  const planningConfig = usePlanningConfig();
  const store2 = itemStore ?? useTimelineItem();
  const findMaxProgressOrPercentage = useProgress(store2);
  const progress2 = createMemo(() => findMaxProgressOrPercentage());
  const configs = () => {
    const cards = planningConfig.getReferencedCards(store2.card);
    const result2 = [];
    const progressValue = progress2();
    for (const card of cards) {
      const dateAttr = getCardAttribute(card, planningConfig.dateField);
      if (!dateAttr) continue;
      const modelAttr = cardModelStore.getAttribute(dateAttr.id);
      const dateRange = parseDateFromComputedAttribute(dateAttr, dateAttr);
      const color = cardModelStore.tryGet(card.model_id)?.card_color ?? "#fafafa";
      const isComputed = attributeTypeRegistry.get(dateAttr.type)?.computed || modelAttr?.is_computed;
      const isMilestone = false;
      const isRange = modelAttr.options?.daterange ?? false;
      result2.push({
        id: card.id,
        name: card.title,
        color,
        isMilestone,
        allDay: dateRange?.allDay ?? false,
        isRange,
        start: dateRange?.start?.toDate() ?? void 0,
        end: dateRange?.end?.toDate() ?? void 0,
        progress: progressValue,
        movable: planningConfig.dateFieldEditable && !isComputed,
        resizable: modelAttr?.options?.daterange && planningConfig.dateFieldEditable && !isMilestone && !isComputed,
        relationAllowed: false,
        stepUnit: precisionToTimeUnit[modelAttr?.options.precision] || "day" /* DAY */
      });
    }
    return result2;
  };
  setupPeriod(store2, configs);
}
function useProgress(store2) {
  return createMemo(() => {
    const attributes = store2.card.attributes;
    let maxProgress = 0;
    let maxPercentage = 0;
    for (const attr of attributes) {
      if (attr.value > 0) {
        if (attr.type === "progress") {
          maxProgress = Math.max(maxProgress, attr.value);
        } else if (attr.type === "percentage") {
          maxPercentage = Math.max(maxPercentage, attr.value);
        }
      }
    }
    return maxProgress > 0 ? maxProgress : maxPercentage;
  });
}
function setupPeriod(store2, configs) {
  createEffect(
    on(
      () => configs(),
      (items) => {
        batch(() => {
          items.forEach((config3) => {
            const period = store2.periods.find((p4) => p4.id === config3.id) ?? TimelinePeriodStore4.create({
              id: config3.id,
              parent: store2
            });
            period.update((draft) => {
              draft.name = config3.name;
              draft.start = config3.start;
              draft.end = config3.end;
              draft.allDay = config3.allDay;
              draft.isRange = config3.isRange;
              draft.color = config3.color;
              draft.isMilestone = config3.isMilestone;
              draft.movable = config3.movable;
              draft.resizable = config3.resizable;
              draft.relationAllowed = config3.relationAllowed;
              draft.stepUnit = config3.stepUnit;
              if (config3.progress >= 0) {
                draft.progress = config3.progress;
              }
            });
            store2.registerPeriod(period);
          });
          store2.unregisterOldPeriods(items.map((e3) => e3.id));
        });
      }
    )
  );
}
function getDateAttr(name2, availableDateAttrGroupMap, card) {
  const dateAttrGrp = availableDateAttrGroupMap.get(name2);
  return dateAttrGrp.getCardAvailableAttributes(card)[0];
}
function updateDateAttribute(card, attr, start, end) {
  return setCardAttribute(
    card,
    attr.id,
    start && end ? formatServerDateRange(attr, moment_default(start), moment_default(end)) : ""
  );
}
function _updateCardStore(result2) {
  cardStore.transaction(() => {
    Object.keys(result2).forEach((cardId) => {
      cardStore.updateById(parseInt(cardId), (c3) => {
        let attributes = [...c3.attributes];
        Object.keys(result2[cardId]).forEach((attrId) => {
          const index2 = _getAttributeIndex(c3, attrId);
          if (typeof index2 !== "undefined") {
            attributes.splice(index2, 1);
          }
          attributes.push(result2[cardId][attrId]);
        });
        return { ...c3, attributes };
      });
    });
  });
}
async function updateDateAttributes(payloads) {
  const cardsByProject = {};
  payloads.forEach((payload) => {
    const itemStore = payload.item;
    const cardId = itemStore.card.id;
    const projectId = itemStore.card.project_id;
    if (!cardsByProject[projectId]) {
      cardsByProject[projectId] = { cards: {} };
    }
    const cards = cardsByProject[projectId].cards;
    if (!cards[cardId]) {
      cards[cardId] = [];
    }
    cards[cardId].push({
      attr_id: payload.period.id,
      ...formatServerDateRange(
        cardModelStore.getAttribute(payload.period.id),
        moment_default(payload.start),
        moment_default(payload.end)
      ),
      project_id: itemStore.card.project_id
    });
  });
  Object.entries(cardsByProject).forEach(async ([projectId, data2]) => {
    const result2 = await batchUpdateCardDates(parseInt(projectId), data2.cards);
    _updateCardStore(result2);
  });
}
async function updateReferencedDateAttributes(availableDateAttrGroupMap, data2, dateFieldName) {
  const cardsByProject = {};
  data2.forEach((payload) => {
    const itemStore = payload.item;
    const cardId = itemStore.card.id;
    if (!cardsByProject[itemStore.card.project_id]) {
      cardsByProject[itemStore.card.project_id] = { cards: {} };
    }
    const acc = cardsByProject[itemStore.card.project_id].cards;
    if (!acc[cardId]) {
      acc[cardId] = [];
    }
    acc[cardId].push({
      attr_id: dateFieldName,
      ...formatServerDateRange(
        getDateAttr(dateFieldName, availableDateAttrGroupMap, itemStore.card),
        moment_default(payload.start),
        moment_default(payload.end)
      )
    });
  });
  Object.entries(cardsByProject).forEach(async ([projectId, _data]) => {
    const result2 = await batchUpdateCardDates(parseInt(projectId), _data.cards);
    _updateCardStore(result2);
  });
}

// public/app/apps/cards/common/timeline/timeline-utils/weakMaps.ts
var weakCardTimelineItemMap = /* @__PURE__ */ new WeakMap();
function getTimelineItemStoreFromWeakMap(card, groupId) {
  const groupMap = weakCardTimelineItemMap.get(card);
  return groupMap ? groupMap.get(groupId) : void 0;
}
function setTimelineItemStoreToWeakMap(card, groupId, store2) {
  let groupMap = weakCardTimelineItemMap.get(card);
  if (!groupMap) {
    groupMap = /* @__PURE__ */ new Map();
    weakCardTimelineItemMap.set(card, groupMap);
  }
  groupMap.set(groupId, store2);
}
function deleteTimelineItemStoreFromWeakMap(card, groupId) {
  const groupMap = weakCardTimelineItemMap.get(card);
  if (groupMap) {
    groupMap.delete(groupId);
    if (groupMap.size === 0) {
      weakCardTimelineItemMap.delete(card);
    }
  }
}
var resetCardTimelineItemWeakMap = () => {
  weakCardTimelineItemMap = /* @__PURE__ */ new WeakMap();
};

// public/app/apps/cards/common/timeline/stores/TimelineView.tsx
var TimelineViewContext = createContext();
function useTimelineViewContext() {
  return useContext(TimelineViewContext);
}
function TimelineViewProvider(props2) {
  const options2 = useAppOptions();
  const [local, others] = splitProps(props2, ["children"]);
  const availableDateAttrs = useAvailableAttributesOfType("date");
  function getAvailableDateAttributes() {
    return availableDateAttrs();
  }
  const periodSelectable = createPeriodSelectable();
  const relationSelectable = createRelationSelectable();
  const timelineStore = TimelineStore.create({
    visibleDays: 30,
    displayWeekNumber: true,
    minutesBreakpoint: 1,
    // disable minutes handling for now.
    visibleWeekDayBreakpoint: 1
  });
  createEffect(on(() => [options2?.period?.start, options2?.period?.end], ([start, end], previous) => {
    const currentPeriod = timelineStore.period;
    const optStart = moment_default(start);
    const optEnd = moment_default(end);
    const periodDaysDiff = optEnd.diff(optStart, "days") + 1;
    const clampedDaysDiff = Math.min(Math.max(periodDaysDiff, 60), 365);
    if (!currentPeriod) {
      timelineStore.setState(produce((draft) => {
        draft.initialized = false;
        draft.initialPeriod = {
          start: new Date(start ?? draft.period.start),
          end: new Date(end ?? draft.period.end)
        };
        draft.period = {
          start: moment_default(start).add(clampedDaysDiff * -1, "days").toDate(),
          end: moment_default(end).add(clampedDaysDiff, "days").toDate()
        };
        draft.visibleDays = start && end ? moment_default(end).diff(moment_default(start), "days") + 1 : 30;
      }));
      return;
    }
    const sameStart = previous ? optStart.isSame(previous?.[0], "day") : false;
    const sameEnd = previous ? optEnd.isSame(previous?.[1], "day") : false;
    const startInPeriod = optStart.isBetween(timelineStore.period.start, timelineStore.period.end, "day", "[]");
    const endInPeriod = optEnd.isBetween(timelineStore.period.start, timelineStore.period.end, "day", "[]");
    const inCurrentPeriod = startInPeriod && endInPeriod;
    timelineStore.setState(produce((draft) => {
      draft.initialized = false;
      draft.initialPeriod = {
        start: new Date(start ?? draft.period.start),
        end: new Date(end ?? draft.period.end)
      };
      if ((!sameStart || !sameEnd) && !inCurrentPeriod) {
        draft.period = {
          start: moment_default(start).add(clampedDaysDiff * -1, "days").toDate(),
          end: moment_default(end).add(clampedDaysDiff, "days").toDate()
        };
      }
      draft.visibleDays = start && end ? moment_default(end).diff(moment_default(start), "days") + 1 : 30;
    }));
  }));
  const scrollToInitialPeriodStart = (behavior = "instant") => {
    const vp = timelineStore.viewport;
    const initialStart = timelineStore.initialPeriod?.start;
    const periodStart = timelineStore.period?.start;
    const columnWidth = timelineStore.columnWidth;
    if (!vp || !initialStart || !periodStart || columnWidth <= 0) return;
    const snapBehavior = timelineStore.snapScrollBehavior;
    if (snapBehavior) {
      behavior = snapBehavior;
      timelineStore.snapScrollBehavior = void 0;
    }
    const dayIndex = getPositionInPeriod(initialStart, periodStart);
    const targetScrollLeft = (dayIndex - 1) * columnWidth - timelineStore.sidebarWidth;
    if (behavior === "instant") {
      const currentScrollLeft = vp.scrollLeft;
      if (Math.abs(currentScrollLeft - targetScrollLeft) < columnWidth * 3) {
        behavior = "smooth";
      }
    }
    vp.scrollTo({
      left: targetScrollLeft,
      behavior
    });
    if (!timelineStore.initialized) {
      timelineStore.initialized = true;
    }
  };
  createEffect(on(() => [timelineStore.initialized, timelineStore.viewport, timelineStore.initialPeriod?.start, timelineStore.columnWidth], ([initialized, vp, start, columnWidth]) => {
    if (initialized || !vp || !start || columnWidth <= 0) return;
    scrollToInitialPeriodStart();
  }));
  const getVisiblePeriodFromScroll = () => {
    const vp = timelineStore.viewport;
    const scrollDays = Math.round((vp.scrollLeft + timelineStore.sidebarWidth) / timelineStore.columnWidth);
    const start = moment_default(timelineStore.period.start).add(scrollDays, "days");
    const end = moment_default(start).add(timelineStore.visibleDays - 1, "days");
    return {
      start,
      end
    };
  };
  createEventListener(() => timelineStore.initialized ? timelineStore.viewport : null, SCROLL_END_EVENT, () => {
    if (!timelineStore.initialized || !timelineStore.viewport || !timelineStore.initialPeriod?.start) return;
    const {
      start: visibleStart,
      end: visibleEnd
    } = getVisiblePeriodFromScroll();
    const granularity = timelineStore.visibleDays >= 180 ? "month" : "day";
    let nextStart = visibleStart;
    if (granularity === "month") {
      const monthStart = moment_default(visibleStart).startOf("month");
      const monthMidpoint = moment_default(monthStart).add(Math.floor(monthStart.daysInMonth() / 2), "days");
      nextStart = visibleStart.isAfter(monthMidpoint) ? moment_default(monthStart).add(1, "month") : monthStart;
      timelineStore.snapScrollBehavior = "smooth";
    }
    const nextEnd = moment_default(nextStart).add(timelineStore.visibleDays - 1, "days");
    const initialStart = timelineStore.initialPeriod?.start;
    const initialEnd = timelineStore.initialPeriod?.end;
    if (initialStart && initialEnd && nextStart.isSame(initialStart, "day") && nextEnd.isSame(initialEnd, "day")) {
      return;
    }
    props2.onChange({
      options: JSON.parse(JSON.stringify({
        ...options2.getState(),
        period: formatPeriodToString({
          start: nextStart,
          end: nextEnd
        })
      }))
    });
  });
  const groupByUngrounded = createMemo(() => options2.group_by[0]?.type === "nothing");
  onCleanup(() => {
    resetCardTimelineItemWeakMap();
  });
  return createComponent(TimelineViewContext.Provider, {
    get value() {
      return {
        ...others,
        matchingCardIds: props2.matchingCardIds,
        groupByUngrouped: groupByUngrounded
      };
    },
    get children() {
      return createComponent(Show, {
        get when() {
          return getAvailableDateAttributes().size > 0;
        },
        get children() {
          return createComponent(TimelineProvider, {
            value: timelineStore,
            get children() {
              return createComponent(SelectPeriodProvider, {
                selectable: periodSelectable,
                get children() {
                  return createComponent(SelectRelationProvider, {
                    selectable: relationSelectable,
                    get children() {
                      return local.children;
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
  });
}

// public/app/apps/cards/common/timeline/stores/Groups.tsx
var GroupsContext = createContext();
function useTimelineGroups() {
  return useContext(GroupsContext);
}
function ManageGroups(props2) {
  const cardStore2 = useCardStore();
  const scopedModelStore = useScopedModelStore();
  const scopedGroupTypeStore = useScopedGroupTypeStore();
  const options2 = useAppOptions();
  const context = useTimelineViewContext();
  let owner;
  const mappedGroups = createMemo(mapArray(() => [props2.groupBy], (groupBy2) => {
    const grpSignal = groupBy2.getGroupStore().react({}, {
      sortBy: "position"
    });
    return {
      get groups() {
        return grpSignal();
      }
    };
  }));
  const completeGrps = createMemo(mapArray(() => {
    owner = getOwner();
    const result2 = [{
      index: 0,
      group: {
        title: "ungrouped"
      }
    }];
    const mapped = mappedGroups();
    for (let i3 = 0; i3 < mapped.length; i3++) {
      const grp = mapped[i3];
      const groups2 = grp.groups;
      for (let j = 0; j < groups2.length; j++) {
        result2.push({
          group: groups2[j],
          index: i3 + j + (options2.showUngroupedCards ? 1 : 0)
        });
      }
    }
    return result2;
  }, (item) => {
    let store2;
    let title;
    const modelStore = scopedModelStore();
    const groupTypeStore = scopedGroupTypeStore();
    if (item.group.title === "ungrouped") {
      if (!props2.groupBy || props2.groupBy.isNothing()) {
        title = _4("(ungrouped)");
      } else {
        title = _4("(no {group_type})", {
          group_type: props2.groupBy.getLabel().toLowerCase()
        });
      }
      store2 = context.timelineItemCreateFn({
        id: "ungrouped",
        title,
        isRoot: true,
        group: item.group,
        visibleChild: true,
        index: 0,
        childrenLoader: () => props2.groupBy.getUngroupedCardsStore().react({}, () => {
          if (options2.sort_by) {
            return {
              sortBy: getCardCompareFunc(options2.sort_by, {
                modelStore,
                groupTypeStore
              })
            };
          }
          return {
            sortBy: "position",
            cmpFunc: defaultCardCompareFunc
          };
        })
      }, owner);
    } else {
      title = item.group.title;
      store2 = context.timelineItemCreateFn({
        id: title,
        title,
        isRoot: true,
        group: item.group,
        visibleChild: true,
        index: item.index,
        childrenLoader: () => (item.group.is_dynamic ? item.group.getCardStore() : cardStore2.scoped({
          groups: matchGroup(item.group.id)
        })).react({}, () => {
          if (options2.sort_by) {
            return {
              sortBy: getCardCompareFunc(options2.sort_by, {
                modelStore,
                groupTypeStore
              })
            };
          }
          return {
            sortBy: "meta:position",
            cmpFunc: defaultCardCompareFunc
          };
        })
      }, owner);
    }
    return store2;
  }));
  const groups = createMemo(() => {
    const grps = completeGrps();
    let results2 = grps;
    if (!options2.showUngroupedCards && grps.length > 0) {
      results2 = grps.slice(1);
    }
    if (options2.hideEmptyGroups && grps.length > 0) {
      results2 = results2.filter((item) => item.children.length > 0);
    }
    for (let i3 = 0; i3 < results2.length; i3++) {
      results2[i3].index = i3;
      results2[i3].position = i3;
    }
    return results2;
  });
  return createComponent(GroupsContext.Provider, {
    value: groups,
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/timeline/timeline-utils/item-selection.ts
function setupTimelineItemSelection() {
  const store2 = useTimelinePeriod();
  const keyboardState2 = useKeyboard();
  const selectable = usePeriodSelectable();
  const groups = useTimelineGroups();
  return (e3) => {
    if (keyboardState2.Control || e3?.ctrlKey) {
      selectable?.toggle(store2);
      return true;
    } else if (keyboardState2.Shift || e3?.shiftKey) {
      const lastSelection = selectable?.selection[selectable?.selection.length - 1] ?? void 0;
      if (!lastSelection) {
        selectable?.toggle(store2);
      } else {
        let start = lastSelection;
        let end = store2;
        if (!isBefore(start.parent.path, end.parent.path)) {
          [start, end] = [end, start];
        }
        const parent = getClosestParent(start.parent, end.parent);
        const data2 = parent ? [parent] : groups();
        const selectedPeriods = /* @__PURE__ */ new Set();
        batch(() => {
          data2.forEach((item) => {
            walkTree(item, (item2) => {
              const itemIsBetweenRange = isBetween(
                item2.path,
                start.parent.path,
                end.parent.path
              );
              if (itemIsBetweenRange) {
                item2.periods.forEach((period) => {
                  selectable?.select(period);
                  selectedPeriods.add(period);
                });
              }
              return false;
            });
          });
          [start, end].map((period) => period.parent).forEach((item) => {
            item.periods.forEach((period) => {
              selectable?.select(period);
              selectedPeriods.add(period);
            });
          });
          selectable?.selection.forEach((period) => {
            if (!selectedPeriods.has(period)) {
              selectable?.unselect(period);
            }
          });
        });
      }
      return true;
    }
    return false;
  };
}

// public/app/apps/cards/common/timeline/timeline-utils/card-item-selection.ts
function getDependencies(store2, fieldNames) {
  return store2.card?.attributes.filter((attr) => fieldNames.includes(attr.name)).map((attr) => {
    return {
      id: attr.id,
      name: attr.name,
      targetIds: attr.value?.map((v3) => v3.id) ?? []
    };
  }) ?? [];
}
function selectDependencyGraph(selectable, groups, store2, fieldNames) {
  store2.periods.forEach((period) => {
    selectable?.select(period);
  });
  const dependencies = getDependencies(store2, fieldNames);
  dependencies.forEach((dep) => {
    dep.targetIds.forEach((id) => {
      const depStore = groups.reduce(
        (acc, store3) => acc ?? store3.find(id),
        void 0
      );
      if (depStore) {
        selectDependencyGraph(
          selectable,
          groups,
          depStore,
          fieldNames
        );
      }
    });
  });
}
function setupCardTimelineItemSelection() {
  const store2 = useTimelinePeriod();
  const keyboardState2 = useKeyboard();
  const selectable = usePeriodSelectable();
  const groups = useTimelineGroups();
  const ganttConfig = getGanttConfig(
    () => store2.parent.card.model_id
  );
  const baseHandler = setupTimelineItemSelection();
  return (e3) => {
    const result2 = baseHandler(e3);
    if (result2) return result2;
    if ((keyboardState2.Alt || e3?.altKey) && ganttConfig()) {
      batch(() => {
        selectDependencyGraph(
          selectable,
          groups(),
          store2.parent,
          ganttConfig().relationship?.name ? [ganttConfig().relationship.name] : []
        );
      });
      return true;
    }
    return false;
  };
}

// public/app/apps/cards/common/timeline/components/tooltip.tsx
var _tmpl$59 = /* @__PURE__ */ template(`<div class="solid-tooltip open"><div class="solid-tooltip-inner"></div><div class="solid-tooltip-arrow"></div></div>`, 6);
function TimelineTooltip(props2) {
  const [opened, setOpen] = createSignal(false);
  const resolved = children(() => props2.children);
  const enable = () => props2.enable;
  const resolvedChild = createMemo(() => resolved.toArray()?.[0]);
  const showTooltip2 = debounce2(() => setOpen(enable()), props2.showDelay ?? 0);
  const hideTooltip2 = debounce2(() => setOpen(false), props2.hideDelay ?? 0);
  createEventListener(() => enable() ? resolvedChild() : null, ["mouseenter", "mousemove"], () => {
    showTooltip2.clear();
    showTooltip2();
  });
  createEventListener(() => enable() ? resolvedChild() : null, "mouseleave", () => {
    hideTooltip2.clear();
    showTooltip2.clear();
    hideTooltip2();
  });
  onCleanup(() => {
    hideTooltip2.clear();
    showTooltip2.clear();
  });
  return [createMemo(resolved), createComponent(Show, {
    get when() {
      return createMemo(() => !!props2.enable)() && !!resolvedChild();
    },
    get children() {
      return createComponent(Portal, {
        get mount() {
          return props2.mount;
        },
        get children() {
          return createComponent(Show, {
            get when() {
              return opened();
            },
            get children() {
              return createComponent(_Tooltip2, mergeProps(props2, {
                get target() {
                  return resolvedChild();
                }
              }));
            }
          });
        }
      });
    }
  })];
}
function _Tooltip2(props2) {
  let tooltipRef;
  let arrowContainer;
  const updatePosition = async () => {
    const {
      x: x3,
      y: y3,
      placement,
      middlewareData
    } = await V(props2.target, tooltipRef, {
      placement: props2.placement ?? "top",
      middleware: [b({
        padding: 5
      }), E({
        padding: 5
      }), O2(10), m({
        element: arrowContainer
      })]
    });
    Object.assign(tooltipRef?.style, {
      left: `${x3}px`,
      top: `${y3}px`
    });
    const {
      x: arrowX,
      y: arrowY
    } = middlewareData.arrow;
    const staticSide = {
      top: "bottom",
      right: "left",
      bottom: "top",
      left: "right"
    }[placement.split("-")[0]];
    Object.assign(arrowContainer.style, {
      left: arrowX != null ? `${arrowX}px` : "",
      top: arrowY != null ? `${arrowY}px` : "",
      right: "",
      bottom: "",
      [staticSide]: "-4px"
    });
  };
  onMount(() => {
    updatePosition();
  });
  return (() => {
    const _el$ = _tmpl$59.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
    const _ref$ = tooltipRef;
    typeof _ref$ === "function" ? use(_ref$, _el$) : tooltipRef = _el$;
    insert(_el$2, () => props2.label);
    const _ref$2 = arrowContainer;
    typeof _ref$2 === "function" ? use(_ref$2, _el$3) : arrowContainer = _el$3;
    return _el$;
  })();
}

// public/app/apps/cards/common/timeline/components/NodeTimelinePeriod.tsx
var _tmpl$60 = /* @__PURE__ */ template(`<div class="timeline-card-progress-bar"><div></div></div>`, 4);
var _tmpl$218 = /* @__PURE__ */ template(`<div class="timeline-card-title"><span></span></div>`, 4);
var _tmpl$312 = /* @__PURE__ */ template(`<div class="timeline-card-content"></div>`, 2);
var _tmpl$411 = /* @__PURE__ */ template(`<button class="menu-item-main-action-button"><span class="menu-item-label"></span></button>`, 4);
var _tmpl$510 = /* @__PURE__ */ template(`<div class="timeline-period-tooltip-content"><span></span><br><span></span><br><span></span></div>`, 10);
function NodeTimelinePeriod() {
  const period = useTimelinePeriod();
  const groups = useTimelineGroups();
  const timelineViewContext = useTimelineViewContext();
  const timelineStore = useTimelineStore();
  const item = useTimelineItem();
  const selectable = usePeriodSelectable();
  const selectionHandler = setupCardTimelineItemSelection();
  const {
    handleTimelineRelations
  } = setupTimelineItemRelation();
  const {
    store: contextMenu,
    ContextMenuProvider
  } = createContextMenu();
  const ganttConfig = getGanttConfig(() => item.card.model_id);
  const options2 = useAppOptions();
  const relationShipApi = useRelationshipApi();
  const onClick = (e3) => {
    if (!selectionHandler(e3)) {
      timelineViewContext.frontend.onPeriodClick(item, period);
    }
  };
  const onPeriodsMoved = (payloads) => {
    timelineViewContext.backend.movePeriods(payloads);
  };
  const onPeriodResized = (prop2, payload) => {
    const isDeletingDates = payload.period.deletingDates;
    let start = void 0;
    let end = void 0;
    if (!isDeletingDates) {
      if (prop2 === "start") {
        start = shiftDate(payload.original.start, payload.minutes, period.stepUnit);
        end = payload.original.end;
      } else {
        start = payload.original.start;
        end = shiftDate(payload.original.end, payload.minutes, period.stepUnit);
      }
    }
    payload.period.deletingDates = false;
    timelineViewContext.backend.resizePeriod(start, end, payload);
  };
  const onCreateRelation = (e3, start) => {
    const _data = e3.dataTransfer?.getData("timeline/create-relation");
    if (!_data || _data === "") return;
    const data2 = JSON.parse(_data);
    const swap = data2.swap ?? false;
    const rootGroups = groups();
    const fromItem = getTimelineItem(rootGroups, data2.path);
    const to = period;
    const from2 = fromItem.periods[0];
    const startAttachement = data2.attachment;
    const dropAttachement = start ? "start" : "end";
    let attachment = `${startAttachement}_${dropAttachement}`;
    const payload = {
      from: swap ? to : from2,
      to: swap ? from2 : to,
      attachment
    };
    const relations = handleTimelineRelations(payload, selectable);
    relations.added.forEach(async (relation) => {
      await relationShipApi.add(relation, ganttConfig());
    });
    relations.removed.forEach(async (relation) => {
      await relationShipApi.remove(relation, ganttConfig());
    });
  };
  const relationCreatorShouldSwap = () => {
    return true;
  };
  const contextMenuItems = [{
    label: _4("Open card"),
    action: () => {
      contextMenu.isOpen = false;
      timelineViewContext.cardModal?.open(item.card);
    }
  }, {
    label: _4(`Delete "{field}"`, {
      field: period.name
    }),
    action: () => {
      timelineViewContext.backend.deletePeriod(period, item.card);
      contextMenu.isOpen = false;
    }
  }];
  return createComponent(TimelinePeriod, {
    store: period,
    get classList() {
      return {
        dragover: period.dragover,
        "invalid-drop": period.invalidDrop,
        finished: item.card?.finished || item.card?.is_archived
      };
    },
    get style() {
      return {
        "--timeline-item-color": item.isCritical ? "red" : period.color
      };
    },
    get children() {
      return [createComponent(Show, {
        get when() {
          return period.relationAllowed;
        },
        get children() {
          return createComponent(TimelineRelationCreator, {
            onDrop: (e3) => onCreateRelation(e3, true),
            start: true,
            get swap() {
              return relationCreatorShouldSwap();
            }
          });
        }
      }), createComponent(Show, {
        get when() {
          return period.resizable;
        },
        get children() {
          return createComponent(TimelinePeriodResizer, {
            start: true,
            onPeriodResized: (p4) => onPeriodResized("start", p4)
          });
        }
      }), createComponent(TimelinePeriodMoveHandler, {
        get enable() {
          return period.movable;
        },
        tabindex: "0",
        onKeyUp: (e3) => {
          if (e3.key === "Enter") {
            onClick(e3);
          }
        },
        onClick,
        onPeriodsMoved,
        get children() {
          return createComponent(ContextMenuProvider, {
            get children() {
              return createComponent(TimelineTooltip, {
                showDelay: 1500,
                get label() {
                  return createComponent(NodePeriodTooltipContent, {});
                },
                get enable() {
                  return !period.moving && !period.resizing && !timelineStore.itemsMoving && !timelineStore.itemsResizing;
                },
                get mount() {
                  return timelineStore.viewport?.querySelector(".timeline");
                },
                get children() {
                  const _el$ = _tmpl$312.cloneNode(true);
                  _el$.$$contextmenu = (e3) => {
                    e3.preventDefault();
                    contextMenu.x = e3.clientX;
                    contextMenu.y = e3.clientY;
                    contextMenu.isOpen = true;
                  };
                  insert(_el$, createComponent(Show, {
                    get when() {
                      return period.progress > 0 && !period.isMilestone && item.children.length === 0;
                    },
                    get children() {
                      const _el$2 = _tmpl$60.cloneNode(true), _el$3 = _el$2.firstChild;
                      createRenderEffect((_p$) => {
                        const _v$ = `${period.progress}%`, _v$2 = darkenColor(period.color, 10);
                        _v$ !== _p$._v$ && _el$3.style.setProperty("width", _p$._v$ = _v$);
                        _v$2 !== _p$._v$2 && _el$3.style.setProperty("background-color", _p$._v$2 = _v$2);
                        return _p$;
                      }, {
                        _v$: void 0,
                        _v$2: void 0
                      });
                      return _el$2;
                    }
                  }), null);
                  insert(_el$, createComponent(Show, {
                    get when() {
                      return !period.isMilestone && options2.displayCardTitle === DisplayCardTitle.INSIDE;
                    },
                    get children() {
                      const _el$4 = _tmpl$218.cloneNode(true), _el$5 = _el$4.firstChild;
                      insert(_el$5, () => item.card?.title);
                      return _el$4;
                    }
                  }), null);
                  insert(_el$, createComponent(Show, {
                    get when() {
                      return options2.displayPeriodTitle === DisplayPeriodTitle.INSIDE;
                    },
                    get children() {
                      const _el$6 = _tmpl$218.cloneNode(true), _el$7 = _el$6.firstChild;
                      insert(_el$7, () => period.name);
                      return _el$6;
                    }
                  }), null);
                  insert(_el$, createComponent(Show, {
                    get when() {
                      return contextMenu.isOpen;
                    },
                    get children() {
                      return createComponent(ContextMenu, {
                        onClickOutside: () => contextMenu.isOpen = false,
                        get children() {
                          return createComponent(Menu, {
                            each: contextMenuItems,
                            "class": "timeline-context-menu",
                            children: (item2) => (() => {
                              const _el$8 = _tmpl$411.cloneNode(true), _el$9 = _el$8.firstChild;
                              addEventListener(_el$8, "click", item2.action, true);
                              insert(_el$9, () => item2.label);
                              return _el$8;
                            })()
                          });
                        }
                      });
                    }
                  }), null);
                  return _el$;
                }
              });
            }
          });
        }
      }), createComponent(Show, {
        get when() {
          return period.resizable;
        },
        get children() {
          return createComponent(TimelinePeriodResizer, {
            end: true,
            onPeriodResized: (p4) => onPeriodResized("end", p4)
          });
        }
      }), createComponent(Show, {
        get when() {
          return period.relationAllowed;
        },
        get children() {
          return createComponent(TimelineRelationCreator, {
            onDrop: (e3) => onCreateRelation(e3, false),
            end: true,
            get swap() {
              return relationCreatorShouldSwap();
            }
          });
        }
      })];
    }
  });
}
function NodePeriodTooltipContent() {
  const period = useTimelinePeriod();
  const item = useTimelineItem();
  const fieldName = () => {
    const attr = item.card.attributes.find((attr2) => attr2.id == period.id);
    return attr?.name ?? "";
  };
  const dateRange = () => {
    const startDate = formatDate2(moment_default(period.start));
    const endDate = formatDate2(moment_default(period.end));
    if (period.isMilestone) return endDate;
    return `${startDate} - ${endDate}`;
  };
  const cardTitle = () => item.card?.title ?? "";
  return (() => {
    const _el$10 = _tmpl$510.cloneNode(true), _el$11 = _el$10.firstChild, _el$12 = _el$11.nextSibling, _el$13 = _el$12.nextSibling, _el$14 = _el$13.nextSibling, _el$15 = _el$14.nextSibling;
    insert(_el$11, cardTitle);
    insert(_el$13, fieldName);
    insert(_el$15, dateRange);
    return _el$10;
  })();
}
delegateEvents(["contextmenu", "click"]);

// public/app/apps/cards/common/timeline/components/providers.tsx
function NodeItemProvider(props2) {
  return createComponent(TimelineItemProvider, {
    get store() {
      return props2.store;
    },
    get children() {
      return props2.children;
    }
  });
}
function NodePeriodProvider(props2) {
  return createComponent(TimelinePeriodProvider, {
    get value() {
      return props2.store;
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/timeline/components/NodeTimelinePeriods.tsx
var _tmpl$61 = /* @__PURE__ */ template(`<div class="timeline-card-period"></div>`, 2);
var _tmpl$219 = /* @__PURE__ */ template(`<div class="timeline-card-content group"><div class="timeline-card-period"></div></div>`, 4);
function NodeTimelinePeriods(props2) {
  const itemStore = useTimelineItem();
  const period = TimelinePeriodStore4.create();
  createEffect(() => {
    const start = itemStore.start();
    const end = itemStore.end();
    const progress2 = itemStore.card.attributes.filter((attr) => attr.type === "progress" && attr.value > 0).reduce((max3, attr) => Math.max(max3, attr.value), 0);
    period.update({
      start,
      end,
      progress: progress2
    });
  });
  return [createComponent(TimelinePeriod, {
    store: period,
    "class": "children-period",
    get children() {
      const _el$ = _tmpl$219.cloneNode(true), _el$2 = _el$.firstChild;
      insert(_el$, createComponent(Show, {
        get when() {
          return period.progress;
        },
        get children() {
          const _el$3 = _tmpl$61.cloneNode(true);
          createRenderEffect((_p$) => {
            const _v$ = `${period.progress}%`, _v$2 = darkenColor("#354663", 10);
            _v$ !== _p$._v$ && _el$3.style.setProperty("width", _p$._v$ = _v$);
            _v$2 !== _p$._v$2 && _el$3.style.setProperty("background-color", _p$._v$2 = _v$2);
            return _p$;
          }, {
            _v$: void 0,
            _v$2: void 0
          });
          return _el$3;
        }
      }), null);
      return _el$;
    }
  }), createComponent(For, {
    get each() {
      return props2.periods;
    },
    children: (period2) => createComponent(NodePeriodProvider, {
      store: period2,
      get children() {
        return createComponent(NodeTimelinePeriod, {});
      }
    })
  })];
}

// public/app/apps/cards/common/ui/card-creator.tsx
var _tmpl$64 = /* @__PURE__ */ template(`<form tabindex="-1" class="card-creator flex-fill"><textarea class="form-control" autofocus></textarea><div class="card-creator-actions"><button type="submit" class="btn btn-success"></button></div></form>`, 8);
var CardCreatorStore = class extends BaseStore {
  canCreate = prop(false);
  isCreating = prop(false);
  groups = prop([]);
  project = useProject();
  onCanCreateCardChange = effect(() => this.canCreateCard(), "onCanCreateCardEffect");
  onCanCreateCardEffect(canCreate) {
    this.canCreate = canCreate;
  }
  createProvider() {
    return (props2) => CardCreatorContext.Provider({
      value: this,
      get children() {
        return props2.children;
      }
    });
  }
  canCreateCard() {
    const project = this.project();
    if (!project || project.is_archived || project.is_portfolio) {
      return false;
    }
    return this.groups.some((group2) => !group2.is_is_creation_hidden) && this.groups.every((group2) => canAddCard(project, group2 ? group2.id : null));
  }
};
var CardCreatorContext = createContext();
function useCardCreator() {
  return useContext(CardCreatorContext);
}
function CardCreator(props2) {
  let inputRef;
  const store2 = useCardCreator();
  const [value2, setValue2] = createSignal("");
  onMount(() => {
    inputRef.focus();
  });
  const onKeyDown = (event2) => {
    if (event2.key === "Enter") {
      event2.preventDefault();
      props2.onCreateCard({
        openModal: event2.ctrlKey,
        title: value2().trim()
      });
    }
    if (event2.key === " ") {
      event2.preventDefault();
      inputRef.value += " ";
    }
  };
  const onKeyUp = (event2) => {
    if (event2.key === "Escape") {
      store2.isCreating = false;
    }
  };
  const onSubmit = (event2) => {
    event2.preventDefault();
    props2.onCreateCard({
      openModal: false,
      title: value2().trim()
    });
  };
  const onCancel = () => store2.isCreating = false;
  return createComponent(ClickOutside, {
    onClickOutside: onCancel,
    get children() {
      const _el$ = _tmpl$64.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling, _el$4 = _el$3.firstChild;
      _el$.addEventListener("submit", onSubmit);
      _el$2.$$keyup = onKeyUp;
      _el$2.$$keydown = onKeyDown;
      _el$2.$$input = (e3) => setValue2(e3.currentTarget.value);
      const _ref$ = inputRef;
      typeof _ref$ === "function" ? use(_ref$, _el$2) : inputRef = _el$2;
      insert(_el$4, () => props2.label ?? _4("Add"));
      insert(_el$3, createComponent(IconButton, {
        "class": "cancel-button",
        icon: "bi-x-lg",
        onClick: onCancel
      }), null);
      createRenderEffect((_p$) => {
        const _v$ = props2.placeholder ?? _4("Name your new card"), _v$2 = !value2().trim();
        _v$ !== _p$._v$ && setAttribute(_el$2, "placeholder", _p$._v$ = _v$);
        _v$2 !== _p$._v$2 && (_el$4.disabled = _p$._v$2 = _v$2);
        return _p$;
      }, {
        _v$: void 0,
        _v$2: void 0
      });
      return _el$;
    }
  });
}
delegateEvents(["input", "keydown", "keyup"]);

// public/app/apps/cards/common/timeline/components/period.tsx
var _tmpl$65 = /* @__PURE__ */ template(`<section class="timeline-period-creator-context-menu"><header></header></section>`, 4);
var _tmpl$220 = /* @__PURE__ */ template(`<button class="btn flex-fill"></button>`, 2);
var _tmpl$313 = /* @__PURE__ */ template(`<button class="menu-item-main-action-button timeline-view-context-menu-item"><span class="timeline-view-menu-item-field-color" aria-hidden="true"></span><span class="menu-item-label"></span></button>`, 6);
var CardPeriodCreator = (props2) => {
  const timeline = useTimelineStore();
  const item = useTimelineItem();
  const dropState = new DropdownState();
  const newPeriod = TimelinePeriodStore4.create({
    isRange: true
  });
  const fields2 = createMemo(() => {
    const pIds = item.periods.map((p4) => p4.id);
    return item.fields()?.filter((f3) => !pIds.includes(f3.id));
  });
  const fieldComponents = () => {
    return fields2().map((field2) => () => createComponent(ExistingCardMenuItem, {
      fieldConfig: field2,
      onFieldSelection: (fieldId) => onFieldSelection(fieldId)
    }));
  };
  const onPeriodCreated = (field2) => {
    const modelAttr = field2.attr;
    const unit = precisionToTimeUnit[modelAttr.options.precision ?? "days"];
    newPeriod.start = moment_default(newPeriod.start).startOf(unit).toDate();
    newPeriod.end = moment_default(newPeriod.end).endOf(unit).toDate();
    if (field2.isMilestone) {
      newPeriod.start = newPeriod.end;
    }
    props2.onPeriodCreated?.(newPeriod);
    resetLocalPeriod();
  };
  const onCreatePeriod = (elt, period) => {
    const availableFields = fields2();
    const shouldCreatePeriodWithoutUserInput = availableFields.length === 1;
    if (newPeriod.start && newPeriod.end) {
      if (shouldCreatePeriodWithoutUserInput) {
        newPeriod.id = availableFields[0].id;
        newPeriod.name = availableFields[0].name;
        newPeriod.isMilestone = availableFields[0].isMilestone;
        newPeriod.isRange = availableFields[0].attr.options?.daterange ?? true;
        onPeriodCreated(availableFields[0]);
      } else {
        dropState.setTriggerRef(elt);
        dropState.open();
      }
    }
  };
  const onFieldSelection = (fieldId) => {
    newPeriod.id = fieldId;
    const _field = fields2().find((f3) => f3.id === fieldId);
    newPeriod.name = _field?.name;
    newPeriod.isMilestone = _field?.isMilestone;
    newPeriod.isRange = _field?.attr.options?.daterange ?? true;
    onPeriodCreated(_field);
    dropState.close();
  };
  const resetLocalPeriod = () => {
    newPeriod.update({
      id: void 0,
      name: void 0,
      start: void 0,
      end: void 0,
      isMilestone: false,
      isRange: true
    });
    newPeriod.isRange = true;
  };
  createEffect(on(() => fields2(), (availableFields) => {
    if (availableFields.length === 1) {
      newPeriod.isRange = availableFields[0].attr.options?.daterange ?? true;
    } else {
      newPeriod.isRange = true;
    }
  }));
  return createComponent(Show, {
    get when() {
      return fields2().length > 0;
    },
    get children() {
      return [createComponent(PeriodCreator, {
        newPeriod,
        onPeriodCreated: onCreatePeriod
      }), createComponent(DropdownContext.Provider, {
        value: dropState,
        get children() {
          return createComponent(DropdownContent, {
            onClose: resetLocalPeriod,
            get mount() {
              return timeline.viewport;
            },
            get children() {
              const _el$ = _tmpl$65.cloneNode(true), _el$2 = _el$.firstChild;
              insert(_el$2, () => _4("Choose a field to create a period"));
              insert(_el$, createComponent(Menu, {
                get each() {
                  return fieldComponents();
                },
                children: (field2) => createComponent(Dynamic, {
                  component: field2
                })
              }), null);
              return _el$;
            }
          });
        }
      })];
    }
  });
};
function ReferencedCardPeriodCreator(props2) {
  const board = useBoard();
  const planningConfig = usePlanningConfig();
  const item = useTimelineItem();
  const dropState = new DropdownState();
  const rootStore = item.getRoot();
  const cardCreatorStore = CardCreatorStore.create({
    groups: [rootStore.group]
  });
  const CardCreatorProvider = cardCreatorStore.createProvider();
  let newPeriod;
  const cards = () => {
    const _cards = planningConfig.getReferencedCards(item.card);
    return _cards.map((card) => {
      const color = cardModelStore.tryGet(card.model_id)?.card_color ?? "#fafafa";
      return {
        id: card.id,
        name: card.title,
        color
      };
    }).filter(Boolean).filter((f3) => !item.periods.find((p4) => p4.id === f3.id)).concat({
      isNewField: true
    });
  };
  const hasExistingCards = createMemo(() => cards().filter((c3) => !c3.isNewField).length > 0);
  const dropdownHeaderContent = createMemo(() => {
    if (hasExistingCards()) {
      return _4("Choose a referenced card or create a new one");
    }
    const relationGrp = planningConfig.relationAttrGroupMap()?.get(planningConfig.relationship);
    const modelName = relationGrp[0].options?.model?.name;
    if (!modelName) return _4("Create a card");
    return _4("Create a {type}", {
      type: modelName
    });
  });
  createEffect(on(() => dropState.isOpened(), (isOpened) => {
    if (isOpened && !hasExistingCards() && cardCreatorStore.canCreate) {
      cardCreatorStore.isCreating = true;
    }
  }));
  const onCreateCard = async (payload) => {
    cardCreatorStore.isCreating = false;
    const groups = [rootStore.group].filter((g3) => g3.id !== void 0);
    const staticGroups = groups.filter((g3) => !g3.is_dynamic);
    const dynamicGroups = groups.filter((g3) => g3.is_dynamic);
    const attr = planningConfig.dateAttrGroupMap()?.get(planningConfig.dateField);
    const cardModel = attr.model;
    const [, request2] = createCard(board, payload.title, staticGroups, cardModel);
    const card = await request2;
    dynamicGroups.forEach((group2) => group2.handleCardEnter(card, false));
    if (card) {
      const relationGrp = planningConfig.relationAttrGroupMap()?.get(planningConfig.relationship);
      await appendCardAttribute(item.card, relationGrp.id, card.id);
      onFieldSelection(card.id);
    }
  };
  let addCardBtnRef;
  createEffect(on(() => cardCreatorStore.isCreating, (isCreating, wasCreating) => {
    if (!isCreating && wasCreating && addCardBtnRef) {
      addCardBtnRef.focus();
    }
  }));
  const fieldComponents = () => {
    return cards().map((field2) => field2.isNewField ? () => createComponent(CardCreatorProvider, {
      get children() {
        return [createComponent(Show, {
          get when() {
            return cardCreatorStore.canCreate && !cardCreatorStore.isCreating;
          },
          get children() {
            const _el$3 = _tmpl$220.cloneNode(true);
            _el$3.$$click = () => cardCreatorStore.isCreating = true;
            const _ref$ = addCardBtnRef;
            typeof _ref$ === "function" ? use(_ref$, _el$3) : addCardBtnRef = _el$3;
            insert(_el$3, () => _4("Add card"));
            return _el$3;
          }
        }), createComponent(Show, {
          get when() {
            return cardCreatorStore.isCreating;
          },
          get children() {
            return createComponent(CardCreator, {
              onCreateCard,
              get label() {
                return _4("Create");
              }
            });
          }
        })];
      }
    }) : () => createComponent(ExistingCardMenuItem, {
      fieldConfig: field2,
      onFieldSelection: (fieldId) => onFieldSelection(fieldId)
    }));
  };
  const onCreatePeriod = (elt, period) => {
    newPeriod = period;
    if (newPeriod.start && newPeriod.end) {
      dropState.setTriggerRef(elt);
      dropState.open();
    }
  };
  const onFieldSelection = (fieldId) => {
    newPeriod.id = fieldId;
    const _field = cards().find((f3) => f3.id === fieldId);
    newPeriod.name = _field?.name;
    const card = cardStore.tryGet(newPeriod.id);
    const attrs2 = cardModelStore.getCardAvailableAttributes(card, {
      type: "date",
      name: planningConfig.dateField
    });
    if (attrs2.length === 0) return;
    const modelAttr = attrs2[0];
    const unit = precisionToTimeUnit[modelAttr.options.precision ?? "days"];
    newPeriod.isRange = modelAttr.options?.daterange ?? true;
    newPeriod.start = moment_default(newPeriod.start).startOf(unit).toDate();
    newPeriod.end = moment_default(newPeriod.end).endOf(unit).toDate();
    props2.onPeriodCreated?.(newPeriod);
    dropState.close();
    resetLocalPeriod();
  };
  const resetLocalPeriod = () => {
    if (!newPeriod) return;
    newPeriod.update({
      id: void 0,
      name: void 0,
      start: void 0,
      end: void 0,
      isRange: true
    });
    newPeriod = void 0;
  };
  return createComponent(Show, {
    get when() {
      return cards().length > 0;
    },
    get children() {
      return [createComponent(PeriodCreator, {
        onPeriodCreated: onCreatePeriod
      }), createComponent(DropdownContext.Provider, {
        value: dropState,
        get children() {
          return createComponent(DropdownContent, {
            onClose: resetLocalPeriod,
            get children() {
              const _el$4 = _tmpl$65.cloneNode(true), _el$5 = _el$4.firstChild;
              insert(_el$5, dropdownHeaderContent);
              insert(_el$4, createComponent(Menu, {
                get each() {
                  return fieldComponents();
                },
                children: (field2) => createComponent(Dynamic, {
                  component: field2
                })
              }), null);
              return _el$4;
            }
          });
        }
      })];
    }
  });
}
function ExistingCardMenuItem(props2) {
  return (() => {
    const _el$6 = _tmpl$313.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.nextSibling;
    _el$6.$$click = () => props2.onFieldSelection(props2.fieldConfig.id);
    _el$6.style.setProperty("flex", "1 1 auto");
    insert(_el$8, () => props2.fieldConfig.name);
    createRenderEffect(() => _el$7.style.setProperty("background", props2.fieldConfig.color));
    return _el$6;
  })();
}
delegateEvents(["click"]);

// public/app/apps/cards/common/timeline/timeline-utils/ui.ts
var import_tinycolor27 = __toESM(require_tinycolor());
function useTimelineHeaderToggleIcon() {
  const store2 = useTimelineItem();
  return () => store2?.visibleChild ? "bi-dash-square-dotted" : "bi-plus-square-dotted";
}
function useTimelineItemColor() {
  const store2 = useTimelineItem();
  const bg = createMemo(() => {
    let color;
    if (store2.card) {
      const model = cardModelStore.getCardModel(store2.card);
      const project = projectStore.tryGetForCard(store2.card, true);
      color = cardModelStore.getExtendedModelProp(model, project, "card_color");
    }
    if (!color) return "rgb(255, 255, 255)";
    const tc = (0, import_tinycolor27.default)(color);
    tc.setAlpha(0.2);
    return tc.toRgbString();
  });
  const text3 = createMemo(() => textColor(bg()));
  return { bg, text: text3 };
}
function useTimelineItemIndentation() {
  const store2 = useTimelineItem();
  return () => (store2.path.length - 1) * 16;
}
function useTimelineItemFontWeight() {
  const store2 = useTimelineItem();
  return () => store2.children?.length > 0 ? "bold" : "thin";
}
function useTimelineItemChildren() {
  const store2 = useTimelineItem();
  return () => store2.children;
}
function useTimelineItemToggleChildrenVisibility() {
  const store2 = useTimelineItem();
  return (event2) => {
    event2.stopPropagation();
    store2.visibleChild = !store2.visibleChild;
  };
}

// public/app/apps/cards/common/timeline/components/SidebarAddCard.tsx
var _tmpl$66 = /* @__PURE__ */ template(`<button class="btn flex-fill"></button>`, 2);
var _tmpl$221 = /* @__PURE__ */ template(`<div class="timeline-card-creator-wrapper"></div>`, 2);
function SidebarAddCard() {
  const options2 = useAppOptions();
  const board = useBoard();
  const timelineViewContext = useTimelineViewContext();
  const rootStore = useTimelineItem();
  const store2 = CardCreatorStore.create({
    groups: [rootStore.group]
  });
  const CardCreatorProvider = store2.createProvider();
  createEffect(on(() => [store2.canCreate, store2.isCreating], ([canCreate, isCreating]) => {
    rootStore.update({
      canCreateCard: canCreate,
      isCreatingCard: isCreating
    });
  }));
  const onCreateCard = async (payload) => {
    store2.isCreating = false;
    const groups = [rootStore.group].filter((g3) => g3.id !== void 0);
    const staticGroups = groups.filter((g3) => !g3.is_dynamic);
    const dynamicGroups = groups.filter((g3) => g3.is_dynamic);
    const [, request2] = createManyCards(board, payload.title, staticGroups);
    const cards = await request2;
    cards.forEach((card) => dynamicGroups.forEach((group2) => group2.handleCardEnter(card, false)));
    if (payload.openModal && cards.length > 0) {
      timelineViewContext.cardModal?.open(cards[0], {
        parentSelector: null,
        showArchived: options2.include_archived
      });
    }
  };
  return (() => {
    const _el$ = _tmpl$221.cloneNode(true);
    insert(_el$, createComponent(CardCreatorProvider, {
      get children() {
        return [createComponent(Show, {
          get when() {
            return store2.canCreate && !store2.isCreating;
          },
          get children() {
            const _el$2 = _tmpl$66.cloneNode(true);
            _el$2.$$click = () => store2.isCreating = true;
            insert(_el$2, () => _4("Add card"));
            return _el$2;
          }
        }), createComponent(Show, {
          get when() {
            return store2.isCreating;
          },
          get children() {
            return createComponent(CardCreator, {
              onCreateCard
            });
          }
        })];
      }
    }));
    return _el$;
  })();
}
delegateEvents(["click"]);

// public/app/apps/cards/common/timeline/components/EmptyTimelineRow.tsx
var _tmpl$67 = /* @__PURE__ */ template(`<div class="timeline-sticky-sidebar no-border-bottom"></div>`, 2);
function EmptyTimelineRow() {
  const options2 = useAppOptions();
  return createComponent(TimelineRow, {
    "class": "empty-row",
    get displayAllItems() {
      return options2.displayAllItems;
    },
    get children() {
      const _el$ = _tmpl$67.cloneNode(true);
      insert(_el$, createComponent(SidebarAddCard, {}));
      return _el$;
    }
  });
}

// public/app/apps/cards/common/timeline/components/RootNodeTimelineItem.tsx
var _tmpl$68 = /* @__PURE__ */ template(`<div class="timeline-sticky-sidebar"><div class="gantt-sidebar_group-header root"><div class="title"><span class="title-text"></span></div></div></div>`, 8);
var _tmpl$222 = /* @__PURE__ */ template(`<div></div>`, 2);
function RootNodeTimelineItem(props2) {
  let ref;
  const timelineView = useTimelineViewContext();
  const timelineStore = useTimelineStore();
  const itemStore = useTimelineItem();
  const options2 = useAppOptions();
  const relationShip = useRelationShip();
  const toggleIcon = useTimelineHeaderToggleIcon();
  const toggleChildrenVisibility = useTimelineItemToggleChildrenVisibility();
  onMount(() => {
    timelineStore.setState("nbRows", (prev) => prev + 1);
  });
  createResizeObserver(() => ref, (size4) => {
    itemStore.groupHeight = size4.height;
  });
  const visibleChildren = createMemo(() => itemStore.children.filter((child) => (child.matchingFilter || child.hasChildrenMatchingFilter) && (child.hasActiveDateField || child.hasChildWithActiveDateField)));
  createEffect(on(() => itemStore.groupHeight, () => {
    if (relationShip) {
      relationShip.dirty = true;
      setTimeout(() => {
        relationShip.dirty = false;
      });
    }
  }));
  onCleanup(() => {
    timelineStore.setState("nbRows", (prev) => prev - 1);
  });
  return (() => {
    const _el$ = _tmpl$222.cloneNode(true);
    const _ref$ = ref;
    typeof _ref$ === "function" ? use(_ref$, _el$) : ref = _el$;
    insert(_el$, createComponent(Show, {
      get when() {
        return !options2.hideEmptyGroups || visibleChildren().length > 0;
      },
      get children() {
        return [createComponent(Show, {
          get when() {
            return !timelineView.groupByUngrouped();
          },
          get children() {
            return createComponent(TimelineRow, {
              "class": "empty-row",
              get displayAllItems() {
                return options2.displayAllItems;
              },
              get children() {
                const _el$2 = _tmpl$68.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.firstChild;
                insert(_el$4, createComponent(Show, {
                  get when() {
                    return visibleChildren().length > 0;
                  },
                  get children() {
                    return createComponent(IconButton, {
                      "class": "toggle-button",
                      get icon() {
                        return toggleIcon();
                      },
                      onClick: toggleChildrenVisibility
                    });
                  }
                }), _el$5);
                insert(_el$5, () => itemStore.title);
                return _el$2;
              }
            });
          }
        }), createComponent(Show, {
          get when() {
            return itemStore.visibleChild;
          },
          get children() {
            return createComponent(VirtualContainer, {
              "class": "timeline-root-group",
              get items() {
                return visibleChildren();
              },
              initialAverageItemHeight: 38,
              get suffixComponent() {
                return createComponent(Show, {
                  get when() {
                    return createMemo(() => visibleChildren().length > 0)() && isOnline();
                  },
                  get children() {
                    return createComponent(EmptyTimelineRow, {});
                  }
                });
              },
              children: (childStore, _5, i3) => createComponent(NodeItemProvider, {
                store: childStore,
                get children() {
                  return props2.children?.(i3());
                }
              })
            });
          }
        })];
      }
    }));
    return _el$;
  })();
}

// public/app/apps/cards/common/timeline/components/SidebarHeader.tsx
var _tmpl$69 = /* @__PURE__ */ template(`<div class="timeline-sticky-sidebar-header"><div class="timeline-sidebar_header gantt"></div></div>`, 4);
var _tmpl$223 = /* @__PURE__ */ template(`<br>`, 1);
var _tmpl$314 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$412 = /* @__PURE__ */ template(`<section class="timeline-sidebar_header-info"><h1></h1><p><span></span></p></section>`, 8);
function SidebarHeader() {
  let triggerRef;
  const dropState = new DropdownState();
  createEventListener(() => dropState.isOpened() ? triggerRef : void 0, "mouseleave", () => {
    dropState.close();
  });
  const isLoading = createMemo(() => {
    let loading = false;
    return loading;
  });
  return (() => {
    const _el$ = _tmpl$69.cloneNode(true), _el$2 = _el$.firstChild;
    insert(_el$2, createComponent(Show, {
      get when() {
        return isLoading();
      },
      get children() {
        return createComponent(LoadingIndicator, {});
      }
    }), null);
    insert(_el$2, createComponent(Dropdown, {
      state: dropState,
      get children() {
        return [createComponent(DropdownTrigger, {
          get children() {
            return createComponent(IconButton, {
              ref(r$) {
                const _ref$ = triggerRef;
                typeof _ref$ === "function" ? _ref$(r$) : triggerRef = r$;
              },
              onMouseEnter: () => dropState.open(),
              type: "button",
              style: "info",
              icon: "bi-info-circle"
            });
          }
        }), createComponent(DropdownContent, {
          placement: "bottom",
          get children() {
            return createComponent(SidebarHeaderContent, {});
          }
        })];
      }
    }), null);
    return _el$;
  })();
}
function SidebarHeaderContent() {
  let contentRef;
  const groups = useTimelineGroups();
  const total = createMemo(() => {
    return groups().reduce((acc, group2) => acc + group2.deepCount, 0);
  });
  const visibleCount = createMemo(() => groups().reduce((acc, group2) => acc + group2.matchingFilterDeepCount, 0));
  const activeDateCount = createMemo(() => groups().reduce((acc, group2) => acc + group2.activeDateFieldDeepCount, 0));
  return (() => {
    const _el$3 = _tmpl$412.cloneNode(true), _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling, _el$6 = _el$5.firstChild;
    const _ref$2 = contentRef;
    typeof _ref$2 === "function" ? use(_ref$2, _el$3) : contentRef = _el$3;
    insert(_el$4, () => _4("View infos"));
    insert(_el$5, createComponent(Show, {
      get when() {
        return visibleCount() > 0;
      },
      get children() {
        return [",", _tmpl$223.cloneNode(true), (() => {
          const _el$8 = _tmpl$314.cloneNode(true);
          createRenderEffect(() => _el$8.innerHTML = _n("<span>{visibleCount}</span> card matching current filter", "<span>{visibleCount}</span> cards matching current filter", visibleCount(), {
            visibleCount: visibleCount()
          }));
          return _el$8;
        })()];
      }
    }), null);
    insert(_el$5, createComponent(Show, {
      get when() {
        return activeDateCount() > 0;
      },
      get children() {
        return [",", _tmpl$223.cloneNode(true), (() => {
          const _el$10 = _tmpl$314.cloneNode(true);
          createRenderEffect(() => _el$10.innerHTML = _n("<span>{activeDateCount}</span> card matching the configuration", "<span>{activeDateCount}</span> cards matching the configuration", activeDateCount(), {
            activeDateCount: activeDateCount()
          }));
          return _el$10;
        })()];
      }
    }), null);
    createRenderEffect(() => _el$6.innerHTML = _n("<span>{total}</span> card", "<span>{total}</span> cards", total(), {
      total: total()
    }));
    return _el$3;
  })();
}

// public/app/apps/cards/common/timeline/constants.ts
var nullColor = "#fafafa";
var nullColors = {
  relationship: "#c2c2c2"
};
var DEFAULT_COLORS = {
  date: nullColor,
  milestone: nullColor,
  dependency: nullColors.relationship
};

// public/app/apps/cards/common/timeline/EventProvider.tsx
var EventContext = createContext();
function useEvent() {
  return useContext(EventContext);
}
function EventProvider(props2) {
  const [state, setState] = createStore({
    allCardsCollapsed: false
  });
  function handleMaximize() {
    setState("allCardsCollapsed", false);
  }
  function handleMinimize() {
    setState("allCardsCollapsed", true);
  }
  onMount(() => {
    window.addEventListener("maximizeAllCards", handleMaximize);
    window.addEventListener("minimizeAllCards", handleMinimize);
    onCleanup(() => {
      window.removeEventListener("maximizeAllCards", handleMaximize);
      window.removeEventListener("minimizeAllCards", handleMinimize);
    });
  });
  return createComponent(EventContext.Provider, {
    value: state,
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/common/timeline/stores/card-timeline-item.ts
var CARD_SHOW_CHILDREN_KEY_PATTERN = "project-gantt-card.<view>.<project>.<id>.show-children";
var getJsonKey = (id, project, view) => CARD_SHOW_CHILDREN_KEY_PATTERN.replace("<id>", `${id}`).replace("<project>", project).replace("<view>", view);
var CardTimelineItemStore = class extends TimelineItemStore2 {
  constructor() {
    super(...arguments);
    this.card = prop();
    this.children = prop([]);
    this.group = prop();
    this.canCreateCard = prop();
    this.isCreatingCard = prop();
    this.childrenLoader = prop();
    this.isCritical = prop(false);
    this.context = useTimelineViewContext();
    this.project = useProject();
    this.relationShip = useRelationShip();
    this.cardCompareFunction = useCardCompareFunction();
    this.windowEvents = useEvent();
    this.options = useAppOptions();
    this.scopedModelStore = useScopedModelStore();
    this.scopedGroupTypeStore = useScopedGroupTypeStore();
  }
  get hasActiveDateField() {
    console.log(
      "warning: hasActiveDateField is not implemented in CardTimelineItemStore"
    );
    return true;
  }
  get hasChildWithActiveDateField() {
    return this.children.some(
      (child) => child.hasActiveDateField || child.hasChildWithActiveDateField
    );
  }
  get matchingFilter() {
    const ids = this.context.matchingCardIds();
    return (
      // if no ids are provided, show all cards
      ids == null || // if no card is provided, it means we are in the root
      !this.card || // if the card is in the list of ids, show it
      this.card && ids !== null && ids.includes(this.card.id)
    );
  }
  get hasChildrenMatchingFilter() {
    return this.children.some(
      (child) => child.matchingFilter || child.hasChildrenMatchingFilter
    );
  }
  get deepCount() {
    const initialCount = !this.card ? 0 : 1;
    if (this.children.length === 0) return initialCount;
    return this.children.reduce(
      (count, child) => count + child.deepCount,
      initialCount
    );
  }
  get matchingFilterDeepCount() {
    const initialCount = !this.card ? 0 : 1;
    return this.children.reduce(
      (count, child) => count + child.matchingFilterDeepCount,
      this.matchingFilter ? initialCount : 0
    );
  }
  get matchingFilterChildrenCount() {
    return this.children.reduce(
      (count, child) => count + (child.matchingFilter ? 1 : 0),
      0
    );
  }
  get activeDateFieldDeepCount() {
    const initialCount = !this.card ? 0 : 1;
    return this.children.reduce(
      (count, child) => count + child.activeDateFieldDeepCount,
      this.hasActiveDateField ? initialCount : 0
    );
  }
  onInit() {
    const children2 = this.childrenLoader();
    const root3 = this.getRoot();
    createEffect(
      on(
        () => children2(),
        (children3) => {
          batch(() => {
            const result2 = [];
            children3.forEach((card, index2) => {
              const id = card.id;
              let childStore = getTimelineItemStoreFromWeakMap(
                card,
                root3.group.id
              );
              if (!childStore) {
                childStore = this.context.timelineItemCreateFn(
                  {
                    card,
                    id,
                    title: card.title,
                    parent: this,
                    childrenLoader: () => {
                      return cardStore.scopedByParent({ id }).react({}, () => {
                        if (this.options.sort_by) {
                          return {
                            sortBy: getCardCompareFunc(this.options.sort_by, {
                              modelStore: this.scopedModelStore(),
                              groupTypeStore: this.scopedGroupTypeStore()
                            })
                          };
                        }
                        return {
                          sortBy: "meta:position",
                          cmpFunc: defaultCardCompareFunc
                        };
                      });
                    }
                  },
                  this.owner
                );
                setTimelineItemStoreToWeakMap(card, root3.group.id, childStore);
              }
              childStore.index = index2;
              childStore.position = index2;
              result2.push(childStore);
            });
            this.children = result2;
          });
        }
      )
    );
    const storageKey = getJsonKey(
      this.id,
      this.project()?.id,
      this.options.name
    );
    const visibleChild = jsonLocalStorage.getItem(storageKey) ?? true;
    this.visibleChild = visibleChild;
    createEffect(
      on(
        () => this.visibleChild,
        (visible) => {
          try {
            requestIdleCallback(() => {
              jsonLocalStorage.setItem(storageKey, visible);
            });
          } catch (error2) {
            jsonLocalStorage.setItem(storageKey, visible);
          }
        },
        { defer: true }
      )
    );
    createEffect(
      on(
        () => [this.windowEvents.allCardsCollapsed],
        ([collapsed]) => {
          for (const child of this.children) {
            child.visibleChild = !collapsed;
          }
        }
      )
    );
    onCleanup(() => {
      if (this.card) {
        deleteTimelineItemStoreFromWeakMap(this.card, root3.group.id);
        this.relationShip?.clear(this.card.id);
      }
    });
  }
};

// public/app/apps/cards/common/timeline/stores/CardCreator.ts
var CardCreatorContext2 = createContext();

// public/app/apps/cards/common/timeline/stores/CriticalPath.ts
var CriticalPathContext = createContext();
function CriticalPathProvider(props2) {
  const options2 = useAppOptions();
  const groups = useTimelineGroups();
  const timelineStore = useTimelineStore();
  const relationShip = useRelationShip();
  const latestPeriods = createMemo(() => {
    const precision = timelineStore.visibleDays < timelineStore.visibleDayBreakpoint ? void 0 : "date";
    return groups().reduce((latests, group2) => {
      const groupLatests = group2.latestPeriods();
      for (const groupLatest of groupLatests) {
        if (latests.length === 0) {
          latests.push(groupLatest);
          continue;
        }
        const diff = compareDates(latests[0]?.end, groupLatest?.end, precision);
        if (diff < 0) {
          latests = [groupLatest];
        } else if (diff === 0) {
          latests.push(groupLatest);
        }
      }
      return latests;
    }, []);
  });
  const criticalItems = () => {
    const result2 = [];
    for (const latest of latestPeriods()) {
      result2.push(latest.parent);
    }
    return result2;
  };
  const criticalPaths = createMemo(
    () => {
      return criticalItems().map((item) => {
        const path = getCriticalPath(relationShip.relations, item);
        return path;
      });
    },
    [],
    {
      equals(prev, next2) {
        if (prev.length !== next2.length) return false;
        for (let i3 = 0; i3 < prev.length; i3++) {
          const prevPath = prev[i3];
          const nextPath = next2[i3];
          if (prevPath.length !== nextPath.length) return false;
          for (let j = 0; j < prevPath.length; j++) {
            if (prevPath[j].id !== nextPath[j].id) return false;
          }
        }
        return true;
      }
    }
  );
  createEffect(
    on(
      () => [criticalPaths(), options2.displayCriticalPath],
      ([paths, displayCriticalPath], previous) => {
        const previousCriticalPaths = previous?.[0] || [];
        const previousCriticalItems = previousCriticalPaths.flat();
        for (const item of previousCriticalItems) {
          item.isCritical = false;
        }
        if (!displayCriticalPath) return;
        for (const path of paths) {
          for (const item of path) {
            item.isCritical = true;
          }
        }
      }
    )
  );
  return CriticalPathContext.Provider({
    value: void 0,
    get children() {
      return props2.children;
    }
  });
}
function getCriticalPath(relations, currentCriticalItem) {
  const predecessors = /* @__PURE__ */ new Map();
  for (const relation of relations) {
    const startItem = relation.start;
    const endItem = relation.end;
    if (!predecessors.has(endItem.id)) {
      predecessors.set(endItem.id, []);
    }
    predecessors.get(endItem.id).push(startItem);
  }
  function findPath(item, visited = /* @__PURE__ */ new Set()) {
    if (visited.has(item.id)) {
      return [];
    }
    visited.add(item.id);
    const itemPredecessors = predecessors.get(item.id) || [];
    if (itemPredecessors.length === 0) {
      return [item];
    }
    let longestPath = [];
    for (const predecessorItem of itemPredecessors) {
      const newVisited = new Set(visited);
      const path = findPath(predecessorItem, newVisited);
      if (path.length > longestPath.length) {
        longestPath = path;
      }
    }
    return [...longestPath, item];
  }
  return findPath(currentCriticalItem);
}

// public/app/apps/cards/common/timeline/TimelineAppOptions.ts
var TimelineAppOptions = class extends AppOptions {
  constructor() {
    super(...arguments);
    this.enableSideDisplay = prop(false);
    this.displayCriticalPath = prop(false);
    this.period = prop(
      formatPeriodToString(DEFAULT_PERIOD)
    );
    this.displayCardTitle = prop(DisplayCardTitle.NONE);
    this.displayPeriodTitle = prop(
      DisplayPeriodTitle.NONE
    );
    this.displayDensity = prop(DisplayDensity.NORMAL);
    /** @deprecated Kept for migration only */
    this.dateFields = prop([]);
    /** @deprecated Kept for migration only */
    this.milestoneFields = prop([]);
    /** @deprecated Kept for migration only */
    this.relationshipFields = prop([]);
  }
};
var PlanningAppOptions = class extends TimelineAppOptions {
  constructor() {
    super(...arguments);
    this.relationship = prop(null);
    this.dateField = prop(null);
  }
};

// public/app/ui/base/form/fields/color-field.tsx
var _tmpl$70 = /* @__PURE__ */ template(`<div class="form-group"><label class="form-label"></label></div>`, 4);
function ColorField(props2) {
  const [local, input] = splitProps(props2, ["label", "allowCardColor"]);
  const form = useForm();
  const field2 = useField();
  const onChange = (val) => form.updateField(field2.valuePath, val);
  return (() => {
    const _el$ = _tmpl$70.cloneNode(true), _el$2 = _el$.firstChild;
    insert(_el$2, () => local.label);
    insert(_el$, createComponent(ColorInput, mergeProps(input, {
      get id() {
        return field2.valuePath;
      },
      get name() {
        return field2.valuePath;
      },
      get value() {
        return field2.state?.value ?? null;
      },
      onColorChange: onChange,
      get allowCardColor() {
        return local.allowCardColor;
      }
    })), null);
    createRenderEffect(() => setAttribute(_el$2, "for", field2.valuePath));
    return _el$;
  })();
}

// public/app/ui/base/forms/intputs/select-input.tsx
var _tmpl$71 = /* @__PURE__ */ template(`<option value=""></option>`, 2);
var _tmpl$224 = /* @__PURE__ */ template(`<select class="form-select"></select>`, 2);
var _tmpl$315 = /* @__PURE__ */ template(`<option></option>`, 2);
function SelectInput(props2) {
  const [local, theme2, select3] = splitProps(props2, ["withDefault", "options", "selected"], ["classList"]);
  const classList2 = () => theme2.classList ?? {};
  return (() => {
    const _el$ = _tmpl$224.cloneNode(true);
    spread(_el$, mergeProps({
      get classList() {
        return classList2();
      }
    }, select3), false, true);
    insert(_el$, createComponent(Show, {
      get when() {
        return !!local.withDefault;
      },
      get children() {
        const _el$2 = _tmpl$71.cloneNode(true);
        insert(_el$2, (() => {
          const _c$ = createMemo(() => typeof local.withDefault === "boolean");
          return () => _c$() ? _4("Default") : local.withDefault;
        })());
        return _el$2;
      }
    }), null);
    insert(_el$, createComponent(For, {
      get each() {
        return local.options;
      },
      children: (option2) => (() => {
        const _el$3 = _tmpl$315.cloneNode(true);
        insert(_el$3, () => option2.label);
        createRenderEffect(() => _el$3.selected = local.selected === option2.value);
        createRenderEffect(() => _el$3.value = option2.value);
        return _el$3;
      })()
    }), null);
    return _el$;
  })();
}

// public/app/ui/base/form/fields/select-field.tsx
var _tmpl$74 = /* @__PURE__ */ template(`<div class="form-group"></div>`, 2);
function SelectField(props2) {
  const [local, input] = splitProps(props2, ["label", "srLabel"]);
  const form = useForm();
  const field2 = useField();
  const label = () => local.label ?? local.srLabel;
  const onChange = (val) => {
    form.updateField(field2.valuePath, val);
  };
  return (() => {
    const _el$ = _tmpl$74.cloneNode(true);
    insert(_el$, createComponent(InputLabel, {
      get ["for"]() {
        return field2.valuePath;
      },
      get classList() {
        return {
          "sr-only": !!local.srLabel
        };
      },
      get children() {
        return label();
      }
    }), null);
    insert(_el$, createComponent(SelectInput, mergeProps(input, {
      get id() {
        return field2.valuePath;
      },
      get name() {
        return field2.valuePath;
      },
      get selected() {
        return field2.state?.value;
      },
      onChange: (e3) => onChange(e3.target.value)
    })), null);
    return _el$;
  })();
}

// public/app/apps/cards/common/ui/card-attribute-select.tsx
var _tmpl$75 = /* @__PURE__ */ template(`<button class="form-select card-attribute-select-trigger" type="button"></button>`, 2);
var _tmpl$225 = /* @__PURE__ */ template(`<ul class="card-attribute-select-content"><li class="card-attribute-select-section"><p class="card-attribute-select-section-title sr-only"></p><ul></ul></li></ul>`, 8);
var _tmpl$316 = /* @__PURE__ */ template(`<li class="card-attribute-select-section"><p class="card-attribute-select-section-title"></p><ul></ul></li>`, 6);
var _tmpl$413 = /* @__PURE__ */ template(`<p class="card-attribute-select-option-tooltip-content"><br></p>`, 3);
var _tmpl$511 = /* @__PURE__ */ template(`<li class="card-attribute-select-option"><button type="button"><span class="card-attribute-select-option-content"><span class="card-attribute-select-option-label"></span></span></button></li>`, 8);
var _tmpl$610 = /* @__PURE__ */ template(`<li class="card-attribute-select-option card-attribute-select-new-option"></li>`, 2);
var _tmpl$76 = /* @__PURE__ */ template(`<button type="button"><span class="card-attribute-select-option-content"><span class="card-attribute-select-option-label"></span></span></button>`, 6);
var _tmpl$84 = /* @__PURE__ */ template(`<form class="card-attribute-select-new-option-form"><input type="text" name="card-attribute-select-new-option-name" required><div><button type="submit"></button><button type="button"></button></div></form>`, 9);
function getModels(attr, scopedModel) {
  const models = [...attr.entries()].map(([_5, attr2]) => ({
    name: attr2.model_name,
    id: attr2.model_id,
    isWorkspace: attr2.model_is_base === "project"
  }));
  if (scopedModel !== void 0 && scopedModel.base_model_type !== "project") {
    return models.filter((model) => model.isWorkspace || model.id === scopedModel.id);
  }
  return models;
}
function CardAttributeSelect(props2) {
  const modelApi = useModelApi();
  const dropdown = new DropdownState();
  const attrs2 = useAvailableAttributesOfType(() => props2.fieldType, () => props2.typeHint, true);
  const options2 = createMemo(() => {
    return [...attrs2()].map(([name2, attrGroup]) => {
      return {
        label: name2,
        value: name2,
        id: attrGroup[0]?.id,
        icon: attrGroup.icon,
        models: getModels(attrGroup, props2.model)
      };
    });
  });
  const availableOptions = createMemo(() => {
    return options2().filter((opt) => props2.selected === opt.value || !props2.excludedOptions?.includes(opt.value));
  });
  const availableOptionsGroupByModel = createMemo(() => {
    const opts = availableOptions();
    const grouped = /* @__PURE__ */ new Map();
    opts.forEach((opt) => {
      opt.models.forEach((model) => {
        const group2 = grouped.get(model.name) ?? [];
        group2.push(opt);
        grouped.set(model.name, group2);
      });
    });
    return [...grouped.entries()].map(([model, options3]) => ({
      options: options3,
      label: model
    }));
  });
  const selectedAttr = createMemo(() => {
    const opts = options2();
    const selected = opts.find((opt) => opt.value === props2.selected);
    return selected?.label ?? props2.placeholder;
  });
  const onSelect = (option2) => {
    props2.onChange?.(option2);
    dropdown.close();
  };
  const onAddNewOption = async (name2) => {
    const type = props2.fieldTypeForNew ?? (Array.isArray(props2.fieldType) ? props2.fieldType[0] : props2.fieldType);
    const opts = props2.newOptionAttributeOptions?.() ?? {};
    await modelApi.createAttribute(props2.model, {
      name: name2,
      type,
      options: opts
    }, null);
    const opt = options2().find((o3) => o3.value === name2);
    if (opt) {
      onSelect(opt);
    }
  };
  const [focusedIndex, setFocusedIndex] = createSignal(0);
  const flattenedCount = createMemo(() => {
    return availableOptionsGroupByModel().reduce((acc, {
      options: options3
    }) => acc + options3.length, 0);
  });
  const groupOffsets = createMemo(() => {
    let sum = 0;
    const offsets = [];
    availableOptionsGroupByModel().forEach(({
      options: options3
    }) => {
      offsets.push(sum);
      sum += options3.length;
    });
    return offsets;
  });
  createEffect(on(() => [availableOptionsGroupByModel(), props2.selected], ([groups, selected]) => {
    let idx = 0;
    let found2 = false;
    for (const group2 of groups) {
      for (const opt of group2.options) {
        if (opt.value === selected) {
          found2 = true;
          break;
        }
        idx++;
      }
      if (found2) break;
    }
    if (found2) {
      setFocusedIndex(idx);
    }
  }));
  const onKeyDown = (e3) => {
    const size4 = flattenedCount() + 1;
    if (e3.key === "ArrowDown") {
      e3.preventDefault();
      setFocusedIndex((i3) => (i3 + 1) % size4);
    } else if (e3.key === "ArrowUp") {
      e3.preventDefault();
      setFocusedIndex((i3) => (i3 - 1 + size4) % size4);
    }
  };
  const isDisabled = createMemo(() => {
    return props2.model === void 0;
  });
  return createComponent(Dropdown, {
    state: dropdown,
    get children() {
      return [createComponent(DropdownTrigger, {
        get children() {
          const _el$ = _tmpl$75.cloneNode(true);
          insert(_el$, selectedAttr);
          createRenderEffect(() => _el$.disabled = isDisabled());
          return _el$;
        }
      }), createComponent(DropdownContent, {
        disableArrow: true,
        get children() {
          return createComponent(ScrollContainer, {
            "class": "card-attribute-select-scroll-container",
            get children() {
              const _el$2 = _tmpl$225.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling;
              _el$2.$$keydown = onKeyDown;
              insert(_el$2, createComponent(For, {
                get each() {
                  return availableOptionsGroupByModel();
                },
                children: ({
                  label,
                  options: options3
                }, grpIndex) => (() => {
                  const _el$6 = _tmpl$316.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.nextSibling;
                  insert(_el$7, label);
                  insert(_el$8, createComponent(For, {
                    each: options3,
                    children: (option2, index2) => createComponent(SelectOption, {
                      option: option2,
                      onSelect,
                      get selected() {
                        return option2.value === props2.selected;
                      },
                      get focus() {
                        return groupOffsets()[grpIndex()] + index2() === focusedIndex();
                      }
                    })
                  }));
                  return _el$6;
                })()
              }), _el$3);
              insert(_el$4, () => _4("Create a new field"));
              insert(_el$5, createComponent(SelectNewOption, {
                onAdd: onAddNewOption,
                get label() {
                  return props2.newOptionLabel;
                },
                get placeholder() {
                  return props2.newOptionPlaceholder;
                },
                get focus() {
                  return flattenedCount() === focusedIndex();
                }
              }));
              return _el$2;
            }
          });
        }
      })];
    }
  });
}
function handleFocus(elt, focus2) {
  const [ready, setReady] = createSignal(false);
  onMount(() => setReady(true));
  const shouldFocus = createMemo(() => focus2() && ready());
  createEffect(() => {
    if (elt() && shouldFocus()) {
      elt().focus();
    }
  });
}
function SelectOption(props2) {
  let ref;
  handleFocus(() => ref, () => props2.focus);
  const showHelp = () => props2.option.models.length > 1;
  const TooltipCmp = () => (() => {
    const _el$9 = _tmpl$413.cloneNode(true), _el$10 = _el$9.firstChild;
    insert(_el$9, () => _4("Found in {count} card types:", {
      count: props2.option.models.length
    }), _el$10);
    insert(_el$9, () => props2.option.models.map((model) => model.name).join(", "), null);
    return _el$9;
  })();
  return (() => {
    const _el$11 = _tmpl$511.cloneNode(true), _el$12 = _el$11.firstChild, _el$13 = _el$12.firstChild, _el$14 = _el$13.firstChild;
    _el$12.$$click = () => props2.onSelect(props2.option);
    const _ref$ = ref;
    typeof _ref$ === "function" ? use(_ref$, _el$12) : ref = _el$12;
    insert(_el$13, createComponent(Icon, {
      get name() {
        return props2.option.icon;
      }
    }), _el$14);
    insert(_el$14, () => props2.option.label);
    insert(_el$13, createComponent(Show, {
      get when() {
        return showHelp();
      },
      get children() {
        return createComponent(Tooltip, {
          get label() {
            return createComponent(TooltipCmp, {});
          },
          get children() {
            return createComponent(Icon, {
              name: "bi-question-circle"
            });
          }
        });
      }
    }), null);
    createRenderEffect(() => _el$11.classList.toggle("selected", !!props2.selected));
    return _el$11;
  })();
}
function SelectNewOption(props2) {
  const [creating, setCreating] = createSignal(false);
  const onSubmit = (e3) => {
    const form = e3.target;
    const data2 = new FormData(form);
    const optionName = data2.get("card-attribute-select-new-option-name");
    e3.preventDefault();
    setCreating(false);
    props2.onAdd(optionName);
  };
  return (() => {
    const _el$15 = _tmpl$610.cloneNode(true);
    insert(_el$15, createComponent(Show, {
      get when() {
        return creating();
      },
      get fallback() {
        return createComponent(AddNewOption, {
          get label() {
            return props2.label;
          },
          get focus() {
            return props2.focus;
          },
          onClick: () => setCreating(true)
        });
      },
      get children() {
        return createComponent(NewOptionForm, {
          get placeholder() {
            return props2.placeholder;
          },
          onCancel: () => setCreating(false),
          onSubmit,
          get focus() {
            return props2.focus;
          }
        });
      }
    }));
    return _el$15;
  })();
}
function AddNewOption(props2) {
  let ref;
  handleFocus(() => ref, () => props2.focus);
  return (() => {
    const _el$16 = _tmpl$76.cloneNode(true), _el$17 = _el$16.firstChild, _el$18 = _el$17.firstChild;
    addEventListener(_el$16, "click", props2.onClick, true);
    const _ref$2 = ref;
    typeof _ref$2 === "function" ? use(_ref$2, _el$16) : ref = _el$16;
    insert(_el$17, createComponent(Icon, {
      name: "bi-plus-lg"
    }), _el$18);
    insert(_el$18, () => props2.label);
    return _el$16;
  })();
}
function NewOptionForm(props2) {
  let input;
  onMount(() => input.focus());
  handleFocus(() => input, () => props2.focus);
  return (() => {
    const _el$19 = _tmpl$84.cloneNode(true), _el$20 = _el$19.firstChild, _el$21 = _el$20.nextSibling, _el$22 = _el$21.firstChild, _el$23 = _el$22.nextSibling;
    addEventListener(_el$19, "submit", props2.onSubmit);
    const _ref$3 = input;
    typeof _ref$3 === "function" ? use(_ref$3, _el$20) : input = _el$20;
    insert(_el$22, createComponent(Icon, {
      name: "bi-check-lg"
    }));
    addEventListener(_el$23, "click", props2.onCancel, true);
    insert(_el$23, createComponent(Icon, {
      name: "bi-x-lg"
    }));
    createRenderEffect(() => setAttribute(_el$20, "placeholder", props2.placeholder ?? _4("Enter a name for the new field")));
    return _el$19;
  })();
}
delegateEvents(["keydown", "click"]);

// public/app/apps/cards/gantt/wizard/fields/CardAttributeSelectField.tsx
var _tmpl$77 = /* @__PURE__ */ template(`<span aria-hidden="true">*&nbsp;</span>`, 2);
var _tmpl$226 = /* @__PURE__ */ template(`<div class="form-group"><div class="form-content"></div></div>`, 4);
function CardAttributeSelectField(props2) {
  const form = useForm();
  const field2 = useField();
  const onChange = (opt) => {
    form.updateField(field2.valuePath, opt.value);
    if (!props2.updateIdField) return;
    const idFieldPath = field2.valuePath.split(".").slice(0, -1).concat("id").join(".");
    form.updateField(idFieldPath, opt.id);
  };
  return (() => {
    const _el$ = _tmpl$226.cloneNode(true), _el$3 = _el$.firstChild;
    insert(_el$, createComponent(InputLabel, {
      get ["for"]() {
        return field2.valuePath;
      },
      get children() {
        return [createMemo(() => props2.label), createComponent(Show, {
          get when() {
            return props2.required;
          },
          get children() {
            return _tmpl$77.cloneNode(true);
          }
        })];
      }
    }), _el$3);
    insert(_el$3, createComponent(CardAttributeSelect, mergeProps(props2, {
      get selected() {
        return field2?.state?.value;
      },
      onChange
    })));
    return _el$;
  })();
}

// public/app/apps/cards/gantt/wizard/utils/options.ts
function dateFieldTypeOptions() {
  return [
    { value: "date" /* Date */, label: _4("Date Range") },
    { value: "milestone" /* Milestone */, label: _4("Milestone") }
  ];
}
function useDateAttributeOptions() {
  const availableDateAttrs = useAvailableAttributesOfType("date", "date", true);
  return () => [...availableDateAttrs().keys()].map((name2) => ({
    value: name2,
    label: name2
  }));
}

// public/app/apps/cards/gantt/wizard/utils/fields.tsx
var _tmpl$78 = /* @__PURE__ */ template(`<div class="gantt-wizard-secondary-date-configuration"><div class="gantt-wizard-secondary-date-configuration-fields"></div><div class="gantt-wizard-secondary-date-configuration-actions"></div></div>`, 6);
var GanttWizardConfigContext = createContext();
function GanttWizardConfigProvider(props2) {
  return createComponent(GanttWizardConfigContext.Provider, {
    get value() {
      return {
        index: props2.index
      };
    },
    get children() {
      return props2.children;
    }
  });
}
function useGanttWizardConfig() {
  return useContext(GanttWizardConfigContext);
}
function useModelAccordingToConfig() {
  const context = useGanttWizardConfig();
  const form = useForm();
  const models = useModels();
  return createMemo(() => {
    const m3 = form.state.configurations[context.index].model.value;
    return models().find((model) => model.id === m3);
  });
}
function MainGanttWizardConfigFields(props2) {
  const context = useGanttWizardConfig();
  const form = useForm();
  const model = useModelAccordingToConfig();
  const Fields = {
    name: form.createFieldProvider("configurations[number].date.name"),
    color: form.createFieldProvider("configurations[number].date.color"),
    type: form.createFieldProvider("configurations[number].date.type")
  };
  return [createComponent(Fields.name, {
    get indexes() {
      return [context.index];
    },
    get children() {
      return createComponent(CardAttributeSelectField, {
        updateIdField: true,
        get label() {
          return _4("Date field");
        },
        fieldType: "date",
        typeHint: "date",
        get model() {
          return model();
        },
        get placeholder() {
          return _4("Choose a date field");
        },
        get newOptionLabel() {
          return _4("Create a new date field");
        },
        newOptionAttributeOptions: () => ({
          daterange: true
        })
      });
    }
  }), createComponent(Show, {
    get when() {
      return props2.displayTypeField;
    },
    get children() {
      return createComponent(Fields.type, {
        get indexes() {
          return [context.index];
        },
        get children() {
          return createComponent(SelectField, {
            get label() {
              return _4("Display type");
            },
            get options() {
              return dateFieldTypeOptions();
            }
          });
        }
      });
    }
  }), createComponent(Fields.color, {
    get indexes() {
      return [context.index];
    },
    get children() {
      return createComponent(ColorField, {
        get label() {
          return _4("Color");
        },
        allowCardColor: true
      });
    }
  })];
}
function SecondaryDatesGanttWizardConfigFields(props2) {
  const context = useGanttWizardConfig();
  const form = useForm();
  const dateAttrOptions = useDateAttributeOptions();
  const model = useModelAccordingToConfig();
  const Fields = {
    name: form.createFieldProvider("configurations[number].secondary_dates[number].name"),
    color: form.createFieldProvider("configurations[number].secondary_dates[number].color"),
    type: form.createFieldProvider("configurations[number].secondary_dates[number].type")
  };
  const valuesToRemoveFromTheList = createMemo(() => {
    const config3 = form.values.configurations[context.index];
    return [config3.date.name, ...config3.secondary_dates.map((d3) => d3.name)];
  });
  const excludedOptions = () => dateAttrOptions().filter((opt) => valuesToRemoveFromTheList().includes(opt.value)).map((opt) => opt.value);
  return [createComponent(Fields.name, {
    get indexes() {
      return [context.index, props2.index()];
    },
    get children() {
      return createComponent(CardAttributeSelectField, {
        updateIdField: true,
        get label() {
          return _4("Field");
        },
        fieldType: "date",
        typeHint: "date",
        get model() {
          return model();
        },
        get excludedOptions() {
          return excludedOptions();
        },
        get placeholder() {
          return _4("Choose a date field");
        },
        get newOptionLabel() {
          return _4("Create a new date field");
        }
      });
    }
  }), createComponent(Fields.type, {
    get indexes() {
      return [context.index, props2.index()];
    },
    get children() {
      return createComponent(SelectField, {
        get label() {
          return _4("Display type");
        },
        get options() {
          return dateFieldTypeOptions();
        }
      });
    }
  }), createComponent(Fields.color, {
    get indexes() {
      return [context.index, props2.index()];
    },
    get children() {
      return createComponent(ColorField, {
        get label() {
          return _4("Color");
        },
        allowCardColor: true
      });
    }
  })];
}
function SecondaryDatesGanttWizardConfigFieldsWrapper() {
  const context = useGanttWizardConfig();
  const form = useForm();
  const removeSecondaryDate = (secondaryDateIndex) => {
    form.removeField(`configurations.${context.index}.secondary_dates.${secondaryDateIndex}`);
  };
  return createComponent(For, {
    get each() {
      return form.state.configurations[context.index].secondary_dates;
    },
    children: (field2, index2) => (() => {
      const _el$ = _tmpl$78.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
      insert(_el$2, createComponent(SecondaryDatesGanttWizardConfigFields, {
        index: index2
      }));
      insert(_el$3, createComponent(IconButton, {
        type: "button",
        style: "danger",
        get ["aria-label"]() {
          return _4("Remove this secondary date config");
        },
        icon: "bi-trash",
        onClick: () => removeSecondaryDate(index2())
      }));
      return _el$;
    })()
  });
}

// public/app/apps/cards/gantt/wizard/steps/AdditionalSettings.tsx
var _tmpl$79 = /* @__PURE__ */ template(`<div role="group"></div>`, 2);
var _tmpl$227 = /* @__PURE__ */ template(`<div class="gantt-wizard-secondary-date-configurations"></div>`, 2);
var _tmpl$317 = /* @__PURE__ */ template(`<div class="gantt-wizard-additional-settings"><p class="step-description"><br><br></p></div>`, 6);
function StepAdditionalSettings() {
  return createComponent(Step, {
    asChild: true,
    children: (eltProps, setRef) => (() => {
      const _el$ = _tmpl$79.cloneNode(true);
      const _ref$ = setRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : setRef = _el$;
      spread(_el$, mergeProps(eltProps, {
        "classList": {
          "gantt-config-wrapper": true,
          "gantt-wizard-additional-settings-step": true
        }
      }), false, true);
      insert(_el$, createComponent(GanttWizardAdditionalSettings, {}));
      return _el$;
    })()
  });
}
function GanttWizardAdditionalSettings() {
  const form = useForm();
  const CONFIG_INDEX = 0;
  const addSecondaryDate = () => {
    form.insertField(`configurations.${CONFIG_INDEX}.secondary_dates`, {
      name: "",
      type: "date" /* Date */,
      color: DEFAULT_COLORS.date
    });
  };
  return (() => {
    const _el$2 = _tmpl$317.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling;
    insert(_el$3, () => _4("Select other fields to display on your gantt chart."), _el$4);
    insert(_el$3, () => _4("All the information related to a card will be displayed on a single line."), _el$5);
    insert(_el$3, () => _4("Dependencies will only apply to the main date range."), null);
    insert(_el$2, createComponent(GanttWizardConfigProvider, {
      index: CONFIG_INDEX,
      get children() {
        const _el$6 = _tmpl$227.cloneNode(true);
        insert(_el$6, createComponent(SecondaryDatesGanttWizardConfigFieldsWrapper, {}), null);
        insert(_el$6, createComponent(IconButton, {
          icon: "bi-plus-lg",
          type: "button",
          get ["aria-label"]() {
            return _4("Add a secondary date configuration");
          },
          onClick: addSecondaryDate
        }), null);
        return _el$6;
      }
    }), null);
    return _el$2;
  })();
}

// public/app/apps/cards/gantt/wizard/steps/BasicSettings.tsx
var _tmpl$80 = /* @__PURE__ */ template(`<div role="group"></div>`, 2);
var _tmpl$228 = /* @__PURE__ */ template(`<div class="gantt-wizard-basic-settings"><p class="step-description"></p><div class="step-content"><div class="date-range-configuration-wrapper"><div class="date-range-configuration"></div><div class="preview-date-range range-source" aria-hidden="true"></div><div class="preview-date-range range-target" aria-hidden="true"></div></div><div class="relationship-configuration-wrapper"><div class="preview-relationship" aria-hidden="true"><div></div><div></div><div></div></div><div class="relationship-configuration"></div></div></div></div>`, 26);
function StepBasicSettings() {
  return createComponent(Step, {
    asChild: true,
    children: (eltProps, setRef) => (() => {
      const _el$ = _tmpl$80.cloneNode(true);
      const _ref$ = setRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : setRef = _el$;
      spread(_el$, mergeProps(eltProps, {
        "classList": {
          "gantt-config-wrapper": true,
          "gantt-wizard-basic-settings-step": true
        }
      }), false, true);
      insert(_el$, createComponent(GanttWizardBasicSettings, {}));
      return _el$;
    })()
  });
}
function GanttWizardBasicSettings() {
  const form = useForm();
  const defaultModel = useDefaultModel();
  const Fields = {
    date: {
      name: form.createFieldProvider("configurations[number].date.name"),
      color: form.createFieldProvider("configurations[number].date.color")
    },
    relationship: {
      name: form.createFieldProvider("configurations[number].relationship.name"),
      color: form.createFieldProvider("configurations[number].relationship.color")
    }
  };
  return (() => {
    const _el$2 = _tmpl$228.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.nextSibling, _el$5 = _el$4.firstChild, _el$6 = _el$5.firstChild, _el$7 = _el$6.nextSibling, _el$8 = _el$7.nextSibling, _el$9 = _el$5.nextSibling, _el$10 = _el$9.firstChild, _el$11 = _el$10.nextSibling;
    insert(_el$3, () => _4("Setup the core data for your gantt chart. This will define the main date range for each card."));
    insert(_el$6, createComponent(Fields.date.name, {
      indexes: [0],
      get children() {
        return createComponent(CardAttributeSelectField, {
          get model() {
            return defaultModel();
          },
          fieldType: "date",
          typeHint: "date",
          get label() {
            return _4("Date field");
          },
          updateIdField: true,
          get placeholder() {
            return _4("Choose a date field");
          },
          get newOptionLabel() {
            return _4("Create a new date field");
          },
          newOptionAttributeOptions: () => ({
            daterange: true
          })
        });
      }
    }), null);
    insert(_el$6, createComponent(Fields.date.color, {
      indexes: [0],
      get children() {
        return createComponent(ColorField, {
          get label() {
            return _4("Color");
          },
          allowCardColor: true
        });
      }
    }), null);
    insert(_el$11, createComponent(Fields.relationship.name, {
      indexes: [0],
      get children() {
        return createComponent(CardAttributeSelectField, {
          get model() {
            return defaultModel();
          },
          fieldType: "relationships",
          fieldTypeForNew: "relationships",
          typeHint: "relationships",
          get label() {
            return _4("Relationship field");
          },
          updateIdField: true,
          get placeholder() {
            return _4("Choose a relationship field");
          },
          get newOptionLabel() {
            return _4("Create a new relationship field");
          }
        });
      }
    }), null);
    insert(_el$11, createComponent(Fields.relationship.color, {
      indexes: [0],
      get children() {
        return createComponent(ColorField, {
          get label() {
            return _4("Color");
          }
        });
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = form.values.configurations[0]?.date.color, _v$2 = form.values.configurations[0]?.date.color, _v$3 = form.values.configurations[0]?.relationship.color;
      _v$ !== _p$._v$ && _el$7.style.setProperty("background-color", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$8.style.setProperty("background-color", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$10.style.setProperty("--preview-relationship-color", _p$._v$3 = _v$3);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0
    });
    return _el$2;
  })();
}

// public/app/apps/cards/gantt/wizard/steps/Info.tsx
var _tmpl$81 = /* @__PURE__ */ template(`<div><i class="bi-bar-chart-steps"></i><p></p><p></p></div>`, 8);
function StepInfo() {
  return createComponent(Step, {
    asChild: true,
    children: (props2, setRef) => (() => {
      const _el$ = _tmpl$81.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling, _el$4 = _el$3.nextSibling;
      const _ref$ = setRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : setRef = _el$;
      spread(_el$, mergeProps(props2, {
        "classList": {
          "gantt-wizard-step-info": true
        }
      }), false, true);
      insert(_el$3, () => _4("Gantt is a methodology that focuses on planning and scheduling projects using a visual chart to represent tasks, their durations, and dependencies over time."));
      insert(_el$4, () => _4("This wizard will help you turn your workspace into a Gantt project. Settings will apply to all gantt views. You will still be able to customize some appearance settings on each gantt views."));
      return _el$;
    })()
  });
}

// public/app/apps/cards/gantt/wizard/steps/MigrateFromV1.tsx
var _tmpl$85 = /* @__PURE__ */ template(`<div role="group"></div>`, 2);
var _tmpl$229 = /* @__PURE__ */ template(`<h2></h2>`, 2);
var _tmpl$318 = /* @__PURE__ */ template(`<h1></h1>`, 2);
var _tmpl$414 = /* @__PURE__ */ template(`<div class="gantt-wizard-main-date-configuration"></div>`, 2);
var _tmpl$512 = /* @__PURE__ */ template(`<div class="gantt-wizard-secondary-date-configurations"></div>`, 2);
var _tmpl$611 = /* @__PURE__ */ template(`<div class="gantt-wizard-migrate-v1"><p class="step-description"></p><div class="step-content"><div class="gantt-wizard-migrate-wrapper"><section class="gantt-wizard-migrate-old-views-wrapper"><section><h1></h1><ul></ul></section><section><h1></h1><div><h2></h2></div></section></section><section></section></div></div></div>`, 26);
var _tmpl$710 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$86 = /* @__PURE__ */ template(`<li></li>`, 2);
var _tmpl$93 = /* @__PURE__ */ template(`<div class="menu-item-main-action-button"><div class="color-rectangle"></div></div>`, 4);
var _tmpl$102 = /* @__PURE__ */ template(`<div class="menu-item-main-action-button"><div class="color-diamond"></div></div>`, 4);
var _tmpl$112 = /* @__PURE__ */ template(`<div class="menu-item-main-action-button"><div class="enter-arrow"><div class="arrow-stem"></div><div class="arrow-branch"></div><div class="arrow-head"></div></div></div>`, 10);
function StepMigrateFromV1() {
  return createComponent(Step, {
    asChild: true,
    children: (eltProps, setRef) => (() => {
      const _el$ = _tmpl$85.cloneNode(true);
      const _ref$ = setRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : setRef = _el$;
      spread(_el$, mergeProps(eltProps, {
        "classList": {
          "gantt-config-wrapper": true,
          "gantt-wizard-migrate-v1-step": true
        }
      }), false, true);
      insert(_el$, createComponent(GanttWizardMigrateV1, {}));
      return _el$;
    })()
  });
}
function GanttWizardMigrateV1() {
  const views = useViews();
  const form = useForm();
  const defaultModel = useDefaultModel();
  const ganttViews = createMemo(() => views().filter((v3) => v3.is_public && v3.mode === "gantt" && !!v3.mode_options?.dateFields?.length));
  const dateAttributes = useAvailableAttributesOfType("date");
  const relationshipAttributes = useAvailableAttributesOfType("relationships");
  const [activeView, setActiveView] = createSignal(ganttViews()?.[0]);
  const Fields = {
    relationship: {
      name: form.createFieldProvider("configurations[number].relationship.name"),
      color: form.createFieldProvider("configurations[number].relationship.color")
    }
  };
  const updateConfigFromView = (view) => {
    const {
      dateFields,
      milestoneFields,
      relationshipFields
    } = view?.mode_options;
    const newMainDateField = dateFields[0];
    const newMainDateId = dateAttributes().get(newMainDateField.name)[0]?.id;
    const newSecondaryDateFields = [...dateFields.slice(1) || [], ...milestoneFields || []].map((field2) => ({
      name: field2.name,
      id: dateAttributes()?.get(field2.name)[0]?.id,
      type: milestoneFields?.find((f3) => f3.name === field2.name) ? "milestone" /* Milestone */ : "date" /* Date */,
      color: field2.color
    })).filter((f3) => !!f3.id);
    const newRelationshipField = relationshipFields?.[0];
    form.updateField("configurations.0.date.name", newMainDateField.name);
    form.updateField("configurations.0.date.id", newMainDateId || "");
    form.updateField("configurations.0.date.color", newMainDateField.color || null);
    form.updateField("configurations.0.date.type", "date" /* Date */);
    if (newRelationshipField) {
      const newRelationshipId = relationshipAttributes().get(newRelationshipField.name)[0]?.id;
      form.updateField("configurations.0.relationship.name", newRelationshipField?.name || "");
      form.updateField("configurations.0.relationship.id", newRelationshipId || "");
      form.updateField("configurations.0.relationship.color", newRelationshipField.color || DEFAULT_COLORS.dependency);
    }
    form.clearField("configurations.0.secondary_dates");
    if (newSecondaryDateFields.length > 0) {
      newSecondaryDateFields.forEach((field2) => {
        form.insertField("configurations.0.secondary_dates", field2);
      });
    }
  };
  createEffect(on(() => activeView(), (view) => {
    updateConfigFromView(view);
  }));
  const addSecondaryDate = () => {
    form.insertField(`configurations.0.secondary_dates`, {
      name: "",
      type: "date" /* Date */,
      color: DEFAULT_COLORS.date
    });
  };
  return (() => {
    const _el$2 = _tmpl$611.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.nextSibling, _el$5 = _el$4.firstChild, _el$6 = _el$5.firstChild, _el$7 = _el$6.firstChild, _el$8 = _el$7.firstChild, _el$9 = _el$8.nextSibling, _el$10 = _el$7.nextSibling, _el$11 = _el$10.firstChild, _el$12 = _el$11.nextSibling, _el$13 = _el$12.firstChild, _el$16 = _el$6.nextSibling;
    insert(_el$8, () => _4("Gantt views"));
    insert(_el$9, createComponent(For, {
      get each() {
        return ganttViews();
      },
      children: (view) => (() => {
        const _el$23 = _tmpl$86.cloneNode(true);
        insert(_el$23, createComponent(Button, {
          type: "button",
          size: "lg",
          get classList() {
            return {
              active: view.id === activeView()?.id
            };
          },
          onClick: () => setActiveView(view),
          get children() {
            return [(() => {
              const _el$24 = _tmpl$710.cloneNode(true);
              insert(_el$24, () => view.name);
              return _el$24;
            })(), createComponent(Show, {
              get when() {
                return view.id === activeView()?.id;
              },
              get children() {
                return createComponent(Icon, {
                  name: "bi-chevron-right"
                });
              }
            })];
          }
        }));
        return _el$23;
      })()
    }));
    insert(_el$11, () => _4("Old view settings"));
    insert(_el$13, () => _4("Dates"));
    insert(_el$12, createComponent(For, {
      get each() {
        return activeView().mode_options.dateFields;
      },
      children: (field2) => (() => {
        const _el$25 = _tmpl$93.cloneNode(true), _el$26 = _el$25.firstChild;
        _el$26.style.setProperty("border", "1px solid #000");
        insert(_el$25, () => field2.name, null);
        createRenderEffect(() => _el$26.style.setProperty("background-color", field2.color));
        return _el$25;
      })()
    }), null);
    insert(_el$12, createComponent(Show, {
      get when() {
        return activeView().mode_options?.milestoneFields;
      },
      get children() {
        return [(() => {
          const _el$14 = _tmpl$229.cloneNode(true);
          insert(_el$14, () => _4("Milestones"));
          return _el$14;
        })(), createComponent(For, {
          get each() {
            return activeView().mode_options.milestoneFields;
          },
          children: (field2) => (() => {
            const _el$27 = _tmpl$102.cloneNode(true), _el$28 = _el$27.firstChild;
            _el$28.style.setProperty("border", "1px solid #000");
            insert(_el$27, () => field2.name, null);
            createRenderEffect(() => _el$28.style.setProperty("background-color", field2.color));
            return _el$27;
          })()
        })];
      }
    }), null);
    insert(_el$12, createComponent(Show, {
      get when() {
        return activeView().mode_options?.relationshipFields;
      },
      get children() {
        return [(() => {
          const _el$15 = _tmpl$229.cloneNode(true);
          insert(_el$15, () => _4("Dependencies"));
          return _el$15;
        })(), createComponent(For, {
          get each() {
            return activeView().mode_options?.relationshipFields;
          },
          children: (field2) => (() => {
            const _el$29 = _tmpl$112.cloneNode(true), _el$30 = _el$29.firstChild, _el$31 = _el$30.firstChild, _el$32 = _el$31.nextSibling, _el$33 = _el$32.nextSibling;
            insert(_el$29, () => field2.name, null);
            createRenderEffect((_p$) => {
              const _v$ = field2.color || "#000", _v$2 = field2.color || "#000", _v$3 = "transparent transparent transparent " + (field2.color || "#000");
              _v$ !== _p$._v$ && _el$31.style.setProperty("background-color", _p$._v$ = _v$);
              _v$2 !== _p$._v$2 && _el$32.style.setProperty("background-color", _p$._v$2 = _v$2);
              _v$3 !== _p$._v$3 && _el$33.style.setProperty("border-color", _p$._v$3 = _v$3);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0,
              _v$3: void 0
            });
            return _el$29;
          })()
        })];
      }
    }), null);
    insert(_el$16, createComponent(Icon, {
      name: "bi-chevron-right"
    }), null);
    insert(_el$16, createComponent(GanttWizardConfigProvider, {
      index: 0,
      get children() {
        return [(() => {
          const _el$17 = _tmpl$318.cloneNode(true);
          insert(_el$17, () => _4("New workspace settings"));
          return _el$17;
        })(), (() => {
          const _el$18 = _tmpl$229.cloneNode(true);
          insert(_el$18, () => _4("Base settings"));
          return _el$18;
        })(), (() => {
          const _el$19 = _tmpl$414.cloneNode(true);
          insert(_el$19, createComponent(MainGanttWizardConfigFields, {}));
          return _el$19;
        })(), (() => {
          const _el$20 = _tmpl$414.cloneNode(true);
          insert(_el$20, createComponent(Fields.relationship.name, {
            indexes: [0],
            get children() {
              return createComponent(CardAttributeSelectField, {
                get model() {
                  return defaultModel();
                },
                fieldType: "relationships",
                fieldTypeForNew: "relationships",
                typeHint: "relationships",
                get label() {
                  return _4("Relationship field");
                },
                updateIdField: true,
                required: true,
                get placeholder() {
                  return _4("Choose a relationship field");
                },
                get newOptionLabel() {
                  return _4("Create a new relationship field");
                }
              });
            }
          }), null);
          insert(_el$20, createComponent(Fields.relationship.color, {
            indexes: [0],
            get children() {
              return createComponent(ColorField, {
                get label() {
                  return _4("Color");
                }
              });
            }
          }), null);
          return _el$20;
        })(), createComponent(Show, {
          get when() {
            return activeView().mode_options?.milestoneFields;
          },
          get children() {
            return [(() => {
              const _el$21 = _tmpl$229.cloneNode(true);
              insert(_el$21, () => _4("Additional settings"));
              return _el$21;
            })(), (() => {
              const _el$22 = _tmpl$512.cloneNode(true);
              insert(_el$22, createComponent(SecondaryDatesGanttWizardConfigFieldsWrapper, {}), null);
              insert(_el$22, createComponent(IconButton, {
                icon: "bi-plus-lg",
                type: "button",
                get ["aria-label"]() {
                  return _4("Add a secondary date configuration");
                },
                onClick: addSecondaryDate
              }), null);
              return _el$22;
            })()];
          }
        })];
      }
    }), null);
    createRenderEffect(() => _el$3.innerHTML = _4(`You already have gantt views in your Workspace.<br/>
          Now, there is only one Gantt configuration for the worspace, and every gantt view are based on it.
          <br/><br/>
          Select one of your view to transfer its date, milestone and dependencies settings into the new gantt configuration.
          <br/>
          All the other view settings will remains the same (filters, group by, etc).
          <br/><br/>
          Don't forget to check the new custom config per card types, that should extend the possibilities of your gantt views!
          `));
    return _el$2;
  })();
}

// public/app/apps/cards/gantt/wizard/steps/OverridesPerTypes.tsx
var _tmpl$87 = /* @__PURE__ */ template(`<div role="group"></div>`, 2);
var _tmpl$230 = /* @__PURE__ */ template(`<div class="gantt-wizard-overrides-per-types"><p class="step-description"><br><br></p></div>`, 6);
var _tmpl$319 = /* @__PURE__ */ template(`<h2></h2>`, 2);
var _tmpl$415 = /* @__PURE__ */ template(`<div class="gantt-wizard-main-date-configuration with-type-field"></div>`, 2);
var _tmpl$513 = /* @__PURE__ */ template(`<div class="gantt-wizard-secondary-date-configurations"></div>`, 2);
var _tmpl$612 = /* @__PURE__ */ template(`<div class="gantt-wizard-override-config"></div>`, 2);
var _tmpl$711 = /* @__PURE__ */ template(`<section class="gantt-wizard-override"><header><h1></h1></header></section>`, 6);
function StepOverridesPerTypes() {
  return createComponent(Step, {
    asChild: true,
    children: (eltProps, setRef) => (() => {
      const _el$ = _tmpl$87.cloneNode(true);
      const _ref$ = setRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : setRef = _el$;
      spread(_el$, mergeProps(eltProps, {
        "classList": {
          "gantt-config-wrapper": true,
          "gantt-wizard-additional-settings-step": true
        }
      }), false, true);
      insert(_el$, createComponent(GanttWizardOverridesPerTypes, {}));
      return _el$;
    })()
  });
}
function GanttWizardOverridesPerTypes() {
  const form = useForm();
  const models = useModels();
  const defaultModel = useDefaultModel();
  const overridePerTypes = () => models().filter((m3) => m3.id !== defaultModel().id);
  return (() => {
    const _el$2 = _tmpl$230.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling;
    insert(_el$3, () => _4("For more control over you gantt chart, you can define specific settings for each card type."), _el$4);
    insert(_el$3, () => _4("Feel free to skip this step if you don't need it."), _el$5);
    insert(_el$2, createComponent(For, {
      get each() {
        return overridePerTypes();
      },
      children: (model) => createComponent(GanttWizardOverride, {
        model
      })
    }), null);
    return _el$2;
  })();
}
function GanttWizardOverride(props2) {
  const form = useForm();
  const configIndex = () => form.get("configurations").findIndex((config3) => config3.model.value === props2.model.id);
  const createConfig = () => {
    form.insertField("configurations", {
      model: props2.model.id,
      date: {
        name: "",
        id: "",
        type: "date" /* Date */,
        color: DEFAULT_COLORS.date
      },
      secondary_dates: []
    });
  };
  const removeConfig = () => {
    form.removeField(`configurations.${configIndex()}`);
  };
  const addSecondaryDate = () => {
    form.insertField(`configurations.${configIndex()}.secondary_dates`, {
      name: "",
      id: "",
      type: "date" /* Date */,
      color: DEFAULT_COLORS.date
    });
  };
  return (() => {
    const _el$6 = _tmpl$711.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.firstChild;
    insert(_el$8, () => props2.model.name);
    insert(_el$7, createComponent(Show, {
      get when() {
        return configIndex() === -1;
      },
      get fallback() {
        return createComponent(IconButton, {
          type: "button",
          icon: "bi-trash",
          style: "danger",
          "aria-label": "Remove config",
          onClick: removeConfig
        });
      },
      get children() {
        return createComponent(IconButton, {
          type: "button",
          icon: "bi-plus",
          "aria-label": "Create config",
          onClick: createConfig
        });
      }
    }), null);
    insert(_el$6, createComponent(Show, {
      get when() {
        return configIndex() !== -1;
      },
      get children() {
        const _el$9 = _tmpl$612.cloneNode(true);
        insert(_el$9, createComponent(GanttWizardConfigProvider, {
          get index() {
            return configIndex();
          },
          get children() {
            return [(() => {
              const _el$10 = _tmpl$319.cloneNode(true);
              insert(_el$10, () => _4("Main date field"));
              return _el$10;
            })(), (() => {
              const _el$11 = _tmpl$415.cloneNode(true);
              insert(_el$11, createComponent(MainGanttWizardConfigFields, {
                displayTypeField: true
              }));
              return _el$11;
            })(), (() => {
              const _el$12 = _tmpl$319.cloneNode(true);
              insert(_el$12, () => _4("Secondary date fields"));
              return _el$12;
            })(), (() => {
              const _el$13 = _tmpl$513.cloneNode(true);
              insert(_el$13, createComponent(SecondaryDatesGanttWizardConfigFieldsWrapper, {}), null);
              insert(_el$13, createComponent(IconButton, {
                icon: "bi-plus-lg",
                type: "button",
                get ["aria-label"]() {
                  return _4("Add a secondary date configuration");
                },
                onClick: addSecondaryDate
              }), null);
              return _el$13;
            })()];
          }
        }));
        return _el$9;
      }
    }), null);
    createRenderEffect(() => _el$7.classList.toggle("empty", !!(configIndex() === -1)));
    return _el$6;
  })();
}

// public/app/apps/cards/gantt/wizard/steps/Success.tsx
var _tmpl$88 = /* @__PURE__ */ template(`<div><i class="bi-patch-check-fill"></i><p class="success-message"></p><p></p></div>`, 8);
function StepSuccess() {
  return createComponent(Step, {
    asChild: true,
    children: (props2, setRef) => (() => {
      const _el$ = _tmpl$88.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling, _el$4 = _el$3.nextSibling;
      const _ref$ = setRef;
      typeof _ref$ === "function" ? use(_ref$, _el$) : setRef = _el$;
      spread(_el$, mergeProps(props2, {
        "classList": {
          "gantt-wizard-step-success": true
        }
      }), false, true);
      insert(_el$3, () => _4("Gantt is properly configured"));
      insert(_el$4, () => _4("You can safely close this modal or continue to the advanced settings pages."));
      return _el$;
    })()
  });
}

// public/app/apps/cards/gantt/wizard/utils/project.ts
async function saveGanttConfig(project, form) {
  const formValues = form.values;
  const apply_gantt_constraints = formValues.apply_gantt_constraints;
  const configurations = formValues.configurations.map((conf) => {
    return {
      ...conf,
      date: {
        ...conf.date,
        name: conf.date.name.trim()
      },
      relationship: conf.relationship ? {
        ...conf.relationship,
        name: conf.relationship.name.trim()
      } : void 0,
      secondary_dates: conf.secondary_dates.map((sd) => {
        return {
          ...sd,
          name: sd.name.trim()
        };
      }).filter((sd) => sd.name !== "")
    };
  }).filter((conf) => conf.date.name !== "");
  updateProject(project, {
    gantt_config: {
      apply_gantt_constraints,
      configurations
    }
  });
  form.markAs("apply_gantt_constraints", { dirty: false, touched: false });
  form.markAs("configurations", { dirty: false, touched: false });
}
function resetGanttConfig(project) {
  updateProject(project, {
    gantt_config: {}
  });
}

// public/app/apps/cards/gantt/wizard/GanttWizardContext.tsx
var ganttWizardModalContext = createContext();
function GanttWizardModalProvider(props2) {
  const project = useProject();
  const models = useModels();
  const form = useForm();
  const views = useViews();
  const stepper = StepperState.create();
  const ganttConfig = () => project().gantt_config;
  const alreadyConfigured = ganttConfig()?.configurations?.[0]?.date?.name?.length > 0;
  const displayMigrationStep = createMemo(() => {
    return !ganttConfig()?.configurations && views().filter((v3) => v3.is_public && v3.mode === "gantt" && !!v3.mode_options?.dateFields?.length).length > 0;
  });
  const infoStep = {
    name: "info" /* INFO */,
    label: () => _4("Getting started"),
    cmp: StepInfo,
    visited: true,
    action: () => {
      if (displayMigrationStep()) return stateMachine.transitionTo("migrate_from_v1" /* MIGRATE_FROM_V1 */);
      return stateMachine.transitionTo("basic_settings" /* BASIC_SETTINGS */);
    }
  };
  const basicSettingsStep = {
    name: "basic_settings" /* BASIC_SETTINGS */,
    label: () => _4("Basic settings"),
    cmp: StepBasicSettings,
    visited: false,
    action: async () => {
      await saveGanttConfig(project(), form);
      if (!state.alreadyConfigured) {
        return stateMachine.transitionTo("success" /* SUCCESS */);
      }
    },
    actionLabel: () => {
      return state.alreadyConfigured ? _4("Save") : _4("Continue");
    },
    canContinue: () => {
      return state.alreadyConfigured ? form.has("configurations.0") && (form.isTouched("configurations.0.date") || form.isTouched("configurations.0.relationship")) && !form.hasErrors() : form.has("configurations.0") && form.isTouched("configurations.0.date") && form.isTouched("configurations.0.relationship") && !form.hasErrors();
    },
    hasModifications: () => {
      const paths = ["configurations.0.date.name", "configurations.0.date.color", "configurations.0.relationship.name", "configurations.0.relationship.color"];
      return form.has("configurations.0") && paths.some((path) => form.isTouched(path) || form.isDirty(path));
    }
  };
  const [state, setState] = createStore({
    alreadyConfigured,
    newDateField: void 0,
    newRelationshipField: void 0,
    steps: [infoStep, basicSettingsStep]
  });
  const getStepIndex = (name2) => state.steps.findIndex((s3) => s3.name === name2);
  const goToStep = (name2) => {
    const stepIndex = getStepIndex(name2);
    stepper.goTo(stepIndex);
  };
  const stateMachine = StateMachine.create({
    current: "info" /* INFO */,
    transitions: [{
      to: "info" /* INFO */,
      action: async () => {
        goToStep("info" /* INFO */);
      }
    }, {
      to: "basic_settings" /* BASIC_SETTINGS */,
      action: async () => {
        goToStep("basic_settings" /* BASIC_SETTINGS */);
        setState("steps", getStepIndex("basic_settings" /* BASIC_SETTINGS */), "visited", true);
      }
    }, {
      to: "constraints" /* CONSTRAINTS */,
      action: async () => {
        goToStep("constraints" /* CONSTRAINTS */);
        setState("steps", getStepIndex("constraints" /* CONSTRAINTS */), "visited", true);
      }
    }, {
      to: "success" /* SUCCESS */,
      action: async () => {
        goToStep("success" /* SUCCESS */);
        setState("steps", getStepIndex("success" /* SUCCESS */), "visited", true);
      }
    }, {
      to: "additional_settings" /* ADDITIONAL_SETTINGS */,
      action: async () => {
        goToStep("additional_settings" /* ADDITIONAL_SETTINGS */);
        setState("steps", getStepIndex("additional_settings" /* ADDITIONAL_SETTINGS */), "visited", true);
      }
    }, {
      to: "overrides_per_types" /* OVERRIDES_PER_TYPES */,
      action: async () => {
        goToStep("overrides_per_types" /* OVERRIDES_PER_TYPES */);
        setState("steps", getStepIndex("overrides_per_types" /* OVERRIDES_PER_TYPES */), "visited", true);
      }
    }, {
      from: "info" /* INFO */,
      action: (to) => {
        if (!state.alreadyConfigured) {
          if (to === "basic_settings" /* BASIC_SETTINGS */) return;
          if (state.steps[getStepIndex(to)]?.visited === true) return;
          return {};
        }
        return;
      }
    }, {
      from: "basic_settings" /* BASIC_SETTINGS */,
      action: (to) => {
        if (!state.alreadyConfigured) {
          if (state.steps[getStepIndex(to)]?.visited === true) return;
          if (to === "info" /* INFO */) return;
          if (to === "success" /* SUCCESS */) return {};
          if (form.isTouched("configurations.0.date") && form.isTouched("configurations.0.relationship")) return;
          return {};
        }
        return;
      }
    }, {
      from: "constraints" /* CONSTRAINTS */,
      action: (to) => {
        if (!state.alreadyConfigured) {
          if (state.steps[getStepIndex(to)]?.visited === true) return;
          if (to === "success" /* SUCCESS */) return {};
          return;
        }
        return;
      }
    }, {
      to: "migrate_from_v1" /* MIGRATE_FROM_V1 */,
      action: async () => {
        goToStep("migrate_from_v1" /* MIGRATE_FROM_V1 */);
        setState("steps", getStepIndex("migrate_from_v1" /* MIGRATE_FROM_V1 */), "visited", true);
      }
    }, {
      from: "migrate_from_v1" /* MIGRATE_FROM_V1 */,
      action: (to) => {
        if (state.steps[getStepIndex(to)]?.visited === true) return;
        if (to === "info" /* INFO */) return;
        if (to === "success" /* SUCCESS */) return {};
        return;
      }
    }]
  });
  const migrationSteps = [{
    name: "migrate_from_v1" /* MIGRATE_FROM_V1 */,
    visited: false,
    label: () => _4("Migrate your existing Gantt settings"),
    cmp: StepMigrateFromV1,
    action: async () => {
      await saveGanttConfig(project(), form);
      return stateMachine.transitionTo("success" /* SUCCESS */);
    },
    actionLabel: () => _4("Save"),
    canContinue: () => {
      return form.has("configurations.0") && form.isTouched("configurations.0.date") && form.isTouched("configurations.0.relationship") && !form.hasErrors();
    },
    hasModifications: () => {
      return form.isTouched("configurations.0.date") || form.isTouched("configurations.0.relationship") || form.isTouched("configurations.0.secondary_dates");
    }
  }];
  const advancedSteps = [{
    name: "additional_settings" /* ADDITIONAL_SETTINGS */,
    visited: false,
    label: () => _4("Additional settings"),
    cmp: StepAdditionalSettings,
    action: () => saveGanttConfig(project(), form),
    actionLabel: () => _4("Save"),
    canContinue: () => {
      return !form.hasErrors() && form.isDirty("configurations.0.secondary_dates");
    },
    hasModifications: () => {
      return form.isTouched("configurations.0.secondary_dates") || form.isDirty("configurations.0.secondary_dates");
    }
  }, {
    name: "overrides_per_types" /* OVERRIDES_PER_TYPES */,
    visited: false,
    label: () => _4("Overrides per types"),
    cmp: StepOverridesPerTypes,
    action: () => saveGanttConfig(project(), form),
    actionLabel: () => _4("Save"),
    canContinue: () => {
      return !form.hasErrors() && form.isDirty("configurations");
    },
    hasModifications: () => {
      if (!form.isTouched("configurations")) return false;
      const config3 = ganttConfig();
      const configLength = config3?.configurations?.length || 0;
      const diffLength = form.state.configurations.length !== configLength;
      const otherModifications = form.state.configurations.slice(1).some((c3, i3) => form.isTouched(`configurations.${i3 + 1}`));
      return diffLength || otherModifications;
    }
  }];
  const successStep = {
    name: "success" /* SUCCESS */,
    visited: false,
    label: () => _4("Ready to use"),
    cmp: StepSuccess,
    action: async () => {
      setState(produce((draft) => {
        draft.alreadyConfigured = true;
        const newSteps = [...draft.steps.slice(0, -1)];
        newSteps.push(...advancedSteps);
        draft.steps = newSteps;
      }));
      stateMachine.transitionTo("additional_settings" /* ADDITIONAL_SETTINGS */);
    },
    actionLabel: () => _4("Continue to advanced settings")
  };
  const migrationSuccessStep = {
    name: "success" /* SUCCESS */,
    visited: false,
    label: () => _4("Ready to use"),
    cmp: StepSuccess,
    action: async () => {
      setState(produce((draft) => {
        draft.alreadyConfigured = true;
        draft.steps = [infoStep, basicSettingsStep, ...advancedSteps];
      }));
      stateMachine.transitionTo("basic_settings" /* BASIC_SETTINGS */);
    },
    actionLabel: () => _4("Continue to Gantt settings")
  };
  onMount(() => {
    if (models().length < 2) {
      advancedSteps.pop();
    }
    if (!state.alreadyConfigured) {
      if (displayMigrationStep()) {
        setState("steps", (prev) => {
          return [prev[0], ...migrationSteps, migrationSuccessStep];
        });
      } else {
        setState("steps", (prev) => [...prev, successStep]);
      }
    } else {
      setState("steps", (prev) => {
        const newSteps = [...prev];
        newSteps.push(...advancedSteps);
        return newSteps;
      });
    }
  });
  return createComponent(ganttWizardModalContext.Provider, {
    value: {
      stepper,
      stateMachine,
      form,
      state,
      setState
    },
    get children() {
      return createComponent(StateMachineProvider, {
        value: stateMachine,
        get children() {
          return props2.children;
        }
      });
    }
  });
}
function useGanttWizardContext() {
  return useContext(ganttWizardModalContext);
}

// public/app/apps/cards/gantt/wizard/GanttWizardForm.tsx
var GanttWizard = class extends BaseForm {
  apply_gantt_constraints = field();
  configurations = fields({
    model: field(),
    date: nestedField({
      name: field(),
      id: field(),
      type: field(),
      color: field()
    }),
    relationship: nestedField({
      name: field(),
      id: field(),
      color: field()
    }),
    secondary_dates: fields({
      name: field(),
      id: field(),
      type: field(),
      color: field()
    })
  });
};
function GanttWizardForm(props2) {
  const project = useProject();
  const defaultModel = useDefaultModel();
  const configAlreadyExists = () => !!project().gantt_config?.configurations;
  const form = GanttWizard.create({
    apply_gantt_constraints: true,
    configurations: []
  });
  onMount(() => {
    if (configAlreadyExists()) {
      const ganttConfig = project().gantt_config;
      form.updateField("apply_gantt_constraints", ganttConfig.apply_gantt_constraints, {
        dirty: false,
        touched: false
      });
      ganttConfig.configurations.forEach((config3) => {
        form.insertField(`configurations`, config3, {
          dirty: false,
          touched: false
        });
      });
    } else {
      form.insertField("configurations", {
        model: defaultModel().id,
        date: {
          name: "",
          id: "",
          type: "date" /* Date */,
          color: DEFAULT_COLORS.date
        },
        relationship: {
          name: "",
          id: "",
          color: DEFAULT_COLORS.dependency
        },
        secondary_dates: []
      }, {
        dirty: false,
        touched: false
      });
    }
  });
  return createComponent(form.Form, {
    "class": "gantt-wizard",
    get onSubmit() {
      return props2.onSubmit;
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/apps/cards/gantt/wizard/GanttWizardModal.tsx
var _tmpl$89 = /* @__PURE__ */ template(`<div class="modal-header-with-rows"><div class="modal-header-row"><h3 class="modal-title"></h3></div><div class="modal-header-row"></div></div>`, 8);
var _tmpl$231 = /* @__PURE__ */ template(`<ol class="stepper-breadcrumb"></ol>`, 2);
var _tmpl$320 = /* @__PURE__ */ template(`<li class="stepper-breadcrumb-item"></li>`, 2);
var _tmpl$416 = /* @__PURE__ */ template(`<span class="modified-mark"></span>`, 2);
var _tmpl$514 = /* @__PURE__ */ template(`<button></button>`, 2);
var _tmpl$613 = /* @__PURE__ */ template(`<div class="gantt-wizard-body"></div>`, 2);
var _tmpl$712 = /* @__PURE__ */ template(`<section class="dropdown-panel"><header></header></section>`, 4);
var _tmpl$810 = /* @__PURE__ */ template(`<div class="spacer"></div>`, 2);
var _tmpl$94 = /* @__PURE__ */ template(`<button type="button" class="menu-item-main-action-button"></button>`, 2);
function GanttWizardModal() {
  const modal = useModal();
  return createComponent(GanttWizardForm, {
    get children() {
      return createComponent(GanttWizardModalProvider, {
        get children() {
          return [(() => {
            const _el$ = _tmpl$89.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$2.nextSibling;
            insert(_el$3, () => _4("Configure gantt for your workspace"));
            insert(_el$2, createComponent(Button, {
              style: "close",
              onClick: () => modal.close()
            }), null);
            insert(_el$4, createComponent(GanttWizardBreadcrumb, {}));
            return _el$;
          })(), createComponent(GanttWizardModalBody, {}), createComponent(GanttWizardModalFooter, {})];
        }
      });
    }
  });
}
function GanttWizardBreadcrumb() {
  const {
    state,
    stateMachine
  } = useGanttWizardContext();
  return (() => {
    const _el$5 = _tmpl$231.cloneNode(true);
    insert(_el$5, createComponent(For, {
      get each() {
        return state.steps;
      },
      children: (step2) => (() => {
        const _el$6 = _tmpl$320.cloneNode(true);
        insert(_el$6, createComponent(BreadcrumbButton, {
          step: step2
        }));
        createRenderEffect(() => _el$6.classList.toggle("active", !!(step2.name === stateMachine.current)));
        return _el$6;
      })()
    }));
    return _el$5;
  })();
}
function BreadcrumbButton(props2) {
  const {
    stateMachine
  } = useGanttWizardContext();
  const disabled = () => !stateMachine.canTransitionTo(props2.step.name) || props2.step.name === stateMachine.current;
  const hasModifications = () => props2.step.hasModifications && props2.step.hasModifications();
  return (() => {
    const _el$7 = _tmpl$514.cloneNode(true);
    _el$7.$$click = () => stateMachine.transitionTo(props2.step.name);
    insert(_el$7, () => props2.step.label(), null);
    insert(_el$7, createComponent(Show, {
      get when() {
        return hasModifications();
      },
      get children() {
        return _tmpl$416.cloneNode(true);
      }
    }), null);
    createRenderEffect(() => _el$7.disabled = disabled());
    return _el$7;
  })();
}
function GanttWizardModalBody() {
  const {
    stepper,
    state
  } = useGanttWizardContext();
  return createComponent(ModalBody, {
    get children() {
      const _el$9 = _tmpl$613.cloneNode(true);
      insert(_el$9, createComponent(Stepper, {
        state: stepper,
        get children() {
          return createComponent(For, {
            get each() {
              return state.steps;
            },
            children: (step2) => createComponent(Dynamic, {
              get component() {
                return step2.cmp;
              }
            })
          });
        }
      }));
      return _el$9;
    }
  });
}
function GanttWizardModalFooter() {
  const project = useProject();
  const modal = useModal();
  const {
    stateMachine,
    state,
    stepper
  } = useGanttWizardContext();
  const currentStep = () => state.steps.find((s3) => s3.name === stateMachine.current);
  const label = () => {
    const step2 = currentStep();
    return step2.actionLabel ? step2.actionLabel() : _4("Continue");
  };
  const onClick = async () => {
    if (currentStep()?.action) {
      await currentStep().action();
    }
  };
  const canContinue = () => {
    const step2 = currentStep();
    if (step2?.canContinue) {
      return step2.canContinue();
    }
    return true;
  };
  const canNext = () => stepper.canNext();
  const canPrevious = () => stepper.canPrevious();
  const goToNext = () => {
    if (canNext()) {
      const currentIndex = state.steps.findIndex((s3) => s3.name === stateMachine.current);
      const nextIndex = currentIndex + 1;
      stateMachine.transitionTo(state.steps[nextIndex].name);
    }
  };
  const goToPrevious = () => {
    if (canPrevious()) {
      const currentIndex = state.steps.findIndex((s3) => s3.name === stateMachine.current);
      const previousIndex = currentIndex - 1;
      stateMachine.transitionTo(state.steps[previousIndex].name);
    }
  };
  const actionDisabled = () => !canContinue();
  const adminActions = [{
    name: _4("Reset gantt configuration"),
    action: () => {
      resetGanttConfig(project());
      modal.close();
    }
  }];
  return createComponent(ModalFooter, {
    get children() {
      return [createComponent(Show, {
        get when() {
          return currentUser2.is_kantree_super_admin;
        },
        get children() {
          return createComponent(Dropdown, {
            get children() {
              return [createComponent(DropdownTrigger, {
                get children() {
                  return createComponent(IconButton, {
                    type: "button",
                    icon: "bi-three-dots-vertical"
                  });
                }
              }), createComponent(DropdownContent, {
                placement: "top-start",
                get children() {
                  const _el$10 = _tmpl$712.cloneNode(true), _el$11 = _el$10.firstChild;
                  insert(_el$11, () => _4("Admin actions"));
                  insert(_el$10, createComponent(Menu, {
                    each: adminActions,
                    children: (action) => (() => {
                      const _el$13 = _tmpl$94.cloneNode(true);
                      addEventListener(_el$13, "click", action.action, true);
                      insert(_el$13, () => action.name);
                      return _el$13;
                    })()
                  }), null);
                  return _el$10;
                }
              })];
            }
          });
        }
      }), createComponent(Show, {
        get when() {
          return state.alreadyConfigured;
        },
        get children() {
          return [createComponent(IconButton, {
            type: "button",
            onClick: () => goToPrevious(),
            get ["aria-label"]() {
              return _4("Previous");
            },
            icon: "bi-chevron-left",
            get disabled() {
              return !canPrevious();
            }
          }), createComponent(IconButton, {
            type: "button",
            onClick: () => goToNext(),
            get ["aria-label"]() {
              return _4("Next");
            },
            icon: "bi-chevron-right",
            get disabled() {
              return !canNext();
            }
          })];
        }
      }), _tmpl$810.cloneNode(true), createComponent(Show, {
        get when() {
          return currentStep()?.footer;
        },
        get children() {
          return createComponent(Dynamic, {
            get component() {
              return currentStep().footer;
            }
          });
        }
      }), createComponent(Show, {
        get when() {
          return currentStep()?.action;
        },
        get children() {
          return createComponent(Button, {
            type: "button",
            "class": "btn",
            onClick,
            get label() {
              return label();
            },
            get disabled() {
              return actionDisabled();
            }
          });
        }
      })];
    }
  });
}
delegateEvents(["click"]);

// public/app/apps/cards/gantt/wizard/utils/modal.tsx
function openGanttWizardModal(project, cardStore2) {
  const Wrapper = () => createComponent(ProjectProvider, {
    get project() {
      return project();
    },
    get children() {
      return createComponent(CardStoreProvider, {
        get store() {
          return cardStore2();
        },
        get children() {
          return createComponent(ScopedModelStoreProvider, {
            get children() {
              return createComponent(ScopedGroupTypeStoreProvider, {
                get children() {
                  return createComponent(AvailableAttributesProvider, {
                    get children() {
                      return createComponent(ViewsProvider, {
                        get children() {
                          return createComponent(GanttWizardModal, {});
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
  });
  return openModal(Wrapper, {
    windowClass: "gantt-wizard-modal"
  });
}

// public/app/apps/cards/gantt/index.tsx
cardsAppRegistry.register("gantt", {
  component: "cards-app-gantt",
  navComponent: "cards-app-nav-gantt",
  title: _lazy("Gantt"),
  description: _lazy("An advanced view to plan visually and manage dependencies"),
  icon: "kfi-timeline",
  filterable: true,
  groupable: true,
  sortable: true,
  freeSort: false,
  projectScoped: true,
  // requireFeatureFlag: 'gantt',
  // featureFlagDescription: _lazy("Unlock Kantree's Project Management super power with Gantt view!"),
  // featureFlagImage: '',
  hiddenBehindFeatureFlag: "gantt",
  mobileReadOnly: true,
  // convertToImage: (title) => {
  //   $broadcast('displayAllGanttItems', true);
  //   const selector = '.timeline-view'
  //   const element = document.querySelector(selector);
  //   if (element) {
  //     const timelineWrapper = element.querySelector('.timeline-wrapper');
  //     const scrollbarHeight = timelineWrapper.offsetHeight - timelineWrapper.clientHeight;
  //     const scrollHeight = timelineWrapper.scrollHeight - scrollbarHeight;
  //     const scrollLeft = timelineWrapper.scrollLeft;
  //     const fragment = document.createDocumentFragment();
  //     const clonedElement = element.cloneNode(true);
  //     fragment.appendChild(clonedElement);
  //     const tempContainer = document.createElement('div');
  //     tempContainer.style.position = 'absolute';
  //     tempContainer.style.top = '-9999px';
  //     tempContainer.style.width = '100%';
  //     tempContainer.appendChild(fragment);
  //     document.body.appendChild(tempContainer);
  //     setTimeout(() => {
  //       const clonedTimelineWrapper = clonedElement.querySelector('.timeline-wrapper')
  //       clonedTimelineWrapper.classList.remove("enter-animation");
  //       clonedTimelineWrapper.style.overflow = "hidden";
  //       clonedTimelineWrapper.scrollLeft = scrollLeft;
  //       clonedElement
  //         .querySelectorAll('.timeline-card-creator-wrapper button')
  //         .forEach((el) => el.style.opacity = 0);
  //       setTimeout(() => {
  //         html2canvas(clonedElement, {
  //           allowTaint: true,
  //           useCORS: true,
  //           logging: true,
  //           scale: 2,
  //           height: scrollHeight,
  //           width: element.clientWidth
  //         }).then((canvas) => {
  //           document.body.removeChild(tempContainer);
  //           canvas.toBlob((blob) => {
  //             const url = URL.createObjectURL(blob);
  //             const a = document.createElement('a');
  //             a.href = url;
  //             a.download = `${title}.png`;
  //             document.body.appendChild(a);
  //             a.click();
  //             document.body.removeChild(a);
  //             URL.revokeObjectURL(url);
  //           });
  //         }).catch((error) => {
  //           console.error('Error capturing selector content:', error);
  //           document.body.removeChild(tempContainer);
  //         });
  //       }, 100);
  //     }, 100);
  //   } else {
  //     console.error('Element ' + selector + ' not found');
  //   }
  //   $broadcast('hideAllGanttItems', false);
  // },
  menu: (store2, board, groupBy2, options2 = {}, onChange) => {
    const project = board ? projectStore.tryGetForCard(board) : null;
    function getPickerRanges() {
      const ranges = {};
      for (let date of specialDateRanges) {
        ranges[date.displayedName] = [date.startDate, date.endDate];
      }
      return ranges;
    }
    const pickerOptions = {
      opens: "center",
      autoApply: true,
      ranges: getPickerRanges(),
      showCustomRangeLabel: false,
      alwaysShowCalendars: true
    };
    return {
      config: () => {
        const localDateRange = options2?.period || DEFAULT_PERIOD;
        const rangeForPicker = {
          start: moment_default(localDateRange.start),
          end: moment_default(localDateRange.end)
        };
        let items = [
          {
            subheader: _4("Visible period")
          },
          {
            component: "datepicker-menu-component",
            params: {
              date: () => rangeForPicker,
              options: () => pickerOptions,
              isRange: () => true,
              onDateChange: (start, end) => {
                const activeRange = dateRangeToActiveRange({
                  start,
                  end
                });
                if (isDateRangesEqual(rangeForPicker, activeRange)) return;
                const newDate = formatPeriodToString(activeRange);
                return onChange({
                  period: {
                    ...options2.period ?? {},
                    ...newDate || {}
                  }
                });
              }
            }
          },
          {
            label: _4("Configure Gantt"),
            icon: "bi-sliders",
            public: true,
            mobile: true,
            action: () => {
              openGanttWizardModal(() => project, () => store2);
            },
            enabled: () => canManageSettings(project)
          },
          {
            subheader: _4("Visibility of cards")
          },
          {
            checkbox: true,
            label: _4("Ungrouped"),
            offline: true,
            mobile: true,
            value: () => !!(options2 || {}).showUngroupedCards,
            toggle: () => onChange({
              showUngroupedCards: !(options2 || {}).showUngroupedCards
            })
          },
          {
            label: _4("Archived"),
            checkbox: true,
            value: () => (options2 || {}).include_archived,
            toggle: () => onChange({
              include_archived: !(options2 || {}).include_archived
            })
          },
          {
            label: _4("Display card titles"),
            submenu: [
              {
                label: _4("Hide"),
                public: true,
                mobile: true,
                action: () => onChange({
                  displayCardTitle: DisplayCardTitle.NONE
                }),
                selected: () => options2.displayCardTitle === DisplayCardTitle.NONE || !options2.displayCardTitle
              },
              // {
              //   label: _("After"),
              //   public: true,
              //   mobile: true,
              //   action: () => onChange({ displayCardTitle: DisplayCardTitle.AFTER }),
              //   selected: () => options.displayCardTitle === DisplayCardTitle.AFTER,
              // },
              {
                label: _4("Inside the period"),
                public: true,
                mobile: true,
                action: () => onChange({
                  displayCardTitle: DisplayCardTitle.INSIDE
                }),
                selected: () => options2.displayCardTitle === DisplayCardTitle.INSIDE
              }
            ]
          },
          {
            label: _4("Display density"),
            icon: "bi-reception-4",
            submenu: [{
              checkbox: true,
              switch: false,
              label: _4("Normal"),
              value: () => !(options2 || {}).displayDensity,
              toggle: () => onChange({
                displayDensity: DisplayDensity.NORMAL
              })
            }, {
              desc: _4("A good balance between space and information density")
            }, {
              checkbox: true,
              switch: false,
              label: _4("Compact"),
              value: () => (options2 || {}).displayDensity === DisplayDensity.COMPACT,
              toggle: () => onChange({
                displayDensity: DisplayDensity.COMPACT
              })
            }, {
              desc: _4("A dense layout to see more cards at once")
            }, {
              checkbox: true,
              switch: false,
              label: _4("Large"),
              value: () => (options2 || {}).displayDensity === DisplayDensity.LARGE,
              toggle: () => onChange({
                displayDensity: DisplayDensity.LARGE
              })
            }, {
              desc: _4("A lot of space for greater readability")
            }]
          },
          {
            label: "--"
          },
          {
            subheader: _4("More")
          },
          // {
          //   checkbox: true,
          //   label: _('Display content out of cards'),
          //   offline: true,
          //   mobile: true,
          //   value: () => !!(options || {}).enableSideDisplay,
          //   toggle: () => onChange({enableSideDisplay: !(options || {}).enableSideDisplay})
          // },
          {
            checkbox: true,
            label: _4("Display critical path"),
            offline: true,
            mobile: true,
            value: () => !!(options2 || {}).displayCriticalPath,
            toggle: () => onChange({
              displayCriticalPath: !(options2 || {}).displayCriticalPath
            })
          },
          {
            checkbox: true,
            label: _4("Strike done cards"),
            offline: true,
            mobile: true,
            value: () => !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0,
            // Default to TRUE
            toggle: () => onChange({
              strikeDoneCards: !!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0 ? false : void 0
            })
          },
          {
            checkbox: true,
            label: _4("Hide empty groups"),
            offline: false,
            mobile: true,
            value: () => !!(options2 || {}).hideEmptyGroups,
            toggle: () => onChange({
              hideEmptyGroups: !(options2 || {}).hideEmptyGroups
            })
          },
          {
            label: _4("iCalendar feed"),
            icon: "link",
            public: false,
            offline: false,
            action: () => $invoke(["cardICalendarModal", (cardICalendarModal) => cardICalendarModal.open({
              id: board.id
            })]),
            enabled: () => !!board
          },
          {
            label: _4("Maximize / minimize"),
            submenu: [{
              label: _4("Maximize all"),
              public: true,
              mobile: true,
              action: () => {
                $broadcast("maximizeAllCards");
              }
            }, {
              label: _4("Minimize all"),
              public: true,
              mobile: true,
              action: () => {
                $broadcast("minimizeAllCards");
              }
            }]
          },
          ...project ? [getFullScreenOption()] : []
        ];
        items = items.concat(getActionsOptions(options2, (changes) => onChange(changes), project));
        return items;
      }
    };
  }
});

// public/app/apps/cards/quadrant/options-menu/axis.ts
var xAxisPosition = [{ name: "top" }, { name: "bottom" }];
function createAxisSubmenu(axisSerie, index2, availableAxeAttributes, options2, onChange) {
  const defaultAxis = {
    name: "",
    cardAttribute: "",
    showGraduation: true,
    step: null,
    min: null,
    max: null,
    type: "number",
    reverse: false,
    position: "bottom"
  };
  const safeAxisSerie = axisSerie || {
    x: { ...defaultAxis, position: "bottom" },
    y: { ...defaultAxis, position: "left" },
    size: "",
    color: ""
  };
  axisSerie = !axisSerie || !axisSerie[index2]?.x?.cardAttribute && !axisSerie[index2]?.y?.cardAttribute ? safeAxisSerie : axisSerie;
  const activeAxisSeries = Array.isArray(options2?.activeAxisSeries) && options2.activeAxisSeries.length > 0 ? options2.activeAxisSeries : [safeAxisSerie];
  const axeFieldsList = Array.from(availableAxeAttributes.values());
  return [
    { subheader: _4("X Axis field") },
    {
      selectbox: true,
      select: (selectedOption) => {
        const updatedAxisSeries = [...activeAxisSeries];
        updatedAxisSeries[index2] = {
          ...updatedAxisSeries[index2],
          x: {
            ...updatedAxisSeries[index2].x,
            cardAttribute: selectedOption.name,
            type: selectedOption.getType().name
          }
        };
        onChange({ activeAxisSeries: updatedAxisSeries });
      },
      selectOptions: axeFieldsList.filter(
        (attr) => attr.name !== activeAxisSeries[index2].y.cardAttribute
      ),
      defaultValue: axisSerie.x.cardAttribute ? axeFieldsList.find((n4) => n4.name === axisSerie.x.cardAttribute) : null,
      optionsLabelProperty: "name",
      noCloseAfterAction: true
    },
    {
      label: _4("More options..."),
      submenu: getAxisSettingSubmenu(axisSerie, index2, "x", activeAxisSeries, onChange)
    },
    { label: "--" },
    { subheader: _4("Y Axis field") },
    {
      selectbox: true,
      select: (selectedOption) => {
        const updatedAxisSeries = [...activeAxisSeries];
        updatedAxisSeries[index2] = {
          ...updatedAxisSeries[index2],
          y: {
            ...updatedAxisSeries[index2].y,
            cardAttribute: selectedOption.name,
            type: selectedOption.getType().name
          }
        };
        onChange({ activeAxisSeries: updatedAxisSeries });
      },
      selectOptions: axeFieldsList.filter(
        (attr) => attr.name !== activeAxisSeries[index2].x.cardAttribute
      ),
      defaultValue: axisSerie.y.cardAttribute ? axeFieldsList.find((n4) => n4.name === axisSerie.y.cardAttribute) : null,
      optionsLabelProperty: "name",
      noCloseAfterAction: true
    },
    {
      label: _4("More options..."),
      submenu: getAxisSettingSubmenu(axisSerie, index2, "y", activeAxisSeries, onChange)
    },
    { label: "--" },
    { subheader: _4("Size field") },
    {
      selectbox: true,
      select: (selectedOption) => {
        const updatedAxisSeries = [...activeAxisSeries];
        updatedAxisSeries[index2] = {
          ...updatedAxisSeries[index2],
          size: selectedOption.name
        };
        onChange({ activeAxisSeries: updatedAxisSeries });
      },
      selectOptions: axeFieldsList,
      defaultValue: axisSerie.size ? axeFieldsList.find((n4) => n4.name === axisSerie.size) : null,
      optionsLabelProperty: "name",
      noCloseAfterAction: true
    },
    { label: "--" },
    {
      label: _4("Remove Axis Pair"),
      icon: "trash",
      action: () => {
        const updatedAxisSeries = activeAxisSeries.filter(
          (_5, i3) => i3 !== index2
        );
        onChange({ activeAxisSeries: updatedAxisSeries });
      },
      noCloseAfterAction: true,
      backAfterAction: true
    }
  ];
}
function getAxisSettingSubmenu(axisSerie, index2, axisType, activeAxisSeries, onChange) {
  const axis = axisSerie[axisType];
  return [
    { subheader: _4("Name (optional)") },
    {
      input: true,
      defaultValue: axis.name || "",
      submit: (value2) => {
        const updatedAxisSeries = [...activeAxisSeries];
        updatedAxisSeries[index2] = {
          ...updatedAxisSeries[index2],
          [axisType]: {
            ...updatedAxisSeries[index2][axisType],
            name: value2
          }
        };
        onChange({ activeAxisSeries: updatedAxisSeries });
      }
    },
    {
      label: _4("Reverse direction"),
      checkbox: true,
      value: () => axis.reverse,
      toggle: () => {
        const updatedAxisSeries = [...activeAxisSeries];
        updatedAxisSeries[index2] = {
          ...updatedAxisSeries[index2],
          [axisType]: {
            ...updatedAxisSeries[index2][axisType],
            reverse: !axis.reverse
          }
        };
        onChange({ activeAxisSeries: updatedAxisSeries });
      }
    },
    { subheader: _4("Position") },
    {
      selectbox: true,
      select: (selectedOption) => {
        const updatedAxisSeries = [...activeAxisSeries];
        updatedAxisSeries[index2] = {
          ...updatedAxisSeries[index2],
          [axisType]: {
            ...updatedAxisSeries[index2][axisType],
            position: selectedOption.name
          }
        };
        onChange({ activeAxisSeries: updatedAxisSeries });
      },
      selectOptions: xAxisPosition,
      defaultValue: xAxisPosition.find((n4) => n4.name === axis.position) || (index2 % 2 === 0 ? xAxisPosition[1] : xAxisPosition[0]),
      optionsLabelProperty: "name",
      noCloseAfterAction: true
    }
  ];
}

// public/app/ui/quadrant/components/sidebarGroup.tsx
var _tmpl$90 = /* @__PURE__ */ template(`<div class="quadrant-sidebar_group-header root"><div class="title"><span class="title-text"></span></div></div>`, 6);
var _tmpl$232 = /* @__PURE__ */ template(`<div class="quadrant-sidebar_group-header"><div class="title title-indented"><div class="title-text draggable"><span></span></div></div></div>`, 8);
var _tmpl$321 = /* @__PURE__ */ template(`<div class="quadrant-sidebar_group-items"></div>`, 2);
var _tmpl$417 = /* @__PURE__ */ template(`<div class="quadrant-sidebar_group"></div>`, 2);
var SidebarGroup = (props2) => {
  const quadrantViewContext = useQuadrantViewContext();
  const store2 = useQuadrantItem();
  const activeAxisSeries = useActiveAxisSeries();
  const options2 = useOptions();
  const project = useProject();
  let validAttributes = false;
  for (const serie of activeAxisSeries()) {
    const availableAxeAttributes = quadrantViewContext.availableAxeAttributes();
    const attributeGroupMap = /* @__PURE__ */ new Map();
    const xAttributeGroup = availableAxeAttributes?.get(serie.x.cardAttribute);
    const yAttributeGroup = availableAxeAttributes?.get(serie.y.cardAttribute);
    if (xAttributeGroup && yAttributeGroup) {
      attributeGroupMap.set(serie.x.cardAttribute, xAttributeGroup);
      attributeGroupMap.set(serie.y.cardAttribute, yAttributeGroup);
      if (areAttributesAvailableForCard(store2.card, attributeGroupMap)) {
        validAttributes = true;
      }
    }
  }
  const filterMatch = createMemo(() => {
    const hasEmptyPoints = Object.values(store2.coordinates).some((coordinate) => coordinate.points?.length > 0);
    return store2.isVisibleInSidebar && (props2.displayIds === null || !store2.card?.id || props2.displayIds.includes(store2.card?.id)) && (store2.isRoot || options2.include_archived ? true : !store2?.card?.is_archived) && !hasEmptyPoints;
  });
  const indentation = () => (store2.path.length - 1) * 16;
  const fontWeight = () => store2.children?.length > 0 ? "bold" : "thin";
  const children2 = () => store2.children;
  const toggleChildrenVisibility = (event2) => {
    event2.stopPropagation();
    store2.displayChildren = !store2.displayChildren;
  };
  const openCardModal = (e3) => {
    quadrantViewContext.cardModal?.open(store2.card);
  };
  const draggableOptions = {
    onDragStart: (e3) => handleDragStart(store2, e3),
    onDragEnd: (e3) => handleDragEnd(store2, e3)
  };
  const isDraggable = createMemo(() => {
    const xAttr = quadrantViewContext.availableAxeAttributes().get(activeAxisSeries()[0].x.cardAttribute);
    const yAttr = quadrantViewContext.availableAxeAttributes().get(activeAxisSeries()[0].y.cardAttribute);
    return isOnline() && !options2.readOnly && canEditAttribute(project(), xAttr[0]) && canEditAttribute(project(), yAttr[0]);
  });
  const toggleIcon = () => store2?.displayChildren ? "bi-dash-square-dotted" : "bi-plus-square-dotted";
  return (() => {
    const _el$ = _tmpl$417.cloneNode(true);
    insert(_el$, createComponent(Show, {
      get when() {
        return filterMatch() && validAttributes;
      },
      get children() {
        return [createComponent(Show, {
          get when() {
            return store2.isRoot;
          },
          get children() {
            const _el$2 = _tmpl$90.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild;
            insert(_el$3, () => createComponent(Show, {
              get when() {
                return children2().length > 0;
              },
              get children() {
                return createComponent(IconButton, {
                  "class": "toggle-button",
                  get icon() {
                    return toggleIcon();
                  },
                  onClick: toggleChildrenVisibility
                });
              }
            }), _el$4);
            insert(_el$4, () => store2.title);
            return _el$2;
          }
        }), createComponent(Show, {
          get when() {
            return !store2.isRoot;
          },
          get children() {
            const _el$5 = _tmpl$232.cloneNode(true), _el$6 = _el$5.firstChild, _el$7 = _el$6.firstChild, _el$8 = _el$7.firstChild;
            insert(_el$6, () => createComponent(Show, {
              get when() {
                return children2().length > 0;
              },
              get children() {
                return createComponent(IconButton, {
                  "class": "toggle-button",
                  get icon() {
                    return toggleIcon();
                  },
                  onClick: toggleChildrenVisibility
                });
              }
            }), _el$7);
            _el$7.addEventListener("dragend", (e3) => handleDragEnd(store2, e3));
            _el$7.addEventListener("dragstart", (e3) => handleDragStart(store2, e3));
            _el$7.$$click = openCardModal;
            insert(_el$8, () => store2.card?.title);
            createRenderEffect((_p$) => {
              const _v$ = !!(store2.card?.finished || store2.card?.is_archived), _v$2 = fontWeight(), _v$3 = `${indentation()}px`, _v$4 = isOnline();
              _v$ !== _p$._v$ && _el$5.classList.toggle("finished", _p$._v$ = _v$);
              _v$2 !== _p$._v$2 && _el$5.style.setProperty("font-weight", _p$._v$2 = _v$2);
              _v$3 !== _p$._v$3 && _el$6.style.setProperty("--indentation", _p$._v$3 = _v$3);
              _v$4 !== _p$._v$4 && setAttribute(_el$7, "draggable", _p$._v$4 = _v$4);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0,
              _v$3: void 0,
              _v$4: void 0
            });
            return _el$5;
          }
        }), createComponent(Show, {
          get when() {
            return children2() && store2.displayChildren !== false;
          },
          get children() {
            const _el$9 = _tmpl$321.cloneNode(true);
            insert(_el$9, createComponent(For, {
              get each() {
                return children2();
              },
              children: (item) => createComponent(NodeItemProvider2, {
                store: item,
                get children() {
                  return createComponent(SidebarGroup, {
                    get displayIds() {
                      return props2.displayIds;
                    }
                  });
                }
              })
            }));
            return _el$9;
          }
        })];
      }
    }));
    createRenderEffect(() => _el$.classList.toggle("root", !!store2.isRoot));
    return _el$;
  })();
};
delegateEvents(["click"]);

// public/app/ui/quadrant/components/nodeItemProvider.tsx
var NodeItemProvider2 = (props2) => createComponent(QuadrantItemProvider, {
  get store() {
    return props2.store;
  },
  get children() {
    return props2.children;
  }
});

// public/app/ui/quadrant/components/canvas.tsx
var _tmpl$91 = /* @__PURE__ */ template(`<div class="canvas"></div>`, 2);
var _tmpl$233 = /* @__PURE__ */ template(`<div class="zone-ghost"></div>`, 2);
var Canvas = (props2) => {
  const options2 = useOptions();
  const quadrantStore = useQuadrantStore();
  const quadrantViewContext = useQuadrantViewContext();
  const activeAxisSeries = useActiveAxisSeries();
  const project = useProject();
  const {
    zones,
    ghostZone,
    editingZone,
    handleZoneDoubleClick,
    handleZoneUpdate,
    handleDeleteZone,
    handleDrawingMove,
    handleDrawingEnd
  } = createZonesManager();
  const [dropdownPosition, setDropdownPosition] = createSignal(null);
  const [selectedCard, setSelectedCard] = createSignal(null);
  const [isDrawingZone, setIsDrawingZone] = createSignal(false);
  const [startPos, setStartPos] = createSignal({
    x: 0,
    y: 0
  });
  let validAxisSeries = [];
  let lastCanvasSize = {
    width: 0,
    height: 0
  };
  onMount(() => {
    const canvas = document.querySelector(".canvas");
    if (!canvas) return;
    const debouncedResize = debounce2(() => {
      const rect = canvas.getBoundingClientRect();
      const newCanvasSize = {
        width: rect.width,
        height: rect.height
      };
      if (lastCanvasSize.width === 0 || lastCanvasSize.height === 0) {
        lastCanvasSize = newCanvasSize;
        return;
      }
      const scaleX = newCanvasSize.width / lastCanvasSize.width;
      const scaleY = newCanvasSize.height / lastCanvasSize.height;
      const zonesList = zones();
      const scaledZones = zonesList.map((zone) => {
        if (!zone.isCustom) return zone;
        return {
          ...zone,
          left: zone.left * scaleX,
          top: zone.top * scaleY,
          width: zone.width * scaleX,
          height: zone.height * scaleY
        };
      });
      const updatedZoneLayout = {
        ...options2.zoneLayout,
        zones: scaledZones
      };
      quadrantViewContext.onChange({
        options: JSON.parse(JSON.stringify({
          ...options2.state,
          zoneLayout: updatedZoneLayout
        }))
      });
      const newTitlePositions = {};
      scaledZones.forEach((zone, index2) => {
        const pos = findBestTitlePosition(scaledZones, index2, rect);
        if (pos) {
          newTitlePositions[index2] = {
            ...pos,
            name: zone.name,
            isCustom: zone.isCustom,
            color: zone.backgroundColor
          };
        }
      });
      quadrantStore.setState("zoneTitlePositions", newTitlePositions);
      lastCanvasSize = newCanvasSize;
    }, 100);
    const observer = new ResizeObserver(debouncedResize);
    observer.observe(canvas);
    onCleanup(() => observer.disconnect());
  });
  const handleMouseDown = (e3) => {
    if (e3.ctrlKey) {
      setIsDrawingZone(true);
      setStartPos({
        x: e3.clientX,
        y: e3.clientY
      });
    }
  };
  const handleMouseMove = (e3) => {
    if (isDrawingZone()) {
      const canvasRect = e3.currentTarget.getBoundingClientRect();
      const xPos = e3.clientX - canvasRect.left;
      const yPos = e3.clientY - canvasRect.top;
      handleDrawingMove({
        x: xPos,
        y: yPos,
        startX: startPos().x - canvasRect.left,
        startY: startPos().y - canvasRect.top
      });
    }
  };
  const handleMouseUp = () => {
    if (isDrawingZone()) {
      setIsDrawingZone(false);
      handleDrawingEnd();
    }
  };
  const handleZoneContextMenu = (e3, index2) => {
    e3.preventDefault();
    handleZoneDoubleClick(index2);
  };
  const handleDrop = async (e3) => {
    if (options2.readOnly) {
      return;
    }
    e3.preventDefault();
    const cardId = e3.dataTransfer.getData("text/plain");
    const card = props2.cards().find((card2) => card2.id == cardId);
    if (card) {
      const canvasRect = e3.currentTarget.getBoundingClientRect();
      const xPos = (e3.clientX - canvasRect.left) / canvasRect.width * 100;
      const yPos = (e3.clientY - canvasRect.top) / canvasRect.height * 100;
      if (xPos < 0 || yPos < 0) {
        return;
      }
      validAxisSeries = activeAxisSeries().filter((series) => series.x.cardAttribute.length > 0 && series.y.cardAttribute.length > 0 && series.x.type && series.y.type && series.x.type !== "lookup" && series.x.type !== "formula" && series.y.type !== "lookup" && series.y.type !== "formula" && series.x.type === "group_type" ? groupHaveElements(series.x, quadrantViewContext, quadrantStore) : series.y.type === "group_type" ? groupHaveElements(series.y, quadrantViewContext, quadrantStore) : true);
      if (validAxisSeries.length === 1) {
        const xAxis = validAxisSeries[0].x;
        const yAxis = validAxisSeries[0].y;
        const xValue = calculateValueFromPercentagePosition(xPos, xAxis);
        const yValue = calculateValueFromPercentagePosition(yPos, yAxis, !yAxis.reverse);
        const xAttribute = xAxis.cardAttribute;
        const yAttribute = yAxis.cardAttribute;
        const key2 = `${xAttribute}-${yAttribute}-0`;
        const point = [{
          x: xPos,
          y: yPos
        }];
        if (xAxis.type === "group_type" || yAxis.type === "group_type") {
          await card.updateCardGroups({
            axis: {
              x: xAxis,
              y: yAxis
            }
          }, xValue, yValue, null, null, quadrantViewContext, quadrantStore);
        }
        await card.updateCardAttributes(project, quadrantViewContext, xAxis.cardAttribute, yAxis.cardAttribute, xValue, yValue);
        card.setState((prevState) => ({
          coordinates: {
            ...prevState.coordinates,
            [key2]: {
              xAttribute,
              yAttribute,
              point,
              serieIndex: 0
            }
          },
          isVisibleInSidebar: false
        }));
      } else if (validAxisSeries.length > 1) {
        setSelectedCard(card);
        setDropdownPosition({
          x: e3.clientX - canvasRect.left,
          y: e3.clientY - canvasRect.top
        });
      } else {
        console.log("Cancel the drop action - no valid axis pairs available");
        return;
      }
    }
  };
  const handleDragOver = (e3) => {
    e3.preventDefault();
  };
  const handleAxisPairSelection = async (index2) => {
    const card = selectedCard();
    if (card) {
      const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
      const xPos = dropdownPosition().x / canvasRect.width * 100;
      const yPos = dropdownPosition().y / canvasRect.height * 100;
      if (xPos < 0 || yPos < 0) {
        setDropdownPosition(null);
        setSelectedCard(null);
        return;
      }
      const xAxis = activeAxisSeries()[index2()].x;
      const yAxis = activeAxisSeries()[index2()].y;
      const xValue = calculateValueFromPercentagePosition(xPos, xAxis);
      const yValue = calculateValueFromPercentagePosition(yPos, yAxis, !yAxis.reverse);
      const xAttribute = xAxis.cardAttribute;
      const yAttribute = yAxis.cardAttribute;
      const key2 = `${xAttribute}-${yAttribute}-${index2()}`;
      const point = [{
        x: xPos,
        y: yPos
      }];
      if (xAxis.type === "group_type" || yAxis.type === "group_type") {
        await card.updateCardGroups({
          axis: {
            x: xAxis,
            y: yAxis
          }
        }, xValue, yValue, null, null, quadrantViewContext, quadrantStore);
      }
      await card.updateCardAttributes(project, quadrantViewContext, xAxis.cardAttribute, yAxis.cardAttribute, xValue, yValue);
      card.setState((prevState) => ({
        coordinates: {
          ...prevState.coordinates,
          [key2]: {
            xAttribute,
            yAttribute,
            point,
            serieIndex: index2()
          }
        },
        isVisibleInSidebar: false
      }));
      setDropdownPosition(null);
      setSelectedCard(null);
    }
  };
  const storeGroups = () => {
    const quadrantStore2 = useQuadrantStore();
    const options3 = useOptions();
    const allGroups = /* @__PURE__ */ new Map();
    for (const serie of activeAxisSeries()) {
      for (const axisName of ["x", "y"]) {
        const axis = serie[axisName];
        if (axis.type === "group_type") {
          const namedAttrGroup = useQuadrantViewContext().activeAxeAttributes().get(axis.cardAttribute);
          if (namedAttrGroup && namedAttrGroup.length > 0) {
            const groupTypeId = namedAttrGroup[0].group_type_id;
            const groupType = cardGroupTypeStore.tryGet(groupTypeId);
            if (groupType) {
              const groupStore = cardGroupStore.scopedByType(groupType, project().top_level_card).scoped({
                is_archived: (v3) => options3.include_archived ? true : !v3
              });
              const groups = groupStore.query();
              groups.forEach((group2) => {
                if (!allGroups.has(group2.type_id)) {
                  allGroups.set(group2.type_id, /* @__PURE__ */ new Map());
                }
                if (!allGroups.get(group2.type_id).has(group2.title)) {
                  allGroups.get(group2.type_id).set(group2.title, group2);
                }
              });
            }
          }
        }
      }
    }
    quadrantStore2.setState("availableGroupType", allGroups);
  };
  createEffect(() => {
    storeGroups();
  });
  return (() => {
    const _el$ = _tmpl$91.cloneNode(true);
    _el$.addEventListener("drop", handleDrop);
    _el$.addEventListener("dragover", handleDragOver);
    _el$.$$mouseup = handleMouseUp;
    _el$.$$mousemove = handleMouseMove;
    _el$.$$mousedown = handleMouseDown;
    insert(_el$, createComponent(ClusterManager, {
      get cards() {
        return props2.cards;
      }
    }), null);
    insert(_el$, () => zones().map((zone, index2) => createComponent(Zone, {
      zone,
      index: index2,
      onDoubleClick: () => handleZoneDoubleClick(index2),
      onUpdate: handleZoneUpdate,
      onDelete: () => handleDeleteZone(index2),
      get editing() {
        return editingZone() === index2;
      },
      onContextMenu: (e3) => handleZoneContextMenu(e3, index2)
    })), null);
    insert(_el$, (() => {
      const _c$ = createMemo(() => !!ghostZone());
      return () => _c$() && (() => {
        const _el$2 = _tmpl$233.cloneNode(true);
        _el$2.style.setProperty("position", "absolute");
        _el$2.style.setProperty("border", "1px dashed #999");
        _el$2.style.setProperty("pointer-events", "none");
        _el$2.style.setProperty("z-index", "4");
        createRenderEffect((_p$) => {
          const _v$ = `${ghostZone().left}px`, _v$2 = `${ghostZone().top}px`, _v$3 = `${ghostZone().width}px`, _v$4 = `${ghostZone().height}px`, _v$5 = ghostZone().backgroundColor;
          _v$ !== _p$._v$ && _el$2.style.setProperty("left", _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && _el$2.style.setProperty("top", _p$._v$2 = _v$2);
          _v$3 !== _p$._v$3 && _el$2.style.setProperty("width", _p$._v$3 = _v$3);
          _v$4 !== _p$._v$4 && _el$2.style.setProperty("height", _p$._v$4 = _v$4);
          _v$5 !== _p$._v$5 && _el$2.style.setProperty("background-color", _p$._v$5 = _v$5);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0,
          _v$4: void 0,
          _v$5: void 0
        });
        return _el$2;
      })();
    })(), null);
    insert(_el$, createComponent(ZoneTitles, {}), null);
    insert(_el$, createComponent(Grid, {}), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return dropdownPosition();
      },
      get children() {
        return createComponent(Dropdown2, {
          get position() {
            return dropdownPosition();
          },
          get options() {
            return validAxisSeries.map((series) => ({
              label: `${series.x.cardAttribute} - ${series.y.cardAttribute}`
            }));
          },
          onSelect: handleAxisPairSelection,
          onClose: () => setDropdownPosition(null)
        });
      }
    }), null);
    return _el$;
  })();
};
delegateEvents(["mousedown", "mousemove", "mouseup"]);

// public/app/ui/quadrant/components/legend.tsx
var _tmpl$95 = /* @__PURE__ */ template(`<div></div>`, 2);
var _tmpl$234 = /* @__PURE__ */ template(`<div class="legend-attribute"></div>`, 2);
var _tmpl$322 = /* @__PURE__ */ template(`<div><div class="legend-graduation"><div class="legend-line"></div></div></div>`, 6);
var Legend = (props2) => {
  const quadrantStore = useQuadrantStore();
  const activeAxisSeries = useActiveAxisSeries();
  const isFirstLegend = createMemo(() => {
    const position = props2.position;
    const firstLegendIndex = activeAxisSeries().findIndex((series) => {
      return position === "top" || position === "bottom" ? series.x.position === position : series.y.position === position;
    });
    return !quadrantStore.hoveredPoint && firstLegendIndex === activeAxisSeries().indexOf(props2.axisPair);
  });
  const values2 = createMemo(() => {
    const {
      min: min3,
      max: max3,
      step: step2,
      reverse
    } = props2.axis;
    if (min3 === void 0 || max3 === void 0 || step2 === void 0) return [];
    const gradations = [];
    for (let value2 = min3; value2 <= max3; value2 += step2) {
      if (!gradations.includes(value2)) {
        gradations.push(value2);
      }
    }
    if (reverse) gradations.reverse();
    return gradations;
  });
  const shouldDisplayValue = (index2, total, position) => {
    let displayFrequency = Math.max(1, Math.floor(total / 10));
    return total <= 5 || index2 % displayFrequency === 0 && position > 0 && position < 100;
  };
  const getPositionStyle = (percentage) => {
    const isHorizontal = props2.position === "top" || props2.position === "bottom";
    const axis = isHorizontal ? "left" : "top";
    const transform = isHorizontal ? "translateX(-50%)" : "translateY(-50%)";
    return {
      [axis]: `${percentage}%`,
      transform
    };
  };
  const renderHoveredPointItems = () => {
    if (JSON.stringify(quadrantStore.hoveredPoint?.[0]?.coordinates.axis) !== JSON.stringify(props2.axisPair)) return null;
    const {
      x: x3,
      y: y3
    } = quadrantStore.hoveredPoint[0].coordinates;
    const percentage = props2.position === "top" || props2.position === "bottom" ? x3 : y3;
    const value2 = calculateValueFromPercentagePosition(percentage, props2.axis, props2.position === "top" || props2.position === "bottom" ? props2.axis.reverse : !props2.axis.reverse);
    return percentage >= 0 && percentage <= 100 && (() => {
      const _el$ = _tmpl$95.cloneNode(true);
      insert(_el$, () => formatValue(props2.axis.values?.[value2] ?? value2, props2.axis, values2()));
      createRenderEffect((_p$) => {
        const _v$ = `legend-item ${props2.position}`, _v$2 = getPositionStyle(percentage);
        _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
        _p$._v$2 = style(_el$, _v$2, _p$._v$2);
        return _p$;
      }, {
        _v$: void 0,
        _v$2: void 0
      });
      return _el$;
    })();
  };
  const renderStaticLegendItems = () => {
    const usedPositions = /* @__PURE__ */ new Set();
    return values2().map((value2, index2) => {
      const position = calculatePercentagePosition(value2, props2.axis, props2.position === "top" || props2.position === "bottom" ? props2.axis.reverse : !props2.axis.reverse);
      if (usedPositions.has(position)) {
        return null;
      }
      usedPositions.add(position);
      return shouldDisplayValue(index2, values2().length, position) && (() => {
        const _el$2 = _tmpl$95.cloneNode(true);
        insert(_el$2, () => formatValue(props2.axis.values?.[value2] ?? value2, props2.axis, values2()));
        createRenderEffect((_p$) => {
          const _v$3 = `legend-item ${props2.position}`, _v$4 = getPositionStyle(position);
          _v$3 !== _p$._v$3 && className(_el$2, _p$._v$3 = _v$3);
          _p$._v$4 = style(_el$2, _v$4, _p$._v$4);
          return _p$;
        }, {
          _v$3: void 0,
          _v$4: void 0
        });
        return _el$2;
      })();
    }).filter((item) => item !== null);
  };
  const shouldDisplayLegend = createMemo(() => {
    return isFirstLegend() || JSON.stringify(quadrantStore.hoveredPoint?.[0]?.coordinates.axis) == JSON.stringify(props2.axisPair);
  });
  return (() => {
    const _el$3 = _tmpl$322.cloneNode(true), _el$5 = _el$3.firstChild, _el$6 = _el$5.firstChild;
    insert(_el$3, createComponent(Show, {
      get when() {
        return shouldDisplayLegend();
      },
      get children() {
        const _el$4 = _tmpl$234.cloneNode(true);
        insert(_el$4, () => props2.axis.name || props2.axis.cardAttribute);
        return _el$4;
      }
    }), _el$5);
    insert(_el$5, createComponent(Show, {
      get when() {
        return shouldDisplayLegend();
      },
      get children() {
        return createMemo(() => !!quadrantStore.hoveredPoint)() ? renderHoveredPointItems() : renderStaticLegendItems();
      }
    }), null);
    createRenderEffect(() => className(_el$3, `legend ${props2.position}`));
    return _el$3;
  })();
};

// public/app/ui/quadrant/components/grid.tsx
var _tmpl$96 = /* @__PURE__ */ template(`<div class="hover-line"></div>`, 2);
var _tmpl$235 = /* @__PURE__ */ template(`<div class="grid"></div>`, 2);
var _tmpl$323 = /* @__PURE__ */ template(`<div></div>`, 2);
var maxLinesByAxe = 100;
var Grid = () => {
  const options2 = useOptions();
  const quadrantStore = useQuadrantStore();
  const activeAxisSeries = useActiveAxisSeries();
  const [currentAxis, setCurrentAxis] = createSignal({
    x: null,
    y: null
  });
  const [allLines, setAllLines] = createSignal({
    x: {},
    y: {}
  });
  const [visibleLines, setVisibleLines] = createSignal([]);
  const prepareLines = (series) => {
    const newLines = {
      x: {},
      y: {}
    };
    const {
      x: x3,
      y: y3
    } = series;
    if (x3.min !== null && x3.max !== null && x3.step !== null && y3.min !== null && y3.max !== null && y3.step !== null) {
      if ((x3.max - x3.min) / x3.step <= maxLinesByAxe) {
        for (let value2 = x3.min; value2 <= x3.max; value2 += x3.step) {
          newLines.x[value2] = {
            value: value2,
            axis: "x",
            cardAttribute: x3.cardAttribute,
            type: x3.type,
            min: x3.min,
            max: x3.max,
            reverse: x3.reverse
          };
        }
      }
      if ((y3.max - y3.min) / y3.step <= maxLinesByAxe) {
        for (let value2 = y3.min; value2 <= y3.max; value2 += y3.step) {
          newLines.y[value2] = {
            value: value2,
            axis: "y",
            cardAttribute: y3.cardAttribute,
            type: y3.type,
            min: y3.min,
            max: y3.max,
            reverse: !y3.reverse
          };
        }
      }
    }
    return newLines;
  };
  const updateAllLines = () => {
    const allPreparedLines = {
      x: {},
      y: {}
    };
    activeAxisSeries().forEach((series) => {
      const lines = prepareLines(series);
      allPreparedLines.x = {
        ...allPreparedLines.x,
        ...lines.x
      };
      allPreparedLines.y = {
        ...allPreparedLines.y,
        ...lines.y
      };
    });
    setAllLines(allPreparedLines);
  };
  const updateVisibleLines = (axis) => {
    const visiblePreparedLines = [];
    if (axis) {
      for (const value2 of Object.values(allLines().x)) {
        if (value2.cardAttribute === axis.x) {
          visiblePreparedLines.push(value2);
        }
      }
      for (const value2 of Object.values(allLines().y)) {
        if (value2.cardAttribute === axis.y) {
          visiblePreparedLines.push(value2);
        }
      }
    }
    setVisibleLines(visiblePreparedLines);
  };
  createEffect(() => {
    updateAllLines();
    if (activeAxisSeries().length > 0) {
      const firstSeries = activeAxisSeries()[0];
      setCurrentAxis({
        x: firstSeries.x.cardAttribute,
        y: firstSeries.y.cardAttribute
      });
      updateVisibleLines({
        x: firstSeries.x.cardAttribute,
        y: firstSeries.y.cardAttribute
      });
    }
  });
  createEffect(() => {
    if (quadrantStore.hoveredPoint) {
      const hoveredPoint = quadrantStore.hoveredPoint[0];
      setCurrentAxis({
        x: hoveredPoint.coordinates.axis.x.cardAttribute,
        y: hoveredPoint.coordinates.axis.y.cardAttribute
      });
      updateVisibleLines({
        x: hoveredPoint.coordinates.axis.x.cardAttribute,
        y: hoveredPoint.coordinates.axis.y.cardAttribute
      });
    } else if (activeAxisSeries().length > 0) {
      const firstSeries = activeAxisSeries()[0];
      setCurrentAxis({
        x: firstSeries.x.cardAttribute,
        y: firstSeries.y.cardAttribute
      });
      updateVisibleLines({
        x: firstSeries.x.cardAttribute,
        y: firstSeries.y.cardAttribute
      });
    }
  });
  const getLinePosition = (line) => {
    return `${calculatePercentagePosition(line.value, line)}%`;
  };
  const getLineClass = (line) => {
    return visibleLines().includes(line) ? "visible" : "";
  };
  const renderHoverLines = () => {
    if (!quadrantStore.hoveredPoint) return null;
    const point = quadrantStore.hoveredPoint[0];
    const xLineStyle = {
      left: `${point.coordinates.x}%`,
      top: "0",
      height: "100%",
      width: "1px",
      "background-color": point.color
    };
    const yLineStyle = {
      top: `${point.coordinates.y}%`,
      left: "0",
      width: "100%",
      height: "1px",
      "background-color": point.color
    };
    return [createComponent(Show, {
      get when() {
        return point.coordinates.x >= 0 && point.coordinates.x <= 100;
      },
      get children() {
        const _el$ = _tmpl$96.cloneNode(true);
        createRenderEffect((_$p) => style(_el$, xLineStyle, _$p));
        return _el$;
      }
    }), createComponent(Show, {
      get when() {
        return point.coordinates.y >= 0 && point.coordinates.y <= 100;
      },
      get children() {
        const _el$2 = _tmpl$96.cloneNode(true);
        createRenderEffect((_$p) => style(_el$2, yLineStyle, _$p));
        return _el$2;
      }
    })];
  };
  return (() => {
    const _el$3 = _tmpl$235.cloneNode(true);
    insert(_el$3, createComponent(Show, {
      get when() {
        return options2.showGrid;
      },
      get children() {
        return createComponent(For, {
          get each() {
            return [...Object.values(allLines().x), ...Object.values(allLines().y)];
          },
          children: (line) => (() => {
            const _el$4 = _tmpl$323.cloneNode(true);
            createRenderEffect((_p$) => {
              const _v$ = `grid-line ${line.axis} ${getLineClass(line)}`, _v$2 = {
                [line.axis === "x" ? "left" : "top"]: getLinePosition(line)
              };
              _v$ !== _p$._v$ && className(_el$4, _p$._v$ = _v$);
              _p$._v$2 = style(_el$4, _v$2, _p$._v$2);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0
            });
            return _el$4;
          })()
        });
      }
    }), null);
    insert(_el$3, renderHoverLines, null);
    return _el$3;
  })();
};

// public/app/ui/quadrant/components/zone.tsx
var _tmpl$97 = /* @__PURE__ */ template(`<div class="zone-container"></div>`, 2);
var _tmpl$236 = /* @__PURE__ */ template(`<button>\u274C</button>`, 2);
var _tmpl$324 = /* @__PURE__ */ template(`<div></div>`, 2);
var Zone = (props2) => {
  const {
    zone,
    index: index2,
    onDoubleClick,
    onUpdate,
    onDelete,
    editing,
    onContextMenu
  } = props2;
  const [name2, setName] = createSignal(zone.name);
  const options2 = useOptions();
  const quadrantStore = useQuadrantStore();
  const isEditing = editing === index2;
  createEffect(() => {
    const zones = options2.zoneLayout.zones;
    const canvas = document.querySelector(".canvas");
    if (!canvas) return;
    const canvasRect = canvas.getBoundingClientRect();
    const bestTitlePosition = findBestTitlePosition(zones, index2, canvasRect);
    if (bestTitlePosition) {
      const titlePosition = {
        left: bestTitlePosition.left,
        top: bestTitlePosition.top,
        isCustom: zone.isCustom,
        name: name2(),
        color: zone.backgroundColor
      };
      const currentTitlePosition = quadrantStore.zoneTitlePositions && quadrantStore.zoneTitlePositions[index2];
      if (!currentTitlePosition || JSON.stringify(currentTitlePosition) !== JSON.stringify(titlePosition)) {
        quadrantStore.setState("zoneTitlePositions", {
          ...quadrantStore.zoneTitlePositions,
          [index2]: titlePosition
        });
      }
    } else {
      quadrantStore.setState("zoneTitlePositions", (positions) => {
        if (positions && positions[index2]) delete positions[index2];
        return positions;
      });
    }
  });
  const handleNameChange = (e3) => {
    setName(e3.target.value);
    onUpdate(index2, {
      ...zone,
      name: e3.target.value
    });
  };
  const handleResize = (corner, event2) => {
    switch (corner) {
      case "top-left":
        zone.left += event2.movementX;
        zone.width -= event2.movementX;
        zone.top += event2.movementY;
        zone.height -= event2.movementY;
        break;
      case "top-right":
        zone.width += event2.movementX;
        zone.top += event2.movementY;
        zone.height -= event2.movementY;
        break;
      case "bottom-left":
        zone.left += event2.movementX;
        zone.width -= event2.movementX;
        zone.height += event2.movementY;
        break;
      case "bottom-right":
        zone.width += event2.movementX;
        zone.height += event2.movementY;
        break;
      default:
        break;
    }
    onUpdate(index2, {
      ...zone
    });
  };
  const handleClickOutside = (e3) => {
    if (!e3.target.closest(".zone-container")) {
      onUpdate(index2, {
        ...zone,
        name: name2()
      });
    }
  };
  const handleEditMode = (e3) => {
    if (e3.type === "dblclick" || e3.ctrlKey && e3.type === "click") {
      onDoubleClick(index2);
      document.addEventListener("click", handleClickOutside, {
        once: true
      });
    }
  };
  const handleDeleteZone = (index3) => {
    console.log(`[Zone] Deleting zone ${index3}`);
    onDelete(index3);
    quadrantStore.setState("zoneTitlePositions", (positions) => {
      const newPositions = {
        ...positions
      };
      if (newPositions[index3]) {
        delete newPositions[index3];
      }
      return newPositions;
    });
  };
  onCleanup(() => {
    document.removeEventListener("click", handleClickOutside);
  });
  return (() => {
    const _el$ = _tmpl$97.cloneNode(true);
    addEventListener(_el$, "contextmenu", onContextMenu, true);
    _el$.$$dblclick = handleEditMode;
    _el$.$$click = handleEditMode;
    _el$.style.setProperty("position", "absolute");
    _el$.style.setProperty("border", isEditing ? "2px dashed #999" : "none");
    insert(_el$, (() => {
      const _c$ = createMemo(() => !!(isEditing && zone.isCustom));
      return () => _c$() && [createMemo(() => ["top-left", "top-right", "bottom-left", "bottom-right"].map((corner) => (() => {
        const _el$3 = _tmpl$324.cloneNode(true);
        _el$3.$$mousedown = (e3) => {
          const onMouseMove = (moveEvent) => handleResize(corner, moveEvent);
          const onMouseUp = () => {
            document.removeEventListener("mousemove", onMouseMove);
            document.removeEventListener("mouseup", onMouseUp);
          };
          document.addEventListener("mousemove", onMouseMove);
          document.addEventListener("mouseup", onMouseUp);
        };
        className(_el$3, `resize-handle ${corner}`);
        _el$3.style.setProperty("position", "absolute");
        _el$3.style.setProperty("width", "10px");
        _el$3.style.setProperty("height", "10px");
        _el$3.style.setProperty("background", "#fff");
        _el$3.style.setProperty("border", "1px solid #666");
        createRenderEffect((_p$) => {
          const _v$6 = {
            background: "#fff",
            cursor: `${corner.includes("top") ? "n" : "s"}${corner.includes("left") ? "w" : "e"}-resize`
          }, _v$7 = `${corner.includes("top") ? "n" : "s"}${corner.includes("left") ? "w" : "e"}-resize`;
          _p$._v$6 = style(_el$3, _v$6, _p$._v$6);
          _v$7 !== _p$._v$7 && _el$3.style.setProperty("cursor", _p$._v$7 = _v$7);
          return _p$;
        }, {
          _v$6: void 0,
          _v$7: void 0
        });
        return _el$3;
      })())), (() => {
        const _el$2 = _tmpl$236.cloneNode(true);
        _el$2.$$click = () => {
          handleDeleteZone(index2);
        };
        _el$2.style.setProperty("position", "absolute");
        _el$2.style.setProperty("top", "5px");
        _el$2.style.setProperty("right", "5px");
        _el$2.style.setProperty("background", "transparent");
        _el$2.style.setProperty("border", "none");
        _el$2.style.setProperty("cursor", "pointer");
        _el$2.style.setProperty("color", "#666");
        _el$2.style.setProperty("font-size", "12px");
        return _el$2;
      })()];
    })());
    createRenderEffect((_p$) => {
      const _v$ = `${zone.left}${zone.isCustom ? "px" : "%"}`, _v$2 = `${zone.top}${zone.isCustom ? "px" : "%"}`, _v$3 = `${zone.width}${zone.isCustom ? "px" : "%"}`, _v$4 = `${zone.height}${zone.isCustom ? "px" : "%"}`, _v$5 = zone.backgroundColor;
      _v$ !== _p$._v$ && _el$.style.setProperty("left", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$.style.setProperty("top", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$.style.setProperty("width", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$.style.setProperty("height", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$.style.setProperty("background-color", _p$._v$5 = _v$5);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0
    });
    return _el$;
  })();
};
delegateEvents(["click", "dblclick", "contextmenu", "mousedown"]);

// public/app/ui/quadrant/components/tooltip.tsx
var _tmpl$98 = /* @__PURE__ */ template(`<div>: <br>: </div>`, 3);
var _tmpl$237 = /* @__PURE__ */ template(`<br>`, 1);
var _tmpl$325 = /* @__PURE__ */ template(`<div class="quadrant-point-tooltip"></div>`, 2);
var Tooltip2 = (props2) => {
  const [tooltipContent, setTooltipContent] = createSignal(null);
  const quadrantStore = useQuadrantStore();
  createEffect(() => {
    if (props2.cluster) {
      const uniqueAxisPairs = [...new Set(props2.cluster.map((item) => `${item.coordinates.axis.x.cardAttribute}---${item.coordinates.axis.y.cardAttribute}`))];
      const content2 = uniqueAxisPairs.map((pair2) => {
        const [xAttribute, yAttribute] = pair2.split("---");
        const values2 = props2.cluster.filter((item) => item.coordinates.axis.x.cardAttribute === xAttribute && item.coordinates.axis.y.cardAttribute === yAttribute);
        const xValue = calculateValueFromPercentagePosition(values2[0].coordinates.x, values2[0].coordinates.axis.x);
        const yValue = calculateValueFromPercentagePosition(values2[0].coordinates.y, values2[0].coordinates.axis.y, !values2[0].coordinates.axis.y.reverse);
        return (() => {
          const _el$ = _tmpl$98.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling, _el$4 = _el$3.nextSibling;
          insert(_el$, xAttribute, _el$2);
          insert(_el$, () => formatValue(xValue, values2[0].coordinates.axis.x, []), _el$3);
          insert(_el$, yAttribute, _el$4);
          insert(_el$, () => formatValue(yValue, values2[0].coordinates.axis.y, []), null);
          return _el$;
        })();
      });
      setTooltipContent(content2);
    } else if (props2.coordinates && props2.getAxisType) {
      const xAttribute = props2.coordinates.axis.x.cardAttribute;
      const yAttribute = props2.coordinates.axis.y.cardAttribute;
      const xValue = calculateValueFromPercentagePosition(props2.coordinates.x, props2.coordinates.axis.x);
      const yValue = calculateValueFromPercentagePosition(props2.coordinates.y, props2.coordinates.axis.y, !props2.coordinates.axis.y.reverse);
      const content2 = [xAttribute, ": ", createMemo(() => formatValue(xValue, props2.coordinates.axis.x, [])), _tmpl$237.cloneNode(true), yAttribute, ": ", createMemo(() => formatValue(yValue, props2.coordinates.axis.y, []))];
      setTooltipContent(content2);
    } else {
      setTooltipContent(null);
    }
  });
  return (() => {
    const _el$6 = _tmpl$325.cloneNode(true);
    insert(_el$6, () => props2.card?.state.card.title && props2.card?.state.card.title, null);
    insert(_el$6, (() => {
      const _c$ = createMemo(() => !!props2.card?.state.card.title);
      return () => _c$() && _tmpl$237.cloneNode(true);
    })(), null);
    insert(_el$6, tooltipContent, null);
    return _el$6;
  })();
};

// public/app/ui/quadrant/components/point.tsx
var _tmpl$99 = /* @__PURE__ */ template(`<p class="point-title"><span class="point-title-background"></span></p>`, 4);
var _tmpl$238 = /* @__PURE__ */ template(`<div class="point"></div>`, 2);
var Point = (props2) => {
  const options2 = useOptions();
  const project = useProject();
  const quadrantStore = useQuadrantStore();
  const activeAxisSeries = useActiveAxisSeries();
  const quadrantViewContext = useQuadrantViewContext();
  const [posX, setPosX] = createSignal(props2.coordinates.x);
  const [posY, setPosY] = createSignal(props2.coordinates.y);
  const [size4, setSize] = createSignal(props2.size || 15);
  const [showTooltip2, setShowTooltip] = createSignal(false);
  const [dragging, setDragging] = createSignal(false);
  const [temporaryPoint, setTemporaryPoint] = createSignal(null);
  let dragImage2 = null;
  const isDraggable = createMemo(() => {
    const xAttr = quadrantViewContext.availableAxeAttributes().get(props2.coordinates.axis.x.cardAttribute);
    const yAttr = quadrantViewContext.availableAxeAttributes().get(props2.coordinates.axis.y.cardAttribute);
    return isOnline() && !options2.readOnly && canEditAttribute(project(), xAttr[0]) && canEditAttribute(project(), yAttr[0]) && props2.coordinates.axis.x.type !== "lookup" && props2.coordinates.axis.x.type !== "formula" && props2.coordinates.axis.y.type !== "lookup" && props2.coordinates.axis.y.type !== "formula";
  });
  const updatePosition = (clientX, clientY) => {
    const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
    const xPos = (clientX - canvasRect.left) / canvasRect.width * 100;
    const yPos = (clientY - canvasRect.top) / canvasRect.height * 100;
    setPosX(xPos);
    setPosY(yPos);
  };
  createEffect(() => {
    if (dragging()) {
      quadrantStore.setState("hoveredPoint", [{
        card: props2.card,
        coordinates: {
          ...props2.coordinates,
          x: posX(),
          y: posY()
        },
        color: props2.color
      }]);
    }
  });
  onCleanup(() => {
    if (dragImage2) {
      document.body.removeChild(dragImage2);
      dragImage2 = null;
    }
    const canvas = document.querySelector(".canvas");
    if (canvas) {
      canvas.removeEventListener("dragover", handleDragOver);
    }
  });
  const handleMouseEnter = () => {
    quadrantStore.setState("hoveredPoint", [{
      card: props2.card,
      coordinates: {
        ...props2.coordinates,
        x: posX(),
        y: posY()
      },
      color: props2.color
    }]);
    if (options2.showInfoOnHover) {
      setShowTooltip(true);
    }
  };
  const handleMouseLeave = () => {
    quadrantStore.setState("hoveredPoint", null);
    setShowTooltip(false);
  };
  const handleDragStart2 = (e3) => {
    if (!isDraggable()) return;
    setDragging(true);
    e3.dataTransfer.setDragImage(new Image(), 0, 0);
    dragImage2 = document.createElement("div");
    Object.assign(dragImage2.style, {
      width: "15px",
      height: "15px",
      borderRadius: "50%",
      backgroundColor: props2.color,
      position: "absolute",
      top: "-99999px",
      pointerEvents: "none",
      opacity: 0.5
    });
    document.body.appendChild(dragImage2);
    e3.dataTransfer.setDragImage(dragImage2, 7.5, 7.5);
    const canvas = document.querySelector(".canvas");
    if (canvas) {
      canvas.addEventListener("dragover", handleDragOver);
    }
  };
  const handleDragOver = (e3) => {
    if (dragging()) {
      updatePosition(e3.clientX, e3.clientY);
      const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
      const xPos = (e3.clientX - canvasRect.left) / canvasRect.width * 100;
      const yPos = (e3.clientY - canvasRect.top) / canvasRect.height * 100;
      const xValue = calculateValueFromPercentagePosition(xPos, props2.coordinates.axis.x);
      const yValue = calculateValueFromPercentagePosition(yPos, props2.coordinates.axis.y, !props2.coordinates.axis.y.reverse);
      const xPercent = calculatePercentagePosition(xValue, props2.coordinates.axis.x);
      const yPercent = calculatePercentagePosition(yValue, props2.coordinates.axis.y, !props2.coordinates.axis.y.reverse);
      setTemporaryPoint({
        x: xPercent,
        y: yPercent
      });
    }
  };
  const handleDragEnd2 = async (e3) => {
    if (!isDraggable()) return;
    setDragging(false);
    const canvas = document.querySelector(".canvas");
    if (canvas) {
      canvas.removeEventListener("dragover", handleDragOver);
    }
    if (dragImage2) {
      document.body.removeChild(dragImage2);
      dragImage2 = null;
    }
    const oldXValue = calculateValueFromPercentagePosition(props2.coordinates.x, props2.coordinates.axis.x);
    const oldYValue = calculateValueFromPercentagePosition(props2.coordinates.y, props2.coordinates.axis.y, !props2.coordinates.axis.y.reverse);
    updatePosition(e3.clientX, e3.clientY);
    const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
    const xPos = (e3.clientX - canvasRect.left) / canvasRect.width * 100;
    const yPos = (e3.clientY - canvasRect.top) / canvasRect.height * 100;
    if (xPos < 0 || yPos < 0) {
      setPosX(props2.coordinates.x);
      setPosY(props2.coordinates.y);
      quadrantStore.setState("hoveredPoint", null);
      setShowTooltip(false);
      return;
    }
    const xValue = calculateValueFromPercentagePosition(xPos, props2.coordinates.axis.x);
    const yValue = calculateValueFromPercentagePosition(yPos, props2.coordinates.axis.y, !props2.coordinates.axis.y.reverse);
    if (props2.coordinates.axis.x.type === "group_type" || props2.coordinates.axis.y.type === "group_type") {
      await props2.card.updateCardGroups(props2.coordinates, xValue, yValue, oldXValue, oldYValue, quadrantViewContext, quadrantStore);
    }
    await props2.card.updateCardAttributes(project, quadrantViewContext, props2.coordinates.axis.x.cardAttribute, props2.coordinates.axis.y.cardAttribute, xValue, yValue);
    quadrantStore.setState("hoveredPoint", null);
    setShowTooltip(false);
    setTemporaryPoint(null);
  };
  const getAxisType = (attribute2) => {
    for (const series of activeAxisSeries()) {
      if (series.x.cardAttribute === attribute2) return series.x.type;
      if (series.y.cardAttribute === attribute2) return series.y.type;
    }
    return null;
  };
  return [(() => {
    const _el$ = _tmpl$238.cloneNode(true);
    addEventListener(_el$, "click", props2.onClick, true);
    _el$.addEventListener("dragend", handleDragEnd2);
    _el$.addEventListener("dragstart", handleDragStart2);
    _el$.addEventListener("mouseleave", handleMouseLeave);
    _el$.addEventListener("mouseenter", handleMouseEnter);
    insert(_el$, createComponent(Show, {
      get when() {
        return options2.enableSideDisplay;
      },
      get children() {
        const _el$2 = _tmpl$99.cloneNode(true), _el$3 = _el$2.firstChild;
        _el$2.style.setProperty("margin", "0");
        insert(_el$2, () => props2.card.state.card.title, _el$3);
        createRenderEffect(() => _el$2.style.setProperty("left", `${size4() && size4() !== 15 ? size4() / 2 + 25 : 20}px`));
        return _el$2;
      }
    }), null);
    insert(_el$, (() => {
      const _c$ = createMemo(() => !!showTooltip2());
      return () => _c$() && createComponent(Tooltip2, {
        get card() {
          return props2.card;
        },
        get coordinates() {
          return {
            ...props2.coordinates,
            x: posX(),
            y: posY()
          };
        },
        getAxisType
      });
    })(), null);
    createRenderEffect((_p$) => {
      const _v$ = isDraggable(), _v$2 = `${size4()}px`, _v$3 = `${size4()}px`, _v$4 = `calc(${posX()}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$5 = `calc(${posY()}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$6 = props2.color, _v$7 = options2.readOnly ? "default" : isDraggable() ? "grab" : "not-allowed";
      _v$ !== _p$._v$ && setAttribute(_el$, "draggable", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$.style.setProperty("width", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$.style.setProperty("height", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$.style.setProperty("left", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$.style.setProperty("top", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$.style.setProperty("background-color", _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$.style.setProperty("cursor", _p$._v$7 = _v$7);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0,
      _v$6: void 0,
      _v$7: void 0
    });
    return _el$;
  })(), createComponent(Show, {
    get when() {
      return temporaryPoint();
    },
    get children() {
      const _el$4 = _tmpl$238.cloneNode(true);
      _el$4.style.setProperty("opacity", "0.7");
      createRenderEffect((_p$) => {
        const _v$8 = `${size4()}px`, _v$9 = `${size4()}px`, _v$10 = `calc(${temporaryPoint().x}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$11 = `calc(${temporaryPoint().y}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$12 = props2.color;
        _v$8 !== _p$._v$8 && _el$4.style.setProperty("width", _p$._v$8 = _v$8);
        _v$9 !== _p$._v$9 && _el$4.style.setProperty("height", _p$._v$9 = _v$9);
        _v$10 !== _p$._v$10 && _el$4.style.setProperty("left", _p$._v$10 = _v$10);
        _v$11 !== _p$._v$11 && _el$4.style.setProperty("top", _p$._v$11 = _v$11);
        _v$12 !== _p$._v$12 && _el$4.style.setProperty("background-color", _p$._v$12 = _v$12);
        return _p$;
      }, {
        _v$8: void 0,
        _v$9: void 0,
        _v$10: void 0,
        _v$11: void 0,
        _v$12: void 0
      });
      return _el$4;
    }
  })];
};
delegateEvents(["click"]);

// public/app/ui/quadrant/components/cluster.tsx
var _tmpl$100 = /* @__PURE__ */ template(`<div class="cluster"><p></p></div>`, 4);
var _tmpl$239 = /* @__PURE__ */ template(`<div class="cluster"></div>`, 2);
var _tmpl$326 = /* @__PURE__ */ template(`<div class="clusters"></div>`, 2);
var Cluster = (props2) => {
  const options2 = useOptions();
  const quadrantStore = useQuadrantStore();
  const quadrantViewContext = useQuadrantViewContext();
  const project = useProject();
  const [dropdownPosition, setDropdownPosition] = createSignal({
    x: 0,
    y: 0
  });
  const [draggingCluster, setDraggingCluster] = createSignal(false);
  const [posX, setPosX] = createSignal(props2.cluster[0].coordinates.x);
  const [posY, setPosY] = createSignal(props2.cluster[0].coordinates.y);
  const [size4, setSize] = createSignal(props2.cluster[0].size || 15);
  const [showTooltip2, setShowTooltip] = createSignal(false);
  const [temporaryPoint, setTemporaryPoint] = createSignal(null);
  let dragImage2 = null;
  const isDraggable = createMemo(() => {
    const xAttr = quadrantViewContext.availableAxeAttributes().get(props2.cluster[0].coordinates.axis.x.cardAttribute);
    const yAttr = quadrantViewContext.availableAxeAttributes().get(props2.cluster[0].coordinates.axis.y.cardAttribute);
    return isOnline() && !options2.readOnly && canEditAttribute(project(), xAttr[0]) && canEditAttribute(project(), yAttr[0]) && props2.cluster.every((item) => item.coordinates.axis.x.type !== "lookup" && item.coordinates.axis.x.type !== "formula" && item.coordinates.axis.y.type !== "lookup" && item.coordinates.axis.y.type !== "formula");
  });
  const updatePosition = (clientX, clientY) => {
    const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
    const xPos = (clientX - canvasRect.left) / canvasRect.width * 100;
    const yPos = (clientY - canvasRect.top) / canvasRect.height * 100;
    setPosX(xPos);
    setPosY(yPos);
  };
  createEffect(() => {
    if (draggingCluster()) {
      quadrantStore.setState("hoveredPoint", props2.cluster.map((item) => ({
        ...item,
        coordinates: {
          ...item.coordinates,
          x: posX(),
          y: posY()
        }
      })));
    }
  });
  onCleanup(() => {
    if (dragImage2) {
      document.body.removeChild(dragImage2);
      dragImage2 = null;
    }
    const canvas = document.querySelector(".canvas");
    if (canvas) {
      canvas.removeEventListener("dragover", handleDragOver);
    }
  });
  const handleClusterClick = (event2, cluster) => {
    if (options2.readOnly) {
      return;
    }
    setOpenCluster([]);
    if (cluster.length > 1) {
      setOpenCluster(cluster);
      const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
      setDropdownPosition({
        x: Math.min(event2.clientX - canvasRect.left, canvasRect.width - 150),
        y: Math.min(event2.clientY - canvasRect.top, canvasRect.height - 150)
      });
    } else {
      openCardModal(cluster[0].card);
    }
  };
  const openCardModal = (card) => {
    setOpenCluster([]);
    console.log("open card", card, quadrantViewContext);
    quadrantViewContext.cardModal?.open(card);
  };
  const handleDocumentClick = (event2) => {
    if (!event2.target.closest(".quadrant-dropdown") && !event2.target.closest(".cluster")) {
      setOpenCluster([]);
    }
  };
  const handleClusterDragStart = (e3) => {
    if (!isDraggable()) return;
    setDraggingCluster(true);
    e3.dataTransfer.setDragImage(new Image(), 0, 0);
    dragImage2 = document.createElement("div");
    Object.assign(dragImage2.style, {
      width: "15px",
      height: "15px",
      borderRadius: "50%",
      backgroundColor: props2.cluster[0].color,
      position: "absolute",
      top: "-99999px",
      pointerEvents: "none",
      opacity: 0.5
    });
    document.body.appendChild(dragImage2);
    e3.dataTransfer.setDragImage(dragImage2, 7.5, 7.5);
    const canvas = document.querySelector(".canvas");
    if (canvas) {
      canvas.addEventListener("dragover", handleDragOver);
    }
  };
  const handleDragOver = (e3) => {
    e3.preventDefault();
    if (draggingCluster()) {
      updatePosition(e3.clientX, e3.clientY);
      const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
      const xPos = (e3.clientX - canvasRect.left) / canvasRect.width * 100;
      const yPos = (e3.clientY - canvasRect.top) / canvasRect.height * 100;
      const firstItem = props2.cluster[0];
      const xValue = calculateValueFromPercentagePosition(xPos, firstItem.coordinates.axis.x);
      const yValue = calculateValueFromPercentagePosition(yPos, firstItem.coordinates.axis.y, !firstItem.coordinates.axis.y.reverse);
      const xPercent = calculatePercentagePosition(xValue, firstItem.coordinates.axis.x);
      const yPercent = calculatePercentagePosition(yValue, firstItem.coordinates.axis.y, !firstItem.coordinates.axis.y.reverse);
      setTemporaryPoint({
        x: xPercent,
        y: yPercent,
        xValue,
        yValue
      });
    }
  };
  const handleClusterDragEnd = async (e3) => {
    if (!isDraggable()) return;
    setDraggingCluster(false);
    const canvas = document.querySelector(".canvas");
    if (canvas) {
      canvas.removeEventListener("dragover", handleDragOver);
    }
    if (dragImage2) {
      document.body.removeChild(dragImage2);
      dragImage2 = null;
    }
    const firstItem = props2.cluster[0];
    const oldXValue = calculateValueFromPercentagePosition(firstItem.coordinates.x, firstItem.coordinates.axis.x);
    const oldYValue = calculateValueFromPercentagePosition(firstItem.coordinates.y, firstItem.coordinates.axis.y, !firstItem.coordinates.axis.y.reverse);
    updatePosition(e3.clientX, e3.clientY);
    const canvasRect = document.querySelector(".canvas").getBoundingClientRect();
    const xPos = (e3.clientX - canvasRect.left) / canvasRect.width * 100;
    const yPos = (e3.clientY - canvasRect.top) / canvasRect.height * 100;
    if (xPos < 0 || yPos < 0) {
      quadrantStore.setState("hoveredPoint", null);
      setShowTooltip(false);
      return;
    }
    await Promise.all(props2.cluster.filter((item) => item.coordinates.axis.x.cardAttribute === firstItem.coordinates.axis.x.cardAttribute && item.coordinates.axis.y.cardAttribute === firstItem.coordinates.axis.y.cardAttribute).map(async (item) => {
      const xValue = calculateValueFromPercentagePosition(xPos, item.coordinates.axis.x);
      const yValue = calculateValueFromPercentagePosition(yPos, item.coordinates.axis.y, !item.coordinates.axis.y.reverse);
      if (item.coordinates.axis.x.type === "group_type" || item.coordinates.axis.y.type === "group_type") {
        await item.card.updateCardGroups(item.coordinates, xValue, yValue, oldXValue, oldYValue, quadrantViewContext, quadrantStore);
      }
      await item.card.updateCardAttributes(project, quadrantViewContext, item.coordinates.axis.x.cardAttribute, item.coordinates.axis.y.cardAttribute, xValue, yValue);
    }));
    quadrantStore.setState("hoveredPoint", null);
    setShowTooltip(false);
    setTemporaryPoint(null);
  };
  document.addEventListener("click", handleDocumentClick);
  onCleanup(() => {
    document.removeEventListener("click", handleDocumentClick);
  });
  function onSelectClusterPoint(index2) {
    openCardModal(props2.cluster[index2()].card.state.card);
  }
  return (() => {
    const _el$ = _tmpl$326.cloneNode(true);
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.cluster.length > 1;
      },
      get children() {
        const _el$2 = _tmpl$100.cloneNode(true), _el$3 = _el$2.firstChild;
        _el$2.addEventListener("dragend", handleClusterDragEnd);
        _el$2.addEventListener("drag", handleDragOver);
        _el$2.addEventListener("dragstart", handleClusterDragStart);
        _el$2.$$click = (e3) => handleClusterClick(e3, props2.cluster);
        _el$2.addEventListener("mouseleave", () => {
          quadrantStore.setState("hoveredPoint", null);
          setShowTooltip(false);
        });
        _el$2.addEventListener("mouseenter", () => {
          quadrantStore.setState("hoveredPoint", props2.cluster);
          if (options2.showInfoOnHover) {
            setShowTooltip(true);
          }
        });
        _el$3.style.setProperty("margin", "0");
        insert(_el$3, () => props2.cluster.length);
        insert(_el$2, (() => {
          const _c$ = createMemo(() => !!showTooltip2());
          return () => _c$() && createComponent(Tooltip2, {
            get cluster() {
              return props2.cluster;
            },
            getAxisType: (attr) => {
              const item = props2.cluster.find((item2) => item2.coordinates.xAttribute === attr || item2.coordinates.yAttribute === attr);
              return item ? item.coordinates.axis.x.cardAttribute === attr ? item.coordinates.axis.x.type : item.coordinates.axis.y.type : void 0;
            }
          });
        })(), null);
        createRenderEffect((_p$) => {
          const _v$ = isDraggable(), _v$2 = `${size4()}px`, _v$3 = `${size4()}px`, _v$4 = `calc(${posX()}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$5 = `calc(${posY()}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$6 = props2.cluster[0].color, _v$7 = options2.readOnly ? "default" : isDraggable() ? "grab" : "not-allowed", _v$8 = `calc(${size4() ? size4() / 2 : 10}px)`;
          _v$ !== _p$._v$ && setAttribute(_el$2, "draggable", _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && _el$2.style.setProperty("width", _p$._v$2 = _v$2);
          _v$3 !== _p$._v$3 && _el$2.style.setProperty("height", _p$._v$3 = _v$3);
          _v$4 !== _p$._v$4 && _el$2.style.setProperty("left", _p$._v$4 = _v$4);
          _v$5 !== _p$._v$5 && _el$2.style.setProperty("top", _p$._v$5 = _v$5);
          _v$6 !== _p$._v$6 && _el$2.style.setProperty("background-color", _p$._v$6 = _v$6);
          _v$7 !== _p$._v$7 && _el$2.style.setProperty("cursor", _p$._v$7 = _v$7);
          _v$8 !== _p$._v$8 && _el$3.style.setProperty("font-size", _p$._v$8 = _v$8);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0,
          _v$4: void 0,
          _v$5: void 0,
          _v$6: void 0,
          _v$7: void 0,
          _v$8: void 0
        });
        return _el$2;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.cluster.length === 1;
      },
      get children() {
        return createComponent(For, {
          get each() {
            return props2.cluster;
          },
          children: (item) => createComponent(Point, {
            get card() {
              return item.card;
            },
            get coordinates() {
              return item.coordinates;
            },
            get color() {
              return item.color;
            },
            get size() {
              return item.size;
            },
            onClick: (e3) => openCardModal(item.card.state.card)
          })
        });
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return createMemo(() => openCluster().length > 1)() && openCluster() === props2.cluster;
      },
      get children() {
        return createComponent(Dropdown2, {
          get position() {
            return dropdownPosition();
          },
          get options() {
            return openCluster().map((item) => ({
              label: item.card.state.card.title
            }));
          },
          onSelect: (index2) => onSelectClusterPoint(index2),
          onClose: () => setOpenCluster([])
        });
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return temporaryPoint();
      },
      get children() {
        const _el$4 = _tmpl$239.cloneNode(true);
        _el$4.style.setProperty("opacity", "0.7");
        createRenderEffect((_p$) => {
          const _v$9 = `${size4()}px`, _v$10 = `${size4()}px`, _v$11 = `calc(${temporaryPoint().x}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$12 = `calc(${temporaryPoint().y}% - ${size4() ? size4() / 2 : 7.5}px)`, _v$13 = props2.cluster[0].color;
          _v$9 !== _p$._v$9 && _el$4.style.setProperty("width", _p$._v$9 = _v$9);
          _v$10 !== _p$._v$10 && _el$4.style.setProperty("height", _p$._v$10 = _v$10);
          _v$11 !== _p$._v$11 && _el$4.style.setProperty("left", _p$._v$11 = _v$11);
          _v$12 !== _p$._v$12 && _el$4.style.setProperty("top", _p$._v$12 = _v$12);
          _v$13 !== _p$._v$13 && _el$4.style.setProperty("background-color", _p$._v$13 = _v$13);
          return _p$;
        }, {
          _v$9: void 0,
          _v$10: void 0,
          _v$11: void 0,
          _v$12: void 0,
          _v$13: void 0
        });
        return _el$4;
      }
    }), null);
    return _el$;
  })();
};
delegateEvents(["click"]);

// public/app/ui/quadrant/components/cluster-manager.tsx
var _tmpl$101 = /* @__PURE__ */ template(`<div class="clusters"></div>`, 2);
var [openCluster, setOpenCluster] = createSignal([]);
var clusterDistance = (x1, y1, x22, y22) => {
  return Math.sqrt((x22 - x1) ** 2 + (y22 - y1) ** 2);
};
var ClusterManager = (props2) => {
  const options2 = useOptions();
  const clusters = createMemo(() => {
    const clustersMap = {};
    props2.cards().forEach((card) => {
      if (!card.coordinates) return;
      Object.keys(card.coordinates).forEach((pair2) => {
        const coordinates = card.coordinates[pair2];
        coordinates.points?.forEach((point) => {
          const coordKey = `${point.x}-${point.y}-${card.serieIndex[pair2]}`;
          const color = card.colors[pair2];
          const size4 = card.sizes[pair2];
          if (!clustersMap[coordKey]) {
            clustersMap[coordKey] = [];
          }
          clustersMap[coordKey].push({
            card,
            coordinates: point,
            color,
            size: size4,
            serieIndex: card.serieIndex[pair2]
          });
        });
      });
    });
    if (options2.groupCloseDots) {
      const clusteredCoords = {};
      Object.keys(clustersMap).forEach((key2) => {
        const [x3, y3, serieIndex] = key2.split("-").map(Number);
        const closeKey = Object.keys(clusteredCoords).find((clusterKey) => {
          const [cx, cy] = clusterKey.split("-").map(Number);
          return clusterDistance(x3, y3, cx, cy) < 5;
        });
        if (closeKey) {
          clusteredCoords[closeKey] = clusteredCoords[closeKey].concat(clustersMap[key2]);
        } else {
          clusteredCoords[key2] = clustersMap[key2];
        }
      });
      return Object.values(clusteredCoords);
    }
    return Object.values(clustersMap);
  });
  return (() => {
    const _el$ = _tmpl$101.cloneNode(true);
    insert(_el$, createComponent(For, {
      get each() {
        return clusters();
      },
      children: (cluster) => createComponent(Cluster, {
        cluster
      })
    }));
    return _el$;
  })();
};

// public/app/ui/quadrant/components/dropdown.tsx
var _tmpl$103 = /* @__PURE__ */ template(`<div class="quadrant-dropdown"></div>`, 2);
var _tmpl$240 = /* @__PURE__ */ template(`<div class="quadrant-dropdown-item"></div>`, 2);
var Dropdown2 = (props2) => {
  const handleSelect = (index2) => {
    props2.onSelect(index2);
    props2.onClose();
  };
  const handleClickOutside = (event2) => {
    if (!event2.target.closest(".quadrant-dropdown")) {
      props2.onClose();
    }
  };
  document.addEventListener("click", handleClickOutside);
  onCleanup(() => {
    document.removeEventListener("click", handleClickOutside);
  });
  return (() => {
    const _el$ = _tmpl$103.cloneNode(true);
    insert(_el$, createComponent(For, {
      get each() {
        return props2.options;
      },
      children: (option2, index2) => (() => {
        const _el$2 = _tmpl$240.cloneNode(true);
        _el$2.$$click = () => handleSelect(index2);
        insert(_el$2, () => option2.label);
        return _el$2;
      })()
    }));
    createRenderEffect((_p$) => {
      const _v$ = `${props2.position.y}px`, _v$2 = `${props2.position.x}px`;
      _v$ !== _p$._v$ && _el$.style.setProperty("top", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$.style.setProperty("left", _p$._v$2 = _v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$;
  })();
};
delegateEvents(["click"]);

// public/app/ui/quadrant/components/zonesManager.tsx
function createZonesManager() {
  const options2 = useOptions();
  const quadrantStore = useQuadrantStore();
  const quadrantViewContext = useQuadrantViewContext();
  const [zones, setZones] = createSignal(options2.zoneLayout?.zones || []);
  const [editingZone, setEditingZone] = createSignal(null);
  const [ghostZone, setGhostZone] = createSignal(null);
  const updateZone = (updatedZones) => {
    const updatedZoneLayout = {
      ...options2.zoneLayout,
      zones: updatedZones
    };
    quadrantViewContext.onChange({
      options: JSON.parse(JSON.stringify({
        ...options2.state,
        zoneLayout: updatedZoneLayout
      }))
    });
  };
  createEffect(() => {
    if (options2.zoneLayout?.zones) {
      if (quadrantStore.setState) {
        quadrantStore.setState("zoneTitlePositions", void 0);
        setTimeout(() => {
          quadrantStore.setState("zoneTitlePositions", {});
        }, 0);
      }
      setZones(options2.zoneLayout.zones);
    }
  });
  const handleZoneDoubleClick = (index2) => {
    setEditingZone(index2);
  };
  const handleZoneUpdate = (index2, newZone) => {
    const updatedZones = zones().map((zone, i3) => i3 === index2 ? newZone : zone);
    if (JSON.stringify(zones()) !== JSON.stringify(updatedZones)) {
      setZones(updatedZones);
      updateZone(updatedZones);
    }
  };
  const handleDeleteZone = (index2) => {
    const updatedZones = zones().filter((_5, i3) => i3 !== index2);
    setZones(updatedZones);
    updateZone(updatedZones);
  };
  const handleDrawingMove = ({
    x: x3,
    y: y3,
    startX,
    startY
  }) => {
    setGhostZone({
      left: Math.min(startX, x3),
      top: Math.min(startY, y3),
      width: Math.abs(x3 - startX),
      height: Math.abs(y3 - startY),
      backgroundColor: pastelizeColor(getComplementaryColor(getColorByIndex(options2.zoneLayout.zones.length + 1)))
    });
  };
  const handleDrawingEnd = () => {
    if (ghostZone()) {
      const newZone = {
        name: `Zone ${zones().length + 1}`,
        backgroundColor: pastelizeColor(getComplementaryColor(getColorByIndex(options2.zoneLayout.zones.length + 1))),
        left: ghostZone().left,
        top: ghostZone().top,
        width: ghostZone().width,
        height: ghostZone().height,
        isCustom: true
      };
      const updatedZones = [...zones(), newZone];
      setZones(updatedZones);
      updateZone(updatedZones);
      setGhostZone(null);
    }
  };
  return {
    zones,
    ghostZone,
    editingZone,
    handleZoneDoubleClick,
    handleZoneUpdate,
    handleDeleteZone,
    handleDrawingMove,
    handleDrawingEnd
  };
}
function getTopmostZoneAtPosition(x3, y3, preprocessedZones) {
  let topmostZone = null;
  for (let i3 = 0; i3 < preprocessedZones.length; i3++) {
    const zone = preprocessedZones[i3];
    if (isPointInZone(x3, y3, zone)) {
      topmostZone = zone;
    }
  }
  return topmostZone;
}
function isPointInZone(x3, y3, zone) {
  return x3 >= zone._left && x3 <= zone._right && y3 >= zone._top && y3 <= zone._bottom;
}
function preprocessZones(zones, canvasRect) {
  return zones.map((zone) => {
    const left = zone.isCustom ? zone.left : zone.left / 100 * canvasRect.width;
    const top2 = zone.isCustom ? zone.top : zone.top / 100 * canvasRect.height;
    const width = zone.isCustom ? zone.width : zone.width / 100 * canvasRect.width;
    const height = zone.isCustom ? zone.height : zone.height / 100 * canvasRect.height;
    return {
      ...zone,
      _left: left,
      _top: top2,
      _right: left + width,
      _bottom: top2 + height
    };
  });
}
function findBestTitlePosition(zones, currentZoneIndex, canvasRect) {
  const preprocessedZones = preprocessZones(zones, canvasRect);
  const currentZone = preprocessedZones[currentZoneIndex];
  if (currentZone._right < 0 || currentZone._left > canvasRect.width || currentZone._bottom < 0 || currentZone._top > canvasRect.height) {
    return null;
  }
  const step2 = 5;
  const startX = currentZone._left;
  const startY = currentZone._top;
  const maxX = currentZone._right - 50;
  const maxY = currentZone._bottom - 20;
  for (let y3 = startY; y3 <= maxY; y3 += step2) {
    for (let x3 = startX; x3 <= maxX; x3 += step2) {
      const zoneAtPoint = getTopmostZoneAtPosition(x3, y3, preprocessedZones);
      if (zoneAtPoint === currentZone) {
        return {
          left: x3,
          top: y3
        };
      }
    }
  }
  return null;
}

// public/app/ui/quadrant/components/zoneTitles.tsx
var _tmpl$104 = /* @__PURE__ */ template(`<div class="zone-titles"></div>`, 2);
var _tmpl$241 = /* @__PURE__ */ template(`<div class="zone-title"></div>`, 2);
var ZoneTitles = () => {
  const quadrantStore = useQuadrantStore();
  const [refresh, setRefresh] = createSignal(0);
  onMount(() => {
    const canvas = document.querySelector(".canvas");
    if (!canvas) return;
    const observer = new ResizeObserver(debounce2(() => {
      setRefresh((r3) => r3 + 1);
    }, 200));
    observer.observe(canvas);
    onCleanup(() => observer.disconnect());
  });
  const zoneTitlePositions = createMemo(() => {
    refresh();
    const positions = quadrantStore.zoneTitlePositions ? Object.values(quadrantStore.zoneTitlePositions) : [];
    return positions;
  });
  return (() => {
    const _el$ = _tmpl$104.cloneNode(true);
    insert(_el$, createComponent(For, {
      get each() {
        return zoneTitlePositions();
      },
      children: (titlePos) => (() => {
        const _el$2 = _tmpl$241.cloneNode(true);
        _el$2.style.setProperty("position", "absolute");
        _el$2.style.setProperty("pointer-events", "none");
        _el$2.style.setProperty("z-index", "-1");
        insert(_el$2, () => titlePos.name);
        createRenderEffect((_p$) => {
          const _v$ = `calc(${titlePos.left}px + 10px)`, _v$2 = `calc(${titlePos.top}px + 10px)`, _v$3 = titlePos.color;
          _v$ !== _p$._v$ && _el$2.style.setProperty("left", _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && _el$2.style.setProperty("top", _p$._v$2 = _v$2);
          _v$3 !== _p$._v$3 && _el$2.style.setProperty("background-color", _p$._v$3 = _v$3);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0
        });
        return _el$2;
      })()
    }));
    return _el$;
  })();
};

// public/app/ui/quadrant/components/cards-context.tsx
var CardsContext = createContext();
var useCards = () => {
  return useContext(CardsContext);
};
var CardsProvider = (props2) => {
  const getCards = props2.store.react(() => {
  });
  return createComponent(CardsContext.Provider, {
    value: getCards,
    get children() {
      return props2.children;
    }
  });
};

// public/app/ui/quadrant/quadrant-utils/dragHandlers.tsx
var copyStyles = (source, target) => {
  const computedStyle = window.getComputedStyle(source);
  for (let key2 of computedStyle) {
    target.style[key2] = computedStyle.getPropertyValue(key2);
  }
};
var handleDragStart = (store2, e3) => {
  e3.stopPropagation();
  if (e3.dataTransfer) {
    e3.dataTransfer.setData("text/plain", store2.card.id);
    const dragImage2 = e3.currentTarget.cloneNode(true);
    const toggleButtons = dragImage2.querySelectorAll(".toggle-button");
    toggleButtons.forEach((button) => button.style.display = "none");
    copyStyles(e3.currentTarget, dragImage2);
    dragImage2.style.position = "absolute";
    dragImage2.style.top = "-99999px";
    document.body.appendChild(dragImage2);
    e3.dataTransfer.setDragImage(dragImage2, 0, 0);
    setTimeout(() => document.body.removeChild(dragImage2), 0);
  }
};
var handleDragEnd = (store2, e3) => {
  return null;
};

// public/app/ui/quadrant/quadrant-utils/axisCalculations.tsx
var calculateAxisValues = (cards, axis, axisCompanion) => {
  let min3 = Infinity, max3 = -Infinity;
  let type = axis.type;
  let values2 = [];
  const activeAxisNamedAttrGroup = useQuadrantViewContext().activeAxeAttributes();
  const options2 = useOptions();
  const project = useProject();
  const calculateMinMax = (value2) => {
    if (value2 < min3) min3 = value2;
    if (value2 > max3) max3 = value2;
  };
  if (type === "lookup" || type === "formula") {
    for (let card of cards) {
      const value2 = getValueWithAttribute(card, axis.cardAttribute);
      if (value2 !== null && value2 !== void 0) {
        type = detectValueType(value2);
        break;
      }
    }
    if (type === "lookup" || type === "formula") {
      type = "string";
    }
  }
  if (type === "group_type") {
    const namedAttrGroup = activeAxisNamedAttrGroup.get(axis.cardAttribute);
    if (!namedAttrGroup || !namedAttrGroup[0].group_type_id) {
      return {
        min: 0,
        max: 1,
        step: 1,
        values: []
      };
    }
    const groupType = cardGroupTypeStore.tryGet(namedAttrGroup[0].group_type_id);
    const groupStore = cardGroupStore.scopedByType(groupType, project().top_level_card).scoped({
      is_archived: (v3) => options2.include_archived ? true : !v3
    });
    const groups = groupStore.query();
    min3 = -1;
    max3 = groups.length;
    return {
      min: min3,
      max: max3,
      step: 1,
      values: groups.map((g3) => g3.title).sort()
    };
  }
  cards.forEach((card) => {
    let value2 = getValueWithAttribute(card, axis.cardAttribute);
    let valueCompanion;
    if (axisCompanion.type === "group_type") {
      const companionAttr = activeAxisNamedAttrGroup.get(axisCompanion.cardAttribute);
      const companionGroupTypeId = companionAttr[0].group_type_id;
      valueCompanion = getGroupTypeValues(card, companionGroupTypeId);
    } else {
      valueCompanion = getValueWithAttribute(card, axisCompanion.cardAttribute);
    }
    if (type === "bool" && value2 === null) {
      value2 = false;
    }
    if (type === "bool" && valueCompanion === null) {
      valueCompanion = false;
    }
    if (value2 !== null && isValueOk(value2, type) && isValueOk(valueCompanion, axisCompanion.type)) {
      values2.push(value2);
      switch (type) {
        case "date":
          const dateValue = new Date(value2).getTime();
          calculateMinMax(dateValue);
          break;
        case "time":
          const timeValue = (/* @__PURE__ */ new Date(`1970-01-01T${value2}Z`)).getTime();
          calculateMinMax(timeValue);
          break;
        case "number":
          calculateMinMax(value2);
          break;
        case "percentage":
          min3 = 0;
          max3 = 100;
          break;
        case "size":
          const sizeOrder = ["S", "M", "L", "XL"];
          const sizeValue = sizeOrder.indexOf(value2);
          calculateMinMax(sizeValue);
          break;
        case "bool":
          const boolValue = value2 ? 1 : 0;
          calculateMinMax(boolValue);
          break;
        case "string":
          const strValues = values2.map((v3) => v3?.toString?.().toLowerCase()).filter((v3, i3, arr) => v3 && arr.indexOf(v3) === i3).sort();
          strValues.forEach((v3, i3) => {
            calculateMinMax(i3);
          });
          return {
            min: min3,
            max: max3,
            step: 1,
            values: strValues
          };
        default:
          break;
      }
    }
  });
  if (values2.length === 0) {
    switch (type) {
      case "date":
        const today = (/* @__PURE__ */ new Date()).getTime();
        min3 = Math.min(today - 864e5 * 10, min3);
        max3 = Math.max(today + 864e5 * 10, max3);
        break;
      case "time":
        min3 = Math.min((/* @__PURE__ */ new Date("1970-01-01T08:00:00Z")).getTime(), min3);
        max3 = Math.max((/* @__PURE__ */ new Date("1970-01-01T18:00:00Z")).getTime(), max3);
        break;
      case "number":
        min3 = 0;
        max3 = 100;
        break;
      case "size":
        min3 = 0;
        max3 = 3;
        break;
      case "bool":
        min3 = 0;
        max3 = 1;
        break;
      default:
        break;
    }
  } else if (values2.length < 5) {
    switch (type) {
      case "date":
        const rangeDate = max3 - min3 || 864e5 * 10;
        min3 = min3 - rangeDate;
        max3 = max3 + rangeDate;
        break;
      case "time":
        const rangeTime = max3 - min3 || 36e5 * 5;
        min3 = Math.max(min3 - rangeTime, (/* @__PURE__ */ new Date("1970-01-01T00:00:00Z")).getTime());
        max3 = Math.min(max3 + rangeTime, (/* @__PURE__ */ new Date("1970-01-01T23:59:59Z")).getTime());
        break;
      case "number":
        const rangeNumber = max3 - min3 || 50;
        min3 = min3 - rangeNumber;
        max3 = max3 + rangeNumber;
        break;
      case "size":
        min3 = 0;
        max3 = 3;
        break;
      case "bool":
        min3 = 0;
        max3 = 1;
        break;
      default:
        break;
    }
  }
  min3 = min3 === Infinity ? 0 : min3;
  max3 = max3 === -Infinity ? 100 : max3;
  let range2 = max3 - min3;
  const step2 = calculateStep(values2, type);
  const padding = step2 * Math.ceil(range2 * 0.05 / step2);
  if (type !== "percentage") {
    min3 -= padding;
    max3 += padding;
  }
  min3 = Math.floor(min3 / step2) * step2;
  max3 = Math.ceil(max3 / step2) * step2;
  values2.map((value2) => calculatePercentagePosition(value2, axis));
  return {
    min: min3,
    max: max3,
    step: step2,
    values: values2
  };
};
var calculateMinDifference = (timeValues) => {
  let minDifference = Infinity;
  for (let i3 = 1; i3 < timeValues.length; i3++) {
    const difference = timeValues[i3] - timeValues[i3 - 1];
    if (difference > 0 && difference < minDifference) {
      minDifference = difference;
    }
  }
  return minDifference;
};
var calculateStep = (values2, type) => {
  if (type === "time" && values2.length > 1) {
    let timeValues = values2.map((value2) => (/* @__PURE__ */ new Date(`1970-01-01T${value2}Z`)).getTime());
    timeValues.sort((a3, b3) => a3 - b3);
    const minDifference = calculateMinDifference(timeValues);
    const steps2 = [6e4, 9e5, 18e5, 36e5];
    const closestStep = steps2.reduce((prev, curr) => Math.abs(curr - minDifference) < Math.abs(prev - minDifference) ? curr : prev);
    return closestStep;
  } else {
    switch (type) {
      case "date":
        return 864e5;
      // one day
      case "time":
        return 36e5;
      // one hour
      case "bool":
        return 0.25;
      default:
        return 1;
    }
  }
};
var calculatePercentagePosition = (value2, axis, forceReverse) => {
  const reverse = forceReverse ?? axis.reverse;
  const type = axis.type === "lookup" || axis.type === "formula" ? detectValueType(value2) : axis.type;
  const range2 = {
    min: axis.min,
    max: axis.max
  };
  if (range2.min === range2.max) return 0;
  let numericValue;
  switch (type) {
    case "date":
      numericValue = new Date(value2).getTime();
      break;
    case "time":
      numericValue = typeof value2 === "string" ? (/* @__PURE__ */ new Date(`1970-01-01T${value2}Z`)).getTime() : value2;
      break;
    case "number":
    case "percentage":
      numericValue = value2;
      break;
    case "size":
      if (typeof value2 === "string") {
        const sizeOrder = ["S", "M", "L", "XL"];
        numericValue = sizeOrder.indexOf(value2);
      } else {
        numericValue = value2;
      }
      if (numericValue === -1) return value2 === "S" ? 0 : 100;
      break;
    case "bool":
      numericValue = value2 ? 1 : 0;
      break;
    case "group_type":
      numericValue = typeof value2 === "number" ? value2 : axis.values?.indexOf(value2);
      break;
    case "string":
      numericValue = axis.values?.indexOf(value2?.toString()?.toLowerCase?.()) ?? -1;
      break;
    default:
      numericValue = 0;
  }
  const percentage = (numericValue - range2.min) / (range2.max - range2.min) * 100;
  return reverse ? 100 - percentage : percentage;
};
var calculateValueFromPercentagePosition = (percentage, axis, forceReverse) => {
  const reverse = forceReverse ?? axis.reverse;
  const type = axis.type === "lookup" || axis.type === "formula" ? detectValueType(axis.values[0]) : axis.type;
  if (reverse) percentage = 100 - percentage;
  const range2 = {
    min: axis.min,
    max: axis.max
  };
  let value2 = percentage / 100 * (range2.max - range2.min) + range2.min;
  const index2 = Math.round(value2);
  switch (type) {
    case "date":
      value2 = Math.round(value2 / axis.step) * axis.step;
      return new Date(value2);
    case "time":
      value2 = Math.round(value2 / axis.step) * axis.step;
      const hours = Math.floor(value2 / 36e5).toString().padStart(2, "0");
      const minutes = Math.floor(value2 % 36e5 / 6e4).toString().padStart(2, "0");
      const seconds = Math.floor(value2 % 6e4 / 1e3).toString().padStart(2, "0");
      return `${hours}:${minutes}:${seconds}`;
    case "size":
      const sizeOrder = ["S", "M", "L", "XL"];
      return sizeOrder[index2] || sizeOrder[Math.max(0, Math.min(index2, sizeOrder.length - 1))];
    case "bool":
      return value2 >= 0.5;
    case "group_type":
    case "string":
      return axis.values?.[index2] || axis.values?.[Math.max(0, Math.min(index2, axis.values?.length - 1))];
    default:
      return Math.round(value2 / axis.step) * axis.step;
  }
};

// public/app/ui/quadrant/quadrant-utils/cardUtils.tsx
var getValueWithAttribute = (cardOrRaw, attribute2) => {
  const card = cardOrRaw?.state?.card || cardOrRaw;
  if (!card?.attributes) return null;
  const attr = card.attributes.find((attr2) => attr2.name === attribute2);
  if (!attr) return null;
  if (attr.type === "date") {
    const dateValue = attr.value?.end ?? attr.value?.start ?? attr.value;
    return new Date(dateValue);
  }
  if (attr.type === "bool") {
    return attr.value === null ? false : attr.value;
  }
  return attr.value ?? null;
};
var getGroupTypeValues = (card, groupTypeId) => {
  const groupAttr = card.groups.filter((group2) => group2.type_id === groupTypeId);
  if (groupAttr.length > 0) {
    const titles = groupAttr.map((group2) => group2.title);
    return titles;
  }
  return [];
};
var formatValue = (value2, axis, referenceValues = []) => {
  const quadrantStore = useQuadrantStore();
  if (value2 === null || value2 === void 0) return "";
  const type = axis.type === "lookup" || axis.type === "formula" ? detectValueType(value2) : axis.type;
  switch (type) {
    case "date":
      const date = new Date(value2);
      const options2 = {
        month: "short",
        day: "numeric",
        year: void 0
      };
      if (referenceValues.some((ref) => new Date(ref).getFullYear() !== date.getFullYear())) {
        options2.year = "numeric";
      }
      return date.toLocaleDateString("en-US", options2);
    case "time":
      try {
        if (typeof value2 === "string" && /^(\d{2}):(\d{2}):(\d{2})$/.test(value2)) {
          return value2;
        } else {
          const dateObj = new Date(value2);
          return dateObj.toISOString().slice(11, 16);
        }
      } catch {
        return "Invalid time";
      }
    case "number":
      return value2.toFixed(0);
    case "percentage":
      return value2.toFixed(1) + "%";
    case "size":
      if (typeof value2 === "string") return value2;
      const sizeOrder = ["S", "M", "L", "XL"];
      return sizeOrder[value2] || "";
    case "bool":
      return value2 ? "Yes" : "No";
    case "group_type":
    case "string":
      if (typeof value2 === "string") {
        return value2;
      }
      const values2 = axis.values ?? [];
      if (value2 < 0 || value2 >= values2.length) {
        return "";
      }
      return values2[value2] || "";
    default:
      return value2.toString();
  }
};
var isValueOk = (value2, type) => {
  if (value2 === null && type !== "bool" || value2 === void 0) return false;
  if (type === null || type === void 0 || type === "") return false;
  switch (type) {
    case "date":
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
      return dateRegex.test(value2) && !isNaN(Date.parse(value2)) || isFinite(value2) && !isNaN(value2);
    case "number":
    case "percentage":
      return typeof value2 === "number" && isFinite(value2) && !isNaN(value2);
    case "size":
      const validSizes = ["S", "M", "L", "XL"];
      return typeof value2 === "string" && validSizes.includes(value2);
    case "time":
      const timeRegex = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/;
      return timeRegex.test(value2);
    case "bool":
      return true;
    case "group_type":
    case "string":
      return typeof value2 === "string" || Array.isArray(value2) && value2.length > 0;
    case "lookup":
    case "formula":
      return isValueOk(value2, detectValueType(value2));
    default:
      return false;
  }
};
var detectValueType = (value2) => {
  if (typeof value2 === "string") {
    if (!isNaN(Date.parse(value2))) return "date";
    if (/^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/.test(value2)) return "time";
    return "string";
  } else if (typeof value2 === "boolean") {
    return "bool";
  } else if (typeof value2 === "number") {
    const lowerTimestampLimit = 9466848e5;
    if (value2 >= lowerTimestampLimit) {
      return "date";
    }
    return "number";
  } else {
    return null;
  }
};
function computeCardsQuadrantProps(card, serie, serieIndex) {
  const availableAxeAttributes = useQuadrantViewContext().availableAxeAttributes();
  let xValues, yValues;
  const xAttribute = serie.x.cardAttribute;
  const yAttribute = serie.y.cardAttribute;
  const options2 = useOptions();
  const rawSerie = options2.activeAxisSeries[serieIndex];
  if (serie.x.type === "group_type") {
    const attr = availableAxeAttributes.get(xAttribute);
    const groupTypeId = attr[0].group_type_id;
    xValues = getGroupTypeValues(card, groupTypeId);
  } else {
    xValues = [getValueWithAttribute(card, xAttribute)];
  }
  if (serie.y.type === "group_type") {
    const attr = availableAxeAttributes.get(yAttribute);
    const groupTypeId = attr[0].group_type_id;
    yValues = getGroupTypeValues(card, groupTypeId);
  } else {
    yValues = [getValueWithAttribute(card, yAttribute)];
  }
  let points = [];
  xValues.forEach((xValue) => {
    yValues.forEach((yValue) => {
      if (isValueOk(xValue, serie.x.type) && isValueOk(yValue, serie.y.type)) {
        const xPos = calculatePercentagePosition(xValue, serie.x);
        const yPos = calculatePercentagePosition(yValue, serie.y, !serie.y.reverse);
        points.push({
          x: xPos,
          y: yPos,
          axis: serie
        });
      }
    });
  });
  const coordinates = {
    xAttribute: serie.x.cardAttribute,
    yAttribute: serie.y.cardAttribute,
    points
  };
  const sizeAttr = rawSerie.size;
  const defaultSize = 15;
  let size4 = defaultSize;
  const cards = useCards();
  if (sizeAttr && availableAxeAttributes.has(sizeAttr)) {
    const sizeValues = cards().map((c3) => getValueWithAttribute(c3, sizeAttr));
    const minSizeValue = Math.min(...sizeValues);
    const maxSizeValue = Math.max(...sizeValues);
    const currentSizeValue = getValueWithAttribute(card, sizeAttr);
    const ratio = (currentSizeValue - minSizeValue) / (maxSizeValue - minSizeValue);
    size4 = currentSizeValue ? size4 * ratio * 3 + 1 : defaultSize;
    size4 = size4 < defaultSize ? defaultSize : size4;
  }
  const colorBy = options2.colorBy;
  let color;
  if (colorBy === "axes" || colorBy === "theme") {
    color = getColorByValue(card, options2, serieIndex);
  } else {
    const colorAttr = availableAxeAttributes.get(colorBy);
    const colorAxis = {
      cardAttribute: colorBy,
      type: colorAttr[0].type
    };
    const colorSerie = calculateAxisValues(cards(), colorAxis, colorAxis);
    const attrValue = getValueWithAttribute(card, colorBy);
    if (attrValue !== void 0 && attrValue !== null) {
      const colorIndex = calculatePercentagePosition(attrValue, {
        type: colorAxis.type,
        min: colorSerie.min,
        max: colorSerie.max
      });
      color = getColorByPercentageIndex(colorIndex);
    } else {
      if (colorAttr) {
        const groupTypeId = colorAttr[0].group_type_id;
        const groupValues = getGroupTypeValues(card, groupTypeId);
        if (groupValues.length > 0) {
          const groupValueIndex = calculatePercentagePosition(groupValues[0], {
            cardAttribute: colorBy,
            type: colorAxis.type,
            min: colorSerie.min,
            max: colorSerie.max
          });
          color = getColorByPercentageIndex(groupValueIndex);
        } else {
          color = getBaseColorFromTheme();
        }
      } else {
        color = getBaseColorFromTheme();
      }
    }
  }
  const key2 = `${serie.x.cardAttribute}-${serie.y.cardAttribute}`;
  return {
    key: key2,
    coordinates,
    color,
    size: size4
  };
}

// public/app/ui/quadrant/quadrant-utils/colorUtils.tsx
var getBaseColorFromTheme = () => {
  return getComputedStyle(document.documentElement).getPropertyValue("--theme-base-primary").trim();
};
var generateColorPalette = (baseColor2, numColors) => {
  const palette = [baseColor2];
  for (let i3 = 1; i3 < numColors; i3++) {
    const colorVariation = `hsl(${i3 * 360 / numColors}, 70%, 50%)`;
    palette.push(colorVariation);
  }
  return palette;
};
var baseColor = getBaseColorFromTheme();
var colorPalette = generateColorPalette(baseColor, 30);
var getColorByIndex = (index2) => {
  return colorPalette[index2 % colorPalette.length];
};
var getColorByPercentageIndex = (percentageIndex) => {
  const normalizedIndex = Math.round(percentageIndex / 100 * (colorPalette.length - 1));
  return colorPalette[normalizedIndex];
};
var getColorByValue = (card, options2, serieIndex) => {
  const {
    colorBy,
    activeAxisSeries
  } = options2;
  if (colorBy === "axes") {
    return getColorByPercentageIndex(serieIndex / activeAxisSeries.length * 100);
  }
  if (colorBy === "theme") {
    return baseColor;
  }
  const attrValue = getValueWithAttribute(card, colorBy);
  if (attrValue !== void 0 && attrValue !== null) {
    const colorIndex = calculatePercentagePosition(attrValue, {
      min: 0,
      max: 100
    });
    return getColorByPercentageIndex(colorIndex);
  } else {
    const attr = card.state.card.attributes.find((attr2) => attr2.name === colorBy);
    if (attr) {
      const groupTypeId = attr.group_type_id;
      const groupValues = getGroupTypeValues(card, groupTypeId);
      if (groupValues.length > 0) {
        const groupValueIndex = calculatePercentagePosition(groupValues[0], {
          min: 0,
          max: 100
        });
        return getColorByPercentageIndex(groupValueIndex);
      }
    }
  }
  return baseColor;
};
var getComplementaryColor = (color) => {
  if (color.startsWith("#")) {
    const rgb = parseInt(color.slice(1), 16);
    const r3 = rgb >> 16 & 255;
    const g3 = rgb >> 8 & 255;
    const b3 = rgb >> 0 & 255;
    const compR = 255 - r3;
    const compG = 255 - g3;
    const compB = 255 - b3;
    return `#${((1 << 24) + (compR << 16) + (compG << 8) + compB).toString(16).slice(1).toUpperCase()}`;
  } else if (color.startsWith("hsl")) {
    const [h3, s3, l3, a3] = color.match(/\d+(\.\d+)?/g).map(Number);
    const complementaryHue = (h3 + 180) % 360;
    if (typeof a3 !== "undefined") {
      return `hsla(${complementaryHue}, ${s3}%, ${l3}%, ${a3})`;
    } else {
      return `hsl(${complementaryHue}, ${s3}%, ${l3}%)`;
    }
  }
  return color;
};
var pastelizeColor = (color) => {
  if (color.startsWith("#")) {
    const rgb = parseInt(color.slice(1), 16);
    let r3 = rgb >> 16 & 255;
    let g3 = rgb >> 8 & 255;
    let b3 = rgb >> 0 & 255;
    r3 = Math.min(255, Math.round(r3 + (255 - r3) * 0.2));
    g3 = Math.min(255, Math.round(g3 + (255 - g3) * 0.2));
    b3 = Math.min(255, Math.round(b3 + (255 - b3) * 0.2));
    return `#${((1 << 24) + (r3 << 16) + (g3 << 8) + b3).toString(16).slice(1).toUpperCase()}`;
  } else if (color.startsWith("hsl")) {
    const [h3, s3, l3, a3] = color.match(/\d+(\.\d+)?/g).map(Number);
    const pastelS = Math.max(60, s3 * 0.85);
    const pastelL = Math.min(85, l3 + 15);
    if (typeof a3 !== "undefined") {
      return `hsla(${h3}, ${pastelS}%, ${pastelL}%, ${a3})`;
    } else {
      return `hsl(${h3}, ${pastelS}%, ${pastelL}%)`;
    }
  }
  return color;
};

// public/app/ui/quadrant/components/active-axis-series-context.tsx
var ActiveAxisSeriesContext = createContext();
function useActiveAxisSeries() {
  return useContext(ActiveAxisSeriesContext);
}
var ActiveAxisSeriesProvider = (props2) => {
  const cards = useCards();
  const options2 = useOptions();
  let owner;
  const activeAxisSeries = createMemo(mapArray(() => {
    owner = getOwner();
    return options2.activeAxisSeries;
  }, (serie) => {
    return runWithOwner(owner, () => {
      const xProps = createMemo(() => {
        const calculatedValues = calculateAxisValues(cards(), serie.x, serie.y);
        const combinedProps = Object.assign({}, serie.x, calculatedValues);
        return combinedProps;
      });
      const yProps = createMemo(() => {
        const calculatedValues = calculateAxisValues(cards(), serie.y, serie.x);
        const combinedProps = Object.assign({}, serie.y, calculatedValues);
        return combinedProps;
      });
      return {
        get x() {
          return xProps();
        },
        get y() {
          return yProps();
        }
      };
    });
  }));
  return createComponent(ActiveAxisSeriesContext.Provider, {
    value: activeAxisSeries,
    get children() {
      return props2.children;
    }
  });
};

// public/app/ui/quadrant/stores/option.tsx
var OptionState2 = class {
  filter = null;
  include_archived = false;
  mode = "quadrant";
  name = "Tasks";
  showUngroupedCards = true;
  showGrid = true;
  activeAxisSeries = [];
  zoneLayout = null;
  readOnly = false;
  enableSideDisplay = true;
  showInfoOnHover = true;
  colorBy = "axes";
  groupCloseDots = true;
  constructor(initialData) {
    Object.assign(this, initialData);
  }
};
var OptionStore2 = class extends createStoreMixin(OptionState2) {
  constructor(initialData) {
    super(initialData);
    this.resetState = new OptionState2(initialData);
  }
  updateOptions(updates) {
    if (this.resetState.name !== updates.name) {
      this.resetState = new OptionState2(updates);
    }
    const updateKeys = Object.keys(updates);
    const allKeys2 = Object.keys(this.state);
    this.setState(produce((draft) => {
      allKeys2.filter((k2) => !updateKeys.includes(k2)).forEach((k2) => {
        draft[k2] = this.resetState[k2];
      });
      Object.keys(updates).forEach((key2) => {
        const value2 = updates[key2];
        if (JSON.stringify(this[key2]) !== JSON.stringify(value2)) {
          draft[key2] = value2;
        }
      });
    }));
  }
};
var OptionContext2 = createContext();
function useOptions() {
  return useContext(OptionContext2);
}

// public/app/ui/quadrant/stores/item.tsx
var QuadrantItemStore = class extends BaseStore {
  id = prop();
  index = prop();
  parent = prop();
  children = prop([]);
  viewportVisible = prop(true);
  displayChildren = prop(true);
  isVisibleInSidebar = prop(true);
  position = prop(0);
  moving = prop(false);
  isRoot = prop(false);
  wrapperRef = prop();
  wrapperWidth = prop();
  wrapperHeight = prop();
  coordinates = prop({});
  colors = prop({});
  sizes = prop({});
  title = prop();
  serieIndex = prop({});
  get path() {
    return [...this.parent?.path ?? [], this.index];
  }
  addChild(store2, index2) {
    if (index2 !== void 0) {
      const newChildren = [...this.children];
      newChildren.splice(index2, 0, store2);
      this.children = newChildren;
    } else {
      this.children = [...this.children, store2];
    }
  }
  sortChildren() {
    const children2 = [...this.children];
    children2.sort((a3, b3) => a3.position - b3.position);
    this.children = children2;
  }
  removeChild(store2) {
    this.children = this.children.filter((child) => child !== store2);
  }
  find(itemOrId) {
    if (typeof itemOrId === "number" || typeof itemOrId === "string") {
      if (this.id === itemOrId) return this;
    } else {
      if (this === itemOrId) return this;
    }
    for (const child of this.children) {
      const found2 = child.find(itemOrId);
      if (found2) return found2;
    }
    return void 0;
  }
  findPath(path) {
    if (path.length === 0) return this;
    const child = this.children[path[0]];
    if (!child) return void 0;
    return child.findPath(path.slice(1));
  }
  getRoot() {
    if (this.isRoot) {
      return this;
    }
    return this.parent.getRoot();
  }
};
var ItemContext2 = createContext();
function useQuadrantItem() {
  return useContext(ItemContext2);
}
var QuadrantItemProvider = (props2) => {
  return createComponent(ItemContext2.Provider, {
    get value() {
      return props2.store;
    },
    get children() {
      return props2.children;
    }
  });
};

// public/app/apps/cards/common/app-options-utils/selected-attributes.ts
var useFieldKeys = [
  "use_date_field",
  "use_field",
  "active_date_attr_ids",
  "active_relation_attr_ids",
  "active_date_attr_id",
  "activeDatesAttrId",
  "activeDateAttrName"
];
function getSelectedAttributes(availableAttrs, options2, constraintToOne = false, forced = true) {
  const selectedAttrs = /* @__PURE__ */ new Map();
  if (!availableAttrs || availableAttrs.size === 0) return selectedAttrs;
  function findByIdOrName(idOrName) {
    for (const [attrName, attrGroup] of availableAttrs) {
      if (typeof idOrName === "string") {
        if (attrGroup.name === idOrName) return attrGroup;
      } else {
        if (attrGroup.find((attr) => attr.id === idOrName)) return attrGroup;
      }
    }
    return null;
  }
  let selectedAttrsIdsOrNames;
  for (const key2 of useFieldKeys) {
    if (!!options2?.[key2]) {
      selectedAttrsIdsOrNames = options2[key2];
      break;
    }
  }
  if (Array.isArray(selectedAttrsIdsOrNames)) {
    for (const idOrName of selectedAttrsIdsOrNames) {
      const selectedAttrGroup = findByIdOrName(idOrName);
      if (selectedAttrGroup) {
        selectedAttrs.set(selectedAttrGroup.name, selectedAttrGroup);
        if (constraintToOne) {
          break;
        }
      }
    }
  } else if (typeof selectedAttrsIdsOrNames !== "undefined") {
    const selectedAttrGroup = findByIdOrName(selectedAttrsIdsOrNames);
    if (selectedAttrGroup)
      selectedAttrs.set(selectedAttrGroup.name, selectedAttrGroup);
  }
  if (forced && selectedAttrs.size === 0 && availableAttrs.size > 0) {
    const firstAvailableAttr = availableAttrs.entries().next().value;
    selectedAttrs.set(firstAvailableAttr[0], firstAvailableAttr[1]);
  }
  return selectedAttrs;
}

// public/app/ui/quadrant/stores/quadrant-view.tsx
var QuadrantViewContext = createContext();
function useQuadrantViewContext() {
  return useContext(QuadrantViewContext);
}
function QuadrantViewProvider(props2) {
  const project = useProject();
  const options2 = useOptions();
  const [local, others] = splitProps(props2, ["children"]);
  const availableAxeAttributes = createMemo(() => {
    const map5 = /* @__PURE__ */ new Map();
    const availableAttributes = [getAvailableAttrsOfType(project(), props2.store, "date"), getAvailableAttrsOfType(project(), props2.store, "number"), getAvailableAttrsOfType(project(), props2.store, "percentage"), getAvailableAttrsOfType(project(), props2.store, "size"), getAvailableAttrsOfType(project(), props2.store, "time"), getAvailableAttrsOfType(project(), props2.store, "bool"), getAvailableAttrsOfType(project(), props2.store, "group_type"), getAvailableAttrsOfType(project(), props2.store, "formula")];
    availableAttributes.forEach((attr) => {
      attr.forEach((value2, key2) => {
        map5.set(key2, value2);
      });
    });
    return map5;
  });
  const activeAxeAttributes = createMemo(() => {
    const names = [];
    options2.activeAxisSeries.forEach((serie) => {
      names.push(serie.x.cardAttribute);
      names.push(serie.y.cardAttribute);
    });
    return getSelectedAttributes(availableAxeAttributes(), {
      active_date_attr_ids: names
    }, false);
  });
  const [matchingCardIds, setMatchingCardIds] = createSignal(props2.matchingCardIds);
  createEffect(() => {
    const newIds = props2.matchingCardIds;
    setMatchingCardIds(newIds);
  });
  return createComponent(QuadrantViewContext.Provider, {
    get value() {
      return {
        ...others,
        activeAxeAttributes,
        availableAxeAttributes,
        matchingCardIds,
        datesEditable: props2.datesEditable
      };
    },
    get children() {
      return local.children;
    }
  });
}

// public/app/ui/quadrant/stores/card-quadrant-item.tsx
var CardQuadrantItemStore = class _CardQuadrantItemStore extends QuadrantItemStore {
  card = prop();
  children = prop([]);
  group = prop();
  canCreateCard = prop();
  isCreatingCard = prop();
  childrenLoader = prop();
  cardCreatorHeight = prop(0);
  activeSeries = useActiveAxisSeries();
  onInit() {
    const project = useProject();
    const options2 = useOptions();
    const children2 = createMemo(() => this.childrenLoader());
    createEffect(on(() => children2()(), (children3) => {
      batch(() => {
        const _project = project();
        const modelStore = getScopedModelStore(_project, cardStore);
        const groupTypeStore = getScopedGroupTypeStore(_project, cardStore);
        const currentChildren = [...this.children];
        const result2 = [];
        children3.forEach((card, index2) => {
          const id = card.id;
          let childStore = currentChildren.find((c3) => c3.id == id);
          if (!childStore) {
            childStore = _CardQuadrantItemStore.create({
              card,
              id,
              title: card.title,
              parent: this,
              childrenLoader: () => {
                return cardStore.scopedByParent({
                  id
                }).react({}, () => {
                });
              }
            }, this.owner);
          }
          childStore.index = index2;
          childStore.position = index2;
          result2.push(childStore);
        });
        this.children = result2;
      });
    }));
    const computedPropsBySeries = createMemo(mapArray(() => this.activeSeries(), (serie, index2) => {
      return runWithOwner(this.owner, () => {
        return createMemo(() => Object.assign(computeCardsQuadrantProps(this.card, serie, index2()), {
          serieIndex: index2()
        }));
      });
    }));
    createEffect(() => {
      batch(() => {
        this.coordinates = void 0;
        this.coordinates = {};
      });
      const newCoordinates = {};
      const newColors = {};
      const newSizes = {};
      const newSerieIndex = {};
      for (const computedCardQuadrantProps of computedPropsBySeries()) {
        const computedProps = computedCardQuadrantProps();
        if (computedProps) {
          const key2 = computedProps.key;
          newCoordinates[key2] = {
            ...computedProps.coordinates,
            serieIndex: computedProps.serieIndex
          };
          newColors[key2] = computedProps.color;
          newSizes[key2] = computedProps.size;
          newSerieIndex[key2] = computedProps.serieIndex;
        }
      }
      batch(() => {
        this.coordinates = newCoordinates;
        this.colors = newColors;
        this.sizes = newSizes;
        this.serieIndex = newSerieIndex;
      });
    });
  }
  async updateCardAttributes(project, quadrantViewContext, xAttr, yAttr, xValue, yValue) {
    const card = this.card;
    if (card) {
      const attrs2 = unwrap(getCardAvailableAttributes(card, quadrantViewContext.availableAxeAttributes()));
      const xAttribute = attrs2.find((attr) => attr.name === xAttr);
      const yAttribute = attrs2.find((attr) => attr.name === yAttr);
      if (xAttribute && xAttribute.type !== "group_type") {
        const attrGrpX = new ModelAttributeGroup([xAttribute]);
        await attrGrpX.setObjAttribute(card, xAttribute, xValue).catch(autoCatchAsRequestErrorDialog([400]));
      }
      if (yAttribute && xAttr !== yAttr && yAttribute.type !== "group_type") {
        const attrGrpY = new ModelAttributeGroup([yAttribute]);
        await attrGrpY.setObjAttribute(card, yAttribute, yValue).catch(autoCatchAsRequestErrorDialog([400]));
      }
    }
  }
  async updateCardGroups(coordinates, xValue, yValue, oldXValue = null, oldYValue = null, quadrantViewContext, quadrantStore) {
    const card = this.card;
    const isXAxisGroup = coordinates.axis.x.type === "group_type";
    const isYAxisGroup = coordinates.axis.y.type === "group_type";
    const hoveredPoints = quadrantStore.hoveredPoint;
    const allGroups = quadrantStore.availableGroupType;
    if (hoveredPoints && (oldXValue || oldYValue)) {
      for (const point of hoveredPoints) {
        if (card.id === point.card.state.card.id) {
          if (isXAxisGroup && point.coordinates.axis.x.type === "group_type") {
            const currentXValue = calculateValueFromPercentagePosition(point.coordinates.x, coordinates.axis.x);
            if (currentXValue !== oldXValue) {
              const xAttr = quadrantViewContext.availableAxeAttributes().get(coordinates.axis.x.cardAttribute);
              const xGroupTypeId = xAttr[0].group_type_id;
              const groupId = allGroups.get(xGroupTypeId)?.get(oldXValue)?.id;
              if (groupId) {
                await removeCardFromGroup(card, [{
                  id: groupId
                }]);
              }
            }
          }
          if (isYAxisGroup && point.coordinates.axis.y.type === "group_type") {
            const currentYValue = calculateValueFromPercentagePosition(point.coordinates.y, coordinates.axis.y, !coordinates.axis.y.reverse);
            if (currentYValue !== oldYValue) {
              const yAttr = quadrantViewContext.availableAxeAttributes().get(coordinates.axis.y.cardAttribute);
              const yGroupTypeId = yAttr[0].group_type_id;
              const groupId = allGroups.get(yGroupTypeId)?.get(oldYValue)?.id;
              if (groupId) {
                await removeCardFromGroup(card, [{
                  id: groupId
                }]);
              }
            }
          }
        }
      }
    }
    if (isXAxisGroup) {
      const xAttr = quadrantViewContext.availableAxeAttributes().get(coordinates.axis.x.cardAttribute);
      const xGroupTypeId = xAttr[0].group_type_id;
      const groupId = allGroups.get(xGroupTypeId)?.get(xValue)?.id;
      if (groupId) {
        await addCardToGroup(card, [{
          id: groupId
        }], card.position);
      }
    }
    if (isYAxisGroup) {
      const yAttr = quadrantViewContext.availableAxeAttributes().get(coordinates.axis.y.cardAttribute);
      const yGroupTypeId = yAttr[0].group_type_id;
      const groupId = allGroups.get(yGroupTypeId)?.get(yValue)?.id;
      if (groupId) {
        await addCardToGroup(card, [{
          id: groupId
        }], card.position);
      }
    }
  }
};
function groupHaveElements(axis, quadrantViewContext, quadrantStore) {
  const allGroups = quadrantStore.availableGroupType;
  const attr = quadrantViewContext.availableAxeAttributes().get(axis.cardAttribute);
  const groupTypeId = attr[0].group_type_id;
  return allGroups.get(groupTypeId) !== void 0 && allGroups.get(groupTypeId).size > 0;
}

// public/app/ui/quadrant/stores/quadrant.tsx
var QuadrantStore = class extends BaseStore {
  hoveredPoint = prop();
  selectedPoint = prop();
  mappedSeries = prop();
  groupTypeValues = createSignal({});
  availableGroupType = prop();
  zonesManager = prop(createZonesManager());
  zoneTitlePositions = prop();
  // activeAxisSeries = prop<Serie[]>([]);
};
var QuadrantContext = createContext({});
var useQuadrantStore = () => {
  return useContext(QuadrantContext);
};
var QuadrantProvider = QuadrantContext.Provider;

// public/app/apps/cards/quadrant/options-menu/zones.ts
function createZoneSubmenu(index2, options2, onChange) {
  return [
    { subheader: _4("Zone Name (optional)") },
    {
      label: _4("Zone Name (optional)"),
      input: true,
      defaultValue: options2.zoneLayout.zones[index2].name || "",
      submit: (value2) => {
        const updatedZones = [...options2.zoneLayout.zones];
        updatedZones[index2] = {
          ...updatedZones[index2],
          name: value2
        };
        onChange({
          zoneLayout: { ...options2.zoneLayout, zones: updatedZones }
        });
      }
    },
    { subheader: _4("Zone Background Color") },
    {
      label: _4("Zone Background Color"),
      colorpicker: true,
      getValue: () => options2.zoneLayout.zones[index2].backgroundColor,
      action: (event2, color) => {
        const updatedZones = [...options2.zoneLayout.zones];
        updatedZones[index2] = {
          ...updatedZones[index2],
          backgroundColor: color
        };
        onChange({
          zoneLayout: { ...options2.zoneLayout, zones: updatedZones }
        });
      },
      noCloseAfterAction: true,
      hasColorPalette: true
    },
    options2.zoneLayout.zones[index2].isCustom && {
      label: _4("Remove Custom Zone"),
      icon: "trash",
      action: () => {
        onChange({
          zoneLayout: {
            ...options2.zoneLayout,
            zones: options2.zoneLayout.zones.filter((_5, i3) => i3 !== index2)
          }
        });
      },
      noCloseAfterAction: true,
      backAfterAction: true
    }
  ];
}
function createPartitionZones(cols, lines, totalWidth, totalHeight) {
  const zones = [];
  const zoneWidth = totalWidth / cols;
  const zoneHeight = totalHeight / lines;
  for (let i3 = 0; i3 < lines; i3++) {
    for (let j = 0; j < cols; j++) {
      zones.push({
        name: `Partition ${i3 * cols + j + 1}`,
        backgroundColor: pastelizeColor(
          getComplementaryColor(getColorByIndex(i3 * cols + j + 1))
        ),
        left: j * zoneWidth,
        top: i3 * zoneHeight,
        width: zoneWidth,
        height: zoneHeight,
        isCustom: false
      });
    }
  }
  return zones;
}

// public/app/apps/cards/quadrant/options-menu/options.ts
function getOptionsMenu(store2, board, groupBy2, options2 = {}, onChange) {
  const project = board ? projectStore.tryGetForCard(board) : null;
  const availableAxeAttributes = getAvailableAttrsOfType(project, store2, [
    "date",
    "number",
    "percentage",
    "size",
    "time",
    "bool",
    "group_type",
    "formula"
  ]);
  if (!options2.zoneLayout || !options2.zoneLayout.zones) {
    options2.zoneLayout = { cols: 0, lines: 0, zones: [] };
  }
  const axeFieldsList = Array.from(availableAxeAttributes.keys()).map(
    (key2) => ({ name: key2 })
  );
  const colorFieldsList = [{ name: "theme" }];
  axeFieldsList.forEach((attr) => {
    if (!colorFieldsList.some((item) => item.name === attr.name)) {
      colorFieldsList.push({ name: attr.name });
    }
  });
  const zoneNumberArray = Array.from({ length: 11 }, (_5, i3) => ({
    name: i3.toString()
  }));
  return {
    config: () => {
      if (!options2.activeAxisSeries) {
        const axis = {
          x: {
            name: "",
            cardAttribute: "",
            showGraduation: true,
            reverse: false,
            position: "bottom"
          },
          y: {
            name: "",
            cardAttribute: "",
            showGraduation: true,
            reverse: false,
            position: "left"
          },
          size: 15,
          color: ""
        };
        return [
          {
            label: _4("Add New Axis Pair"),
            icon: "bi-plus-lg",
            submenu: createAxisSubmenu(
              axis,
              0,
              availableAxeAttributes,
              options2,
              onChange
            )
          }
        ];
      }
      return [
        { subheader: _4("Visibility of cards") },
        {
          label: _4("Archived"),
          checkbox: true,
          value: () => (options2 || {}).include_archived,
          toggle: () => onChange({ include_archived: !(options2 || {}).include_archived })
        },
        { label: "--" },
        {
          label: _4("Edit axis pair"),
          submenu: createAxisSubmenu(
            options2.activeAxisSeries[0],
            0,
            availableAxeAttributes,
            options2,
            onChange
          )
        },
        // For Multi axis series management
        // { subheader: _('Axes Configuration') },
        // ...activeAxisSeries.length > 0 ? activeAxisSeries.map((axis, index) => ({
        //   label: axis.x.cardAttribute && axis.y.cardAttribute ? `${axis.x.cardAttribute} - ${axis.y.cardAttribute}` : `Axis Pair ${index + 1}`,
        //   submenu: createAxisSubmenu(axis, index, availableAxeAttributes, options, onChange)
        // })) : [],
        // activeAxisSeries.length === 0 && {
        //   label: _('Add New Axis Pair'),
        //   icon: 'bi-plus-lg',
        //   action: () => {
        //     const updatedAxisSeries = [...activeAxisSeries, {
        //       x: { name: "", cardAttribute: "", showGraduation: true, reverse: false, position: (activeAxisSeries.length % 2 === 0) ? 'bottom' : 'top' },
        //       y: { name: "", cardAttribute: "", showGraduation: true, reverse: false, position: (activeAxisSeries.length % 2 === 0) ? 'left' : 'right' },
        //       size: 15,
        //       color: ""
        //     }];
        //     onChange({ activeAxisSeries: updatedAxisSeries });
        //   },
        //   noCloseAfterAction: true,
        // },
        { label: "--" },
        { subheader: _4("Zones Configuration") },
        { subheader: _4("Columns") },
        {
          label: _4("Columns"),
          selectbox: true,
          select: (selectedOption) => {
            const cols = parseInt(selectedOption.name, 10);
            const totalWidth = 100;
            const totalHeight = 100;
            const partitionZones = createPartitionZones(
              cols,
              options2.zoneLayout.lines,
              totalWidth,
              totalHeight
            );
            const updatedZoneLayout = {
              ...options2.zoneLayout,
              cols,
              zones: [
                ...partitionZones,
                ...options2.zoneLayout.zones.filter((zone) => zone.isCustom)
              ]
            };
            onChange({ zoneLayout: updatedZoneLayout });
          },
          selectOptions: zoneNumberArray,
          defaultValue: zoneNumberArray.find(
            (n4) => n4.name === options2.zoneLayout.cols.toString()
          ) || zoneNumberArray[0],
          optionsLabelProperty: "name",
          noCloseAfterAction: true
        },
        { subheader: _4("Lines") },
        {
          label: _4("Lines"),
          selectbox: true,
          select: (selectedOption) => {
            const lines = parseInt(selectedOption.name, 10);
            const totalWidth = 100;
            const totalHeight = 100;
            const partitionZones = createPartitionZones(
              options2.zoneLayout.cols,
              lines,
              totalWidth,
              totalHeight
            );
            const updatedZoneLayout = {
              ...options2.zoneLayout,
              lines,
              zones: [
                ...partitionZones,
                ...options2.zoneLayout.zones.filter((zone) => zone.isCustom)
              ]
            };
            onChange({ zoneLayout: updatedZoneLayout });
          },
          selectOptions: zoneNumberArray,
          defaultValue: zoneNumberArray.find(
            (n4) => n4.name === options2.zoneLayout.lines.toString()
          ) || zoneNumberArray[0],
          optionsLabelProperty: "name",
          noCloseAfterAction: true
        },
        {
          label: _4("Configure Zones"),
          submenu: options2.zoneLayout.zones.map((zone, index2) => ({
            label: zone.name ? zone.name : `Zone ${index2 + 1}`,
            submenu: createZoneSubmenu(index2, options2, onChange)
          }))
        },
        { label: "--" },
        {
          checkbox: true,
          label: _4("Show Grid"),
          offline: true,
          mobile: true,
          value: () => !!options2?.showGrid || options2?.showGrid === void 0,
          toggle: () => onChange({
            showGrid: !!options2?.showGrid || options2?.showGrid === void 0 ? false : void 0
          })
        },
        {
          checkbox: true,
          label: _4("Read only"),
          offline: true,
          mobile: true,
          value: () => !!(options2 || {}).readOnly,
          toggle: () => onChange({ readOnly: !(options2 || {}).readOnly })
        },
        {
          checkbox: true,
          label: _4("Display title"),
          offline: true,
          mobile: true,
          value: () => !!options2?.enableSideDisplay || options2?.enableSideDisplay === void 0,
          toggle: () => onChange({
            enableSideDisplay: !!options2?.enableSideDisplay || options2?.enableSideDisplay === void 0 ? false : void 0
          })
        },
        {
          checkbox: true,
          label: _4("Show info on hover"),
          offline: true,
          mobile: true,
          value: () => !!options2?.showInfoOnHover || options2?.showInfoOnHover === void 0,
          toggle: () => onChange({
            showInfoOnHover: !!options2?.showInfoOnHover || options2?.showInfoOnHover === void 0 ? false : void 0
          })
        },
        {
          checkbox: true,
          label: _4("Group close dots"),
          offline: true,
          mobile: true,
          value: () => !!options2?.groupCloseDots || options2?.groupCloseDots === void 0,
          toggle: () => onChange({
            groupCloseDots: !!options2?.groupCloseDots || options2?.groupCloseDots === void 0 ? false : void 0
          })
        },
        { subheader: _4("Color by") },
        {
          selectbox: true,
          select: (selectedOption) => onChange({ colorBy: selectedOption.name }),
          selectOptions: colorFieldsList,
          defaultValue: options2?.colorBy ? colorFieldsList.find((n4) => n4.name === options2?.colorBy) : colorFieldsList[0],
          optionsLabelProperty: "name",
          noCloseAfterAction: true
        },
        ...project ? [getFullScreenOption()] : [],
        ...getActionsOptions(options2, (changes) => onChange(changes), project)
      ];
    }
  };
}

// public/app/apps/cards/quadrant/index.js
cardsAppRegistry.register("quadrant", {
  component: "cards-app-quadrant",
  navComponent: "cards-app-nav-quadrant",
  title: _lazy("Quadrant"),
  description: _lazy("Visualize your cards on a 2-axis chart"),
  icon: "bi-grid-3x3-gap-fill",
  filterable: true,
  hiddenBehindFeatureFlag: "quadrant",
  mobileReadOnly: true,
  convertToImage: (title) => {
    exportElementToImage(title, ".quadrant-content");
  },
  menu: (...args) => getOptionsMenu(...args)
});

// public/app/apps/cards/planning/index.tsx
cardsAppRegistry.register("planning", {
  component: "cards-app-planning",
  navComponent: "cards-app-nav-planning",
  title: _lazy("Planning (beta)"),
  icon: "kfi-timeline",
  filterable: true,
  groupable: true,
  sortable: true,
  freeSort: false,
  projectScoped: true,
  hiddenBehindFeatureFlag: "planning",
  mobileReadOnly: true,
  menu: (store2, board, groupBy2, options2 = {}, onChange) => {
    const project = board ? projectStore.tryGetForCard(board) : null;
    function getPickerRanges() {
      const ranges = {};
      for (let date of specialDateRanges) {
        ranges[date.displayedName] = [date.startDate, date.endDate];
      }
      return ranges;
    }
    const pickerOptions = {
      opens: "center",
      autoApply: true,
      ranges: getPickerRanges(),
      showCustomRangeLabel: false,
      alwaysShowCalendars: true
    };
    const nullValueForCardState = {
      id: null,
      label: _4("None")
    };
    const relationships = Array.from(getAvailableAttrsOfType(project, null, "relationships").values()).map((namedAttrGroup) => ({
      id: namedAttrGroup.name,
      label: namedAttrGroup.name,
      namedAttrGroup
    }));
    return {
      config: () => {
        const localDateRange = options2?.period || DEFAULT_PERIOD;
        const rangeForPicker = {
          start: moment_default(localDateRange.start),
          end: moment_default(localDateRange.end)
        };
        let dateFieldOptions = [];
        if (options2?.relationship !== nullValueForCardState.id) {
          const dateFields = getAvailableAttrsOfType(project, null, "date");
          dateFieldOptions = Array.from(dateFields.values()).map((namedAttrGroup) => {
            return {
              id: namedAttrGroup.name,
              label: namedAttrGroup.name,
              namedAttrGroup
            };
          });
        }
        const items = [{
          label: _4("Planning configuration")
        }, {
          subheader: _4("Relationship field")
        }, {
          selectbox: true,
          selectOptions: [nullValueForCardState].concat(relationships),
          optionsLabelProperty: "label",
          defaultValue: options2?.relationship ? relationships.find((r3) => r3.id === options2.relationship) : nullValueForCardState,
          select: (obj) => {
            onChange({
              relationship: obj.id
            });
          }
        }, {
          subheader: _4("Date field")
        }, {
          selectbox: true,
          disabled: () => options2?.relationship === nullValueForCardState.id,
          selectOptions: [nullValueForCardState].concat(dateFieldOptions),
          optionsLabelProperty: "label",
          defaultValue: options2?.dateField ? dateFieldOptions.find((r3) => r3.id === options2.dateField) : nullValueForCardState,
          select: (obj) => {
            onChange({
              dateField: obj.id
            });
          }
        }, {
          label: "--"
        }, {
          subheader: _4("Visible period")
        }, {
          component: "datepicker-menu-component",
          params: {
            date: () => rangeForPicker,
            options: () => pickerOptions,
            isRange: () => true,
            onDateChange: (start, end) => {
              const activeRange = dateRangeToActiveRange({
                start,
                end
              });
              if (isDateRangesEqual(rangeForPicker, activeRange)) return;
              const newDate = formatPeriodToString(activeRange);
              return onChange({
                period: {
                  ...options2.period ?? {},
                  ...newDate || {}
                }
              });
            }
          }
        }, {
          subheader: _4("Visibility of cards")
        }, {
          checkbox: true,
          label: _4("Ungrouped"),
          offline: true,
          mobile: true,
          value: () => !!(options2 || {}).showUngroupedCards,
          toggle: () => onChange({
            showUngroupedCards: !(options2 || {}).showUngroupedCards
          })
        }, {
          label: _4("Archived"),
          checkbox: true,
          value: () => (options2 || {}).include_archived,
          toggle: () => onChange({
            include_archived: !(options2 || {}).include_archived
          })
        }, {
          label: _4("Display period titles"),
          submenu: [{
            label: _4("Hide"),
            public: true,
            mobile: true,
            action: () => onChange({
              displayPeriodTitle: DisplayPeriodTitle.NONE
            }),
            selected: () => options2.displayPeriodTitle === DisplayCardTitle.NONE || !options2.displayPeriodTitle
          }, {
            label: _4("Inside"),
            public: true,
            mobile: true,
            action: () => onChange({
              displayPeriodTitle: DisplayPeriodTitle.INSIDE
            }),
            selected: () => options2.displayPeriodTitle === DisplayPeriodTitle.INSIDE
          }]
        }, {
          label: _4("Display density"),
          icon: "bi-reception-4",
          submenu: [{
            checkbox: true,
            switch: false,
            label: _4("Normal"),
            value: () => !(options2 || {}).displayDensity,
            toggle: () => onChange({
              displayDensity: DisplayDensity.NORMAL
            })
          }, {
            desc: _4("A good balance between space and information density")
          }, {
            checkbox: true,
            switch: false,
            label: _4("Compact"),
            value: () => (options2 || {}).displayDensity === DisplayDensity.COMPACT,
            toggle: () => onChange({
              displayDensity: DisplayDensity.COMPACT
            })
          }, {
            desc: _4("A dense layout to see more cards at once")
          }, {
            checkbox: true,
            switch: false,
            label: _4("Large"),
            value: () => (options2 || {}).displayDensity === DisplayDensity.LARGE,
            toggle: () => onChange({
              displayDensity: DisplayDensity.LARGE
            })
          }, {
            desc: _4("A lot of space for greater readability")
          }]
        }, {
          label: "--"
        }, {
          subheader: _4("More")
        }, {
          checkbox: true,
          label: _4("Hide empty groups"),
          offline: false,
          mobile: true,
          value: () => !!(options2 || {}).hideEmptyGroups,
          toggle: () => onChange({
            hideEmptyGroups: !(options2 || {}).hideEmptyGroups
          })
        }, {
          label: _4("Maximize / minimize"),
          submenu: [{
            label: _4("Maximize all"),
            public: true,
            mobile: true,
            action: () => {
              $broadcast("maximizeAllCards");
            }
          }, {
            label: _4("Minimize all"),
            public: true,
            mobile: true,
            action: () => {
              $broadcast("minimizeAllCards");
            }
          }]
        }, {
          label: "--"
        }, ...project ? [getFullScreenOption()] : [], ...getActionsOptions(options2, (changes) => onChange(changes), project)];
        return items;
      }
    };
  }
});

// public/app/apps/cards/map/index.js
cardsAppRegistry.register("map", {
  component: "cards-app-map",
  title: _lazy("Map"),
  description: _lazy("Visualize cards with locations on a map"),
  icon: "bi-geo-alt-fill",
  filterable: true,
  lockable: true,
  searchable: true,
  needsField: "location",
  mobileReadOnly: true,
  menu: (store2, board, groupBy2, options2 = {}, onChange) => {
    return {
      config: () => () => {
        return [
          ...getCommonModeOptions(options2, (changes) => onChange(changes))
        ];
      }
    };
  }
});

// public/app/apps/project/app-registry.js
var ProjectAppRegistry = class extends AppRegistry {
  get(name2, ...args) {
    return cardsAppRegistry.get(name2, ...args) || super.get(name2, ...args);
  }
};
var projectAppRegistry = new ProjectAppRegistry({ setNameOnItem: true });

// public/app/apps/portfolio/app-registry.js
var portfolioAppRegistry = new ProjectAppRegistry({ setNameOnItem: true });

// public/app/apps/portfolio/overview/index.js
portfolioAppRegistry.register("overview", {
  component: "portfolio-overview-app",
  title: _lazy("Workspaces"),
  icon: "bi-columns-gap",
  navComponent: "portfolio-overview-app-nav",
  noView: true,
  hideAppName: true,
  default: true
});

// public/app/apps/portfolio/index.js
portfolioAppRegistry.register("cards", {
  component: "project-cards-app",
  navComponent: "project-cards-app-nav",
  title: _lazy("Cards"),
  hideAppName: true,
  cardsFilterable: true
});
portfolioAppRegistry.register("activities", {
  component: "project-activities-app",
  title: _lazy("Journal"),
  icon: "kfi-journal",
  color: "#0ec0de",
  navComponent: "project-activities-app-nav",
  reset: true
});
portfolioAppRegistry.register("report", {
  component: "project-report-app",
  title: _lazy("Dashboard"),
  icon: "bi-graph-up",
  color: "#0ec0de",
  navComponent: "project-report-app-nav",
  mobileReadOnly: true,
  reset: true,
  confirmViewReset: (view) => {
    return view && view.mode_options && (view.mode_options.widgets || view.mode_options.title);
  }
});
portfolioAppRegistry.register("files", {
  component: "project-files-app",
  title: _lazy("Files"),
  icon: "bi-folder",
  color: "#0ec0de",
  navComponent: "project-files-app-nav",
  mobileReadOnly: true
});

// public/app/apps/project/forms/index.js
projectAppRegistry.register("forms", {
  component: "project-forms-app",
  title: _lazy("Forms"),
  icon: "kfi-form",
  color: "#0ec0de",
  reset: true,
  draftable: false,
  noView: true,
  hidden: true
});
projectAppRegistry.register("form", {
  component: "project-form-app",
  navComponent: "project-form-app-nav",
  title: _lazy("Form"),
  description: _lazy("Publish a form to collect data from people external to the workspace"),
  icon: "kfi-form",
  color: "#0ec0de",
  reset: true,
  draftable: false,
  shareable: false,
  hideAppName: true,
  keepUntitled: true
});

// public/app/apps/project/report/index.js
projectAppRegistry.register("report", {
  component: "project-report-app",
  title: _lazy("Dashboard"),
  description: _lazy("Visualize your workspace data with customizable reports."),
  icon: "bi-graph-up",
  color: "#0ec0de",
  navComponent: "project-report-app-nav",
  mobileReadOnly: true,
  reset: true,
  confirmViewReset: (view) => {
    return view && view.mode_options && (view.mode_options.widgets || view.mode_options.title);
  }
});

// public/app/apps/project/activities/index.js
projectAppRegistry.register("activities", {
  component: "project-activities-app",
  title: _lazy("Journal"),
  description: _lazy("Keep track of your workspace's activities and changes."),
  icon: "kfi-journal",
  color: "#0ec0de",
  navComponent: "project-activities-app-nav",
  reset: true
});

// public/app/apps/project/files/index.js
projectAppRegistry.register("files", {
  component: "project-files-app",
  title: _lazy("Files"),
  description: _lazy("See all files attached across all cards in your workspace"),
  icon: "bi-folder",
  color: "#0ec0de",
  navComponent: "project-files-app-nav",
  mobileReadOnly: true
});

// public/app/apps/project/logs/index.js
projectAppRegistry.register("logs", {
  component: "project-logs-app",
  title: _lazy("Logs"),
  description: _lazy("Manage card logs and download logs reports"),
  icon: "kfi-logs",
  color: "#0ec0de",
  navComponent: "project-logs-app-nav",
  reset: true
});

// public/app/apps/project/automations/index.js
projectAppRegistry.register("automations", {
  component: "project-automations-app",
  title: _lazy("Automations"),
  icon: "bolt",
  navComponent: "project-automations-app-nav",
  mobileReadOnly: true,
  noView: true,
  hideAppName: true
});

// public/app/apps/project/cards/index.js
projectAppRegistry.register("cards", {
  component: "project-cards-app",
  navComponent: "project-cards-app-nav",
  title: _lazy("Cards"),
  hideAppName: true,
  cardsFilterable: true
});

// public/app/apps/project/integrations/index.js
projectAppRegistry.register("integrations", {
  name: "integrations",
  component: "project-integrations-app",
  title: _lazy("Integrations"),
  icon: "bi-plug-fill",
  mobileReadOnly: true,
  noView: true,
  hideAppName: true
});

// public/app/apps/project/overview/index.js
projectAppRegistry.register("overview", {
  component: "project-overview-app",
  title: _lazy("Workspace Info"),
  icon: "home",
  navComponent: "project-overview-app-nav",
  hidden: true,
  noView: true,
  hideFromSidebar: true,
  hideAppName: true,
  default: true,
  priority: 1
});

// public/app/apps/global/app-registry.js
var GlobalAppRegistry = class extends AppRegistry {
  get(name2, ...args) {
    return cardsAppRegistry.get(name2, ...args) || super.get(name2, ...args);
  }
};
var globalAppRegistry = new GlobalAppRegistry({ setNameOnItem: true });

// public/app/apps/global/cards/index.js
globalAppRegistry.register("cards", {
  title: _lazy("Cards"),
  component: "global-cards-app",
  navComponent: "global-cards-app-nav"
});

// public/app/apps/global/report/index.js
globalAppRegistry.register("report", {
  title: _lazy("Dashboard"),
  component: "global-report-app",
  navComponent: "global-report-app-nav",
  icon: "bar-chart"
});

// public/app/services/feature-flags.js
function hasFeatureFlag(org2, flag) {
  return org2 && org2.feature_flags && org2.feature_flags.includes(flag);
}
function fenceBehindFeatureFlag(org2, flag, callback) {
  if (hasFeatureFlag(org2, flag)) {
    callback();
  } else {
    $invoke(["orgSettingsModal", (orgSettingsModal) => orgSettingsModal.open(org2, "billing")]);
  }
}

// public/app/apps/utils.ts
function getAvailableApps(project, filterScopes, options2) {
  if (!project) {
    return globalAppRegistry.getAll(options2);
  }
  if (!project.is_portfolio) {
    return projectAppRegistry.getAll(options2);
  }
  if (filterScopes?.[0]?.[0] === "portfolio") {
    return globalAppRegistry.getAll(options2);
  }
  return portfolioAppRegistry.getAll(options2);
}
function getAvailableCardsApps(project, filterScopes) {
  const org2 = orgStore.tryGetForProject(project);
  return cardsAppRegistry.getAll().filter(
    (app) => (!app.projectScoped || project && !project.is_portfolio) && (!app.hiddenBehindFeatureFlag || currentUser2.is_kantree_admin || org2 && hasFeatureFlag(org2, app.hiddenBehindFeatureFlag))
  );
}
function isAppAvailable(app, project, filterScopes) {
  const org2 = orgStore.tryGetForProject(project);
  return (!app.projectScoped || project && !project.is_portfolio) && (!app.hiddenBehindFeatureFlag || currentUser2.is_kantree_admin || org2 && hasFeatureFlag(org2, app.hiddenBehindFeatureFlag));
}
function getAppForView(view) {
  if (!view.project_id) {
    return globalAppRegistry.get(view.mode);
  }
  if (!projectStore.tryGet(view.project_id)?.is_portfolio) {
    return projectAppRegistry.get(view.mode);
  }
  if (view.filter_scopes?.[0]?.[0] === "portfolio") {
    return globalAppRegistry.get(view.mode);
  }
  return portfolioAppRegistry.get(view.mode);
}

// public/app/stores/view.ts
var ViewStore = class extends Store {
  format(view) {
    if (!view.icon && view.mode) {
      view.default_icon = getAppForView(view)?.icon;
    }
    return view;
  }
  tryGetFromView(view) {
    if (view.from_view_id) {
      return this.tryGet(view.from_view_id);
    }
    return null;
  }
  scopedByGlobal() {
    return this.scoped({ project_id: query_exports.isUndefined() });
  }
  scopedByProject(project) {
    return this.scoped(() => ({ project_id: callOrValue(project).id }));
  }
  scopedByBoard(project, board, noDraftFromExistingView = false) {
    return this.scopedByProject(project).scoped(() => (view) => {
      if (noDraftFromExistingView && view._draft) {
        const fromView = this.tryGet(view.from_view_id);
        if (fromView && fromView.project_id === project.id) {
          return false;
        }
      }
      return !view.limit_to_ref || view.card_ref === null || view.card_ref === board.ref;
    });
  }
  reorderAfterChange(view, oldPosition, oldCategoryId) {
    if (view && view.position === oldPosition && view.category_id === oldCategoryId) return;
    this.transaction(() => {
      const bounds = computeMoveBounds(oldPosition, view.position);
      const q = {
        position: (value2) => value2 >= bounds.lower && (bounds.upper === null || value2 <= bounds.upper)
      };
      if (view) {
        q["id"] = query_exports.neq(view.id);
      }
      this.updateManyMatching(q, { position: (v3) => v3 + bounds.shift });
    });
  }
  reorderAfterRemoval(removedView) {
    this.reorderAfterChange(null, removedView.position, removedView.category_id);
  }
  isGlobalView(view) {
    return typeof view.project_id === "undefined";
  }
  isProjectView(view) {
    return view.project_id;
  }
  isDraftView(view) {
    return !!view._draft;
  }
  tryGetDraftView(fromView) {
    return this.query({ _draft: true, from_view_id: (id) => !fromView && !id || fromView && id === fromView.id })?.[0];
  }
  upsertDraftView(viewProps = {}, fromView) {
    const draftView = this.tryGetDraftView(fromView);
    if (fromView) {
      if (draftView) {
        this.remove(draftView);
      }
      viewProps.from_view_id = fromView.id;
      viewProps.card_ref = fromView.card_ref;
    } else {
      this.removeManyMatching({
        _draft: true,
        from_view_id: (id) => viewProps.from_view_id ? viewProps.from_view_id === id : !id,
        id: (id) => draftView ? draftView.id !== id : true
      });
    }
    return this.upsert(Object.assign({
      _draft: true,
      is_public: false,
      icon: null,
      name: _4("Unsaved view")
    }, draftView, viewProps));
  }
  formatDraftView(view, viewProps = {}, defaultProps = {}, availableProps = []) {
    if (!!view && !!viewProps.mode && viewProps.mode !== view.mode) {
      viewProps = {
        ...viewProps,
        mode_options: { ...defaultProps.mode_options, ...viewProps.mode_options }
      };
    }
    if (!view) {
      viewProps = {
        ...defaultProps,
        ...viewProps,
        mode_options: { ...defaultProps.mode_options, ...viewProps.mode_options }
      };
    } else {
      viewProps = { ...availableProps.reduce((accu, propName) => {
        accu[propName] = view[propName];
        return accu;
      }, {}), ...viewProps, from_view_id: view.from_view_id || (this.isDraftView(view) ? null : view.id) };
    }
    return viewProps;
  }
  upsertDraftFromView(view, viewChanges, defaultProps, availableProps) {
    viewChanges = this.formatDraftView(view, viewChanges, defaultProps, availableProps);
    return this.upsertDraftView(viewChanges, view && !this.isDraftView(view) ? view : null);
  }
  hasChanges(view, changes) {
    return Object.keys(changes).some((propName) => !equals(changes[propName], view[propName]));
  }
};
var viewStore = new ViewStore({
  typeName: "view"
}, idbLocalStorage);

// public/app/stores/instances.ts
var attributeTypeStore = new Store({
  typeName: "attributeType"
}, idbLocalStorage);
var integrationTypeStore = new Store();
var requestStore = new Store({
  typeName: "request"
}, idbLocalStorage);

// public/app/stores/project-offline-availability.ts
var projectOfflineTTL = 86400;
var [offlineProjects, setOfflineProjects] = createStorageSignal("offlineProjects", {}, { api: localStorage });
clearExpiredEntries();
setInterval(clearExpiredEntries, 3e5);
createEffect(() => {
  if (isConnected()) {
    clearExpiredEntries();
  }
});
function setKeepProjectOffline(project, keep = true, permanent = false) {
  if (keep) {
    setOfflineProjects((prev) => ({ ...prev, [project.id]: [moment_default().unix(), permanent] }));
  } else if (offlineProjects()?.[project.id] >= 0) {
    setOfflineProjects((prev) => omit_default(prev, project.id));
  }
}
function isProjectAvailableOffline(project) {
  return !!offlineProjects()?.[project.id];
}
function isProjectAccessible(project) {
  return isConnected() || isProjectAvailableOffline(project);
}
function clearAllProjectAvailableOffline() {
  setOfflineProjects({});
}
function clearExpiredEntries() {
  if (!isConnected()) {
    return;
  }
  const now = moment_default().unix();
  setOfflineProjects((prev) => omit_default(prev, ([since, permanent]) => !permanent && now - since < projectOfflineTTL));
}

// public/app/stores/utils/clear-all.js
async function clearAllStores() {
  await idbLocalStorage.clear();
  for (let store2 of Object.values(instances_exports)) {
    if (store2 instanceof Store) {
      store2.reset();
    }
  }
  clearAllProjectAvailableOffline();
  return true;
}

// public/app/services/auth-session.js
function clearStorageBeforeLogout() {
  clearAllStores();
  clearCurrentUser();
  closePushConnection();
  localStorage.clear();
}
var RedirectLoginHandler = class {
  login() {
    document.location = location.protocol + "//" + serverConfig.server_name + "/login?next=" + encodeURIComponent(document.location.href);
  }
  logout() {
    clearStorageBeforeLogout();
    document.location = location.protocol + "//" + serverConfig.server_name + "/logout";
  }
  signup() {
    document.location = location.protocol + "//" + serverConfig.server_name + "/signup?next=" + encodeURIComponent(document.location.href);
  }
};
var authSession = createProxyHandler(new RedirectLoginHandler());

// public/app/ui/base/topbar.jsx
var _tmpl$105 = /* @__PURE__ */ template(`<a class="navbar-brand hidden-xs hidden-with-sidebar" href="/">Kantree</a>`, 2);
var _tmpl$242 = /* @__PURE__ */ template(`<ul class="navbar-actions hidden-xs"><li><a href="javascript:" class="btn btn-topbar"></a></li><li><a href="javascript:" class="btn btn-topbar"></a></li></ul>`, 10);
var _tmpl$327 = /* @__PURE__ */ template(`<div id="topbar"><button type="button" class="btn btn-topbar btn-icon btn-sidebar-toggle visible-xs-block"></button></div>`, 4);
function TopBar(props2) {
  let logoStyle;
  if (serverConfig.navbar_logo_url) {
    logoStyle = {
      "background-image": "url(" + serverConfig.navbar_logo_url + ")"
    };
  }
  const toggleSidebar = () => {
    if (isScreensizeXS()) {
      $invoke(["navSidebar", (navSidebar) => navSidebar.toggle()]);
    }
  };
  return (() => {
    const _el$ = _tmpl$327.cloneNode(true), _el$2 = _el$.firstChild;
    _el$2.$$click = toggleSidebar;
    insert(_el$2, createComponent(Icon, {
      name: "bars"
    }));
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.withLogo;
      },
      get children() {
        const _el$3 = _tmpl$105.cloneNode(true);
        createRenderEffect((_p$) => {
          const _v$ = isAuthenticated() ? "" : "_self", _v$2 = logoStyle;
          _v$ !== _p$._v$ && setAttribute(_el$3, "target", _p$._v$ = _v$);
          _p$._v$2 = style(_el$3, _v$2, _p$._v$2);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0
        });
        return _el$3;
      }
    }), null);
    insert(_el$, () => props2.children, null);
    insert(_el$, createComponent(Show, {
      get when() {
        return createMemo(() => !!props2.withAuth)() && !isAuthenticated();
      },
      get children() {
        const _el$4 = _tmpl$242.cloneNode(true), _el$5 = _el$4.firstChild, _el$6 = _el$5.firstChild, _el$7 = _el$5.nextSibling, _el$8 = _el$7.firstChild;
        addEventListener(_el$6, "click", authSession.login(), true);
        insert(_el$6, () => _4("Login"));
        addEventListener(_el$8, "click", authSession.signup(), true);
        insert(_el$8, () => _4("Signup"));
        return _el$4;
      }
    }), null);
    return _el$;
  })();
}
delegateEvents(["click"]);

// public/app/ui/base/forms/fields/helper.tsx
function splitFieldProps(props2, ...args) {
  return splitProps(props2, ["name", "validate", "transform", "keepActive", "keepState", "of"], ...args);
}

// public/app/ui/base/forms/fields/form-field.tsx
var _tmpl$106 = /* @__PURE__ */ template(`<div class="form-group"></div>`, 2);
function FormField(props2) {
  const [fieldData, local, others] = splitFieldProps(props2, ["children", "of", "info"]);
  return createComponent(Field, mergeProps(() => mergeProps({
    of: local.of
  }, fieldData), {
    children: (field2, inputProps) => (() => {
      const _el$ = _tmpl$106.cloneNode(true);
      spread(_el$, others, false, true);
      insert(_el$, () => local.children(field2, inputProps), null);
      insert(_el$, createComponent(Show, {
        get when() {
          return local.info;
        },
        get children() {
          return local.info;
        }
      }), null);
      return _el$;
    })()
  }));
}

// public/app/ui/base/forms/fields/labelled-field.tsx
function LabelledFormField(props2) {
  const [field2, local, others] = splitFieldProps(props2, ["children", "label", "labelClass"]);
  return createComponent(FormField, mergeProps(() => mergeProps(field2, others), {
    children: (field3, inputProps) => {
      return [createComponent(InputLabel, {
        get ["class"]() {
          return local.labelClass;
        },
        get ["for"]() {
          return props2.name;
        },
        get children() {
          return local.label;
        }
      }), createMemo(() => local.children(field3, inputProps))];
    }
  }));
}

// public/app/ui/base/forms/form.tsx
function createForm2(options2) {
  const [form, {
    Form: Form3,
    Field: Field3
  }] = createForm(options2);
  return [form, {
    Form: Form3,
    FormField: (props2) => FormField(mergeProps({
      of: form
    }, props2)),
    LabelledFormField: (props2) => LabelledFormField(mergeProps({
      of: form
    }, props2)),
    TextField: (props2) => {
      const [field2, input, others] = splitFieldProps(props2, ["required", "disabled", "onValue", "type"]);
      return createComponent(LabelledFormField, mergeProps(() => mergeProps({
        of: form
      }, field2, others), {
        children: (field3, inputProps) => createComponent(TextInput, mergeProps({
          get value() {
            return field3.value;
          },
          get classList() {
            return {
              "ng-dirty": field3.touched,
              "ng-invalid": !!field3.error
            };
          }
        }, () => mergeProps(inputProps, input)))
      }));
    },
    TextAreaField: (props2) => {
      const [field2, input, others] = splitFieldProps(props2, ["required", "disabled"]);
      return createComponent(LabelledFormField, mergeProps(() => mergeProps({
        of: form
      }, field2, others), {
        children: (field3, inputProps) => createComponent(TextAreaInput, mergeProps({
          get value() {
            return field3.value;
          },
          get required() {
            return input.required;
          },
          get disabled() {
            return input.disabled;
          },
          get classList() {
            return {
              "ng-dirty": !!field3.touched,
              "ng-invalid": !!field3.error
            };
          }
        }, inputProps))
      }));
    },
    CheckField: (props2) => {
      const [field2, input, others] = splitFieldProps(props2, ["label", "checked", "labelClass", "containerClass"]);
      return createComponent(Field3, mergeProps(() => mergeProps({
        of: form
      }, field2), {
        children: (f3, inputProps) => createComponent(CheckInput, mergeProps(() => mergeProps(input, others, inputProps), {
          get classList() {
            return {
              "ng-dirty": f3.touched,
              "ng-invalid": !!f3.error
            };
          }
        }))
      }));
    }
  }];
}

// public/app/ui/base/forms/select.jsx
var _tmpl$107 = /* @__PURE__ */ template(`<option></option>`, 2);
var _tmpl$243 = /* @__PURE__ */ template(`<select class="form-select"></select>`, 2);
var _tmpl$328 = /* @__PURE__ */ template(`<div><select class="form-select"></select></div>`, 4);
function SelectInput2(props2) {
  props2 = mergeProps({
    withDefault: false,
    disabled: false
  }, props2);
  const [local, others] = splitProps(props2, ["name", "label", "options", "selected", "selectClass", "labelClass", "withDefault"]);
  return (() => {
    const _el$ = _tmpl$243.cloneNode(true);
    spread(_el$, mergeProps({
      get classList() {
        return {
          [local.selectClass]: local.selectClass
        };
      },
      get name() {
        return local.name;
      },
      get id() {
        return local.name;
      }
    }, others), false, true);
    insert(_el$, createComponent(Show, {
      get when() {
        return local.withDefault;
      },
      get children() {
        const _el$2 = _tmpl$107.cloneNode(true);
        _el$2.value = null;
        insert(_el$2, () => _4("Default"));
        return _el$2;
      }
    }), null);
    insert(_el$, createComponent(For, {
      get each() {
        return local.options;
      },
      children: (item) => (() => {
        const _el$3 = _tmpl$107.cloneNode(true);
        insert(_el$3, (() => {
          const _c$ = createMemo(() => !!item.label);
          return () => _c$() ? typeof item.label === "string" ? item.label : item.label.fn : item.title?.toString();
        })());
        createRenderEffect(() => _el$3.selected = local.selected === item.value);
        createRenderEffect(() => _el$3.value = item.value);
        return _el$3;
      })()
    }), null);
    return _el$;
  })();
}
function SelectField2(props2) {
  props2 = mergeProps({
    withMargin: true,
    withDefault: false,
    disabled: false
  }, props2);
  const [local, others] = splitProps(props2, ["name", "label", "options", "selected", "selectClass", "labelClass", "containerClass", "withMargin", "withDefault"]);
  return (() => {
    const _el$4 = _tmpl$328.cloneNode(true), _el$5 = _el$4.firstChild;
    insert(_el$4, createComponent(Show, {
      get when() {
        return local.label;
      },
      get children() {
        return createComponent(InputLabel, {
          get ["for"]() {
            return local.name;
          },
          "class": "form-label",
          get classList() {
            return {
              [local.labelClass]: local.labelClass
            };
          },
          get children() {
            return local.label;
          }
        });
      }
    }), _el$5);
    spread(_el$5, mergeProps({
      get classList() {
        return {
          [local.selectClass]: local.selectClass
        };
      },
      get name() {
        return local.name;
      },
      get id() {
        return local.name;
      }
    }, others), false, true);
    insert(_el$5, createComponent(Show, {
      get when() {
        return local.withDefault;
      },
      get children() {
        const _el$6 = _tmpl$107.cloneNode(true);
        _el$6.value = null;
        insert(_el$6, () => _4("Default"));
        return _el$6;
      }
    }), null);
    insert(_el$5, createComponent(For, {
      get each() {
        return local.options;
      },
      children: (item) => (() => {
        const _el$7 = _tmpl$107.cloneNode(true);
        insert(_el$7, () => typeof item.label === "string" ? item.label : item.label.fn);
        createRenderEffect(() => _el$7.selected = local.selected === item.value);
        createRenderEffect(() => _el$7.value = item.value);
        return _el$7;
      })()
    }), null);
    createRenderEffect((_$p) => classList(_el$4, {
      "form-group": local.withMargin,
      [local.containerClass]: local.containerClass
    }, _$p));
    return _el$4;
  })();
}

// public/app/ui/base/widgets/MemberList.tsx
var _tmpl$108 = /* @__PURE__ */ template(`<div class="btn-group"></div>`, 2);
var _tmpl$244 = /* @__PURE__ */ template(`<div class="controls"></div>`, 2);
var _tmpl$329 = /* @__PURE__ */ template(`<div class="role"></div>`, 2);
var _tmpl$418 = /* @__PURE__ */ template(`<div></div>`, 2);
var _tmpl$515 = /* @__PURE__ */ template(`<div class="members-table-header"><div></div><div class="name"></div></div>`, 6);
var _tmpl$614 = /* @__PURE__ */ template(`<div class="member-list"><div class="members"></div></div>`, 4);
var _tmpl$713 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$811 = /* @__PURE__ */ template(`<a></a>`, 2);
var _tmpl$910 = /* @__PURE__ */ template(`<small>@</small>`, 2);
var _tmpl$109 = /* @__PURE__ */ template(`<span class="badge user-badge badge-yellow"></span>`, 2);
var _tmpl$113 = /* @__PURE__ */ template(`<span class="badge user-badge badge-yellow">L</span>`, 2);
var _tmpl$122 = /* @__PURE__ */ template(`<span class="badge user-badge badge-blue">A</span>`, 2);
var _tmpl$132 = /* @__PURE__ */ template(`<span class="badges"></span>`, 2);
var _tmpl$142 = /* @__PURE__ */ template(`<div class="teams"></div>`, 2);
var _tmpl$152 = /* @__PURE__ */ template(`<div class="actions"></div>`, 2);
var _tmpl$162 = /* @__PURE__ */ template(`<div class="member-list-item"><div class="avatar-container"></div><div class="name-container"><div class="name"></div></div></div>`, 8);
function MemberList(props2) {
  props2 = mergeProps({
    members: [],
    roles: [],
    defaultViewMode: "table",
    filter: "",
    showHeader: true,
    canEditRoles: true
  }, props2);
  const [viewMode, setViewMode] = createSignal(props2.defaultViewMode);
  const [filter4, setFilter] = createSignal(props2.filter);
  const membersHaveTeams = createMemo(() => props2.members.some((m3) => m3.teams?.length));
  const membersHaveInvites = createMemo(() => props2.members.some((m3) => !m3.user));
  const matchFilter = (member) => {
    if (!member.user) {
      return member.email.toLowerCase().indexOf(filter4().toLowerCase()) !== -1;
    }
    return member.user.username.toLowerCase().indexOf(filter4().toLowerCase()) !== -1 || (member.user.display_name || "").toLowerCase().indexOf(filter4().toLowerCase()) !== -1;
  };
  return (() => {
    const _el$ = _tmpl$614.cloneNode(true), _el$4 = _el$.firstChild;
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.filterable || props2.showViewModeSwitcher;
      },
      get children() {
        const _el$2 = _tmpl$244.cloneNode(true);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props2.showInvite;
          },
          get children() {
            return createComponent(Button, {
              "class": "btn-ghost me-2",
              onClick: () => props2.onInvite(),
              get children() {
                return [createComponent(Icon, {
                  name: "fa-user-plus"
                }), " ", createMemo(() => _4("Invite new members"))];
              }
            });
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props2.filterable && props2.members.length > 1;
          },
          get children() {
            return createComponent(TextInput, {
              type: "text",
              "class": "form-control",
              get placeholder() {
                return _4("Filter members");
              },
              get value() {
                return filter4();
              },
              onInput: (e3) => setFilter(e3.target.value)
            });
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props2.showViewModeSwitcher;
          },
          get children() {
            const _el$3 = _tmpl$108.cloneNode(true);
            insert(_el$3, createComponent(IconButton, {
              get ["class"]() {
                return `${viewMode() === "table" ? "active" : null}`;
              },
              onClick: () => setViewMode("table"),
              icon: "bi-ul-list"
            }), null);
            insert(_el$3, createComponent(IconButton, {
              get ["class"]() {
                return `${viewMode() === "cards" ? "active" : null}`;
              },
              onClick: () => setViewMode("cards"),
              icon: "bi-person-badge"
            }), null);
            insert(_el$3, createComponent(IconButton, {
              get ["class"]() {
                return `${viewMode() === "tiles" ? "active" : null}`;
              },
              onClick: () => setViewMode("tiles"),
              icon: "bi-person-vcard-fill"
            }), null);
            return _el$3;
          }
        }), null);
        return _el$2;
      }
    }), _el$4);
    insert(_el$4, createComponent(Show, {
      get when() {
        return viewMode() === "table" && props2.showHeader;
      },
      get children() {
        const _el$5 = _tmpl$515.cloneNode(true), _el$6 = _el$5.firstChild, _el$7 = _el$6.nextSibling;
        insert(_el$7, () => _4("Name"));
        insert(_el$5, createComponent(Show, {
          get when() {
            return props2.canEditRoles && props2.roles && props2.roles.length;
          },
          get children() {
            const _el$8 = _tmpl$329.cloneNode(true);
            insert(_el$8, () => _4("Role"));
            return _el$8;
          }
        }), null);
        insert(_el$5, createComponent(Show, {
          get when() {
            return membersHaveTeams();
          },
          get children() {
            const _el$9 = _tmpl$418.cloneNode(true);
            insert(_el$9, () => _4("Teams"));
            return _el$9;
          }
        }), null);
        insert(_el$5, createComponent(Show, {
          get when() {
            return createMemo(() => !!props2.editable)() && (membersHaveInvites() || props2.showRemove);
          },
          get children() {
            return _tmpl$418.cloneNode(true);
          }
        }), null);
        return _el$5;
      }
    }), null);
    insert(_el$4, createComponent(For, {
      get each() {
        return props2.members;
      },
      children: (member) => createComponent(Show, {
        get when() {
          return !props2.filterable || !filter4() || matchFilter(member);
        },
        get children() {
          return createComponent(MemberListItem, {
            member,
            get roles() {
              return props2.roles;
            },
            get isUserConnected() {
              return props2.presenceManager?.isUserConnected(member.user);
            },
            get editable() {
              return props2.editable;
            },
            get showRemove() {
              return props2.showRemove;
            },
            get showPresence() {
              return props2.showPresence;
            },
            get onRemove() {
              return props2.onRemove;
            },
            get onRoleChange() {
              return props2.onRoleChange;
            },
            get onResendInvite() {
              return props2.onResendInvite;
            },
            get canEditRoles() {
              return props2.canEditRoles;
            }
          });
        }
      })
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = !!(viewMode() === "cards"), _v$2 = !!(viewMode() === "table"), _v$3 = !!(viewMode() === "tiles");
      _v$ !== _p$._v$ && _el$4.classList.toggle("cards-view", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$4.classList.toggle("table-view", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$4.classList.toggle("tiles-view", _p$._v$3 = _v$3);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0
    });
    return _el$;
  })();
}
function MemberListItem(props2) {
  props2 = mergeProps({
    canEditRoles: true
  }, props2);
  const unlicensedTooltip = _4("User with Limited Access to Kantree. Can only be invited as observer in workspaces. Can't be assigned");
  const orgAdminTooltip = _4("Admin of this organisation. Automatically admin of the project");
  const teamAdminTooltip = _4("Admin of this team. Automatically admin of the project");
  const roleMenu = createMemo(() => ({
    config: props2.roles.map((role) => ({
      label: role.name,
      small: role.description,
      action: () => props2.onRoleChange(props2.member, role.id)
    }))
  }));
  const roleEditable = createMemo(() => {
    return props2.editable && !props2.member.is_unlicensed && !props2.member.is_org_admin && !props2.member.is_team_admin;
  });
  const roleName = createMemo(() => {
    if (props2.member.is_unlicensed) {
      return _4("Observer");
    }
    if (props2.member.is_org_admin || props2.member.is_team_admin) {
      return _4("Admin");
    }
    if (props2.member.role) {
      return props2.roles?.find((r3) => r3.id === props2.member.role?.id)?.name ?? _4("None");
    }
    return props2.roles?.find((role) => role.id === props2.member.permission)?.name || _4("None");
  });
  const roleTooltip = createMemo(() => {
    if (props2.member.is_unlicensed) {
      return unlicensedTooltip;
    }
    if (props2.member.is_org_admin) {
      return orgAdminTooltip;
    }
    if (props2.member.is_team_admin) {
      return teamAdminTooltip;
    }
  });
  const hasBadges = createMemo(() => {
    return props2.member.user && props2.member.user.is_from_approved_domain === false || props2.member.is_unlicensed || props2.member.is_org_admin || props2.member.is_team_admin;
  });
  async function removeMember(member) {
    await confirmDeleteDialog2();
    props2.onRemove(member);
  }
  function getTeamColor(teamId) {
    const team = teamStore.tryGet(teamId);
    return team ? team.color : null;
  }
  const displayName = createMemo(() => {
    if (!props2.member.user) {
      return "";
    }
    return props2.member.user.display_name.length > 50 ? `${props2.member.user.display_name.slice(0, 50)}...` : props2.member.user.display_name;
  });
  const userName = createMemo(() => {
    if (!props2.member.user) {
      return "";
    }
    return props2.member.user.username.length > 50 ? `${props2.member.user.username.slice(0, 50)}...` : props2.member.user.username;
  });
  return (() => {
    const _el$11 = _tmpl$162.cloneNode(true), _el$12 = _el$11.firstChild, _el$13 = _el$12.nextSibling, _el$14 = _el$13.firstChild;
    insert(_el$12, createComponent(UserAvatar, {
      get user() {
        return props2.member.user;
      }
    }));
    insert(_el$14, createComponent(Show, {
      get when() {
        return !currentUser2.is_kantree_admin && props2.member.user;
      },
      get children() {
        const _el$15 = _tmpl$713.cloneNode(true);
        insert(_el$15, () => props2.member.user.display_name);
        return _el$15;
      }
    }), null);
    insert(_el$14, createComponent(Show, {
      get when() {
        return currentUser2.is_kantree_admin && props2.member.user;
      },
      get children() {
        const _el$16 = _tmpl$811.cloneNode(true);
        insert(_el$16, displayName);
        createRenderEffect(() => setAttribute(_el$16, "href", `admin#users/${props2.member.user.id}`));
        return _el$16;
      }
    }), null);
    insert(_el$14, createComponent(Show, {
      get when() {
        return !props2.member.user;
      },
      get children() {
        const _el$17 = _tmpl$713.cloneNode(true);
        insert(_el$17, () => props2.member.email);
        return _el$17;
      }
    }), null);
    insert(_el$14, createComponent(Show, {
      get when() {
        return props2.member.user && props2.member.user.username != props2.member.user.display_name;
      },
      get children() {
        const _el$18 = _tmpl$910.cloneNode(true), _el$19 = _el$18.firstChild;
        insert(_el$18, userName, null);
        return _el$18;
      }
    }), null);
    insert(_el$14, createComponent(Show, {
      get when() {
        return hasBadges();
      },
      get children() {
        const _el$20 = _tmpl$132.cloneNode(true);
        insert(_el$20, createComponent(Show, {
          get when() {
            return props2.member.user && props2.member.user.is_from_approved_domain === false;
          },
          get children() {
            return createComponent(Tooltip, {
              get label() {
                return _4("This user is not from an officially approved domain");
              },
              get children() {
                const _el$21 = _tmpl$109.cloneNode(true);
                insert(_el$21, createComponent(Icon, {
                  name: "bi-globe"
                }));
                return _el$21;
              }
            });
          }
        }), null);
        insert(_el$20, createComponent(Show, {
          get when() {
            return props2.member.is_unlicensed;
          },
          get children() {
            return createComponent(Tooltip, {
              label: unlicensedTooltip,
              get children() {
                return _tmpl$113.cloneNode(true);
              }
            });
          }
        }), null);
        insert(_el$20, createComponent(Show, {
          get when() {
            return props2.member.is_org_admin || props2.member.is_team_admin;
          },
          get children() {
            return createComponent(Tooltip, {
              get label() {
                return props2.member.is_org_admin ? orgAdminTooltip : teamAdminTooltip;
              },
              get children() {
                return _tmpl$122.cloneNode(true);
              }
            });
          }
        }), null);
        return _el$20;
      }
    }), null);
    insert(_el$11, createComponent(Show, {
      get when() {
        return props2.canEditRoles;
      },
      get children() {
        const _el$24 = _tmpl$329.cloneNode(true);
        insert(_el$24, createComponent(Show, {
          get when() {
            return !roleEditable();
          },
          get children() {
            const _el$25 = _tmpl$713.cloneNode(true);
            insert(_el$25, roleName, null);
            insert(_el$25, createComponent(Show, {
              get when() {
                return roleTooltip();
              },
              get children() {
                return createComponent(Tooltip, {
                  get label() {
                    return roleTooltip();
                  },
                  get children() {
                    return createComponent(Icon, {
                      name: "fa-question-circle"
                    });
                  }
                });
              }
            }), null);
            return _el$25;
          }
        }), null);
        insert(_el$24, createComponent(Show, {
          get when() {
            return roleEditable();
          },
          get children() {
            return createComponent(NgComponent, {
              directive: "member-tile-change-role-button",
              get menu() {
                return roleMenu();
              },
              get name() {
                return roleName();
              }
            });
          }
        }), null);
        return _el$24;
      }
    }), null);
    insert(_el$11, createComponent(Show, {
      get when() {
        return props2.member.teams?.length;
      },
      get children() {
        const _el$26 = _tmpl$142.cloneNode(true);
        insert(_el$26, createComponent(For, {
          get each() {
            return props2.member.teams;
          },
          children: (team) => createComponent(Tooltip, {
            get label() {
              return team.name;
            },
            get children() {
              return createComponent(ColorizeElement, {
                get bgColor() {
                  return getTeamColor(team.id);
                },
                get children() {
                  const _el$28 = _tmpl$713.cloneNode(true);
                  insert(_el$28, () => team.name.substring(0, 2));
                  return _el$28;
                }
              });
            }
          })
        }));
        return _el$26;
      }
    }), null);
    insert(_el$11, createComponent(Show, {
      get when() {
        return props2.editable && (!props2.member.user || props2.showRemove);
      },
      get children() {
        const _el$27 = _tmpl$152.cloneNode(true);
        insert(_el$27, createComponent(Show, {
          get when() {
            return !props2.member.user;
          },
          get children() {
            return createComponent(Tooltip, {
              get label() {
                return _4("Resend invite email");
              },
              get children() {
                return createComponent(IconButton, {
                  "class": "btn-text",
                  icon: "bi-send-fill",
                  onClick: () => props2.onResendInvite(props2.member)
                });
              }
            });
          }
        }), null);
        insert(_el$27, createComponent(Show, {
          get when() {
            return props2.showRemove;
          },
          get children() {
            return createComponent(Tooltip, {
              get label() {
                return createMemo(() => !!props2.member.user)() ? _4("Remove this member") : _4("Remove this invite");
              },
              get children() {
                return createComponent(IconButton, {
                  "class": "btn-danger btn-text",
                  icon: "bi-person-fill-dash",
                  onClick: () => removeMember(props2.member)
                });
              }
            });
          }
        }), null);
        return _el$27;
      }
    }), null);
    return _el$11;
  })();
}

// public/app/ui/base/widgets/TinyCalendar.tsx
var _tmpl$110 = /* @__PURE__ */ template(`<div class="header"><button type="button" class="btn btn-icon btn-text"><i class="fa fa-angle-left"></i></button><span></span><button type="button" class="btn btn-icon btn-text"><i class="fa fa-angle-right"></i></button></div>`, 12);
var _tmpl$245 = /* @__PURE__ */ template(`<div class="week names"></div>`, 2);
var _tmpl$330 = /* @__PURE__ */ template(`<button type="button" class="btn btn-icon btn-text"><i class="fa fa-rss"></i></button>`, 4);
var _tmpl$419 = /* @__PURE__ */ template(`<i class="fa fa-spin fa-spinner"></i>`, 2);
var _tmpl$516 = /* @__PURE__ */ template(`<div class="day"></div>`, 2);
var _tmpl$615 = /* @__PURE__ */ template(`<div class="week"></div>`, 2);
var _tmpl$714 = /* @__PURE__ */ template(`<div class="day"><div class="number"></div></div>`, 4);
var _tmpl$812 = /* @__PURE__ */ template(`<span class="dot"></span>`, 2);
function TinyCalendar(props2) {
  const [month, setMonth] = createSignal(moment_default());
  const [weeks, setWeeks] = createSignal([]);
  let dayLabels = [];
  let weekdays = moment_default.weekdaysShort();
  let d3 = getFirstDayOfWeek();
  while (dayLabels.length < 7) {
    dayLabels.push(weekdays[d3]);
    if (++d3 > 6) {
      d3 = 0;
    }
  }
  const [cards, {
    mutate: mutateCards,
    refetch: refetchCards
  }] = createResource(() => new Promise((resolve2) => {
    let localCards = {};
    props2.onMonthChanged(month().clone().date(1).format("YYYY-MM-DD"), month().clone().add(1, "months").date(0).format("YYYY-MM-DD"), (cards2) => {
      for (const card of cards2) {
        for (const attr of card.attributes.filter((attr2) => !!attr2.value && (attr2.type === "date" || attributeTypeRegistry.get(attr2.type)?.computed))) {
          const modelAttr = attributeTypeRegistry.get(attr.type);
          const {
            end: d4
          } = parseDateFromComputedAttribute(modelAttr, attr) || {};
          if (!d4 || !d4.isSame(this.month, "month")) {
            return;
          }
          let n4 = d4.date();
          if (typeof localCards[n4] === "undefined") {
            localCards[n4] = [];
          }
          if (localCards[n4].indexOf(card) === -1) {
            localCards[n4].push(card);
          }
        }
      }
      resolve2(localCards);
    });
  }), {
    initialValue: {}
  });
  const buildWeek = (date, month2) => {
    const days = [];
    for (let i3 = 0; i3 < 7; i3++) {
      days.push({
        name: date.format("dd").substring(0, 1),
        number: date.date(),
        isCurrentMonth: date.month() === month2.month(),
        isToday: date.isSame(/* @__PURE__ */ new Date(), "day"),
        date
      });
      date = date.clone();
      date.add(1, "d");
    }
    return days;
  };
  const buildMonth = (start, month2) => {
    const localWeeks = [];
    let done = false, date = start.clone(), monthIndex = date.month(), count = 0;
    while (!done) {
      localWeeks.push({
        days: buildWeek(date.clone(), month2)
      });
      date.add(1, "week");
      done = count++ > 2 && monthIndex !== date.month();
      monthIndex = date.month();
    }
    return localWeeks;
  };
  const move = (delta) => {
    mutateCards({});
    setMonth(month().clone().add(delta, "months"));
    const monthStart = month().date(1);
    let start = monthStart.clone().day(getFirstDayOfWeek());
    if (start.isAfter(monthStart)) {
      start = start.subtract(1, "week");
    }
    setWeeks(buildMonth(start, month()));
    refetchCards();
  };
  move(0);
  return [(() => {
    const _el$ = _tmpl$110.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling, _el$4 = _el$3.nextSibling;
    _el$2.$$click = () => move(-1);
    insert(_el$3, () => month().format("MMMM, YYYY"), null);
    insert(_el$3, (() => {
      const _c$ = createMemo(() => !!props2.onFeedClick);
      return () => _c$() && createComponent(Show, {
        get when() {
          return !cards.loading;
        },
        get fallback() {
          return _tmpl$419.cloneNode(true);
        },
        get children() {
          const _el$6 = _tmpl$330.cloneNode(true);
          _el$6.$$click = () => props2.onFeedClick();
          return _el$6;
        }
      });
    })(), null);
    _el$4.$$click = () => move(1);
    return _el$;
  })(), (() => {
    const _el$5 = _tmpl$245.cloneNode(true);
    insert(_el$5, createComponent(Index, {
      each: dayLabels,
      children: (lbl) => (() => {
        const _el$8 = _tmpl$516.cloneNode(true);
        insert(_el$8, lbl);
        return _el$8;
      })()
    }));
    return _el$5;
  })(), createComponent(For, {
    get each() {
      return weeks();
    },
    children: (week) => (() => {
      const _el$9 = _tmpl$615.cloneNode(true);
      insert(_el$9, createComponent(For, {
        get each() {
          return week.days;
        },
        children: (day) => (() => {
          const _el$10 = _tmpl$714.cloneNode(true), _el$11 = _el$10.firstChild;
          _el$10.$$click = () => props2.onSelect(day);
          insert(_el$11, () => day.number);
          insert(_el$10, (() => {
            const _c$2 = createMemo(() => !!(day.isCurrentMonth && cards != void 0 && cards()[day.number]));
            return () => _c$2() && createComponent(Index, {
              get each() {
                return cards()[day.number].slice(0, 5);
              },
              children: (c3) => _tmpl$812.cloneNode(true)
            });
          })(), null);
          createRenderEffect((_p$) => {
            const _v$ = !!day.isToday, _v$2 = !day.isCurrentMonth;
            _v$ !== _p$._v$ && _el$10.classList.toggle("today", _p$._v$ = _v$);
            _v$2 !== _p$._v$2 && _el$10.classList.toggle("different-month", _p$._v$2 = _v$2);
            return _p$;
          }, {
            _v$: void 0,
            _v$2: void 0
          });
          return _el$10;
        })()
      }));
      return _el$9;
    })()
  })];
}
delegateEvents(["click"]);

// public/app/ui/system/banners.jsx
var _tmpl$111 = /* @__PURE__ */ template(`<button type="button" class="btn btn-icon btn-close"></button>`, 2);
var _tmpl$246 = /* @__PURE__ */ template(`<div class="system-top-banner"><span class="content"></span></div>`, 4);
var [banners, setBanners] = createStore([]);
function showBanner(banner, props2) {
  const id = uuid4();
  let promise = new Promise((resolve2) => {
    setBanners((prev) => [...prev, {
      id,
      banner,
      props: {
        ...props2,
        onClose: resolve2
      }
    }]);
  });
  return {
    promise,
    close: () => setBanners((prev) => prev.filter((i3) => i3.id !== id))
  };
}
function SystemBannerContainer() {
  function onClose(id, callback) {
    setBanners((prev) => prev.filter((info) => info.id !== id));
    callback && callback();
  }
  return createComponent(For, {
    each: banners,
    children: (info) => {
      const [local, others] = splitProps(info.props, ["onClose"]);
      return createComponent(info.banner, mergeProps(others, {
        onClose: () => onClose(info.id, local.onClose)
      }));
    }
  });
}
function SystemBanner(props2) {
  return (() => {
    const _el$ = _tmpl$246.cloneNode(true), _el$2 = _el$.firstChild;
    const _ref$ = props2.ref;
    typeof _ref$ === "function" ? use(_ref$, _el$) : props2.ref = _el$;
    insert(_el$2, () => props2.children);
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.onClose;
      },
      get children() {
        const _el$3 = _tmpl$111.cloneNode(true);
        addEventListener(_el$3, "click", props2.onClose, true);
        return _el$3;
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = props2.color, _v$2 = textColor(props2.color);
      _v$ !== _p$._v$ && _el$.style.setProperty("background-color", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$.style.setProperty("color", _p$._v$2 = _v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$;
  })();
}
delegateEvents(["click"]);

// virtual-ns:compare-versions
var compare_versions_default = compareVersions;

// public/app/config/release-announcements.js
var releaseAnnouncements = [
  // {
  //   version: '7.0.0',
  //   modal: ['en', 'fr'],
  //   controller: 'KantreeReleaseCtrl7_0_0'
  // },
  // {
  //   version: '7.2.0',
  //   modal: ['en', 'fr']
  // },
  // {
  //   version: '8.12.0',
  //   modal: ['en', 'fr']
  // },
  // {
  //   version: '10.0.0',
  //   modal: ['en', 'fr']
  // },
  // {
  //   version: '10.2.0',
  //   message: _lazy("New refreshed interface and a much more powerful My Work area")
  // },
  // {
  //   version: '10.4.0',
  //   message: _lazy("Simplified cross workspace relations and new powerful no-code capabilities")
  // },
];

// public/app/services/release-announcements.js
var [unreadReleaseAnnouncements, setUnreadReleaseAnnouncements] = createStore([]);
async function fetchProductUpdates(limit = null) {
  try {
    const data2 = await api_default.config.get_changelog.get({ limit }, { ignoreErrorHandlers: true });
    return data2.versions || [];
  } catch (e3) {
    console.error("Failed to fetch product updates:", e3);
    return [];
  }
}
function checkUnreadReleaseAnnouncements() {
  setUnreadReleaseAnnouncements(releaseAnnouncements.filter((r3) => !isReleaseAnnouncementRead(r3.version)).sort((a3, b3) => compare_versions_default(a3.version, b3.version)));
}
function isReleaseAnnouncementRead(version) {
  const versionNumberRegexp = /^[0-9]+\.[0-9]+\.[0-9]+/;
  if (!version.match(versionNumberRegexp)) {
    return true;
  }
  let latestVersionRead = get(currentUser2.app_params, "release_notes_version_read");
  if (!latestVersionRead && (get(currentUser2.app_params, "latest_read_release_modal_date") || (currentUser2.onboarded || []).includes("project"))) {
    latestVersionRead = "7.0.0";
  } else if (!latestVersionRead) {
    return true;
  }
  if (!latestVersionRead.match(versionNumberRegexp)) {
    if (latestVersionRead.indexOf("-") !== -1) {
      latestVersionRead = latestVersionRead.split("-")[0];
    } else if (serverConfig.version.match(versionNumberRegexp)) {
      latestVersionRead = serverConfig.version;
    } else if (!serverConfig.version.match(versionNumberRegexp) && serverConfig.version.indexOf("-") !== -1) {
      latestVersionRead = serverConfig.version.split("-")[0];
    } else {
      console.log(`Release notes for ${version} are ignored as no version can be identified`);
      return true;
    }
  }
  return compare_versions_default(version, latestVersionRead) <= 0;
}
function markReleaseAnnouncementAsRead(version) {
  if (isReleaseAnnouncementRead(version)) return Promise.resolve();
  return api_default.user.mark_release_version_as_read.post({ version }, { ignoreErrorHandlers: true }).then(() => {
    setCurrentUser("app_params", "release_notes_version_read", version);
  }, () => Promise.resolve());
}

// public/app/ui/system/release-announcements.jsx
var _tmpl$114 = /* @__PURE__ */ template(`<a target="_blank" class="block"> <span class="btn"> </span></a>`, 4);
var _tmpl$247 = /* @__PURE__ */ template(`<span> </span>`, 2);
var ReleaseAnnouncement = class {
  constructor(release) {
    this.release = release;
    this.controller = null;
    this.onClosePromise = null;
    this.markAsReadOnClose = true;
    this.open();
  }
  open() {
    if (this.release.modal) {
      this.controller = $digest(["releaseAnnouncementModal", (releaseAnnouncementModal) => {
        return releaseAnnouncementModal.open(this.release);
      }]);
      this.onClosePromise = this.controller.result;
    } else {
      this.controller = showBanner(ReleaseAnnouncementBanner, {
        release: this.release
      });
      this.onClosePromise = this.controller.promise;
    }
    this.onClosePromise.then(() => {
      if (this.markAsReadOnClose) {
        markReleaseAnnouncementAsRead(this.release.version);
      }
    }).finally(() => {
      this.destroy();
    });
  }
  close(markAsReadOnClose = true) {
    this.markAsReadOnClose = markAsReadOnClose;
    this.controller.close();
  }
  destroy() {
    this.onClosePromise = null;
    this.controller = null;
    this.markAsReadOnClose = true;
  }
};
function showNextUnreadReleaseAnnouncement() {
  const unreadReleases = unreadReleaseAnnouncements.filter((r3) => !r3.manual);
  if (unreadReleases.length > 0) {
    showReleaseAnnouncement(unreadReleases[0]);
  }
}
function showReleaseAnnouncement(release) {
  return new ReleaseAnnouncement(release);
}
function ReleaseAnnouncementBanner(props2) {
  let message, ref;
  if (props2.release.message) {
    message = props2.release.message;
  } else {
    message = _4("Kantree has been updated to version {version}. Check out what's new!", {
      version: props2.release.version
    });
  }
  const externalLink = () => props2.release.externalLink ?? true;
  return createComponent(SystemBanner, {
    ref(r$) {
      const _ref$ = ref;
      typeof _ref$ === "function" ? _ref$(r$) : ref = r$;
    },
    style: "background-color: #6feda6; color: #062e17",
    get onClose() {
      return props2.onClose;
    },
    get children() {
      return [createComponent(Show, {
        get when() {
          return externalLink();
        },
        get children() {
          const _el$ = _tmpl$114.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling, _el$4 = _el$3.firstChild;
          addEventListener(_el$, "click", props2.onClose, true);
          insert(_el$, createComponent(Icon, {
            name: "bi-broadcast"
          }), _el$2);
          insert(_el$, () => message.toString(), _el$3);
          insert(_el$3, () => _4("Learn more"), _el$4);
          insert(_el$3, createComponent(Icon, {
            name: "bi-box-arrow-up-right",
            "class": "right"
          }), null);
          createRenderEffect(() => setAttribute(_el$, "href", `https://kantree.io/changelog/${getCurrentLocale()}/${props2.release.version}`));
          return _el$;
        }
      }), createComponent(Show, {
        get when() {
          return !externalLink();
        },
        get children() {
          const _el$5 = _tmpl$247.cloneNode(true), _el$6 = _el$5.firstChild;
          insert(_el$5, createComponent(Icon, {
            name: "bi-broadcast"
          }), _el$6);
          insert(_el$5, () => message.toString(), null);
          return _el$5;
        }
      })];
    }
  });
}
delegateEvents(["click"]);

// node_modules/@solidjs/router/dist/index.js
function createBeforeLeave() {
  let listeners = /* @__PURE__ */ new Set();
  function subscribe(listener) {
    listeners.add(listener);
    return () => listeners.delete(listener);
  }
  let ignore = false;
  function confirm(to, options2) {
    if (ignore) return !(ignore = false);
    const e3 = {
      to,
      options: options2,
      defaultPrevented: false,
      preventDefault: () => e3.defaultPrevented = true
    };
    for (const l3 of listeners) l3.listener({
      ...e3,
      from: l3.location,
      retry: (force) => {
        force && (ignore = true);
        l3.navigate(to, {
          ...options2,
          resolve: false
        });
      }
    });
    return !e3.defaultPrevented;
  }
  return {
    subscribe,
    confirm
  };
}
var depth;
function saveCurrentDepth() {
  if (!window.history.state || window.history.state._depth == null) {
    window.history.replaceState({
      ...window.history.state,
      _depth: window.history.length - 1
    }, "");
  }
  depth = window.history.state._depth;
}
if (!isServer) {
  saveCurrentDepth();
}
function keepDepth(state) {
  return {
    ...state,
    _depth: window.history.state && window.history.state._depth
  };
}
function notifyIfNotBlocked(notify2, block3) {
  let ignore = false;
  return () => {
    const prevDepth = depth;
    saveCurrentDepth();
    const delta = prevDepth == null ? null : depth - prevDepth;
    if (ignore) {
      ignore = false;
      return;
    }
    if (delta && block3(delta)) {
      ignore = true;
      window.history.go(-delta);
    } else {
      notify2();
    }
  };
}
var hasSchemeRegex = /^(?:[a-z0-9]+:)?\/\//i;
var trimPathRegex = /^\/+|(\/)\/+$/g;
var mockBase = "http://sr";
function normalizePath2(path, omitSlash = false) {
  const s3 = path.replace(trimPathRegex, "$1");
  return s3 ? omitSlash || /^[?#]/.test(s3) ? s3 : "/" + s3 : "";
}
function resolvePath(base3, path, from2) {
  if (hasSchemeRegex.test(path)) {
    return void 0;
  }
  const basePath = normalizePath2(base3);
  const fromPath = from2 && normalizePath2(from2);
  let result2 = "";
  if (!fromPath || path.startsWith("/")) {
    result2 = basePath;
  } else if (fromPath.toLowerCase().indexOf(basePath.toLowerCase()) !== 0) {
    result2 = basePath + fromPath;
  } else {
    result2 = fromPath;
  }
  return (result2 || "/") + normalizePath2(path, !result2);
}
function invariant2(value2, message) {
  if (value2 == null) {
    throw new Error(message);
  }
  return value2;
}
function joinPaths(from2, to) {
  return normalizePath2(from2).replace(/\/*(\*.*)?$/g, "") + normalizePath2(to);
}
function extractSearchParams(url2) {
  const params = {};
  url2.searchParams.forEach((value2, key2) => {
    params[key2] = value2;
  });
  return params;
}
function createMatcher(path, partial2, matchFilters) {
  const [pattern2, splat] = path.split("/*", 2);
  const segments = pattern2.split("/").filter(Boolean);
  const len = segments.length;
  return (location2) => {
    const locSegments = location2.split("/").filter(Boolean);
    const lenDiff = locSegments.length - len;
    if (lenDiff < 0 || lenDiff > 0 && splat === void 0 && !partial2) {
      return null;
    }
    const match2 = {
      path: len ? "" : "/",
      params: {}
    };
    const matchFilter = (s3) => matchFilters === void 0 ? void 0 : matchFilters[s3];
    for (let i3 = 0; i3 < len; i3++) {
      const segment = segments[i3];
      const locSegment = locSegments[i3];
      const dynamic = segment[0] === ":";
      const key2 = dynamic ? segment.slice(1) : segment;
      if (dynamic && matchSegment(locSegment, matchFilter(key2))) {
        match2.params[key2] = locSegment;
      } else if (dynamic || !matchSegment(locSegment, segment)) {
        return null;
      }
      match2.path += `/${locSegment}`;
    }
    if (splat) {
      const remainder = lenDiff ? locSegments.slice(-lenDiff).join("/") : "";
      if (matchSegment(remainder, matchFilter(splat))) {
        match2.params[splat] = remainder;
      } else {
        return null;
      }
    }
    return match2;
  };
}
function matchSegment(input, filter4) {
  const isEqual2 = (s3) => s3.localeCompare(input, void 0, {
    sensitivity: "base"
  }) === 0;
  if (filter4 === void 0) {
    return true;
  } else if (typeof filter4 === "string") {
    return isEqual2(filter4);
  } else if (typeof filter4 === "function") {
    return filter4(input);
  } else if (Array.isArray(filter4)) {
    return filter4.some(isEqual2);
  } else if (filter4 instanceof RegExp) {
    return filter4.test(input);
  }
  return false;
}
function scoreRoute(route) {
  const [pattern2, splat] = route.pattern.split("/*", 2);
  const segments = pattern2.split("/").filter(Boolean);
  return segments.reduce((score2, segment) => score2 + (segment.startsWith(":") ? 2 : 3), segments.length - (splat === void 0 ? 0 : 1));
}
function createMemoObject(fn) {
  const map5 = /* @__PURE__ */ new Map();
  const owner = getOwner();
  return new Proxy({}, {
    get(_5, property2) {
      if (!map5.has(property2)) {
        runWithOwner(owner, () => map5.set(property2, createMemo(() => fn()[property2])));
      }
      return map5.get(property2)();
    },
    getOwnPropertyDescriptor() {
      return {
        enumerable: true,
        configurable: true
      };
    },
    ownKeys() {
      return Reflect.ownKeys(fn());
    }
  });
}
function mergeSearchString(search, params) {
  const merged = new URLSearchParams(search);
  Object.entries(params).forEach(([key2, value2]) => {
    if (value2 == null || value2 === "") {
      merged.delete(key2);
    } else {
      merged.set(key2, String(value2));
    }
  });
  const s3 = merged.toString();
  return s3 ? `?${s3}` : "";
}
function expandOptionals(pattern2) {
  let match2 = /(\/?\:[^\/]+)\?/.exec(pattern2);
  if (!match2) return [pattern2];
  let prefix5 = pattern2.slice(0, match2.index);
  let suffix = pattern2.slice(match2.index + match2[0].length);
  const prefixes = [prefix5, prefix5 += match2[1]];
  while (match2 = /^(\/\:[^\/]+)\?/.exec(suffix)) {
    prefixes.push(prefix5 += match2[1]);
    suffix = suffix.slice(match2[0].length);
  }
  return expandOptionals(suffix).reduce((results2, expansion) => [...results2, ...prefixes.map((p4) => p4 + expansion)], []);
}
var MAX_REDIRECTS = 100;
var RouterContextObj = createContext();
var RouteContextObj = createContext();
var useRouter = () => invariant2(useContext(RouterContextObj), "<A> and 'use' router primitives can be only used inside a Route.");
var useRoute = () => useContext(RouteContextObj) || useRouter().base;
var useResolvedPath = (path) => {
  const route = useRoute();
  return createMemo(() => route.resolvePath(path()));
};
var useHref = (to) => {
  const router = useRouter();
  return createMemo(() => {
    const to_ = to();
    return to_ !== void 0 ? router.renderPath(to_) : to_;
  });
};
var useNavigate = () => useRouter().navigatorFactory();
var useLocation = () => useRouter().location;
var useMatch = (path, matchFilters) => {
  const location2 = useLocation();
  const matchers = createMemo(() => expandOptionals(path()).map((path2) => createMatcher(path2, void 0, matchFilters)));
  return createMemo(() => {
    for (const matcher2 of matchers()) {
      const match2 = matcher2(location2.pathname);
      if (match2) return match2;
    }
  });
};
var useParams = () => useRouter().params;
var useSearchParams = () => {
  const location2 = useLocation();
  const navigate2 = useNavigate();
  const setSearchParams = (params, options2) => {
    const searchString = untrack(() => location2.pathname + mergeSearchString(location2.search, params) + location2.hash);
    navigate2(searchString, {
      scroll: false,
      resolve: false,
      ...options2
    });
  };
  return [location2.query, setSearchParams];
};
var useBeforeLeave = (listener) => {
  const s3 = useRouter().beforeLeave.subscribe({
    listener,
    location: useLocation(),
    navigate: useNavigate()
  });
  onCleanup(s3);
};
function createRoutes(routeDef, base3 = "") {
  const {
    component,
    load: load2,
    children: children2,
    info
  } = routeDef;
  const isLeaf = !children2 || Array.isArray(children2) && !children2.length;
  const shared = {
    key: routeDef,
    component,
    load: load2,
    info
  };
  return asArray2(routeDef.path).reduce((acc, originalPath) => {
    for (const expandedPath of expandOptionals(originalPath)) {
      const path = joinPaths(base3, expandedPath);
      let pattern2 = isLeaf ? path : path.split("/*", 1)[0];
      pattern2 = pattern2.split("/").map((s3) => {
        return s3.startsWith(":") || s3.startsWith("*") ? s3 : encodeURIComponent(s3);
      }).join("/");
      acc.push({
        ...shared,
        originalPath,
        pattern: pattern2,
        matcher: createMatcher(pattern2, !isLeaf, routeDef.matchFilters)
      });
    }
    return acc;
  }, []);
}
function createBranch(routes2, index2 = 0) {
  return {
    routes: routes2,
    score: scoreRoute(routes2[routes2.length - 1]) * 1e4 - index2,
    matcher(location2) {
      const matches3 = [];
      for (let i3 = routes2.length - 1; i3 >= 0; i3--) {
        const route = routes2[i3];
        const match2 = route.matcher(location2);
        if (!match2) {
          return null;
        }
        matches3.unshift({
          ...match2,
          route
        });
      }
      return matches3;
    }
  };
}
function asArray2(value2) {
  return Array.isArray(value2) ? value2 : [value2];
}
function createBranches(routeDef, base3 = "", stack = [], branches = []) {
  const routeDefs = asArray2(routeDef);
  for (let i3 = 0, len = routeDefs.length; i3 < len; i3++) {
    const def = routeDefs[i3];
    if (def && typeof def === "object") {
      if (!def.hasOwnProperty("path")) def.path = "";
      const routes2 = createRoutes(def, base3);
      for (const route of routes2) {
        stack.push(route);
        const isEmptyArray = Array.isArray(def.children) && def.children.length === 0;
        if (def.children && !isEmptyArray) {
          createBranches(def.children, route.pattern, stack, branches);
        } else {
          const branch = createBranch([...stack], branches.length);
          branches.push(branch);
        }
        stack.pop();
      }
    }
  }
  return stack.length ? branches : branches.sort((a3, b3) => b3.score - a3.score);
}
function getRouteMatches(branches, location2) {
  for (let i3 = 0, len = branches.length; i3 < len; i3++) {
    const match2 = branches[i3].matcher(location2);
    if (match2) {
      return match2;
    }
  }
  return [];
}
function createLocation(path, state) {
  const origin = new URL(mockBase);
  const url2 = createMemo((prev) => {
    const path_ = path();
    try {
      return new URL(path_, origin);
    } catch (err) {
      console.error(`Invalid path ${path_}`);
      return prev;
    }
  }, origin, {
    equals: (a3, b3) => a3.href === b3.href
  });
  const pathname = createMemo(() => url2().pathname);
  const search = createMemo(() => url2().search, true);
  const hash = createMemo(() => url2().hash);
  const key2 = () => "";
  return {
    get pathname() {
      return pathname();
    },
    get search() {
      return search();
    },
    get hash() {
      return hash();
    },
    get state() {
      return state();
    },
    get key() {
      return key2();
    },
    query: createMemoObject(on(search, () => extractSearchParams(url2())))
  };
}
var intent;
function getIntent() {
  return intent;
}
var inLoadFn = false;
function getInLoadFn() {
  return inLoadFn;
}
function setInLoadFn(value2) {
  inLoadFn = value2;
}
function createRouterContext(integration, branches, getContext, options2 = {}) {
  const {
    signal: [source, setSource],
    utils = {}
  } = integration;
  const parsePath = utils.parsePath || ((p4) => p4);
  const renderPath = utils.renderPath || ((p4) => p4);
  const beforeLeave = utils.beforeLeave || createBeforeLeave();
  const basePath = resolvePath("", options2.base || "");
  if (basePath === void 0) {
    throw new Error(`${basePath} is not a valid base path`);
  } else if (basePath && !source().value) {
    setSource({
      value: basePath,
      replace: true,
      scroll: false
    });
  }
  const [isRouting, setIsRouting] = createSignal(false);
  const start = async (callback) => {
    setIsRouting(true);
    try {
      await startTransition(callback);
    } finally {
      setIsRouting(false);
    }
  };
  const [reference2, setReference] = createSignal(source().value);
  const [state, setState] = createSignal(source().state);
  const location2 = createLocation(reference2, state);
  const referrers = [];
  const submissions = createSignal(isServer ? initFromFlash() : []);
  const matches3 = createMemo(() => {
    if (typeof options2.transformUrl === "function") {
      return getRouteMatches(branches(), options2.transformUrl(location2.pathname));
    }
    return getRouteMatches(branches(), location2.pathname);
  });
  const params = createMemoObject(() => {
    const m3 = matches3();
    const params2 = {};
    for (let i3 = 0; i3 < m3.length; i3++) {
      Object.assign(params2, m3[i3].params);
    }
    return params2;
  });
  const baseRoute = {
    pattern: basePath,
    path: () => basePath,
    outlet: () => null,
    resolvePath(to) {
      return resolvePath(basePath, to);
    }
  };
  createRenderEffect(() => {
    const {
      value: value2,
      state: state2
    } = source();
    untrack(() => {
      start(() => {
        intent = "native";
        if (value2 !== reference2()) setReference(value2);
        setState(state2);
        resetErrorBoundaries();
        submissions[1]([]);
      }).then(() => {
        intent = void 0;
      });
    });
  });
  return {
    base: baseRoute,
    location: location2,
    params,
    isRouting,
    renderPath,
    parsePath,
    navigatorFactory,
    matches: matches3,
    beforeLeave,
    preloadRoute,
    singleFlight: options2.singleFlight === void 0 ? true : options2.singleFlight,
    submissions
  };
  function navigateFromRoute(route, to, options3) {
    untrack(() => {
      if (typeof to === "number") {
        if (!to) ;
        else if (utils.go) {
          utils.go(to);
        } else {
          console.warn("Router integration does not support relative routing");
        }
        return;
      }
      const {
        replace: replace4,
        resolve: resolve2,
        scroll,
        state: nextState
      } = {
        replace: false,
        resolve: true,
        scroll: true,
        ...options3
      };
      const resolvedTo = resolve2 ? route.resolvePath(to) : resolvePath("", to);
      if (resolvedTo === void 0) {
        throw new Error(`Path '${to}' is not a routable path`);
      } else if (referrers.length >= MAX_REDIRECTS) {
        throw new Error("Too many redirects");
      }
      const current = reference2();
      if (resolvedTo !== current || nextState !== state()) {
        if (isServer) {
          const e3 = voidFn();
          e3 && (e3.response = {
            status: 302,
            headers: new Headers({
              Location: resolvedTo
            })
          });
          setSource({
            value: resolvedTo,
            replace: replace4,
            scroll,
            state: nextState
          });
        } else if (beforeLeave.confirm(resolvedTo, options3)) {
          const len = referrers.push({
            value: current,
            replace: replace4,
            scroll,
            state: state()
          });
          start(() => {
            intent = "navigate";
            setReference(resolvedTo);
            setState(nextState);
            resetErrorBoundaries();
            submissions[1]([]);
          }).then(() => {
            if (referrers.length === len) {
              intent = void 0;
              navigateEnd({
                value: resolvedTo,
                state: nextState
              });
            }
          });
        }
      }
    });
  }
  function navigatorFactory(route) {
    route = route || useContext(RouteContextObj) || baseRoute;
    return (to, options3) => navigateFromRoute(route, to, options3);
  }
  function navigateEnd(next2) {
    const first2 = referrers[0];
    if (first2) {
      if (next2.value !== first2.value || next2.state !== first2.state) {
        setSource({
          ...next2,
          replace: first2.replace,
          scroll: first2.scroll
        });
      }
      referrers.length = 0;
    }
  }
  function preloadRoute(url2, preloadData) {
    const matches4 = getRouteMatches(branches(), url2.pathname);
    const prevIntent = intent;
    intent = "preload";
    for (let match2 in matches4) {
      const {
        route,
        params: params2
      } = matches4[match2];
      route.component && route.component.preload && route.component.preload();
      const {
        load: load2
      } = route;
      inLoadFn = true;
      preloadData && load2 && runWithOwner(getContext(), () => load2({
        params: params2,
        location: {
          pathname: url2.pathname,
          search: url2.search,
          hash: url2.hash,
          query: extractSearchParams(url2),
          state: null,
          key: ""
        },
        intent: "preload"
      }));
      inLoadFn = false;
    }
    intent = prevIntent;
  }
  function initFromFlash() {
    const e3 = voidFn();
    return e3 && e3.router && e3.router.submission ? [e3.router.submission] : [];
  }
}
function createRouteContext(router, parent, outlet, match2) {
  const {
    base: base3,
    location: location2,
    params
  } = router;
  const {
    pattern: pattern2,
    component,
    load: load2
  } = match2().route;
  const path = createMemo(() => match2().path);
  component && component.preload && component.preload();
  inLoadFn = true;
  const data2 = load2 ? load2({
    params,
    location: location2,
    intent: intent || "initial"
  }) : void 0;
  inLoadFn = false;
  const route = {
    parent,
    pattern: pattern2,
    path,
    outlet: () => component ? createComponent(component, {
      params,
      location: location2,
      data: data2,
      get children() {
        return outlet();
      }
    }) : outlet(),
    resolvePath(to) {
      return resolvePath(base3.path(), to, path());
    }
  };
  return route;
}
var createRouterComponent = (router) => (props2) => {
  const {
    base: base3
  } = props2;
  const routeDefs = children(() => props2.children);
  const branches = createMemo(() => createBranches(routeDefs(), props2.base || ""));
  let context;
  const routerState = createRouterContext(router, branches, () => context, {
    base: base3,
    singleFlight: props2.singleFlight,
    transformUrl: props2.transformUrl
  });
  router.create && router.create(routerState);
  return createComponent(RouterContextObj.Provider, {
    value: routerState,
    get children() {
      return createComponent(Root, {
        routerState,
        get root() {
          return props2.root;
        },
        get load() {
          return props2.rootLoad;
        },
        get children() {
          return [createMemo(() => (context = getOwner()) && null), createComponent(Routes, {
            routerState,
            get branches() {
              return branches();
            }
          })];
        }
      });
    }
  });
};
function Root(props2) {
  const location2 = props2.routerState.location;
  const params = props2.routerState.params;
  const data2 = createMemo(() => props2.load && untrack(() => {
    setInLoadFn(true);
    props2.load({
      params,
      location: location2,
      intent: getIntent() || "initial"
    });
    setInLoadFn(false);
  }));
  return createComponent(Show, {
    get when() {
      return props2.root;
    },
    keyed: true,
    get fallback() {
      return props2.children;
    },
    children: (Root2) => createComponent(Root2, {
      params,
      location: location2,
      get data() {
        return data2();
      },
      get children() {
        return props2.children;
      }
    })
  });
}
function Routes(props2) {
  if (isServer) {
    const e3 = voidFn();
    if (e3 && e3.router && e3.router.dataOnly) {
      dataOnly(e3, props2.routerState, props2.branches);
      return;
    }
    e3 && ((e3.router || (e3.router = {})).matches || (e3.router.matches = props2.routerState.matches().map(({
      route,
      path,
      params
    }) => ({
      path: route.originalPath,
      pattern: route.pattern,
      match: path,
      params,
      info: route.info
    }))));
  }
  const disposers = [];
  let root3;
  const routeStates = createMemo(on(props2.routerState.matches, (nextMatches, prevMatches, prev) => {
    let equal2 = prevMatches && nextMatches.length === prevMatches.length;
    const next2 = [];
    for (let i3 = 0, len = nextMatches.length; i3 < len; i3++) {
      const prevMatch = prevMatches && prevMatches[i3];
      const nextMatch = nextMatches[i3];
      if (prev && prevMatch && nextMatch.route.key === prevMatch.route.key) {
        next2[i3] = prev[i3];
      } else {
        equal2 = false;
        if (disposers[i3]) {
          disposers[i3]();
        }
        createRoot((dispose2) => {
          disposers[i3] = dispose2;
          next2[i3] = createRouteContext(props2.routerState, next2[i3 - 1] || props2.routerState.base, createOutlet(() => routeStates()[i3 + 1]), () => props2.routerState.matches()[i3]);
        });
      }
    }
    disposers.splice(nextMatches.length).forEach((dispose2) => dispose2());
    if (prev && equal2) {
      return prev;
    }
    root3 = next2[0];
    return next2;
  }));
  return createOutlet(() => routeStates() && root3)();
}
var createOutlet = (child) => {
  return () => createComponent(Show, {
    get when() {
      return child();
    },
    keyed: true,
    children: (child2) => createComponent(RouteContextObj.Provider, {
      value: child2,
      get children() {
        return child2.outlet();
      }
    })
  });
};
function dataOnly(event2, routerState, branches) {
  const url2 = new URL(event2.request.url);
  const prevMatches = getRouteMatches(branches, new URL(event2.router.previousUrl || event2.request.url).pathname);
  const matches3 = getRouteMatches(branches, url2.pathname);
  for (let match2 = 0; match2 < matches3.length; match2++) {
    if (!prevMatches[match2] || matches3[match2].route !== prevMatches[match2].route) event2.router.dataOnly = true;
    const {
      route,
      params
    } = matches3[match2];
    route.load && route.load({
      params,
      location: routerState.location,
      intent: "preload"
    });
  }
}
function intercept([value2, setValue2], get7, set4) {
  return [get7 ? () => get7(value2()) : value2, set4 ? (v3) => setValue2(set4(v3)) : setValue2];
}
function querySelector(selector) {
  if (selector === "#") {
    return null;
  }
  try {
    return document.querySelector(selector);
  } catch (e3) {
    return null;
  }
}
function createRouter(config3) {
  let ignore = false;
  const wrap4 = (value2) => typeof value2 === "string" ? {
    value: value2
  } : value2;
  const signal = intercept(createSignal(wrap4(config3.get()), {
    equals: (a3, b3) => a3.value === b3.value && a3.state === b3.state
  }), void 0, (next2) => {
    !ignore && config3.set(next2);
    return next2;
  });
  config3.init && onCleanup(config3.init((value2 = config3.get()) => {
    ignore = true;
    signal[1](wrap4(value2));
    ignore = false;
  }));
  return createRouterComponent({
    signal,
    create: config3.create,
    utils: config3.utils
  });
}
function bindEvent(target, type, handler) {
  target.addEventListener(type, handler);
  return () => target.removeEventListener(type, handler);
}
function scrollToHash(hash, fallbackTop) {
  const el2 = querySelector(`#${hash}`);
  if (el2) {
    el2.scrollIntoView();
  } else if (fallbackTop) {
    window.scrollTo(0, 0);
  }
}
function getPath(url2) {
  const u3 = new URL(url2);
  return u3.pathname + u3.search;
}
function StaticRouter(props2) {
  let e3;
  const url2 = props2.url || (e3 = voidFn()) && getPath(e3.request.url) || "";
  const obj = {
    value: props2.transformUrl ? props2.transformUrl(url2) : url2
  };
  return createRouterComponent({
    signal: [() => obj, (next2) => Object.assign(obj, next2)]
  })(props2);
}
var LocationHeader = "Location";
var PRELOAD_TIMEOUT = 5e3;
var CACHE_TIMEOUT = 18e4;
var cacheMap = /* @__PURE__ */ new Map();
if (!isServer) {
  setInterval(() => {
    const now = Date.now();
    for (let [k2, v3] of cacheMap.entries()) {
      if (!v3[3].count && now - v3[0] > CACHE_TIMEOUT) {
        cacheMap.delete(k2);
      }
    }
  }, 3e5);
}
function getCache() {
  if (!isServer) return cacheMap;
  const req = voidFn();
  if (!req) throw new Error("Cannot find cache context");
  return (req.router || (req.router = {})).cache || (req.router.cache = /* @__PURE__ */ new Map());
}
function cache2(fn, name2) {
  if (fn.GET) fn = fn.GET;
  const cachedFn = (...args) => {
    const cache5 = getCache();
    const intent2 = getIntent();
    const inLoadFn2 = getInLoadFn();
    const owner = getOwner();
    const navigate2 = owner ? useNavigate() : void 0;
    const now = Date.now();
    const key2 = name2 + hashKey(args);
    let cached = cache5.get(key2);
    let tracking;
    if (isServer) {
      const e3 = voidFn();
      if (e3) {
        const dataOnly2 = (e3.router || (e3.router = {})).dataOnly;
        if (dataOnly2) {
          const data2 = e3 && (e3.router.data || (e3.router.data = {}));
          if (data2 && key2 in data2) return data2[key2];
          if (Array.isArray(dataOnly2) && !dataOnly2.includes(key2)) {
            data2[key2] = void 0;
            return Promise.resolve();
          }
        }
      }
    }
    if (getListener() && !isServer) {
      tracking = true;
      onCleanup(() => cached[3].count--);
    }
    if (cached && cached[0] && (isServer || intent2 === "native" || cached[3].count || Date.now() - cached[0] < PRELOAD_TIMEOUT)) {
      if (tracking) {
        cached[3].count++;
        cached[3][0]();
      }
      if (cached[2] === "preload" && intent2 !== "preload") {
        cached[0] = now;
      }
      let res2 = cached[1];
      if (!inLoadFn2) {
        res2 = "then" in cached[1] ? cached[1].then(handleResponse(false), handleResponse(true)) : handleResponse(false)(cached[1]);
        !isServer && intent2 === "navigate" && startTransition(() => cached[3][1](cached[0]));
      } else "then" in res2 && res2.catch(() => {
      });
      return res2;
    }
    let res = !isServer && sharedConfig.context && sharedConfig.has(key2) ? sharedConfig.load(key2) : fn(...args);
    if (cached) {
      cached[0] = now;
      cached[1] = res;
      cached[2] = intent2;
      !isServer && intent2 === "navigate" && startTransition(() => cached[3][1](cached[0]));
    } else {
      cache5.set(key2, cached = [now, res, intent2, createSignal(now)]);
      cached[3].count = 0;
    }
    if (tracking) {
      cached[3].count++;
      cached[3][0]();
    }
    if (isServer) {
      const e3 = voidFn();
      if (e3 && e3.router.dataOnly) return e3.router.data[key2] = res;
    }
    if (!inLoadFn2) {
      res = "then" in res ? res.then(handleResponse(false), handleResponse(true)) : handleResponse(false)(res);
    } else "then" in res && res.catch(() => {
    });
    if (isServer && sharedConfig.context && sharedConfig.context.async && !sharedConfig.context.noHydrate) {
      const e3 = voidFn();
      (!e3 || !e3.serverOnly) && sharedConfig.context.serialize(key2, res);
    }
    return res;
    function handleResponse(error2) {
      return async (v3) => {
        if (v3 instanceof Response) {
          if (v3.headers.has("Location")) {
            if (navigate2) {
              startTransition(() => {
                let url2 = v3.headers.get(LocationHeader);
                if (url2 && url2.startsWith("/")) {
                  navigate2(url2, {
                    replace: true
                  });
                } else if (!isServer && url2) {
                  window.location.href = url2;
                }
              });
            }
            return;
          }
          if (v3.customBody) v3 = await v3.customBody();
        }
        if (error2) throw v3;
        return v3;
      };
    }
  };
  cachedFn.keyFor = (...args) => name2 + hashKey(args);
  cachedFn.key = name2;
  return cachedFn;
}
cache2.set = (key2, value2) => {
  const cache5 = getCache();
  const now = Date.now();
  let cached = cache5.get(key2);
  if (cached) {
    cached[0] = now;
    cached[1] = value2;
    cached[2] = "preload";
  } else {
    cache5.set(key2, cached = [now, value2, , createSignal(now)]);
    cached[3].count = 0;
  }
};
cache2.clear = () => getCache().clear();
function hashKey(args) {
  return JSON.stringify(args, (_5, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result2, key2) => {
    result2[key2] = val[key2];
    return result2;
  }, {}) : val);
}
function isPlainObject(obj) {
  let proto;
  return obj != null && typeof obj === "object" && (!(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype);
}
var actions = /* @__PURE__ */ new Map();
function setupNativeEvents(preload = true, explicitLinks = false, actionBase = "/_server", transformUrl) {
  return (router) => {
    const basePath = router.base.path();
    const navigateFromRoute = router.navigatorFactory(router.base);
    let preloadTimeout = {};
    function isSvg(el2) {
      return el2.namespaceURI === "http://www.w3.org/2000/svg";
    }
    function handleAnchor(evt) {
      if (evt.defaultPrevented || evt.button !== 0 || evt.metaKey || evt.altKey || evt.ctrlKey || evt.shiftKey) return;
      const a3 = evt.composedPath().find((el2) => el2 instanceof Node && el2.nodeName.toUpperCase() === "A");
      if (!a3 || explicitLinks && !a3.hasAttribute("link")) return;
      const svg4 = isSvg(a3);
      const href = svg4 ? a3.href.baseVal : a3.href;
      const target = svg4 ? a3.target.baseVal : a3.target;
      if (target || !href && !a3.hasAttribute("state")) return;
      const rel = (a3.getAttribute("rel") || "").split(/\s+/);
      if (a3.hasAttribute("download") || rel && rel.includes("external")) return;
      const url2 = svg4 ? new URL(href, document.baseURI) : new URL(href);
      if (url2.origin !== window.location.origin || basePath && url2.pathname && !url2.pathname.toLowerCase().startsWith(basePath.toLowerCase())) return;
      return [a3, url2];
    }
    function handleAnchorClick(evt) {
      const res = handleAnchor(evt);
      if (!res) return;
      const [a3, url2] = res;
      const to = router.parsePath(url2.pathname + url2.search + url2.hash);
      const state = a3.getAttribute("state");
      evt.preventDefault();
      navigateFromRoute(to, {
        resolve: false,
        replace: a3.hasAttribute("replace"),
        scroll: !a3.hasAttribute("noscroll"),
        state: state && JSON.parse(state)
      });
    }
    function handleAnchorPreload(evt) {
      const res = handleAnchor(evt);
      if (!res) return;
      const [a3, url2] = res;
      if (typeof transformUrl === "function") {
        url2.pathname = transformUrl(url2.pathname);
      }
      if (!preloadTimeout[url2.pathname]) router.preloadRoute(url2, a3.getAttribute("preload") !== "false");
    }
    function handleAnchorIn(evt) {
      const res = handleAnchor(evt);
      if (!res) return;
      const [a3, url2] = res;
      if (typeof transformUrl === "function") {
        url2.pathname = transformUrl(url2.pathname);
      }
      if (preloadTimeout[url2.pathname]) return;
      preloadTimeout[url2.pathname] = setTimeout(() => {
        router.preloadRoute(url2, a3.getAttribute("preload") !== "false");
        delete preloadTimeout[url2.pathname];
      }, 200);
    }
    function handleAnchorOut(evt) {
      const res = handleAnchor(evt);
      if (!res) return;
      const [, url2] = res;
      if (typeof transformUrl === "function") {
        url2.pathname = transformUrl(url2.pathname);
      }
      if (preloadTimeout[url2.pathname]) {
        clearTimeout(preloadTimeout[url2.pathname]);
        delete preloadTimeout[url2.pathname];
      }
    }
    function handleFormSubmit(evt) {
      if (evt.defaultPrevented) return;
      let actionRef = evt.submitter && evt.submitter.hasAttribute("formaction") ? evt.submitter.getAttribute("formaction") : evt.target.getAttribute("action");
      if (!actionRef) return;
      if (!actionRef.startsWith("https://action/")) {
        const url2 = new URL(actionRef, mockBase);
        actionRef = router.parsePath(url2.pathname + url2.search);
        if (!actionRef.startsWith(actionBase)) return;
      }
      if (evt.target.method.toUpperCase() !== "POST") throw new Error("Only POST forms are supported for Actions");
      const handler = actions.get(actionRef);
      if (handler) {
        evt.preventDefault();
        const data2 = new FormData(evt.target);
        if (evt.submitter && evt.submitter.name) data2.append(evt.submitter.name, evt.submitter.value);
        handler.call({
          r: router,
          f: evt.target
        }, data2);
      }
    }
    delegateEvents(["click", "submit"]);
    document.addEventListener("click", handleAnchorClick);
    if (preload) {
      document.addEventListener("mouseover", handleAnchorIn);
      document.addEventListener("mouseout", handleAnchorOut);
      document.addEventListener("focusin", handleAnchorPreload);
      document.addEventListener("touchstart", handleAnchorPreload);
    }
    document.addEventListener("submit", handleFormSubmit);
    onCleanup(() => {
      document.removeEventListener("click", handleAnchorClick);
      if (preload) {
        document.removeEventListener("mouseover", handleAnchorIn);
        document.removeEventListener("mouseout", handleAnchorOut);
        document.removeEventListener("focusin", handleAnchorPreload);
        document.removeEventListener("touchstart", handleAnchorPreload);
      }
      document.removeEventListener("submit", handleFormSubmit);
    });
  };
}
function Router(props2) {
  if (isServer) return StaticRouter(props2);
  const getSource = () => {
    const url2 = window.location.pathname + window.location.search;
    return {
      value: props2.transformUrl ? props2.transformUrl(url2) + window.location.hash : url2 + window.location.hash,
      state: window.history.state
    };
  };
  const beforeLeave = createBeforeLeave();
  return createRouter({
    get: getSource,
    set({
      value: value2,
      replace: replace4,
      scroll,
      state
    }) {
      if (replace4) {
        window.history.replaceState(keepDepth(state), "", value2);
      } else {
        window.history.pushState(state, "", value2);
      }
      scrollToHash(window.location.hash.slice(1), scroll);
      saveCurrentDepth();
    },
    init: (notify2) => bindEvent(window, "popstate", notifyIfNotBlocked(notify2, (delta) => {
      if (delta && delta < 0) {
        return !beforeLeave.confirm(delta);
      } else {
        const s3 = getSource();
        return !beforeLeave.confirm(s3.value, {
          state: s3.state
        });
      }
    })),
    create: setupNativeEvents(props2.preload, props2.explicitLinks, props2.actionBase, props2.transformUrl),
    utils: {
      go: (delta) => window.history.go(delta),
      beforeLeave
    }
  })(props2);
}
var _tmpl$115 = /* @__PURE__ */ template(`<a>`);
function A2(props2) {
  props2 = mergeProps({
    inactiveClass: "inactive",
    activeClass: "active"
  }, props2);
  const [, rest2] = splitProps(props2, ["href", "state", "class", "activeClass", "inactiveClass", "end"]);
  const to = useResolvedPath(() => props2.href);
  const href = useHref(to);
  const location2 = useLocation();
  const isActive = createMemo(() => {
    const to_ = to();
    if (to_ === void 0) return [false, false];
    const path = normalizePath2(to_.split(/[?#]/, 1)[0]).toLowerCase();
    const loc = normalizePath2(location2.pathname).toLowerCase();
    return [props2.end ? path === loc : loc.startsWith(path + "/") || loc === path, path === loc];
  });
  return (() => {
    const _el$ = _tmpl$115();
    spread(_el$, mergeProps(rest2, {
      get href() {
        return href() || props2.href;
      },
      get state() {
        return JSON.stringify(props2.state);
      },
      get classList() {
        return {
          ...props2.class && {
            [props2.class]: true
          },
          [props2.inactiveClass]: !isActive()[0],
          [props2.activeClass]: isActive()[0],
          ...rest2.classList
        };
      },
      "link": "",
      get ["aria-current"]() {
        return isActive()[1] ? "page" : void 0;
      }
    }), false, false);
    return _el$;
  })();
}

// public/app/routes/ng-compat.js
angular_default.module("kantree").directive("navigateTo", [
  "$state",
  "$timeout",
  function($state, $timeout2) {
    return {
      restrict: "A",
      link: (scope, el2, attrs2) => {
        const def = {};
        scope.$watch(() => attrs2.navigateTo, (val) => {
          def.state = $state.href(val);
          el2.attr("href", def.state);
        });
        clickHandler(el2, $state, $timeout2, def);
      }
    };
  }
]);
angular_default.module("kantree").factory("$state", [
  function() {
    return {
      get params() {
        return new Proxy(this, {
          get(target, prop2, receiver) {
            return untrack(() => target.routeParams?.[prop2] || target.searchParams?.[prop2]);
          }
        });
      },
      includes(name2, params) {
        if (!this.current?.name || this.current.fullName.split(".").slice(0, name2.split(".").length).join(".") !== name2) {
          return false;
        }
        if (params) {
          for (const [k2, v3] of Object.entries(params)) {
            if (v3 !== this.params[k2]) {
              return false;
            }
          }
        }
        return true;
      },
      is(name2) {
        return this.current?.fullName === name2;
      },
      reload() {
        document.location.reload();
      }
    };
  }
]);
angular_default.module("kantree").directive("uiSref", [
  "$state",
  "$timeout",
  function($state, $timeout2) {
    return {
      restrict: "A",
      link: (scope, el2, attrs2) => {
        let href;
        const ref = parseStateRef(attrs2.uiSref, $state.current.name);
        const def = { state: ref.state };
        const update2 = (val) => {
          if (val) def.params = angular_default.copy(val);
          try {
            href = $state.href(ref.state, def.params);
          } catch (e3) {
            console.error(e3);
            href = null;
          }
          if (href !== null) attrs2.$set("href", href);
        };
        if (ref.paramExpr) {
          scope.$watch(ref.paramExpr, function(val) {
            if (val !== def.params) update2(val);
          }, true);
          def.params = angular_default.copy(scope.$eval(ref.paramExpr));
        }
        update2();
        clickHandler(el2, $state, $timeout2, def);
      }
    };
  }
]);
angular_default.module("kantree").directive("uiState", [
  "$state",
  "$timeout",
  function($state, $timeout2) {
    return {
      restrict: "A",
      link: (scope, el2, attrs2) => {
        const def = {};
        let href;
        const update2 = () => {
          try {
            href = $state.href(def.state, def.params);
          } catch {
            href = null;
          }
          if (href !== null) attrs2.$set("href", href);
        };
        scope.$watch(attrs2.uiState, (val) => {
          def.state = val;
          update2();
        });
        def.state = angular_default.copy(scope.$eval(attrs2.uiState));
        if (attrs2.uiStateParams) {
          scope.$watch(attrs2.uiStateParams, (val) => {
            if (val !== def.params) {
              def.params = val;
              update2();
            }
          }, true);
          def.params = angular_default.copy(scope.$eval(attrs2.uiStateParams));
        }
        update2();
        clickHandler(el2, $state, $timeout2, def);
      }
    };
  }
]);
function clickHandler(el2, $state, $timeout2, def) {
  el2.on("click", (e3) => {
    const button = e3.which || e3.button;
    if (!(button > 1 || e3.ctrlKey || e3.metaKey || e3.shiftKey || el2.attr("target"))) {
      e3.preventDefault();
      const transition = $timeout2(() => $state.go(def.state, def.params));
      e3.preventDefault = () => $timeout2.cancel(transition);
    }
  });
}
function parseStateRef(ref, current) {
  var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
  if (preparsed) ref = current + "(" + preparsed[1] + ")";
  parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
  if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
  return { state: parsed[1], paramExpr: parsed[3] || null };
}

// public/app/routes/routing.jsx
var routes = [];
var indexedRoutes = /* @__PURE__ */ new Map();
function addRoute(options2) {
  if (!options2.path) {
    const Component = options2.component;
    for (const child of options2.children) {
      const name2 = options2.name + "." + child.name;
      const ChildComponent = child.component;
      addRoute({
        ...child,
        name: name2,
        component: () => createComponent(Component, {
          get children() {
            return createComponent(ChildComponent, {});
          }
        })
      });
    }
    return;
  }
  routes.push(prepareRouteRecursively(options2));
}
function prepareRouteRecursively(route, parent) {
  if (route.name) {
    route = {
      ...route,
      fullName: (parent ? `${parent.fullName}.` : "") + route.name,
      fullPath: ((parent ? `${parent.fullPath}/` : "") + route.path).replace("//", "/")
    };
    indexedRoutes.set(route.fullName, route);
  } else {
    route = {
      ...route
    };
  }
  if (route.redirectTo) {
    route.component = () => {
      const navigate2 = useNavigate2();
      navigate2(route.redirectTo);
    };
  } else if (route.component) {
    route.component = wrapRouteComponent(route);
  }
  if (route.children) {
    route.children = route.children.map((child) => prepareRouteRecursively(child, route));
  }
  return route;
}
function wrapRouteComponent(route) {
  const Component = route.component;
  return (props2) => {
    const params = useParams();
    const [searchParams, setSearchParams] = useSearchParams();
    createEffect(() => {
      if (isBootstraped()) {
        const $state = ngApp.$injector.get("$state");
        $state.current = route;
        $state.routeParams = params;
        $state.searchParams = searchParams;
        $state.setSearchParams = setSearchParams;
        ngApp.$injector.get("$rootScope").$applyAsync();
        ngApp.$injector.get("$rootScope").$broadcast("$stateChangeSuccess");
      }
    });
    return createComponent(Component, {
      get children() {
        return props2.children;
      }
    });
  };
}
function getRoute(name2) {
  return indexedRoutes.get(name2);
}
function routeHref(nameOrPath, params) {
  let path = nameOrPath;
  if (nameOrPath[0] !== "/") {
    path = indexedRoutes.get(nameOrPath)?.fullPath;
    if (!path) {
      return "";
    }
  }
  let finalPath = "";
  const segmentParams = [];
  for (const segment of path.replace(/^\//, "").split("/")) {
    if (segment[0] === ":") {
      const paramName = segment.slice(1);
      if (!params?.[paramName]) {
        console.warn(`Missing path segment :${paramName} for ${path}`);
        return "";
      }
      finalPath += "/" + params[paramName];
      segmentParams.push(paramName);
    } else {
      finalPath += "/" + segment;
    }
  }
  const searchParams = Object.fromEntries(Object.entries(params || {}).filter(([key2, value2]) => !segmentParams.includes(key2) && key2 !== "#" && value2));
  if (Object.keys(searchParams).length) {
    finalPath += "?" + new URLSearchParams(searchParams).toString();
  }
  if (params?.["#"]) {
    finalPath += "#" + params["#"];
  }
  return finalPath;
}
function useNavigate2() {
  const navigate2 = useNavigate();
  return (name2, params, options2) => {
    const href = routeHref(name2, params);
    return navigate2(href, {
      ...options2,
      routeName: name2,
      routeParams: params
    });
  };
}
function A3(props2) {
  const [local, others] = splitProps(props2, ["href", "route", "routeParams"]);
  const href = createMemo(() => local.route ? routeHref(local.route, local.routeParams) : local.href);
  return createComponent(A2, mergeProps({
    get href() {
      return href();
    }
  }, others, {
    get children() {
      return props2.children;
    }
  }));
}
function Router2() {
  return createComponent(Router, {
    root: NgStateSync,
    explicitLinks: true,
    children: routes
  });
}
function NgStateSync(props2) {
  const navigate2 = useNavigate2();
  createEffect(() => {
    if (isBootstraped()) {
      const $state = ngApp.$injector.get("$state");
      $state.go = navigate2;
      $state.href = routeHref;
    }
  });
  useBeforeLeave(() => {
    ngApp.$injector?.get("$rootScope")?.$broadcast("$beforeLeaveState");
  });
  return props2.children;
}

// public/app/routes/page-decorators.jsx
function useAuthenticated(callback, preventOnboardingRedirect = false) {
  const navigate2 = useNavigate();
  const [isReady, setReady] = createSignal(false);
  (async () => {
    await loadCurrentUser();
    if (!isAuthenticated()) {
      authSession.login();
      return;
    }
    if (!preventOnboardingRedirect && !(currentUser2.onboarded || []).includes("user")) {
      navigate2("/onboarding");
      return;
    }
    await loadAppContext();
    setReady(true);
    callback && callback();
  })();
  return isReady;
}
function AuthenticatedPage(props2) {
  const isReady = useAuthenticated(null, props2.preventOnboardingRedirect);
  return createComponent(Show, {
    get when() {
      return isReady();
    },
    get children() {
      return props2.children;
    }
  });
}
function ColorizedPage(props2) {
  let lastBeforeLeaveEvent;
  useBeforeLeave((e3) => {
    lastBeforeLeaveEvent = e3;
  });
  onCleanup(() => {
    let route;
    if (lastBeforeLeaveEvent?.options.routeName) {
      route = getRoute(lastBeforeLeaveEvent.options.routeName);
    }
    if (!route?.colorized) {
      setPageColor();
    }
  });
  return createMemo(() => props2.children);
}
function UnavailableOffline(props2) {
  const [isReady, setReady] = createSignal(false);
  (async () => {
    await loadCurrentUser();
    if (!isConnected() && isAuthenticated()) {
      errorDialog(_4("Not available while offline"));
      navigate("/");
    } else {
      setReady(true);
    }
  })();
  return createComponent(Show, {
    get when() {
      return isReady();
    },
    get children() {
      return props2.children;
    }
  });
}
function HideSystemSidebar(props2) {
  const isAlreadyHidden = document.body.classList.contains("no-sidebar");
  const [isReady, setReady] = createSignal(isAlreadyHidden);
  let restoreSidebar = false;
  (async () => {
    await loadCurrentUser();
    if (!isAlreadyHidden && (!props2.anonymousOnly || !isAuthenticated())) {
      document.body.classList.toggle("no-sidebar", true);
      document.documentElement.style.setProperty("--system-sidebar-width", "0px");
      restoreSidebar = true;
    }
    setReady(true);
  })();
  onCleanup(() => {
    if (restoreSidebar) {
      document.body.classList.toggle("no-sidebar", false);
      document.documentElement.style.setProperty("--system-sidebar-width", "60px");
    }
  });
  return createComponent(Show, {
    get when() {
      return isReady();
    },
    get children() {
      return props2.children;
    }
  });
}

// public/app/config/locale.js
var availableLocales = [
  { code: "en", label: "English" },
  { code: "fr", label: "Fran\xE7ais" },
  { code: "de", label: "Deutsch" },
  { code: "es", label: "Espa\xF1ol" },
  { code: "it", label: "Italiano" },
  { code: "pt", label: "Portugu\xEAs" }
];
var availableTimeFormats = [
  { format: "am_pm", label: _lazy("AM/PM") },
  { format: "24h", label: _lazy("24h") }
];
function getAvailableWeekStarts() {
  const starts = [];
  for (let dow of [0, 1, 6]) {
    starts.push({ dow, label: moment_default.weekdays()[dow] });
  }
  return starts;
}

// public/app/routes/account/panels/Settings.jsx
var _tmpl$116 = /* @__PURE__ */ template(`<div id="user-settings-panel"><div class="account-footer"><br> <em></em></div></div>`, 7);
var _tmpl$248 = /* @__PURE__ */ template(`<div class="alert alert-small alert-warning alert-actionnable"><span> </span></div>`, 4);
var _tmpl$331 = /* @__PURE__ */ template(`<p class="form-text"></p>`, 2);
function SettingsPanel() {
  const [successUpdate, setSuccessUpdate] = createSignal(false);
  const [uploading, setUploading] = createSignal(false);
  const availableLocalesFormatted = availableLocales.map((elem) => {
    return {
      ...elem,
      value: elem.code
    };
  });
  const availableWeekStarts = getAvailableWeekStarts().map((elem) => {
    return {
      ...elem,
      value: elem.dow
    };
  });
  const availableTimeFormatsFormatted = availableTimeFormats.map((elem) => {
    return {
      ...elem,
      value: elem.format
    };
  });
  const [profileForm, {
    Form: Form3,
    TextField: TextField2
  }] = createForm2({
    initialValues: {
      username: currentUser2.username,
      email: currentUser2.email,
      displayName: currentUser2.display_name
    },
    validateOn: "input"
  });
  const update2 = async (values2) => {
    const user = await api_default.user.update.post({
      username: values2.username,
      email: values2.email,
      display_name: values2.displayName
    });
    if (user) {
      setCurrentUser(user);
      setSuccessUpdate(true);
      setTimeout(() => setSuccessUpdate(false), 5e3);
    }
  };
  const sendValidationEmail = async () => {
    const posted = await api_default.user.send_email_validation.post();
    if (posted) {
      infoDialog(_4("We have sent you an email to confirm your email address. Please follow the link inside."));
    }
  };
  const updatePreferences = async (e3) => {
    let preferencesForm = {
      locale: currentUser2.locale,
      dow_start: currentUser2.dow_start,
      time_format: currentUser2.time_format
    };
    preferencesForm = {
      ...preferencesForm,
      [e3.target.id]: e3.target.value === "null" ? null : e3.target.value
    };
    const user = await api_default.user.update.post(preferencesForm);
    if (user) {
      if (e3.target.id === "locale") {
        setTimeout(() => window.location.reload(), 500);
      }
      setCurrentUser(user);
      updateMomentLocaleWithUserSettings();
    }
  };
  const updateEmailSettings = async (e3) => {
    let emailSettings = {
      email_notifications: currentUser2.email_notifications,
      email_newsletter: currentUser2.email_newsletter
    };
    emailSettings = {
      ...emailSettings,
      [e3.target.id]: e3.target.checked
    };
    const user = await api_default.user.update.post(emailSettings);
    if (user) {
      setCurrentUser(user);
    }
  };
  const updateAvatar = async (event2) => {
    setUploading(true);
    try {
      const resp = await upload({
        url: api_default.user.update.url(),
        data: {
          avatar: event2.target.files[0]
        }
      });
      if (resp) setCurrentUser(resp.data);
      setUploading(false);
    } catch (err) {
      console.log(err);
      errorDialog(_4("An error ocurred while uploading your file"));
      setUploading(false);
    }
  };
  const removeAvatar = async () => {
    const user = await api_default.user.update.post({
      clear_avatar: true
    });
    setCurrentUser(user);
  };
  const clearOfflineCache = async () => {
    const cleared = await clearAllStores();
    if (cleared) {
      successDialog(_4("Offline data have been deleted"));
    }
  };
  return (() => {
    const _el$ = _tmpl$116.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.nextSibling, _el$5 = _el$4.nextSibling;
    insert(_el$, createComponent(Panel, {
      get header() {
        return _4("Your profile");
      },
      get children() {
        return createComponent(Form3, {
          onSubmit: (values2) => update2(values2),
          get children() {
            return [createComponent(TextField2, {
              required: true,
              name: "username",
              get label() {
                return _4("Username:");
              },
              get validate() {
                return [required("required")];
              },
              get disabled() {
                return serverConfig.readonly_username;
              }
            }), createComponent(TextField2, {
              name: "email",
              get label() {
                return _4("Email:");
              },
              type: "email",
              get validate() {
                return [required("required"), email("email format")];
              },
              get disabled() {
                return serverConfig.readonly_email;
              },
              get info() {
                return createComponent(Show, {
                  get when() {
                    return !currentUser2.email_validated && serverConfig.validate_user_emails;
                  },
                  get children() {
                    const _el$6 = _tmpl$248.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.firstChild;
                    insert(_el$7, createComponent(Icon, {
                      name: "bi-exclamation-triangle-fill"
                    }), _el$8);
                    insert(_el$7, () => _4("Please verify your email again"), null);
                    insert(_el$6, createComponent(Button, {
                      style: "warning",
                      "class": "pull-right",
                      onClick: () => sendValidationEmail(),
                      get children() {
                        return _4("Send verification email");
                      }
                    }), null);
                    return _el$6;
                  }
                });
              }
            }), createComponent(TextField2, {
              name: "displayName",
              get label() {
                return _4("Display name:");
              },
              get placeholder() {
                return _4("Leave empty to use username");
              },
              get info() {
                return (() => {
                  const _el$9 = _tmpl$331.cloneNode(true);
                  insert(_el$9, () => _4("This can be set to use a more human friendly name instead of your username"));
                  return _el$9;
                })();
              }
            }), createComponent(Button, {
              type: "submit",
              style: "primary",
              get disabled() {
                return !profileForm.touched || profileForm.invalid;
              },
              disableoffline: true,
              get children() {
                return _4("Update");
              }
            }), createComponent(Show, {
              get when() {
                return successUpdate();
              },
              get children() {
                return createComponent(Icon, {
                  name: "fa-check",
                  "class": "text-success"
                });
              }
            })];
          }
        });
      }
    }), _el$2);
    insert(_el$, createComponent(Panel, {
      get header() {
        return _4("Preferences");
      },
      get children() {
        return [createComponent(SelectField2, {
          onChange: updatePreferences,
          id: "locale",
          name: "userLang",
          get label() {
            return _4("Language:");
          },
          options: availableLocalesFormatted,
          get selected() {
            return currentUser2.locale;
          }
        }), createComponent(SelectField2, {
          onChange: updatePreferences,
          id: "dow_start",
          name: "userDowStart",
          get label() {
            return _4("Week starts on:");
          },
          options: availableWeekStarts,
          withDefault: true,
          get selected() {
            return currentUser2.dow_start;
          }
        }), createComponent(SelectField2, {
          onChange: updatePreferences,
          id: "time_format",
          name: "userTimeFormat",
          get label() {
            return _4("Time format:");
          },
          options: availableTimeFormatsFormatted,
          withDefault: true,
          get selected() {
            return currentUser2.time_format;
          }
        })];
      }
    }), _el$2);
    insert(_el$, createComponent(Panel, {
      get header() {
        return _4("Email settings");
      },
      get children() {
        return [createComponent(CheckInput, {
          containerClass: "form-switch",
          onChange: updateEmailSettings,
          name: "userEmailNotif",
          id: "email_notifications",
          get label() {
            return _4("Receive email notifications");
          },
          get checked() {
            return currentUser2.email_notifications;
          }
        }), createComponent(CheckInput, {
          containerClass: "form-switch",
          onChange: updateEmailSettings,
          name: "userEmailNewsletter",
          id: "email_newsletter",
          get label() {
            return _4("Receive product updates and tips");
          },
          get checked() {
            return currentUser2.email_newsletter;
          }
        })];
      }
    }), _el$2);
    insert(_el$, createComponent(Panel, {
      get header() {
        return _4("Profile picture");
      },
      get children() {
        return createComponent(VStack, {
          get children() {
            return [createComponent(Show, {
              get when() {
                return !currentUser2.is_auto_generated_avatar;
              },
              get children() {
                return createComponent(ProfileAvatar, {
                  get src() {
                    return currentUser2.avatar;
                  }
                });
              }
            }), createComponent(HStack, {
              get children() {
                return [createComponent(FileInputButton, {
                  get label() {
                    return _4("Select a new picture");
                  },
                  btnClass: "btn-default",
                  onChangeFn: updateAvatar,
                  get disabled() {
                    return uploading();
                  }
                }), createComponent(Show, {
                  get when() {
                    return currentUser2.avatar && !currentUser2.is_auto_generated_avatar;
                  },
                  get children() {
                    return createComponent(Button, {
                      style: "danger",
                      "class": "btn-ghost ms-1",
                      onClick: () => removeAvatar(),
                      get children() {
                        return [createComponent(Icon, {
                          name: "bi-trash-fill"
                        }), " ", createMemo(() => _4("Remove"))];
                      }
                    });
                  }
                }), createComponent(Show, {
                  get when() {
                    return uploading();
                  },
                  get children() {
                    return createComponent(Icon, {
                      name: "spin",
                      "class": "fa-spinner"
                    });
                  }
                })];
              }
            })];
          }
        });
      }
    }), _el$2);
    insert(_el$, createComponent(Panel, {
      get header() {
        return _4("Offline data");
      },
      get children() {
        return createComponent(Button, {
          style: "danger",
          "class": "btn-ghost",
          onClick: clearOfflineCache,
          get children() {
            return _4("Clear offline data");
          }
        });
      }
    }), _el$2);
    insert(_el$2, () => _4("Feel free to contact us at contact@kantree.io"), _el$3);
    insert(_el$2, () => _4("Current Kantree's version:"), _el$4);
    insert(_el$5, () => serverConfig.version);
    return _el$;
  })();
}

// public/app/routes/account/panels/Appearance.jsx
var import_tinycolor28 = __toESM(require_tinycolor());
var _tmpl$117 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$249 = /* @__PURE__ */ template(`<span class="form-check mod-user-theme"><label class="nav-theme-thumbnail mod-sidebar" for="themeSidebar"><div class="nav-theme-thumbnail-sidebar"></div><div class="nav-theme-thumbnail-right-container"><div class="nav-theme-thumbnail-topbar"></div><div class="nav-theme-thumbnail-content"></div></div></label><input class="form-check-input" type="radio" value="sidebar" name="layout" id="themeSidebar"><label class="form-check-label" for="themeSidebar"></label></span>`, 15);
var _tmpl$332 = /* @__PURE__ */ template(`<span class="form-check mod-user-theme"><label class="nav-theme-thumbnail mod-topbar" for="themeTopbar"><div class="nav-theme-thumbnail-topbar"></div><div class="nav-theme-thumbnail-bottom-container"><div class="nav-theme-thumbnail-sidebar"></div><div class="nav-theme-thumbnail-content"></div></div></label><input class="form-check-input" type="radio" value="topbar" name="layout" id="themeTopbar"><label class="form-check-label" for="themeTopbar"></label></span>`, 15);
var _tmpl$420 = /* @__PURE__ */ template(`<div class="form-check mod-user-theme mod-user-theme-color"><label class="preview" for="themeColorCustom"></label><input class="form-check-input" type="radio" name="themeColorCustom" id="themeColorCustom"><label class="form-check-label" for="themeColorCustom"></label></div>`, 7);
var _tmpl$517 = /* @__PURE__ */ template(`<div class="form-check mod-user-theme mod-user-theme-color"><label class="preview"></label><input class="form-check-input" type="radio" name="mainTheme"><label class="form-check-label"></label></div>`, 7);
var defaultThemeColors = [{
  name: _lazy("Indigo"),
  hex: "#292961"
}, {
  name: _lazy("Light Indigo"),
  hex: "#4b4ba3"
}, {
  name: _lazy("Blue"),
  hex: "#1a3652"
}, {
  name: _lazy("Light Blue"),
  hex: "#2261a1"
}, {
  name: _lazy("Red"),
  hex: "#691a16"
}, {
  name: _lazy("Light Red"),
  hex: "#a62e21"
}, {
  name: _lazy("Dark"),
  hex: "#2e2e2e"
}, {
  name: _lazy("Light"),
  hex: "#dfdfdf"
}];
function AppearancePanel() {
  const [customColor, setCustomColor] = createSignal(import_tinycolor28.default.random().toHexString());
  let themeColors;
  const updateThemeName = (name2) => {
    saveTheme(name2, themeState.color);
  };
  const updateThemeColor = (color) => {
    saveTheme(themeName(), color);
  };
  const getBoardColor = () => themeColor() || "#0c6442";
  const refreshThemeColors = () => {
    let defaultColor;
    if (themeState.color !== "" && !defaultThemeColors.some((tc) => tc.hex === themeState.color)) {
      setCustomColor(themeState.color);
    }
    if (serverConfig.theme_color) {
      defaultColor = {
        name: _4("Default"),
        hex: (0, import_tinycolor28.default)(serverConfig.theme_color).toHexString()
      };
    } else {
      defaultColor = {
        name: _4("Default"),
        hex: ""
      };
    }
    themeColors = [defaultColor].concat(defaultThemeColors);
  };
  refreshThemeColors();
  const pickCustomColor = (newColor) => {
    setCustomColor(newColor);
    updateThemeColor((0, import_tinycolor28.default)(newColor).toHexString());
  };
  const pickCustomColorDebounced = debounce2((color) => {
    if (color) pickCustomColor(color.color);
  }, 200);
  const colorPickerOptions = {
    config: [{
      component: "menu-item-color-palette",
      onUpdate: pickCustomColorDebounced,
      params: {
        defaultColor: customColor()
      }
    }]
  };
  return [(() => {
    const _el$ = _tmpl$117.cloneNode(true);
    insert(_el$, () => _4("Customize the appearance of the topbar and sidebar. You can overwrite color per workspace (in workspace settings)"));
    return _el$;
  })(), createComponent(Show, {
    get when() {
      return !isScreensizeXS();
    },
    get children() {
      return createComponent(Panel, {
        withBody: false,
        headerTag: "h4",
        get header() {
          return _4("Theme:");
        },
        get children() {
          return [(() => {
            const _el$2 = _tmpl$249.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$3.nextSibling, _el$6 = _el$5.nextSibling;
            _el$5.addEventListener("change", (e3) => updateThemeName(e3.target.value));
            insert(_el$6, () => _4("Sidebar (default)"));
            createRenderEffect((_p$) => {
              const _v$ = !!(themeName() === "sidebar"), _v$2 = `background-color: ${getBoardColor()}`;
              _v$ !== _p$._v$ && _el$3.classList.toggle("is-selected", _p$._v$ = _v$);
              _p$._v$2 = style(_el$4, _v$2, _p$._v$2);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0
            });
            createRenderEffect(() => _el$5.checked = themeName() === "sidebar");
            return _el$2;
          })(), (() => {
            const _el$7 = _tmpl$332.cloneNode(true), _el$8 = _el$7.firstChild, _el$9 = _el$8.firstChild, _el$10 = _el$8.nextSibling, _el$11 = _el$10.nextSibling;
            _el$10.addEventListener("change", (e3) => updateThemeName(e3.target.value));
            insert(_el$11, () => _4("Topbar"));
            createRenderEffect((_p$) => {
              const _v$3 = !!(themeName() === "topbar"), _v$4 = `background-color: ${getBoardColor()} `;
              _v$3 !== _p$._v$3 && _el$8.classList.toggle("is-selected", _p$._v$3 = _v$3);
              _p$._v$4 = style(_el$9, _v$4, _p$._v$4);
              return _p$;
            }, {
              _v$3: void 0,
              _v$4: void 0
            });
            createRenderEffect(() => _el$10.checked = themeName() === "topbar");
            return _el$7;
          })()];
        }
      });
    }
  }), createComponent(Panel, {
    withBody: false,
    headerTag: "h4",
    get header() {
      return _4("Main theme color:");
    },
    get children() {
      return [createComponent(For, {
        each: themeColors,
        children: (themeColor2) => (() => {
          const _el$16 = _tmpl$517.cloneNode(true), _el$17 = _el$16.firstChild, _el$18 = _el$17.nextSibling, _el$19 = _el$18.nextSibling;
          _el$18.addEventListener("change", (e3) => updateThemeColor(e3.target.value));
          insert(_el$19, () => themeColor2.name.toString());
          createRenderEffect((_p$) => {
            const _v$7 = `background-color: ${themeColor2.hex}`, _v$8 = "themeColor" + themeColor2.name, _v$9 = !!(themeColor2.hex === themeState.color), _v$10 = "themeColor" + themeColor2.name, _v$11 = "themeColor" + themeColor2.name;
            _p$._v$7 = style(_el$17, _v$7, _p$._v$7);
            _v$8 !== _p$._v$8 && setAttribute(_el$17, "for", _p$._v$8 = _v$8);
            _v$9 !== _p$._v$9 && _el$17.classList.toggle("is-selected", _p$._v$9 = _v$9);
            _v$10 !== _p$._v$10 && setAttribute(_el$18, "id", _p$._v$10 = _v$10);
            _v$11 !== _p$._v$11 && setAttribute(_el$19, "for", _p$._v$11 = _v$11);
            return _p$;
          }, {
            _v$7: void 0,
            _v$8: void 0,
            _v$9: void 0,
            _v$10: void 0,
            _v$11: void 0
          });
          createRenderEffect(() => _el$18.value = themeColor2.hex);
          createRenderEffect(() => _el$18.checked = themeColor2.hex === themeState.color);
          return _el$16;
        })()
      }), (() => {
        const _el$12 = _tmpl$420.cloneNode(true), _el$13 = _el$12.firstChild, _el$14 = _el$13.nextSibling, _el$15 = _el$14.nextSibling;
        _el$14.addEventListener("change", () => pickCustomColor(customColor()));
        insert(_el$15, () => _4("Custom"));
        insert(_el$12, createComponent(NgComponent, {
          directive: "account-appearance-color-picker-button",
          get defaultColor() {
            return customColor();
          },
          dropDownOptions: colorPickerOptions
        }), null);
        createRenderEffect((_p$) => {
          const _v$5 = customColor(), _v$6 = !!(customColor() === themeState.color);
          _v$5 !== _p$._v$5 && _el$13.style.setProperty("background-color", _p$._v$5 = _v$5);
          _v$6 !== _p$._v$6 && _el$13.classList.toggle("is-selected", _p$._v$6 = _v$6);
          return _p$;
        }, {
          _v$5: void 0,
          _v$6: void 0
        });
        createRenderEffect(() => _el$14.value = customColor());
        createRenderEffect(() => _el$14.checked = customColor() === themeState.color);
        return _el$12;
      })()];
    }
  })];
}

// public/app/routes/account/panels/Security.jsx
var import_qrious = __toESM(require_qrious());
var _tmpl$118 = /* @__PURE__ */ template(`<button type="button" class="btn btn-primary"></button>`, 2);
var _tmpl$250 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$333 = /* @__PURE__ */ template(`<canvas></canvas>`, 2);
var _tmpl$421 = /* @__PURE__ */ template(`<div><p></p><p><strong></strong></p></div>`, 8);
var _tmpl$518 = /* @__PURE__ */ template(`<div><p></p></div>`, 4);
function SecurityPanel() {
  const logoutAllDevices = async () => {
    await confirmDialog({
      title: _4("Are you sure?")
    });
    const logout = await api_default.user.logout_all_devices.post();
    if (logout) {
      authSession.logout();
    }
  };
  return [createComponent(Show, {
    get when() {
      return serverConfig.user_can_reset_password;
    },
    get children() {
      return createComponent(UpdatePasswordSection, {});
    }
  }), createComponent(Show, {
    get when() {
      return serverConfig.enable_2fa;
    },
    get children() {
      return createComponent(Enable2FaSection, {});
    }
  }), createComponent(Show, {
    get when() {
      return !serverConfig.hide_logout;
    },
    get children() {
      return createComponent(Panel, {
        get header() {
          return _4("Logout");
        },
        get children() {
          return createComponent(Button, {
            style: "primary",
            onClick: logoutAllDevices,
            disableoffline: true,
            get children() {
              return _4("Logout from all devices");
            }
          });
        }
      });
    }
  })];
}
function UpdatePasswordSection() {
  const [form, {
    Form: Form3,
    TextField: TextField2
  }] = createForm2({
    initialValues: {
      userOldPwd: "",
      userNewPwd: ""
    },
    validateOn: "input"
  });
  let timeout = null;
  const [successUpdate, setSuccessUpdate] = createSignal(false);
  const updatePassword = async (values2) => {
    clearTimeout(timeout);
    await api_default.user.update_user_password.post({
      old_password: values2.userOldPwd,
      password: values2.userNewPwd
    });
    setValues(form, {
      "userOldPwd": "",
      "userNewPwd": ""
    }, {
      shouldValidate: false,
      shouldFocus: false,
      shouldTouched: false,
      shouldDirty: false
    });
    setCurrentUser("has_password", true);
    setSuccessUpdate(true);
    timeout = setTimeout(() => {
      setSuccessUpdate(false);
    }, 5e3);
  };
  onCleanup(() => {
    clearTimeout(timeout);
  });
  return createComponent(Panel, {
    get header() {
      return _4("Change your password");
    },
    get children() {
      return createComponent(Form3, {
        "class": "panel-body",
        onSubmit: (values2) => updatePassword(values2),
        get children() {
          return [createComponent(Show, {
            get when() {
              return currentUser2.has_password;
            },
            get children() {
              return createComponent(TextField2, {
                required: true,
                type: "password",
                id: "userOldPwd",
                name: "userOldPwd",
                get label() {
                  return _4("Current password:");
                },
                get validate() {
                  return [required("required")];
                }
              });
            }
          }), createComponent(TextField2, {
            required: true,
            type: "password",
            id: "userNewPwd",
            name: "userNewPwd",
            get label() {
              return _4("New password:");
            },
            get validate() {
              return [required("required")];
            }
          }), createComponent(Button, {
            type: "submit",
            style: "primary",
            get disabled() {
              return form.invalid;
            },
            disableoffline: true,
            get children() {
              return _4("Update");
            }
          }), createComponent(Show, {
            get when() {
              return successUpdate();
            },
            get children() {
              return createComponent(Icon, {
                name: "bi-check-lg",
                "class": "text-success"
              });
            }
          })];
        }
      });
    }
  });
}
function Enable2FaSection() {
  let recoveryCode, otpQRCode;
  const [enabling2FA, setEnabling2FA] = createSignal(false);
  const [form, {
    Form: Form3,
    TextField: TextField2
  }] = createForm2({
    initialValues: {
      user2faCode: ""
    },
    validateOn: "input"
  });
  const enable2FA = async (code2) => {
    const resp = await api_default.user.enable_two_factor_auth.post({
      code: code2.user2faCode || null
    });
    if (resp) {
      setEnabling2FA(true);
      if (resp.recovery_code) {
        recoveryCode = resp.recovery_code;
        setCurrentUser({
          "2fa_enabled": true
        });
      } else {
        const timeout = setTimeout(() => {
          const qr = new import_qrious.default({
            element: otpQRCode,
            value: resp.otpauth_url,
            size: 200
          });
          clearTimeout(timeout);
        });
      }
    }
  };
  const disable2FA = async () => {
    await confirmDialog({
      title: _4("Are you sure?")
    });
    const deleted = await api_default.user.disable_two_factor_auth.delete();
    if (deleted) {
      setEnabling2FA(false);
      setCurrentUser({
        "2fa_enabled": false
      });
    }
  };
  return createComponent(Panel, {
    get header() {
      return _4("Two Factor Authentification");
    },
    get children() {
      return [createComponent(Show, {
        get when() {
          return createMemo(() => !!!currentUser2["2fa_enabled"])() && !enabling2FA();
        },
        get children() {
          const _el$ = _tmpl$118.cloneNode(true);
          _el$.$$click = enable2FA;
          insert(_el$, () => _4("Enable 2FA"));
          return _el$;
        }
      }), createComponent(Show, {
        get when() {
          return createMemo(() => !!!currentUser2["2fa_enabled"])() && enabling2FA();
        },
        get children() {
          return createComponent(Form3, {
            "class": "panel-body",
            onSubmit: (values2) => enable2FA(values2),
            get children() {
              return [(() => {
                const _el$2 = _tmpl$250.cloneNode(true);
                insert(_el$2, () => _4("Scan the following QR code with your 2FA application"));
                return _el$2;
              })(), (() => {
                const _el$3 = _tmpl$333.cloneNode(true);
                const _ref$ = otpQRCode;
                typeof _ref$ === "function" ? use(_ref$, _el$3) : otpQRCode = _el$3;
                return _el$3;
              })(), createComponent(TextField2, {
                required: true,
                id: "user2faCode",
                name: "user2faCode",
                get label() {
                  return _4("Enter a valid code to activate 2FA:");
                },
                get validate() {
                  return [required("required")];
                }
              }), createComponent(Button, {
                type: "submit",
                style: "primary",
                get disabled() {
                  return form.invalid;
                },
                get children() {
                  return _4("Activate");
                }
              })];
            }
          });
        }
      }), createComponent(Show, {
        get when() {
          return currentUser2["2fa_enabled"];
        },
        get children() {
          const _el$4 = _tmpl$518.cloneNode(true), _el$5 = _el$4.firstChild;
          insert(_el$5, () => _4("Two Factor Authentfication is enabled on your account"));
          insert(_el$4, createComponent(Show, {
            get when() {
              return enabling2FA();
            },
            get children() {
              const _el$6 = _tmpl$421.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.nextSibling, _el$9 = _el$8.firstChild;
              insert(_el$7, () => _4("Note down the following one-time recovery password in case your device is lost:"));
              insert(_el$9, recoveryCode);
              return _el$6;
            }
          }), null);
          insert(_el$4, createComponent(Button, {
            style: "danger",
            onClick: disable2FA,
            get children() {
              return _4("Disable 2FA");
            }
          }), null);
          return _el$4;
        }
      })];
    }
  });
}
delegateEvents(["click"]);

// public/app/routes/account/panels/ThirdParty.jsx
var _tmpl$119 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$251 = /* @__PURE__ */ template(`<div class="panel-body"><p></p></div>`, 4);
var _tmpl$334 = /* @__PURE__ */ template(`<ul class="list-group"></ul>`, 2);
var _tmpl$422 = /* @__PURE__ */ template(`<li class="list-group-item"><div class="list-group-item-description"></div></li>`, 4);
var _tmpl$519 = /* @__PURE__ */ template(`<p><a class="btn btn-default" target="_self"></a></p>`, 4);
function ThirdPartyPanel() {
  const [providers, setProviders] = createSignal();
  const [accounts, setAccounts] = createSignal();
  const refresh = async () => {
    const accounts2 = await api_default.user.list_third_party_accounts.get();
    if (accounts2) setAccounts(accounts2);
  };
  onMount(async () => {
    const fetchedProviders = await api_default.third_party_account_providers.list_third_party_account_providers.get();
    if (fetchedProviders) setProviders(fetchedProviders.filter((p4) => !!p4.login_url));
    await refresh();
  });
  const isConnected2 = (provider) => {
    return (accounts() || []).filter((acc) => acc.provider === provider).length > 0;
  };
  const remove3 = async (account) => {
    await api_default.user.remove_third_party_account.delete({
      provider: account.provider
    });
    await refresh();
  };
  const notConnectedProviders = createMemo(() => providers()?.filter((p4) => !isConnected2(p4.provider)) || []);
  return [createComponent(Panel, {
    withBody: false,
    get header() {
      return _4("Third-party accounts");
    },
    get children() {
      return [(() => {
        const _el$ = _tmpl$251.cloneNode(true), _el$2 = _el$.firstChild;
        insert(_el$2, () => _4("Connect or disconnect third-party accounts"));
        insert(_el$, createComponent(Show, {
          get when() {
            return createMemo(() => !!accounts())() && accounts().length === 0;
          },
          get children() {
            const _el$3 = _tmpl$119.cloneNode(true);
            insert(_el$3, () => _4("No accounts"));
            return _el$3;
          }
        }), null);
        return _el$;
      })(), (() => {
        const _el$4 = _tmpl$334.cloneNode(true);
        insert(_el$4, createComponent(For, {
          get each() {
            return accounts();
          },
          children: (account) => (() => {
            const _el$5 = _tmpl$422.cloneNode(true), _el$6 = _el$5.firstChild;
            insert(_el$6, () => account.name);
            insert(_el$5, createComponent(IconButton, {
              onClick: () => remove3(account),
              size: "sm",
              style: "danger",
              icon: "trash",
              get tooltip() {
                return {
                  label: _4("Disconnect")
                };
              },
              hideoffline: true
            }), null);
            return _el$5;
          })()
        }));
        return _el$4;
      })()];
    }
  }), createComponent(Show, {
    get when() {
      return notConnectedProviders().length > 0;
    },
    get children() {
      return createComponent(Panel, {
        get header() {
          return _4("Connect new third-party account");
        },
        get children() {
          return createComponent(For, {
            get each() {
              return notConnectedProviders();
            },
            children: (provider) => (() => {
              const _el$7 = _tmpl$519.cloneNode(true), _el$8 = _el$7.firstChild;
              insert(_el$8, createComponent(Show, {
                get when() {
                  return provider.icon;
                },
                get children() {
                  return createComponent(Icon, {
                    get name() {
                      return provider.icon;
                    }
                  });
                }
              }), null);
              insert(_el$8, () => provider.login_label, null);
              createRenderEffect(() => setAttribute(_el$8, "href", provider.login_url));
              return _el$7;
            })()
          });
        }
      });
    }
  })];
}

// public/app/ui/utils/processingStatus.jsx
function usePromiseStatus() {
  const [status, setStatus] = createSignal();
  const [data2, setData] = createSignal();
  return [status, (start) => {
    setStatus("pending");
    return start().then((data3) => {
      setData(data3);
      setStatus("resolved");
      return data3;
    }).catch((e3) => {
      setStatus("rejected");
      return Promise.reject(e3);
    });
  }, data2];
}
function ButtonStatus(props2) {
  const resolved = children(() => props2.children);
  const [showSuccess, setShowSuccess] = createSignal(false);
  let originalLabel = resolved.toArray()[0].innerHTML;
  createEffect(() => {
    const btns = resolved.toArray();
    if (props2.status === "pending") {
      setShowSuccess(false);
      for (const btn of btns) {
        if (btn) {
          btn.disabled = true;
          if (props2.labelWhenPending) {
            originalLabel = btn.innerHTML;
            btn.innerHTML = props2.labelWhenPending.toString();
          }
        }
      }
    } else {
      for (const btn of btns) {
        if (btn) {
          btn.disabled = false;
          if (props2.labelWhenPending) {
            btn.innerHTML = originalLabel.toString();
          }
        }
      }
      if (props2.status === "resolved") {
        setShowSuccess(true);
      }
    }
  });
  return [createMemo(resolved), createComponent(Show, {
    get when() {
      return showSuccess();
    },
    get children() {
      return createComponent(Icon, {
        name: "fa-check",
        "class": "text-success ms-3"
      });
    }
  })];
}

// public/app/routes/account/panels/Developer.jsx
var _tmpl$120 = /* @__PURE__ */ template(`<p> <a href="https://kantree.io/help/api" target="_blank"></a></p>`, 4);
var _tmpl$252 = /* @__PURE__ */ template(`<p><strong></strong></p>`, 4);
var _tmpl$335 = /* @__PURE__ */ template(`<div class="panel-body"><p></p></div>`, 4);
var _tmpl$423 = /* @__PURE__ */ template(`<ul class="list-group"></ul>`, 2);
var _tmpl$520 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$616 = /* @__PURE__ */ template(`<li class="list-group-item"><div class="list-group-item-description"></div></li>`, 4);
var _tmpl$715 = /* @__PURE__ */ template(`<div class="form-group"></div>`, 2);
var _tmpl$813 = /* @__PURE__ */ template(`<div class="form-group mb-3"><p class="form-label">:</p></div>`, 4);
var _tmpl$911 = /* @__PURE__ */ template(`<div class="d-flex justify-content-end align-items-center"></div>`, 2);
function DeveloperPanel() {
  const [apiKeys, setApiKeys] = createSignal([]);
  const [oauthApps, setOauthApps] = createSignal([]);
  const [oauthApp, {
    Form: Form3,
    TextAreaField,
    TextField: TextField2,
    CheckField
  }] = createForm2({
    validateOn: "input"
  });
  const refreshOAuthApps = async () => {
    const apps = await api_default.oauth.list_apps.get();
    if (apps) setOauthApps(apps);
  };
  onMount(async () => {
    const fetchedApiKeys = await api_default.user.list_api_keys.get();
    if (fetchedApiKeys) setApiKeys(fetchedApiKeys);
    await refreshOAuthApps();
  });
  const createApiKey = async () => {
    const apiKey = await api_default.user.create_api_key.post();
    if (apiKey) setApiKeys((prev) => [...prev, apiKey]);
  };
  const revokeApiKey = async (apiKey) => {
    await confirmDeleteDialog2();
    const revoked = api_default.user.revoke_api_key.delete({
      key: apiKey.key
    });
    if (revoked) setApiKeys((prev) => prev.filter((k2) => k2.key !== apiKey.key));
  };
  const removeOAuthApp = async (app) => {
    await confirmDeleteDialog2();
    const deleted = await api_default.oauth.delete_app.delete({
      app_id: app.id
    });
    if (deleted) await refreshOAuthApps();
  };
  const editOauthApp = (app) => {
    for (const field2 in app) {
      if (field2 === "scope") {
        const scope = Object.fromEntries((app.scope || "").split(" ").map((s3) => [s3, true]));
        for (let scopeField in scope) {
          setValue(oauthApp, "scope." + scopeField, true);
        }
      } else if (field2 === "redirect_uris") {
        setValue(oauthApp, "redirect_uris", (app.redirect_uris || []).join("\n"));
      } else {
        setValue(oauthApp, field2, app[field2]);
      }
    }
  };
  return [createComponent(Show, {
    get when() {
      return getValue(oauthApp, "name", {
        shouldActive: false
      }) === void 0;
    },
    get children() {
      return [(() => {
        const _el$ = _tmpl$120.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
        insert(_el$, () => _4("Control & integrate with Kantree."), _el$2);
        insert(_el$3, () => _4("API documentation"));
        return _el$;
      })(), createComponent(Panel, {
        get header() {
          return _4("API Key");
        },
        get children() {
          return [(() => {
            const _el$4 = _tmpl$252.cloneNode(true), _el$5 = _el$4.firstChild;
            insert(_el$5, () => _4("Your personal api key. Do not share it with anyone"));
            return _el$4;
          })(), createComponent(For, {
            get each() {
              return apiKeys();
            },
            children: (key2) => (() => {
              const _el$9 = _tmpl$520.cloneNode(true);
              insert(_el$9, createComponent(Show, {
                when: key2,
                get children() {
                  return createComponent(CopyableReadonlyInput, {
                    get value() {
                      return key2.key;
                    },
                    containerClass: "mb-2"
                  });
                }
              }), null);
              insert(_el$9, createComponent(Button, {
                style: "danger",
                onClick: () => revokeApiKey(key2),
                disableoffline: true,
                get label() {
                  return [createComponent(Icon, {
                    name: "trash"
                  }), " ", createMemo(() => _4("Revoke API key"))];
                }
              }), null);
              return _el$9;
            })()
          }), createComponent(Show, {
            get when() {
              return !apiKeys().length;
            },
            get children() {
              return createComponent(Button, {
                style: "primary",
                onClick: () => createApiKey(),
                disableoffline: true,
                get label() {
                  return _4("Request an API key");
                }
              });
            }
          })];
        }
      }), createComponent(Panel, {
        withBody: false,
        get header() {
          return _4("OAuth apps");
        },
        get children() {
          return [(() => {
            const _el$6 = _tmpl$335.cloneNode(true), _el$7 = _el$6.firstChild;
            insert(_el$7, () => _4("Create third-party apps which can safely connect to Kantree's accounts"));
            return _el$6;
          })(), (() => {
            const _el$8 = _tmpl$423.cloneNode(true);
            insert(_el$8, createComponent(For, {
              get each() {
                return oauthApps();
              },
              children: (localOauthApp) => (() => {
                const _el$10 = _tmpl$616.cloneNode(true), _el$11 = _el$10.firstChild;
                insert(_el$11, () => capitalize(localOauthApp.name));
                insert(_el$10, createComponent(IconButton, {
                  size: "sm",
                  onClick: () => editOauthApp(localOauthApp),
                  icon: "fa-pencil",
                  get tooltip() {
                    return {
                      label: _4("Edit")
                    };
                  }
                }), null);
                insert(_el$10, createComponent(Tooltip, {
                  get label() {
                    return _4("Remove");
                  },
                  get children() {
                    return createComponent(IconButton, {
                      style: "danger",
                      size: "sm",
                      onClick: () => removeOAuthApp(localOauthApp),
                      icon: "trash"
                    });
                  }
                }), null);
                return _el$10;
              })()
            }));
            return _el$8;
          })(), createComponent(Button, {
            style: "primary",
            onClick: () => setValue(oauthApp, "name", ""),
            get children() {
              return [createComponent(Icon, {
                name: "bi-plus-lg"
              }), " ", createMemo(() => _4("Create"))];
            }
          })];
        }
      })];
    }
  }), createComponent(Show, {
    get when() {
      return getValue(oauthApp, "name", {
        shouldActive: false
      }) != void 0;
    },
    get children() {
      return createComponent(OauthAppEditor, {
        app: oauthApp,
        Form: Form3,
        TextAreaField,
        TextField: TextField2,
        CheckField,
        onCancel: async () => {
          reset2(oauthApp);
          setValue(oauthApp, "name", void 0);
          await refreshOAuthApps();
        }
      });
    }
  })];
}
function OauthAppEditor(props2) {
  const [status, start] = usePromiseStatus();
  const save = async (values2) => {
    const data2 = {
      name: values2.name,
      description: values2.description,
      client_uri: values2.client_uri,
      redirect_uris: values2.redirect_uris.split("\n").filter(Boolean),
      scope: Object.keys(values2.scope).filter((k2) => values2.scope[k2]).join(" "),
      trusted: values2.trusted,
      system_app: values2.system_app || false
    };
    let req;
    if (values2.id) {
      data2["app_id"] = values2.id;
      req = api_default.oauth.update_app.put(data2);
    } else {
      req = api_default.oauth.create_app.post(data2);
    }
    const response = await req;
    return () => {
      if (response) {
        if (!values2.id) {
          setValue(props2.app, "id", response.id);
          setValue(props2.app, "client_id", response.client_id);
          setValue(props2.app, "client_secret", response.client_secret);
        }
        props2.onSave?.(data2);
      }
    };
  };
  return createComponent(props2.Form, {
    onSubmit: (values2) => start(() => save(values2)),
    get children() {
      return [createComponent(props2.TextField, {
        type: "hidden",
        name: "id",
        id: "id",
        disabled: true
      }), createComponent(Show, {
        get when() {
          return getValue(props2.app, "id");
        },
        get children() {
          return createComponent(Panel, {
            get header() {
              return _4("OAuth app credentials");
            },
            get children() {
              return [createComponent(Show, {
                get when() {
                  return props2.app.user;
                },
                get children() {
                  return createComponent(props2.TextField, {
                    type: "text",
                    name: "username",
                    id: "username",
                    get label() {
                      return [createMemo(() => _4("User")), ":"];
                    },
                    disabled: true
                  });
                }
              }), createComponent(props2.TextField, {
                type: "text",
                name: "client_id",
                id: "client_id",
                get label() {
                  return [createMemo(() => _4("Client ID")), ":"];
                },
                disabled: true
              }), createComponent(props2.TextField, {
                type: "text",
                name: "client_secret",
                id: "client_secret",
                get label() {
                  return [createMemo(() => _4("Client Secret")), ":"];
                },
                disabled: true
              })];
            }
          });
        }
      }), createComponent(Panel, {
        get header() {
          return _4("OAuth app details");
        },
        get children() {
          return [createComponent(props2.TextField, {
            type: "text",
            name: "name",
            id: "name",
            get label() {
              return [createMemo(() => _4("Name")), "*:"];
            },
            required: true,
            get validate() {
              return [required("required")];
            }
          }), (() => {
            const _el$12 = _tmpl$715.cloneNode(true);
            insert(_el$12, createComponent(props2.TextAreaField, {
              get label() {
                return [createMemo(() => _4("Description")), ":"];
              },
              id: "description",
              name: "description"
            }));
            return _el$12;
          })(), createComponent(Show, {
            get when() {
              return currentUser2.is_kantree_admin;
            },
            get children() {
              return createComponent(props2.CheckField, {
                containerClass: "form-switch",
                name: "trusted",
                id: "trusted",
                get label() {
                  return _4("Trusted");
                },
                get checked() {
                  return getValue(props2.app, "trusted");
                }
              });
            }
          }), createComponent(props2.TextField, {
            type: "url",
            name: "client_uri",
            id: "client_uri",
            get label() {
              return [createMemo(() => _4("Homepage URL")), "*:"];
            },
            required: true,
            get validate() {
              return [required("required"), url("url")];
            }
          }), createComponent(props2.TextAreaField, {
            get label() {
              return [createMemo(() => _4("Callback URLs")), "*:"];
            },
            id: "redirect_uris",
            name: "redirect_uris",
            required: true,
            get validate() {
              return [required("required")];
            }
          }), (() => {
            const _el$13 = _tmpl$813.cloneNode(true), _el$14 = _el$13.firstChild, _el$15 = _el$14.firstChild;
            insert(_el$14, () => _4("Permissions"), _el$15);
            insert(_el$13, createComponent(props2.CheckField, {
              containerClass: "form-switch",
              id: "scope.read_user",
              onChange: (e3) => setValue(props2.app, "scope.read_user", e3.target.checked),
              name: "scope.read_user",
              get label() {
                return _4("Read user info");
              },
              get checked() {
                return getValue(props2.app, "scope.read_user");
              }
            }), null);
            insert(_el$13, createComponent(props2.CheckField, {
              containerClass: "form-switch",
              id: "scope.read_workspace",
              onChange: (e3) => setValue(props2.app, "scope.read_workspace", e3.target.checked),
              name: "scope.read_workspace",
              get label() {
                return _4("Read-only access to workspaces");
              },
              get checked() {
                return getValue(props2.app, "scope.read_workspace");
              }
            }), null);
            insert(_el$13, createComponent(props2.CheckField, {
              containerClass: "form-switch",
              id: "scope.write_workspace",
              onChange: (e3) => setValue(props2.app, "scope.write_workspace", e3.target.checked),
              name: "scope.write_workspace",
              get label() {
                return _4("Read/Write access to workspaces");
              },
              get checked() {
                return getValue(props2.app, "scope.write_workspace");
              }
            }), null);
            return _el$13;
          })(), (() => {
            const _el$16 = _tmpl$911.cloneNode(true);
            insert(_el$16, createComponent(Button, {
              "class": "btn-ghost",
              onClick: () => props2.onCancel?.(),
              get children() {
                return _4("Cancel");
              }
            }), null);
            insert(_el$16, createComponent(ButtonStatus, {
              get status() {
                return status();
              },
              labelWhenPending: "Saving...",
              get children() {
                return createComponent(Button, {
                  style: "success",
                  "class": "ms-1",
                  type: "submit",
                  get disabled() {
                    return props2.app.invalid;
                  },
                  get children() {
                    return _4("Save");
                  }
                });
              }
            }), null);
            return _el$16;
          })()];
        }
      })];
    }
  });
}

// public/app/routes/account/panels/Delete.jsx
var _tmpl$121 = /* @__PURE__ */ template(`<p><br></p>`, 3);
var _tmpl$253 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$336 = /* @__PURE__ */ template(`<p><strong></strong></p>`, 4);
function DeleteAccountPanel() {
  const [loading, setLoading] = createSignal(true);
  const [canBeDeleted, setCanBeDeleted] = createSignal(false);
  const [deleting, setDeleting] = createSignal(false);
  const [deleteForm, {
    Form: Form3,
    TextField: TextField2
  }] = createForm2({
    initialValues: {
      password: ""
    },
    validateOn: "input"
  });
  onMount(async () => {
    const can = await api_default.user.can_be_deleted.get();
    setCanBeDeleted(can);
    setLoading(false);
  });
  const deleteAccount = async (values2) => {
    setDeleting(true);
    try {
      const deleted = await api_default.user.delete.delete({
        password: values2.password
      }, {
        ignoreErrorHandlers: true
      });
      if (deleted) {
        authSession.logout();
        autoCatchAsRequestErrorDialog([403]);
      }
    } catch (err) {
      setDeleting(false);
    }
  };
  return [createComponent(Show, {
    get when() {
      return loading();
    },
    get children() {
      return createComponent(LoadingIndicator, {});
    }
  }), createComponent(Show, {
    get when() {
      return createMemo(() => !!!loading())() && !canBeDeleted();
    },
    get children() {
      const _el$ = _tmpl$121.cloneNode(true), _el$2 = _el$.firstChild;
      insert(_el$, () => _4("As it currently stands, you cannot delete your account."), _el$2);
      insert(_el$, () => _4("To be able to delete it, please settle your outstanding invoices or transfer ownership of your organization."), null);
      return _el$;
    }
  }), createComponent(Show, {
    get when() {
      return createMemo(() => !!!loading())() && canBeDeleted();
    },
    get children() {
      return createComponent(Form3, {
        onSubmit: (values2) => deleteAccount(values2),
        get children() {
          return [(() => {
            const _el$3 = _tmpl$253.cloneNode(true);
            insert(_el$3, () => _4("We are very sorry to see you leave. If there is anything we can do to make your experience with Kantree better, do not hesitate to drop us a line at contact@kantree.io."));
            return _el$3;
          })(), (() => {
            const _el$4 = _tmpl$336.cloneNode(true), _el$5 = _el$4.firstChild;
            insert(_el$5, () => _4("This is a permanent deletion. We will not be able to recover your account!"));
            return _el$4;
          })(), createComponent(TextField2, {
            type: "password",
            required: true,
            name: "password",
            id: "userPwd",
            get label() {
              return _4("Password:");
            },
            get validate() {
              return [required("required")];
            }
          }), createComponent(Button, {
            type: "submit",
            style: "danger",
            get disabled() {
              return deleteForm.invalid || deleting();
            },
            disableoffline: true,
            get label() {
              return createMemo(() => !!deleting())() ? _4("Deleting...") : _4("Delete your account");
            }
          })];
        }
      });
    }
  })];
}

// public/app/routes/account/panels/index.jsx
var accountPanels = [{
  name: "settings",
  title: _lazy("Account"),
  path: "/",
  component: SettingsPanel
}, {
  name: "appearance",
  title: _lazy("Appearance"),
  path: "/appearance",
  component: AppearancePanel
}, {
  name: "security",
  title: _lazy("Security"),
  path: "/security",
  component: SecurityPanel,
  enabled: () => (serverConfig.user_can_reset_password || serverConfig.enable_2fa) && isConnected()
}, {
  name: "third-party-accounts",
  title: _lazy("Third-party accounts"),
  path: "/third-party-accounts",
  component: ThirdPartyPanel,
  enabled: () => isConnected()
}, {
  name: "developer",
  title: _lazy("Developer"),
  path: "/developer",
  component: DeveloperPanel,
  enabled: () => !serverConfig.disable_user_api_keys && isConnected()
}, {
  name: "delete",
  title: _lazy("Delete account"),
  path: "/delete",
  component: DeleteAccountPanel,
  enabled: () => serverConfig.user_can_delete_account && isConnected()
}];
var panels_default = accountPanels;

// public/app/routes/account/AccountPage.jsx
var _tmpl$123 = /* @__PURE__ */ template(`<div></div>`, 2);
function AccountPage(props2) {
  const navigate2 = useNavigate2();
  fetchCurrentUserData(true);
  const panels = panels_default.filter((panel) => !panel.enabled || panel.enabled());
  const sidebarConfig = {
    header: [{
      type: "page-header",
      options: {
        title: _4("Account settings")
      }
    }],
    content: panels.map((panel) => {
      const active = useMatch(() => "/account" + panel.path);
      return {
        panel,
        type: "button",
        options: {
          label: panel.title,
          icon: panel.icon,
          action: () => navigate2("/account" + panel.path)
        },
        active
      };
    })
  };
  return [createComponent(NavSidebar, {
    config: sidebarConfig
  }), createComponent(PageContainer, {
    get children() {
      return [createComponent(TopBar, {}), createComponent(PageContainerView, {
        id: "user-view",
        get children() {
          const _el$ = _tmpl$123.cloneNode(true);
          insert(_el$, createComponent(Show, {
            get when() {
              return currentUser2.needs_terms_validation;
            },
            get children() {
              return createComponent(Alert, {
                style: "info",
                actionnable: true,
                get children() {
                  return [createComponent(AlertContent, {
                    get children() {
                      return [createComponent(Icon, {
                        name: "bi-info-square-fill"
                      }), " ", createMemo(() => _4("We have updated our terms and they require your validation"))];
                    }
                  }), createComponent(Button, {
                    style: "info",
                    onClick: () => openTermsModal(),
                    get label() {
                      return _4("View");
                    }
                  })];
                }
              });
            }
          }), null);
          insert(_el$, () => props2.children, null);
          return _el$;
        }
      })];
    }
  })];
}

// public/app/utils/angular/index.js
var AngularClass = class {
  constructor(...args) {
    if (this.constructor.$inject) {
      this.constructor.$inject.forEach((dependency, i3) => {
        this[dependency.substr(0, 1) === "$" ? dependency : "$" + dependency] = args[i3];
      });
    }
  }
};
function angularClassMixin(supercls, ...mixins) {
  const cls = class extends supercls {
    static $injectFromMixins = [];
    static get $inject() {
      return (super.$inject || []).concat(cls.$injectFromMixins);
    }
  };
  for (let mixin3 of mixins) {
    if (typeof mixin3["$inject"] !== "undefined") {
      cls.$injectFromMixins.push(...mixin3.$inject);
    }
    const mixinPropKeys = Object.getOwnPropertyNames(mixin3);
    for (let propKey of mixinPropKeys) {
      if (propKey !== "constructor") {
        const desc = Object.getOwnPropertyDescriptor(mixin3, propKey);
        Object.defineProperty(cls.prototype, propKey, desc);
      }
    }
  }
  return cls;
}
function bindToScope(scope, func) {
  scope.$on("$destroy", func());
}
function $onEvent(scope, event2, fn) {
  scope.$on("$destroy", event2.subscribe((...args) => {
    fn(...args);
    scope.$applyAsync();
  }));
}

// public/app/routes/account/ng-components/appearanceColorPickerButton.js
angular_default.module("kantree").component("accountAppearanceColorPickerButton", {
  bindings: {
    defaultColor: "<",
    dropDownOptions: "<"
  },
  template: `
      <button class="btn btn-link btn-sm"
        drop-menu="$ctrl.colorPickerOptions"
        ng-style="{color: $ctrl.textColor($ctrl.defaultColor)}">
        {{::_('Change')}}
      </button>`,
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.textColor = textColor;
      this.colorPickerOptions = this.dropDownOptions;
    }
  }
});

// public/app/routes/account/index.jsx
addRoute({
  name: "account",
  path: "/account",
  component: (props2) => createComponent(AuthenticatedPage, {
    preventOnboardingRedirect: true,
    get children() {
      return createComponent(AccountPage, {
        get children() {
          return props2.children;
        }
      });
    }
  }),
  children: panels_default.map((panel) => ({
    name: panel.name,
    path: panel.path,
    component: panel.component
  }))
});

// public/app/routes/route-data.jsx
var _tmpl$124 = /* @__PURE__ */ template(`<div class="router-loader-indicator text-center"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid"><g transform="translate(20 50)"><circle cx="0" cy="0" r="6" fill="#e6e6e6"><animateTransform attributeName="transform" type="scale" begin="-0.375s" calcMode="spline" keySplines="0.3 0 0.7 1;0.3 0 0.7 1" values="0;1;0" keyTimes="0;0.5;1" dur="1s" repeatCount="indefinite"></animateTransform></circle></g><g transform="translate(40 50)"><circle cx="0" cy="0" r="6" fill="#bbbbbb"><animateTransform attributeName="transform" type="scale" begin="-0.25s" calcMode="spline" keySplines="0.3 0 0.7 1;0.3 0 0.7 1" values="0;1;0" keyTimes="0;0.5;1" dur="1s" repeatCount="indefinite"></animateTransform></circle></g><g transform="translate(60 50)"><circle cx="0" cy="0" r="6" fill="#a6a6a6"><animateTransform attributeName="transform" type="scale" begin="-0.125s" calcMode="spline" keySplines="0.3 0 0.7 1;0.3 0 0.7 1" values="0;1;0" keyTimes="0;0.5;1" dur="1s" repeatCount="indefinite"></animateTransform></circle></g><g transform="translate(80 50)"><circle cx="0" cy="0" r="6" fill="#848484"><animateTransform attributeName="transform" type="scale" begin="0s" calcMode="spline" keySplines="0.3 0 0.7 1;0.3 0 0.7 1" values="0;1;0" keyTimes="0;0.5;1" dur="1s" repeatCount="indefinite"></animateTransform></circle></g></svg></div>`, 28);
var _tmpl$254 = /* @__PURE__ */ template(`<div class="page-container"></div>`, 2);
var RouteDataContext = createContext();
function useRouteData() {
  return useContext(RouteDataContext);
}
function RouteData(props2) {
  const data2 = props2.loader();
  const [isLoading, setLoading] = createSignal(data2.loading);
  let isFirstLoad = true;
  createEffect(() => {
    if (data2.loading) {
      if (!isFirstLoad && !props2.hideTransition) {
        setLoading(true);
      }
    } else {
      setLoading(false);
      if (isFirstLoad) {
        isFirstLoad = false;
        if (props2.onBeforeLeave) {
          useBeforeLeave(props2.onBeforeLeave);
        }
        if (props2.onCleanup) {
          onCleanup(props2.onCleanup);
        }
      } else if (props2.onDataReload) {
        untrack(() => props2.onDataReload(data2()));
      }
    }
  });
  return createComponent(RouteDataContext.Provider, {
    value: data2,
    get children() {
      return [createComponent(Show, {
        get when() {
          return isLoading() && !props2.hideLoader;
        },
        get children() {
          return props2.indicator || createComponent(RouteLoaderIndicator, {});
        }
      }), createComponent(Show, {
        get when() {
          return !isLoading() && !data2.error;
        },
        get children() {
          return props2.children;
        }
      }), createComponent(Show, {
        get when() {
          return data2.error;
        },
        get children() {
          return [createComponent(Show, {
            get when() {
              return props2.onError;
            },
            get children() {
              return props2.onError(data2.error);
            }
          }), createComponent(Show, {
            get when() {
              return !props2.onError;
            },
            get children() {
              return createComponent(RouteLoaderError, {
                get error() {
                  return data2.error;
                }
              });
            }
          })];
        }
      })];
    }
  });
}
function RouteLoaderIndicator() {
  return _tmpl$124.cloneNode(true);
}
function RouteLoaderError(props2) {
  return (() => {
    const _el$2 = _tmpl$254.cloneNode(true);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props2.error.status === 404;
      },
      get children() {
        return _4("Page not found");
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props2.error.status !== 404;
      },
      get children() {
        return _4("An error occured");
      }
    }), null);
    return _el$2;
  })();
}

// public/app/routes/admin/components/OauthPanel.jsx
init_icons();
var _tmpl$125 = /* @__PURE__ */ template(`<i class="bi-plus-lg"></i>`, 2);
var _tmpl$255 = /* @__PURE__ */ template(`<div class="admin-filter"></div>`, 2);
var _tmpl$337 = /* @__PURE__ */ template(`<div class="page-container"><div class="admin-view page-container-view" id="admin-oauth-panel"></div></div>`, 4);
var _tmpl$424 = /* @__PURE__ */ template(`<th ng-if="selectable"></th>`, 2);
var _tmpl$521 = /* @__PURE__ */ template(`<th></th>`, 2);
var _tmpl$617 = /* @__PURE__ */ template(`<tr class="loader"><td><i class="fa fa-spin fa-spinner"></i> </td></tr>`, 6);
var _tmpl$716 = /* @__PURE__ */ template(`<tfoot><tr><td><div class="btn-group"></div></td></tr></tfoot>`, 8);
var _tmpl$814 = /* @__PURE__ */ template(`<a class="page-link" href="javascript:void(0);"><span>&raquo;&raquo;</span></a>`, 4);
var _tmpl$912 = /* @__PURE__ */ template(`<a href="javascript:void(0);" ng-show="export"></a>`, 2);
var _tmpl$1010 = /* @__PURE__ */ template(`<nav ng-if="paginated"><ul class="pagination"><li class="page-item"><a class="page-link" href="javascript:void(0);"><span>&laquo;&laquo;</span></a></li><li class="page-item"><a class="page-link" href="javascript:void(0);"><span>&laquo;</span></a></li><li class="page-item"><a class="page-link" href="javascript:void(0);"><span>&raquo;</span></a></li><li class="page-item"></li></ul><p class="align-center"></p></nav>`, 26);
var _tmpl$1110 = /* @__PURE__ */ template(`<div class="admin-table"><table class="table table-striped table-bordered table-hover"><thead><tr></tr></thead><tbody></tbody></table></div>`, 10);
var _tmpl$126 = /* @__PURE__ */ template(`<i></i>`, 2);
var _tmpl$133 = /* @__PURE__ */ template(`<a href="javascript:void(0);"></a>`, 2);
var _tmpl$143 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$153 = /* @__PURE__ */ template(`<td ng-if="selectable"><input class="form-check-input" type="checkbox"></td>`, 3);
var _tmpl$163 = /* @__PURE__ */ template(`<td></td>`, 2);
var _tmpl$172 = /* @__PURE__ */ template(`<tr></tr>`, 2);
var _tmpl$182 = /* @__PURE__ */ template(`<a navigate-to="{{col.link(row[col.property], row)}}" ng-if="col.link"></a>`, 2);
var _tmpl$192 = /* @__PURE__ */ template(`<div ng-bind-html="col.widget(row[col.property], row)"></div>`, 2);
var _tmpl$202 = /* @__PURE__ */ template(`<td uib-tooltip="{{col.tooltip ? col.tooltip(row[col.property], row) : ''}}"></td>`, 2);
var _tmpl$2110 = /* @__PURE__ */ template(`<button class="btn btn-default btn-icon"><i></i></button>`, 4);
var _tmpl$2210 = /* @__PURE__ */ template(`<button class="btn btn-default"></button>`, 2);
var _tmpl$2310 = /* @__PURE__ */ template(`<li class="page-item"><a href="javascript:void(0);" class="page-link"><span></span></a></li>`, 6);
function AdminOauthPanel() {
  const [oauthApp, {
    Form: Form3,
    TextAreaField,
    TextField: TextField2,
    CheckField
  }] = createForm2({
    validateOn: "input"
  });
  const columns2 = [{
    title: "#ID",
    property: "id"
  }, {
    title: _4("Name"),
    property: "name",
    click: function(value2, app) {
      for (const field2 in app) {
        if (field2 === "scope") {
          const scope = Object.fromEntries((app.scope || "").split(" ").map((s3) => [s3, true]));
          for (let scopeField in scope) {
            setValue(oauthApp, "scope." + scopeField, true);
          }
        } else if (field2 === "redirect_uris") {
          setValue(oauthApp, "redirect_uris", (app.redirect_uris || []).join("\n"));
        } else {
          setValue(oauthApp, field2, app[field2]);
        }
      }
    }
  }, {
    title: _4("URL"),
    property: "client_uri",
    link: function(_5, o3) {
      return o3.client_uri;
    }
  }, {
    title: _4("Trusted"),
    property: "trusted",
    format: function(value2) {
      return value2 ? "Yes" : "No";
    }
  }, {
    title: _4("System app"),
    property: "user",
    format: function(value2) {
      return value2 ? "No" : "Yes";
    }
  }];
  function createApp() {
    setValues(oauthApp, {
      name: "",
      system_app: true
    });
  }
  function load2(cb2) {
    api_default.oauth.list_apps.get({
      all: true
    }).then(cb2);
  }
  load2.$inject = ["cb"];
  function loader10(cb2) {
    api_default.oauth.list_apps.get({
      all: true
    }).then(cb2);
  }
  return (() => {
    const _el$ = _tmpl$337.cloneNode(true), _el$4 = _el$.firstChild;
    insert(_el$, createComponent(TopBar, {
      get children() {
        const _el$2 = _tmpl$255.cloneNode(true);
        insert(_el$2, createComponent(Show, {
          get when() {
            return getValue(oauthApp, "name", {
              shouldActive: false
            }) === void 0;
          },
          get children() {
            return createComponent(Button, {
              "class": "btn-primary",
              onClick: () => createApp(),
              get children() {
                return [_tmpl$125.cloneNode(true), " ", createMemo(() => _4("Add new app"))];
              }
            });
          }
        }));
        return _el$2;
      }
    }), _el$4);
    insert(_el$4, createComponent(Show, {
      get when() {
        return getValue(oauthApp, "name", {
          shouldActive: false
        }) === void 0;
      },
      get children() {
        return createComponent(AdminTable, {
          loader: ({
            cb: cb2
          }) => loader10(cb2),
          columns: columns2
        });
      }
    }), null);
    insert(_el$4, createComponent(Show, {
      get when() {
        return getValue(oauthApp, "name", {
          shouldActive: false
        }) !== void 0;
      },
      get children() {
        return createComponent(OauthAppEditor, {
          app: oauthApp,
          Form: Form3,
          TextAreaField,
          TextField: TextField2,
          CheckField,
          onCancel: async () => {
            reset2(oauthApp);
            setValue(oauthApp, "name", void 0);
          }
        });
      }
    }), null);
    return _el$;
  })();
}
function AdminTable(props2) {
  const [local, others] = splitProps(props2, ["columns", "loader", "rows", "filter", "paginated", "actions", "sortable", "export", "selectedRows", "selectable"]);
  const [page, setPage] = createSignal(1);
  const [totalResults, setTotalResults] = createSignal(0);
  const [nextPage, setNextPage] = createSignal(0);
  const [prevPage, setPrevPage] = createSignal(null);
  const [lastPage, setLastPage] = createSignal(null);
  const [pages, setPages] = createSignal([]);
  const [sortBy3, setSortBy2] = createSignal(null);
  const [sortAsc, setSortAsc] = createSignal(false);
  const [selectedRows, setSelectedRows] = createSignal([]);
  const [loading, setLoading] = createSignal(true);
  const [rows, setRows] = createSignal(local.rows || []);
  function toggleRowSelection(row) {
    if (selectedRows().indexOf(row) === -1) {
      setSelectedRows((prev) => prev.push(row));
    } else {
      setSelectedRows((prev) => prev.splice(prev.indexOf(row), 1));
    }
  }
  function loadRows(page2) {
    setLoading(true);
    local.loader({
      page: page2,
      filter: local.filter,
      sortBy: sortBy3(),
      sortAsc: sortAsc(),
      cb: function(data2) {
        setLoading(false);
        setSelectedRows([]);
        if (!local.paginated) {
          const cloneData = [...data2];
          setRows(cloneData);
          setTotalResults(data2.length);
          return;
        }
        setRows(data2.results);
        setPage(page2);
        setNextPage(data2.next_page);
        setPrevPage(data2.prev_page);
        setLastPage(data2.nb_pages);
        setTotalResults(data2.total);
        const pages2 = [];
        var edge = 4;
        var middle = page2 < edge + 1 ? edge + 1 : page2 >= data2.nb_pages - edge ? data2.nb_pages - edge : page2;
        for (var i3 = 1; i3 <= data2.nb_pages; i3++) {
          if (i3 >= middle - edge && i3 <= middle + edge) {
            pages2.push(i3);
          }
          setPages(pages2);
        }
      }
    });
  }
  function toggleSort(col) {
    if (sortBy3() === col) {
      setSortAsc((prev) => !prev);
    } else {
      setSortBy2(col);
      setSortAsc(false);
    }
    loadRows(1);
  }
  function doAction(action, row) {
    var cb2 = function() {
      loadRows(page());
    };
    action.action(row, cb2);
  }
  onMount(() => {
    if (!local.rows && loadRows) {
      loadRows(page());
    }
  });
  createEffect((prevFilter) => {
    if (local.filter || prevFilter && !local.filter) {
      loadRows(1);
    }
  });
  return (() => {
    const _el$5 = _tmpl$1110.cloneNode(true), _el$6 = _el$5.firstChild, _el$7 = _el$6.firstChild, _el$8 = _el$7.firstChild, _el$11 = _el$7.nextSibling;
    insert(_el$8, createComponent(Show, {
      get when() {
        return local.selectable;
      },
      get children() {
        return _tmpl$424.cloneNode(true);
      }
    }), null);
    insert(_el$8, createComponent(For, {
      get each() {
        return local.columns;
      },
      children: (col) => (() => {
        const _el$32 = _tmpl$521.cloneNode(true);
        insert(_el$32, createComponent(Show, {
          get when() {
            return local.sortable && (col.sortable === void 0 || col.sortable);
          },
          get children() {
            const _el$33 = _tmpl$133.cloneNode(true);
            _el$33.$$click = () => toggleSort(col);
            insert(_el$33, () => col.title, null);
            insert(_el$33, createComponent(Show, {
              get when() {
                return col === sortBy3();
              },
              get children() {
                const _el$34 = _tmpl$126.cloneNode(true);
                createRenderEffect((_p$) => {
                  const _v$7 = !!sortAsc(), _v$8 = !sortAsc();
                  _v$7 !== _p$._v$7 && _el$34.classList.toggle("bi-caret-up-fill", _p$._v$7 = _v$7);
                  _v$8 !== _p$._v$8 && _el$34.classList.toggle("bi-caret-down-fill", _p$._v$8 = _v$8);
                  return _p$;
                }, {
                  _v$7: void 0,
                  _v$8: void 0
                });
                return _el$34;
              }
            }), null);
            return _el$33;
          }
        }), null);
        insert(_el$32, createComponent(Show, {
          get when() {
            return !local.sortable || col.sortable !== void 0 && !col.sortable;
          },
          get children() {
            const _el$35 = _tmpl$143.cloneNode(true);
            insert(_el$35, () => col.title);
            return _el$35;
          }
        }), null);
        return _el$32;
      })()
    }), null);
    insert(_el$8, createComponent(Show, {
      get when() {
        return local.actions && !local.selectable;
      },
      get children() {
        return _tmpl$521.cloneNode(true);
      }
    }), null);
    insert(_el$11, createComponent(Show, {
      get when() {
        return loading();
      },
      get children() {
        const _el$12 = _tmpl$617.cloneNode(true), _el$13 = _el$12.firstChild, _el$14 = _el$13.firstChild, _el$15 = _el$14.nextSibling;
        insert(_el$13, () => _4("Loading"), null);
        createRenderEffect(() => setAttribute(_el$13, "colspan", local.columns.length + 2));
        return _el$12;
      }
    }), null);
    insert(_el$11, createComponent(For, {
      get each() {
        return rows();
      },
      children: (row) => (() => {
        const _el$36 = _tmpl$172.cloneNode(true);
        insert(_el$36, createComponent(Show, {
          get when() {
            return local.selectable;
          },
          get children() {
            const _el$37 = _tmpl$153.cloneNode(true), _el$38 = _el$37.firstChild;
            _el$38.$$click = () => toggleRowSelection(row);
            return _el$37;
          }
        }), null);
        insert(_el$36, createComponent(For, {
          get each() {
            return local.columns;
          },
          children: (col) => (() => {
            const _el$40 = _tmpl$202.cloneNode(true);
            insert(_el$40, createComponent(Show, {
              get when() {
                return !col.widget && !col.link && !col.click;
              },
              get children() {
                const _el$41 = _tmpl$143.cloneNode(true);
                insert(_el$41, (() => {
                  const _c$ = createMemo(() => !!col.format);
                  return () => _c$() ? col.format(row[col.property], row) : row[col.property];
                })());
                return _el$41;
              }
            }), null);
            insert(_el$40, createComponent(Show, {
              get when() {
                return col.click;
              },
              get children() {
                const _el$42 = _tmpl$133.cloneNode(true);
                _el$42.$$click = () => col.click(row[col.property], row);
                insert(_el$42, (() => {
                  const _c$2 = createMemo(() => !!col.format);
                  return () => _c$2() ? col.format(row[col.property], row) : row[col.property];
                })());
                return _el$42;
              }
            }), null);
            insert(_el$40, createComponent(Show, {
              get when() {
                return col.link;
              },
              get children() {
                const _el$43 = _tmpl$182.cloneNode(true);
                insert(_el$43, (() => {
                  const _c$3 = createMemo(() => !!col.format);
                  return () => _c$3() ? col.format(row[col.property], row) : row[col.property];
                })());
                return _el$43;
              }
            }), null);
            insert(_el$40, createComponent(Show, {
              get when() {
                return col.widget;
              },
              get children() {
                return _tmpl$192.cloneNode(true);
              }
            }), null);
            return _el$40;
          })()
        }), null);
        insert(_el$36, createComponent(Show, {
          get when() {
            return local.actions && !local.selectable;
          },
          get children() {
            const _el$39 = _tmpl$163.cloneNode(true);
            insert(_el$39, createComponent(For, {
              get each() {
                return local.actions;
              },
              children: (action) => (() => {
                const _el$45 = _tmpl$2110.cloneNode(true), _el$46 = _el$45.firstChild;
                _el$45.$$click = () => doAction(action, row);
                createRenderEffect((_p$) => {
                  const _v$9 = action.title, _v$10 = iconClass(action.icon);
                  _v$9 !== _p$._v$9 && setAttribute(_el$45, "uib-tooltip", _p$._v$9 = _v$9);
                  _v$10 !== _p$._v$10 && className(_el$46, _p$._v$10 = _v$10);
                  return _p$;
                }, {
                  _v$9: void 0,
                  _v$10: void 0
                });
                return _el$45;
              })()
            }));
            return _el$39;
          }
        }), null);
        return _el$36;
      })()
    }), null);
    insert(_el$6, createComponent(Show, {
      get when() {
        return selectedRows().length;
      },
      get children() {
        const _el$16 = _tmpl$716.cloneNode(true), _el$17 = _el$16.firstChild, _el$18 = _el$17.firstChild, _el$19 = _el$18.firstChild;
        insert(_el$19, createComponent(For, {
          get each() {
            return local.actions;
          },
          children: (action) => (() => {
            const _el$47 = _tmpl$2210.cloneNode(true);
            _el$47.$$click = () => doAction(action, selectedRows, true);
            insert(_el$47, createComponent(Show, {
              get when() {
                return action.icon;
              },
              get children() {
                const _el$48 = _tmpl$126.cloneNode(true);
                createRenderEffect(() => setAttribute(_el$48, "ng-class", iconClass(action.icon)));
                return _el$48;
              }
            }), null);
            insert(_el$47, () => action.title, null);
            return _el$47;
          })()
        }));
        createRenderEffect(() => setAttribute(_el$18, "colspan", columns.length + 2));
        return _el$16;
      }
    }), null);
    insert(_el$5, createComponent(Show, {
      get when() {
        return local.paginated;
      },
      get children() {
        const _el$20 = _tmpl$1010.cloneNode(true), _el$21 = _el$20.firstChild, _el$22 = _el$21.firstChild, _el$23 = _el$22.firstChild, _el$24 = _el$22.nextSibling, _el$25 = _el$24.firstChild, _el$26 = _el$24.nextSibling, _el$27 = _el$26.firstChild, _el$28 = _el$26.nextSibling, _el$30 = _el$21.nextSibling;
        _el$23.$$click = () => loadRows(1);
        _el$25.$$click = () => loadRows(prevPage());
        insert(_el$21, createComponent(For, {
          get each() {
            return pages();
          },
          children: (p4) => (() => {
            const _el$49 = _tmpl$2310.cloneNode(true), _el$50 = _el$49.firstChild, _el$51 = _el$50.firstChild;
            _el$50.$$click = () => loadRows(p4);
            insert(_el$51, p4);
            createRenderEffect(() => _el$49.classList.toggle("active", !!(p4 === page())));
            return _el$49;
          })()
        }), _el$26);
        _el$26.classList.toggle("disabled", !n);
        _el$27.$$click = () => loadRows(nextPage());
        insert(_el$28, createComponent(Show, {
          get when() {
            return nextPage();
          },
          get children() {
            const _el$29 = _tmpl$814.cloneNode(true);
            _el$29.$$click = () => loadRows(lastPage());
            createRenderEffect(() => setAttribute(_el$29, "uib-tooltip", _4("Last page")));
            return _el$29;
          }
        }));
        insert(_el$30, () => _4("{total} results found", {
          total: totalResults()
        }), null);
        insert(_el$30, createComponent(Show, {
          get when() {
            return local.export;
          },
          get children() {
            const _el$31 = _tmpl$912.cloneNode(true);
            _el$31.$$click = () => local.export({
              filter,
              sortBy: sortBy3,
              sortAsc
            });
            insert(_el$31, () => _4("Export to XLSX"));
            return _el$31;
          }
        }), null);
        createRenderEffect((_p$) => {
          const _v$ = !!(lastPage() === 1), _v$2 = _4("First page"), _v$3 = !prevPage(), _v$4 = _4("Previous page"), _v$5 = _4("Next page"), _v$6 = !!(lastPage() === 1);
          _v$ !== _p$._v$ && _el$22.classList.toggle("disabled", _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && setAttribute(_el$23, "uib-tooltip", _p$._v$2 = _v$2);
          _v$3 !== _p$._v$3 && _el$24.classList.toggle("disabled", _p$._v$3 = _v$3);
          _v$4 !== _p$._v$4 && setAttribute(_el$25, "uib-tooltip", _p$._v$4 = _v$4);
          _v$5 !== _p$._v$5 && setAttribute(_el$27, "uib-tooltip", _p$._v$5 = _v$5);
          _v$6 !== _p$._v$6 && _el$28.classList.toggle("disabled", _p$._v$6 = _v$6);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0,
          _v$4: void 0,
          _v$5: void 0,
          _v$6: void 0
        });
        return _el$20;
      }
    }), null);
    return _el$5;
  })();
}
delegateEvents(["click"]);

// public/app/routes/admin/panels.jsx
var adminPanels = [{
  name: "overview",
  path: "/",
  title: _lazy("Overview"),
  component: () => createComponent(NgComponent, {
    directive: "admin-overview-panel"
  })
}, {
  name: "users",
  path: "/users",
  title: _lazy("Users"),
  component: () => {
    const data2 = useRouteData();
    return createComponent(NgComponent, {
      directive: "admin-users-panel",
      get adminConfig() {
        return data2();
      }
    });
  }
}, {
  name: "orgs",
  path: "/orgs",
  title: _lazy("Organizations"),
  component: () => createComponent(NgComponent, {
    directive: "admin-orgs-panel"
  })
}, {
  name: "oauth",
  path: "/oauth",
  title: _lazy("OAuth apps"),
  // component: () => <NgComponent directive="admin-oauth-panel" /> TODO: if all good delete the component and this line
  component: () => createComponent(AdminOauthPanel, {})
}, {
  name: "logs",
  path: "/logs",
  title: _lazy("Logs"),
  component: () => createComponent(NgComponent, {
    directive: "admin-logs-panel"
  }),
  enabled: () => false
  // disabled until we fix log display
  // enabled: () => serverConfig.has_logs
}];
var panels_default2 = adminPanels;

// public/app/routes/admin/AdminPage.jsx
function AdminPage(props2) {
  const navigate2 = useNavigate2();
  const location2 = useLocation();
  if (!currentUser2.is_kantree_admin) {
    navigate2("/");
    return;
  }
  const panels = [];
  let currentPanel;
  for (const panel of panels_default2) {
    if (!panel.enabled || panel.enabled()) {
      panels.push(panel);
      if (`/admin${panel.path}` === location2.pathname) {
        currentPanel = panel;
      }
    }
  }
  if (!currentPanel) {
    currentPanel = panels[0];
  }
  const sidebarConfig = {
    header: [{
      type: "page-header",
      options: {
        title: _4("Admin")
      }
    }],
    content: panels.map((panel) => {
      return {
        panel,
        type: "button",
        options: {
          label: panel.title,
          icon: panel.icon,
          action: () => {
            currentPanel = panel;
            navigate2("/admin" + panel.path);
          }
        },
        active: () => currentPanel === panel
      };
    })
  };
  return [createComponent(NavSidebar, {
    config: sidebarConfig
  }), createMemo(() => props2.children)];
}

// public/app/routes/admin/ng-components/logs-panel.js
angular_default.module("kantree").directive("adminLogsPanel", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/routes/admin/ng-components/templates/logs-panel.html",
      controller: [
        "$scope",
        "$q",
        "$timeout",
        function($scope2, $q, $timeout2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.refresh = function() {
            $q.when(api_default.admin.get_logs.get({}, { ignoreErrorHandlers: true }), (logs) => {
              $scope2.logs = logs;
              $timeout2(function() {
                jquery_default("#logs").scrollTop(jquery_default("#logs")[0].scrollHeight);
              });
            });
          };
          $scope2.refresh();
          $scope2.download = function() {
            window.open(api_default.admin.get_logs.url() + "?tail=0");
          };
          $timeout2($scope2.refresh, 6e4);
        }
      ]
    };
  }
]);

// public/app/routes/admin/ng-components/oauth-panel.js
angular_default.module("kantree").directive("adminOauthPanel", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/routes/admin/ng-components/templates/oauth-panel.html",
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.columns = [
            { "title": "#ID", "property": "id" },
            {
              "title": _4("Name"),
              "property": "name",
              "click": function(value2, app) {
                $scope2.app = app;
              }
            },
            {
              "title": _4("URL"),
              "property": "client_uri",
              "link": function(_5, o3) {
                return o3.client_uri;
              }
            },
            {
              "title": _4("Trusted"),
              "property": "trusted",
              "format": function(value2) {
                return value2 ? "Yes" : "No";
              }
            },
            {
              "title": _4("System app"),
              "property": "user",
              "format": function(value2) {
                return value2 ? "No" : "Yes";
              }
            }
          ];
          $scope2.load = function(cb2) {
            $q.when(api_default.oauth.list_apps.get({ all: true }), cb2);
          };
          $scope2.select = function(app) {
            $scope2.oauthApp = angular_default.copy(app);
          };
          $scope2.createApp = function() {
            $scope2.app = { system_app: true };
          };
        }
      ]
    };
  }
]);

// public/app/routes/admin/ng-components/orgs-panel.js
angular_default.module("kantree").directive("adminOrgsPanel", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/routes/admin/ng-components/templates/orgs-panel.html",
      controller: [
        "$scope",
        "$q",
        "$state",
        "fileSelectModal",
        function($scope2, $q, $state, fileSelectModal) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.orgFilter = { value: "" };
          $scope2.columns = [
            { "title": "#ID", "property": "id" },
            {
              "title": _4("Name"),
              "property": "name",
              "link": function(_5, o3) {
                return $state.href("org.hub", { slug: o3.slug });
              }
            },
            { "title": _4("Members"), "property": "nb_members" },
            { "title": _4("Workspaces"), "property": "nb_projects" },
            { "title": _4("Status"), "property": "status" },
            {
              "title": _4("Created at"),
              "property": "created_at",
              "format": function(value2) {
                return fromNow(value2);
              },
              "tooltip": function(value2) {
                return formatDate(value2, "YYYY-MM-DD hh:mm:ss");
              }
            },
            {
              "title": _4("URL"),
              "property": "slug",
              "link": function(slug) {
                return $state.href("org.hub", { slug });
              },
              "sortable": false
            }
          ];
          $scope2.filterShortcutsMenu = { config: [
            { label: _4("Has no workspaces"), action: () => $scope2.setFilter("!workspaces") },
            { label: _4("Has no members"), action: () => $scope2.setFilter("!members") },
            { label: _4("Has billing"), action: () => $scope2.setFilter("+paid") }
          ] };
          if (serverConfig.payments_enabled) {
            $scope2.filterShortcutsMenu.config.push(
              { label: _4("Trialing"), action: () => $scope2.setFilter("+trialing") },
              { label: _4("Unpaid"), action: () => $scope2.setFilter("+unpaid") },
              { label: _4("Canceled"), action: () => $scope2.setFilter("+canceled") },
              { label: _4("Active"), action: () => $scope2.setFilter("+active") },
              { label: _4("Stripe payment"), action: () => $scope2.setFilter("+stripe") },
              { label: _4("Manual payment"), action: () => $scope2.setFilter("+manualpayment") }
            );
          }
          $scope2.orgActions = [
            {
              "title": _4("Delete"),
              "icon": "trash",
              "action": (orgs, cb2) => {
                $q.when(confirmDeleteDialog2().then(() => api_default.admin.bulk_delete_orgs.delete({ ids: orgs.map((o3) => o3.id) })), cb2);
              }
            }
          ];
          $scope2.addMenu = { config: [
            { label: _4("Create a new team"), icon: "plus", action: () => $scope2.createOrg() },
            { label: "--" },
            { label: _4("Import a team backup from an URL"), icon: "cloud-upload", action: () => $scope2.importOrgFromURL() },
            { label: _4("Import a team backup from a file"), icon: "upload", action: () => $scope2.importOrgFromFile() }
          ] };
          $scope2.setFilter = function(filter4) {
            $scope2.orgFilter.value = filter4;
          };
          $scope2.loadOrgs = function(page, filter4, sortBy3, sortAsc, cb2) {
            $q.when(api_default.admin.list_organizations.get({
              page,
              filter: filter4,
              sort_by: sortBy3 ? sortBy3.property : null,
              sort_asc: sortAsc
            }), cb2);
          };
          $scope2.export = function(filter4, sortBy3, sortAsc) {
            document.location = api_default.admin.export_organizations.url() + "?" + $.param({ filter: filter4, sortBy: sortBy3 ? sortBy3.property : null, sortAsc });
          };
          $scope2.createOrg = function() {
            $q.when(
              inputDialog(_4("Team name:"), { required: true }).then(
                (name2) => api_default.admin.create_org.post({ name: name2 }, { ignoreErrorHandlers: true }).catch(autoCatchAsRequestErrorDialog([400]))
              ),
              (org2) => $state.go("org.hub", { slug: org2.slug })
            );
          };
          $scope2.importOrgFromFile = function() {
            fileSelectModal.open().then((file) => {
              $scope2.createOrgInProgress = 1;
              upload({
                url: api_default.admin.import_org_from_file.url(),
                data: { file },
                arrayKey: ""
              }, function(evt) {
                $scope2.createOrgInProgress = parseInt(100 * evt.loaded / evt.total);
              }).then(function(resp) {
                infoDialog(_4("Import in progress..."));
                $scope2.createOrgInProgress = false;
              }, function(resp) {
                errorDialog(_4("An error occured while uploading your file"));
                $scope2.createOrgInProgress = false;
              });
            });
          };
          $scope2.importOrgFromURL = function() {
            inputDialog(_4("URL of the file to import:"), { required: true }).then((url2) => {
              api_default.admin.import_org_from_url.post({ url: url2 }, { ignoreErrorHandlers: true }).then(() => {
                infoDialog(_4("Import in progress..."));
              }, autoCatchAsRequestErrorDialog([400]));
            });
          };
        }
      ]
    };
  }
]);

// public/app/routes/admin/ng-components/overview-panel.js
angular_default.module("kantree").directive("adminOverviewPanel", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/routes/admin/ng-components/templates/overview-panel.html",
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.paymentsEnabled = serverConfig.payments_enabled;
          $scope2.counters = [
            { "title": _4("Total number of users"), "property": "total_users" },
            { "title": _4("Licensed users"), "property": "licensed_users" },
            { "title": _4("Active users"), "property": "activate_users_30days" },
            { "title": _4("Disabled users"), "property": "disabled_users" },
            { "title": _4("Unlicensed users"), "property": "unlicensed_users" },
            { "title": _4("Teams"), "property": "total_orgs" },
            { "title": _4("Paying teams"), "property": "paying_orgs" },
            { "title": _4("Workspaces"), "property": "total_projects" }
          ];
          $scope2.showLicensingDetails = false;
          $q.when(api_default.admin.get_stats.get(), (stats) => {
            $scope2.stats = stats;
            if (stats.licensed) {
              $scope2.expiresAt = moment_default(stats.expire_at).format("LL");
              $scope2.expiresIn = moment_default(stats.expire_at).fromNow();
            }
          });
          $scope2.skipMissingCounters = function(counter3) {
            return $scope2.stats && typeof $scope2.stats[counter3.property] !== "undefined";
          };
        }
      ]
    };
  }
]);

// public/app/routes/admin/ng-components/table.js
angular_default.module("kantree").directive("adminTable", [
  function() {
    return {
      templateUrl: "/static/app/routes/admin/ng-components/templates/table.html",
      replace: true,
      scope: {
        columns: "<",
        loader: "&",
        rows: "=?",
        filter: "<?",
        paginated: "<?",
        actions: "<?",
        sortable: "<?",
        export: "&?",
        selectedRows: "=?",
        selectable: "<?"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.page = 1;
          $scope2.sortBy = null;
          $scope2.sortAsc = false;
          $scope2.selectedRows = [];
          $scope2.toggleSort = function(col) {
            if ($scope2.sortBy === col) {
              $scope2.sortAsc = !$scope2.sortAsc;
            } else {
              $scope2.sortBy = col;
              $scope2.sortAsc = false;
            }
            $scope2.loadRows(1);
          };
          $scope2.toggleRowSelection = function(row) {
            if ($scope2.selectedRows.indexOf(row) === -1) {
              $scope2.selectedRows.push(row);
            } else {
              $scope2.selectedRows.splice($scope2.selectedRows.indexOf(row), 1);
            }
          };
          $scope2.doAction = function(action, row) {
            var cb2 = function() {
              $scope2.loadRows($scope2.page);
            };
            action.action(row, cb2);
          };
          $scope2.loadRows = function(page) {
            $scope2.loading = true;
            $scope2.loader({ page, filter: $scope2.filter, sortBy: $scope2.sortBy, sortAsc: $scope2.sortAsc, cb: function(data2) {
              $scope2.loading = false;
              $scope2.selectedRows = [];
              if (!$scope2.paginated) {
                $scope2.rows = data2;
                $scope2.totalResults = data2.length;
                return;
              }
              $scope2.rows = data2.results;
              $scope2.page = page;
              $scope2.next_page = data2.next_page;
              $scope2.prev_page = data2.prev_page;
              $scope2.last_page = data2.nb_pages;
              $scope2.totalResults = data2.total;
              $scope2.pages = [];
              var edge = 4;
              var middle = page < edge + 1 ? edge + 1 : page >= data2.nb_pages - edge ? data2.nb_pages - edge : page;
              for (var i3 = 1; i3 <= data2.nb_pages; i3++) {
                if (i3 >= middle - edge && i3 <= middle + edge) {
                  $scope2.pages.push(i3);
                }
              }
            } });
          };
          if (!$scope2.rows && $scope2.loadRows) {
            $scope2.loadRows($scope2.page);
          }
          var updateFilter = debounce2(function() {
            $scope2.loadRows(1);
          }, 700);
          $scope2.$watch("filter", function(filter4, prevFilter) {
            if (filter4 || prevFilter && !filter4) {
              updateFilter();
            }
          });
        }
      ]
    };
  }
]);

// public/app/routes/admin/ng-components/users-panel.js
angular_default.module("kantree").directive("adminUsersPanel", [
  "$state",
  function($state) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/routes/admin/ng-components/templates/users-panel.html",
      scope: {
        adminConfig: "<"
      },
      controller: [
        "$scope",
        "projectSettingsModal",
        "$q",
        "$timeout",
        "fileSelectModal",
        function($scope2, projectSettingsModal, $q, $timeout2, fileSelectModal) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.user = null;
          $scope2.paymentsEnabled = serverConfig.payments_enabled;
          $scope2.canResetPassword = serverConfig.user_can_reset_password;
          $scope2.canAddUsers = $scope2.adminConfig.can_add_new_users;
          $scope2.superAdminEnabled = !serverConfig.admin_can_access_all_projects;
          $scope2.isSuperAdmin = currentUser2.is_kantree_super_admin;
          $scope2.userFilter = { value: "" };
          $scope2.exportOrgMembershipsUrl = api_default.admin.export_organizations_memberships.url();
          $scope2.columns = [
            { "title": "#ID", "property": "id" },
            {
              "title": _4("Username"),
              "property": "username",
              "click": function(value2, user) {
                $scope2.selectUser(user);
              }
            },
            { "title": _4("Email"), "property": "email" },
            {
              "title": _4("Role"),
              "property": "role",
              "format": function(value2, user) {
                if (user.is_disabled) {
                  return _4("Disabled");
                }
                return user.role;
              }
            },
            { "title": _4("Workspaces"), "property": "nb_projects" },
            { "title": _4("Organizations"), "property": "nb_org_memberships" },
            {
              "title": _4("Last active"),
              "property": "last_activity_at",
              "format": function(value2) {
                return value2 ? fromNow(value2) : _4("Never");
              },
              "tooltip": function(value2) {
                return value2 ? formatDate(value2, "YYYY-MM-DD hh:mm:ss") : "";
              }
            },
            {
              "title": _4("Last access"),
              "property": "last_access_at",
              "format": function(value2) {
                return value2 ? formatDate(value2, "ll") : _4("Never");
              }
            },
            {
              "title": _4("Signup at"),
              "property": "signup_at",
              "format": function(value2) {
                return fromNow(value2);
              },
              "tooltip": function(value2) {
                return formatDate(value2, "YYYY-MM-DD hh:mm:ss");
              }
            },
            {
              "title": _4("2FA"),
              "property": "2fa_enabled",
              "format": function(value2) {
                return value2 ? "Yes" : "No";
              }
            }
          ];
          $scope2.filterShortcutsMenu = { config: [
            { label: _4("Active in the last 30 days"), action: () => $scope2.setFilter("+active") },
            { label: _4("Accessed in the last 30 days"), action: () => $scope2.setFilter("+access") },
            { label: _4("NOT active in the last 30 days"), action: () => $scope2.setFilter("!active") },
            { label: _4("NOT accessed in the last 30 days"), action: () => $scope2.setFilter("!access") },
            { label: _4("Has NEVER been active"), action: () => $scope2.setFilter('active="never"') },
            { label: _4("Has NEVER accessed kantree passed the signup date"), action: () => $scope2.setFilter('access="never"') },
            { label: _4("Participates to no workspaces"), action: () => $scope2.setFilter("!workspaces") },
            { label: _4("Participates to no org workspaces"), action: () => $scope2.setFilter("!orgworkspaces") },
            { label: _4("Has no personal workspaces"), action: () => $scope2.setFilter("!persoworkspaces") },
            { label: _4("Belongs to no orgs"), action: () => $scope2.setFilter("!orgs") },
            { label: _4("Is disabled"), action: () => $scope2.setFilter("+disabled") },
            { label: _4("Is auto disabled"), action: () => $scope2.setFilter("+autodisabled") },
            { label: _4("Is unlicensed"), action: () => $scope2.setFilter("!licensed") },
            { label: _4("Is licensed"), action: () => $scope2.setFilter("+licensed") },
            { label: _4("Is admin"), action: () => $scope2.setFilter("+admin") },
            { label: _4("Is super admin"), action: () => $scope2.setFilter("+superadmin") },
            { label: _4("Has 2FA enabled"), action: () => $scope2.setFilter("+twofactorauth") },
            { label: _4("Has 2FA disabled"), action: () => $scope2.setFilter("!twofactorauth") },
            { label: _4("Signed up through SSO"), action: () => $scope2.setFilter("+sso") },
            { label: _4("Is not using SSO"), action: () => $scope2.setFilter("!sso") },
            { label: _4("Is in multiple billable orgs"), action: () => $scope2.setFilter("+multilicensed") }
          ] };
          $scope2.userActions = [
            {
              "title": _4("Disable"),
              "action": function(users, cb2) {
                $q.when(api_default.admin.bulk_update_users.put({
                  ids: users.map(function(u3) {
                    return u3.id;
                  }),
                  is_disabled: true
                }), cb2);
              }
            },
            {
              "title": _4("Enable"),
              "action": function(users, cb2) {
                $q.when(api_default.admin.bulk_update_users.put({
                  ids: users.map(function(u3) {
                    return u3.id;
                  }),
                  is_disabled: false
                }), cb2);
              }
            },
            {
              "title": _4("Make unlicensed"),
              "action": function(users, cb2) {
                $q.when(api_default.admin.bulk_update_users.put({
                  ids: users.map(function(u3) {
                    return u3.id;
                  }),
                  role: "unlicensed"
                }), cb2);
              }
            },
            {
              "title": _4("Make user"),
              "action": function(users, cb2) {
                $q.when(api_default.admin.bulk_update_users.put({
                  ids: users.map(function(u3) {
                    return u3.id;
                  }),
                  role: "user"
                }), cb2);
              }
            },
            {
              "title": _4("Make admin"),
              "action": function(users, cb2) {
                $q.when(api_default.admin.bulk_update_users.put({
                  ids: users.map(function(u3) {
                    return u3.id;
                  }),
                  role: "admin"
                }), cb2);
              }
            },
            {
              "title": _4("Delete"),
              "icon": "trash",
              "action": function(users, cb2) {
                confirmDeleteDialog2().then(() => {
                  $q.when(api_default.admin.bulk_delete_users.delete({
                    ids: users.map((u3) => u3.id)
                  }), cb2);
                });
              }
            }
          ];
          if (serverConfig.has_approved_domains) {
            $scope2.columns.push({
              "title": _4("Approved domain"),
              "property": "is_from_approved_domain",
              "format": function(approved) {
                return approved ? _4("Yes") : _4("No");
              }
            });
            $scope2.filterShortcutsMenu.config.push({ label: _4("NOT from approved domain"), action: () => $scope2.setFilter("!approved") });
          }
          $scope2.projectColumns = [
            { "title": "#ID", "property": "id" },
            { "title": _4("Title"), "property": "title" },
            {
              "title": _4("Archived?"),
              "property": "is_archived",
              "format": function(v3) {
                return v3 ? "Y" : "N";
              }
            },
            {
              "title": _4("URL"),
              "property": "slug",
              "link": function(slug) {
                return $state.href("project", { projectId: slug });
              }
            }
          ];
          $scope2.projectActions = [
            {
              "title": _4("Settings"),
              "icon": "cog",
              "action": function(project) {
                cardStore.upsert(project);
                projectSettingsModal.open(project);
              }
            },
            {
              "title": _4("Delete"),
              "icon": "trash",
              "action": function(row) {
                confirmDeleteDialog2().then(() => {
                  $q.when(api_default.admin.delete_project.delete({ user_id: $scope2.user.id, project_id: row.id }), () => {
                    $scope2.showUserProjectsTab();
                  });
                });
              }
            }
          ];
          $scope2.orgColumns = [
            { "title": "#ID", "property": "id" },
            { "title": _4("Name"), "property": "name" },
            {
              "title": _4("Role"),
              "property": "permission",
              "format": function(roleId) {
                var role = availableOrgRoles.find(function(role2) {
                  return roleId === role2.id;
                });
                return role ? role.name : null;
              }
            },
            { "title": _4("Members"), "property": "nb_members" },
            { "title": _4("Workspaces"), "property": "nb_projects" },
            {
              "title": _4("URL"),
              "property": "slug",
              "link": function(slug) {
                return $state.href("org.hub", { slug });
              }
            }
          ];
          $scope2.addUserMenu = { config: [
            { label: _4("Add new user"), icon: "plus", action: () => $scope2.createUser() },
            { label: "--" },
            { label: _4("Synchronize users from CSV/XLSX file"), action: () => $scope2.bulkImportUsers(true) },
            { label: _4("Bulk create/update users from CSV/XLSX file"), action: () => $scope2.bulkImportUsers() },
            { label: _4("Bulk delete users from CSV/XLSX file"), action: () => $scope2.bulkDeleteUsers() },
            { label: _4("How to structure your CSV/XLSX files?"), action: () => window.open("https://kantree.io/help/enterprise/admin") }
          ] };
          $scope2.setFilter = function(filter4) {
            $scope2.userFilter.value = filter4;
          };
          $scope2.loadUsers = function(page, filter4, sortBy3, sortAsc, cb2) {
            $q.when(api_default.admin.list_users.get({ page, filter: filter4, sort_by: sortBy3 ? sortBy3.property : null, sort_asc: sortAsc }), cb2);
          };
          $scope2.export = function(filter4, sortBy3, sortAsc) {
            document.location = api_default.admin.export_users.url() + "?" + $.param({ filter: filter4, sortBy: sortBy3 ? sortBy3.property : null, sortAsc });
          };
          $scope2.createUser = function() {
            $scope2.user = { must_reset_password_at_login: true };
            $scope2.userTab = "user";
          };
          $scope2.selectUser = function(user) {
            if (user) {
              $scope2.user = angular_default.copy(user);
              $scope2.userTab = "user";
              $scope2.origUser = user;
            } else {
              $scope2.user = null;
            }
          };
          $scope2.showUserProjectsTab = function() {
            $scope2.projects = null;
            $scope2.userTab = "projects";
            $q.when(api_default.admin.list_user_projects.get({ user_id: $scope2.user.id }), (projects) => {
              $scope2.projects = projects;
            });
          };
          $scope2.showUserOrgsTab = function() {
            $scope2.orgs = null;
            $scope2.userTab = "orgs";
            $q.when(api_default.admin.list_user_org_memberships.get({ user_id: $scope2.user.id }), (orgs) => {
              $scope2.orgs = orgs;
            });
          };
          $scope2.saveUser = function() {
            if (typeof $scope2.user.id !== "undefined") {
              $scope2.saving = true;
              const data2 = {
                user_id: $scope2.user.id,
                username: $scope2.user.username,
                display_name: $scope2.user.display_name,
                email: $scope2.user.email,
                role: $scope2.user.role,
                can_join_organizations: $scope2.user.can_join_organizations,
                can_create_organizations: $scope2.user.can_create_organizations,
                can_create_projects: $scope2.user.can_create_projects,
                can_create_private_projects: $scope2.user.can_create_private_projects,
                subscription_required: $scope2.user.subscription_required,
                must_reset_password_at_login: $scope2.user.must_reset_password_at_login,
                system_message: $scope2.user.system_message
              };
              if ($scope2.origUser.is_disabled !== $scope2.user.is_disabled) {
                data2["is_disabled"] = $scope2.user.is_disabled;
              }
              $q.when(api_default.admin.update_user.put(data2, { ignoreErrorHandlers: true }), (user) => {
                Object.assign($scope2.origUser, user);
                $timeout2(function() {
                  $scope2.saving = false;
                }, 500);
              }, autoCatchAsRequestErrorDialog([400]));
            } else {
              $q.when(api_default.admin.create_user.post({
                username: $scope2.user.username,
                password: $scope2.user.password,
                email: $scope2.user.email,
                must_reset_password_at_login: $scope2.user.must_reset_password_at_login,
                display_name: $scope2.user.display_name
              }), (user) => {
                $scope2.selectUser(user);
              }, autoCatchAsRequestErrorDialog([400]));
            }
          };
          $scope2.deleteUser = function() {
            confirmDeleteDialog2().then(() => {
              $q.when(api_default.admin.delete_user.delete({ user_id: $scope2.user.id }), () => {
                $scope2.user = null;
              });
            });
          };
          $scope2.resetPassword = function() {
            $q.when(api_default.admin.reset_password.post({ user_id: $scope2.user.id }), (r3) => {
              infoDialog(
                _4('You can also use the following link: <span style="word-break:break-word;">{link}</span>', { link: r3.link }),
                _4("An email has been sent to the user with a link to reset his password")
              );
            });
          };
          $scope2.logoutUser = function() {
            $q.when(api_default.admin.logout_user.post({ user_id: $scope2.user.id }), () => {
              successDialog(_4("User has been disconnected from all his devices"));
            });
          };
          $scope2.disable2FA = function() {
            $q.when(api_default.admin.disable_2fa.post({ user_id: $scope2.user.id }), () => {
              $scope2.user["2fa_enabled"] = false;
              successDialog(_4("2FA disabled"));
            });
          };
          $scope2.bulkImportUsers = function(sync2) {
            fileSelectModal.open().then((file) => {
              $scope2.uploadInProgress = 1;
              upload({
                url: api_default.admin.bulk_import_users_csv.url(),
                data: { file, sync: !!sync2 },
                arrayKey: ""
              }, function(evt) {
                $scope2.uploadInProgress = parseInt(100 * evt.loaded / evt.total);
              }).then(function(resp) {
                infoDialog(_4("Processing in progress, refresh in a few moments to see the changes..."));
                $scope2.uploadInProgress = false;
              }, function(resp) {
                errorDialog(_4("An error occured while uploading your file"));
                $scope2.uploadInProgress = false;
              });
            });
          };
          $scope2.bulkDeleteUsers = function() {
            fileSelectModal.open().then((file) => {
              $scope2.uploadInProgress = 1;
              upload({
                url: api_default.admin.bulk_delete_users_csv.url(),
                data: { file },
                arrayKey: ""
              }, function(evt) {
                $scope2.uploadInProgress = parseInt(100 * evt.loaded / evt.total);
              }).then(function(resp) {
                infoDialog(_4("Processing in progress, refresh in a few moments to see the changes..."));
                $scope2.uploadInProgress = false;
              }, function(resp) {
                errorDialog(_4("An error occured while uploading your file"));
                $scope2.uploadInProgress = false;
              });
            });
          };
          $scope2.impersonate = function() {
            $q.when(confirmDialog({
              title: _4("Are you sure?"),
              text: _4("Impersonating this user will give you access to all his data. Make sure you have the user approval before doing so.")
            }), () => {
              clearStorageBeforeLogout();
              document.location = prependBaseUrl(`/admin/impersonate?user_id=${$scope2.user.id}`);
            });
          };
        }
      ]
    };
  }
]);

// public/app/routes/admin/index.jsx
function adminRouteData() {
  const [data2] = createResource(() => {
    return api_default.admin.get_admin_config.get({}, {
      ignoreErrorHandlers: true
    }).catch(() => ({}));
  });
  return data2;
}
addRoute({
  name: "admin",
  path: "/admin",
  component: (props2) => createComponent(AuthenticatedPage, {
    preventOnboardingRedirect: true,
    get children() {
      return createComponent(RouteData, {
        loader: adminRouteData,
        get children() {
          return createComponent(AdminPage, {
            get children() {
              return props2.children;
            }
          });
        }
      });
    }
  }),
  children: panels_default2.map((panel) => ({
    name: panel.name,
    path: panel.path,
    component: panel.component
  }))
});

// public/app/loaders/form.js
var loader4 = new StoreLoader(requestFormStore);
function getOrLoadRequestForm(projectId, formId, options2) {
  return loader4.getOrLoad(formId, api_default.project_request_forms.get_request_form, { project_id: projectId, request_form_id: formId }, options2);
}
function loadRequestFormBySlug(slug, options2) {
  return loader4.load(api_default.request_form.get_request_form, { request_form_id: slug }, options2);
}
function loadAllRequestFormsForProject(project, options2) {
  return loader4.loadMany(api_default.project_request_forms.list_request_forms, { project_id: project.id }, options2);
}
function loadAllRequestFormsForOrg(org2, options2) {
  return loader4.loadMany(api_default.organizations.list_request_forms, { org_id: org2.id }, options2);
}

// public/app/routes/form/RequestFormPage.jsx
var _tmpl$127 = /* @__PURE__ */ template(`<div class="error"></div>`, 2);
var _tmpl$256 = /* @__PURE__ */ template(`<div class="text-center m-3"></div>`, 2);
var _tmpl$338 = /* @__PURE__ */ template(`<div class="loader"><i class="fa fa-spinner fa-spin"></i></div>`, 4);
var _tmpl$425 = /* @__PURE__ */ template(`<p class="powered-by"><a href="https://kantree.io"></a></p>`, 4);
var _tmpl$522 = /* @__PURE__ */ template(`<div id="request-form-wrapper"></div>`, 2);
function RequestFormPage() {
  const params = useParams();
  const [searchParams] = useSearchParams();
  const navigate2 = useNavigate2();
  const hideHeader = () => searchParams.noheader == 1;
  const hideFooter = () => searchParams.nofooter == 1;
  const [showLoginRedirect, setShowLoginRedirect] = createSignal(false);
  const [form] = createResource(params.formSlug, (slug) => {
    return loadRequestFormBySlug(slug, {
      ignoreErrorHandlers: true
    });
  });
  createEffect(() => {
    if (form.error && form.error.status === 403 && !isAuthenticated()) {
      setShowLoginRedirect(true);
      setTimeout(() => authSession.login(), 5e3);
    }
  });
  const errorMessage = createMemo(() => form.error && (form.error.status === 403 ? _4("Not authorized") : _4("Not found")));
  const onSubmitted = (request2) => {
    if (request2.token) {
      const params2 = {
        requestToken: request2.token,
        as: 1,
        confirm: 1
      };
      if (isAuthenticated()) {
        window.open(routeHref("request", params2));
      } else {
        navigate2("request", params2);
      }
    } else {
      successDialog(_4("Your request has been successfully submitted"));
    }
  };
  onSubmitted.$inject = ["request"];
  return createComponent(PageContainer, {
    get children() {
      return createComponent(PageContainerView, {
        id: "request-form-view",
        get children() {
          const _el$ = _tmpl$522.cloneNode(true);
          insert(_el$, createComponent(Show, {
            get when() {
              return !form.loading && !form.error;
            },
            get children() {
              return createComponent(NgComponent, {
                directive: "request-form",
                get form() {
                  return form();
                },
                onSubmitted,
                get hideHeader() {
                  return hideHeader();
                },
                resetOnSubmit: true
              });
            }
          }), null);
          insert(_el$, createComponent(Show, {
            get when() {
              return form.error;
            },
            get children() {
              const _el$2 = _tmpl$127.cloneNode(true);
              insert(_el$2, errorMessage);
              return _el$2;
            }
          }), null);
          insert(_el$, createComponent(Show, {
            get when() {
              return createMemo(() => !!!isEmbedded())() && showLoginRedirect();
            },
            get children() {
              const _el$3 = _tmpl$256.cloneNode(true);
              insert(_el$3, () => _4("You are not logged in. You will be redirected to login page in a few seconds..."));
              return _el$3;
            }
          }), null);
          insert(_el$, createComponent(Show, {
            get when() {
              return form.loading;
            },
            get children() {
              return _tmpl$338.cloneNode(true);
            }
          }), null);
          insert(_el$, createComponent(Show, {
            get when() {
              return !hideFooter();
            },
            get children() {
              const _el$5 = _tmpl$425.cloneNode(true), _el$6 = _el$5.firstChild;
              insert(_el$6, () => _4("Powered by Kantree"));
              insert(_el$5, createComponent(Show, {
                get when() {
                  return createMemo(() => !!!isEmbedded())() && showLoginRedirect();
                },
                get children() {
                  return ["- ", createComponent(A3, {
                    onClick: () => authSession.login(),
                    get children() {
                      return _4("Login");
                    }
                  })];
                }
              }), null);
              return _el$5;
            }
          }), null);
          createRenderEffect(() => _el$.classList.toggle("hide-footer", !!hideFooter()));
          return _el$;
        }
      });
    }
  });
}

// public/app/routes/form/index.jsx
addRoute({
  name: "request_form",
  path: "/f/:formSlug",
  component: () => createComponent(HideSystemSidebar, {
    anonymousOnly: true,
    get children() {
      return createComponent(RequestFormPage, {});
    }
  })
});

// public/app/routes/utils.jsx
function navigateToView(view, navigateTo2 = null) {
  if (!navigateTo2) {
    navigateTo2 = useNavigate2();
  }
  const project = projectStore.tryGet(view.project_id) || {};
  if (!project.slug) {
    if (view?._draft) {
      navigateTo2("search", {
        view: view?.id
      });
    } else {
      navigateTo2("myWork.dashboard", {
        viewId: view?.id
      });
    }
  } else {
    navigateToProject(project, null, view, navigateTo2);
  }
}
function $navigateToView(view) {
  navigateToView(view, ngApp.$injector.get("$state").go);
}
function navigateToProject(project, board = null, view = null, navigateTo2 = null) {
  if (!navigateTo2) {
    navigateTo2 = useNavigate2();
  }
  if (project.is_portfolio) {
    navigateTo2("portfolio", {
      projectId: project.slug,
      view: view?.id
    });
  } else if (board && board.board_created && board.parent_id || view?.card_ref) {
    navigateTo2("project_board", {
      projectId: project.slug,
      cardRef: board ? board.ref : view?.card_ref,
      view: view?.id
    });
  } else {
    navigateTo2("project", {
      projectId: project.slug,
      view: view?.id,
      "#": board ? board.ref : void 0
    });
  }
}
function $navigateToProject(project, board = null, view = null) {
  navigateToProject(project, board, view, ngApp.$injector.get("$state").go);
}
function projectRouteHref(project, board = null, view = null) {
  if (project.is_portfolio) {
    return routeHref("portfolio", {
      projectId: project.slug,
      view: view?.id
    });
  } else if (board && board.board_created && board.parent_id || view?.card_ref) {
    return routeHref("project_board", {
      projectId: project.slug,
      cardRef: board ? board.ref : view?.card_ref,
      view: view?.id
    });
  } else {
    return routeHref("project", {
      projectId: project.slug,
      view: view?.id,
      "#": board ? board.ref : void 0
    });
  }
}
function updateLocationHash(hash) {
  if (isUndefined(hash)) return;
  document.location.hash = hash !== null ? hash.toString() : "";
}

// public/app/ui/project/components/Tile.jsx
var _tmpl$128 = /* @__PURE__ */ template(`<div class="project-tile-cover"></div>`, 2);
var _tmpl$257 = /* @__PURE__ */ template(`<div class="project-tile-portfolio-shadow"></div>`, 2);
var _tmpl$339 = /* @__PURE__ */ template(`<span class="path"></span>`, 2);
var _tmpl$426 = /* @__PURE__ */ template(`<span class="activity d-block d-sm-inline"> </span>`, 2);
var _tmpl$523 = /* @__PURE__ */ template(`<span>+</span>`, 2);
var _tmpl$618 = /* @__PURE__ */ template(`<div class="project-tile-infos"><h3></h3><div class="project-tile-members stacked-members-avatar"></div></div>`, 6);
var _tmpl$717 = /* @__PURE__ */ template(`<div class="project-tile-buttons"></div>`, 2);
var _tmpl$815 = /* @__PURE__ */ template(`<div class="project-tile"></div>`, 2);
var _tmpl$913 = /* @__PURE__ */ template(`<span></span>`, 2);
function ProjectTile(props2) {
  props2 = mergeProps({
    showFavoriteBtn: true
  }, props2);
  const [loading, setLoading] = createSignal(true);
  const isMember = createMemo(() => {
    return props2.project.members_preview?.find((m3) => m3.username === currentUser2.username) || currentUser2.is_kantree_admin;
  });
  const imageCoverUrl = createMemo(() => {
    if (props2.card && props2.card.image_cover_url) {
      return props2.card.image_cover_url;
    } else {
      return cardStore.tryGet(props2.project.top_level_card?.id)?.image_cover_url || props2.project.image_cover_url;
    }
  });
  const [members, setMembers] = createSignal([]);
  const [remainingMembersCount, setRemainingMembersCount] = createSignal(0);
  createEffect(() => {
    if (props2.project.members_preview?.length) {
      setMembers(props2.project.members_preview.slice(0, 3));
      setRemainingMembersCount(Math.max(0, props2.project.members_preview.length - 3));
    }
  });
  const toggleFavorite = () => {
    if (props2.card) {
      toggleCardAsFavorite(props2.card);
    } else {
      toggleProjectAsFavorite(props2.project);
    }
  };
  const isFav = () => !props2.card ? isFavorite("project", props2.project.id) : isFavorite("card", props2.card.id);
  const color = createMemo(() => {
    if (props2.card && props2.card.model_id) {
      const model = cardModelStore.tryGet(props2.card.model_id);
      if (model && model.card_color) {
        return model.card_color;
      }
    }
    return props2.project.color;
  });
  const isAccessible = createMemo(() => {
    return props2.project.id && isProjectAccessible(props2.project);
  });
  let off, coverEl, portfolioShadowEl, portfolioShadowEl2;
  createEffect(() => {
    off && off();
    off = null;
    if (imageCoverUrl()) {
      coverEl.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.4),rgba(0, 0, 0, 0.4)), url(${imageCoverUrl()})`;
      coverEl.style.backgroundRepeat = "no-repeat";
      coverEl.style.backgroundSize = "cover";
    } else if (color()) {
      const offs = [colorizeElement(coverEl, color())];
      if (props2.project.is_portfolio) {
        offs.push(colorizeElement(portfolioShadowEl, color()), colorizeElement(portfolioShadowEl2, color()));
      }
      off = offMany(offs);
      if (!imageCoverUrl()) {
        coverEl.style.backgroundImage = "none";
      }
    } else {
      off = null;
      coverEl.style.backgroundImage = null;
    }
  });
  onMount(() => {
    if (loading) {
      setLoading(false);
    }
  });
  return (() => {
    const _el$ = _tmpl$815.cloneNode(true);
    insert(_el$, createComponent(Dynamic, {
      get component() {
        return isAccessible() ? props2.useSimpleAnchorTag ? "a" : A3 : "span";
      },
      get href() {
        return createMemo(() => !!isAccessible())() ? projectRouteHref(props2.project, props2.card) : null;
      },
      get classList() {
        return {
          "archived": props2.card && props2.card.is_archived || props2.project.is_archived,
          "covered": imageCoverUrl() !== void 0
        };
      },
      get children() {
        return [(() => {
          const _el$2 = _tmpl$128.cloneNode(true);
          const _ref$ = coverEl;
          typeof _ref$ === "function" ? use(_ref$, _el$2) : coverEl = _el$2;
          createRenderEffect(() => _el$2.classList.toggle("portfolio-cover", !!props2.project.is_portfolio));
          return _el$2;
        })(), createComponent(Show, {
          get when() {
            return createMemo(() => !!props2.project.is_portfolio)() && isScreensizeXS();
          },
          get children() {
            return [(() => {
              const _el$3 = _tmpl$257.cloneNode(true);
              const _ref$2 = portfolioShadowEl;
              typeof _ref$2 === "function" ? use(_ref$2, _el$3) : portfolioShadowEl = _el$3;
              return _el$3;
            })(), (() => {
              const _el$4 = _tmpl$257.cloneNode(true);
              const _ref$3 = portfolioShadowEl2;
              typeof _ref$3 === "function" ? use(_ref$3, _el$4) : portfolioShadowEl2 = _el$4;
              return _el$4;
            })()];
          }
        }), (() => {
          const _el$5 = _tmpl$618.cloneNode(true), _el$6 = _el$5.firstChild, _el$11 = _el$6.nextSibling;
          insert(_el$6, () => props2.card ? props2.card.title : props2.project.title, null);
          insert(_el$6, createComponent(Show, {
            get when() {
              return createMemo(() => !!props2.project.id)() && isProjectAvailableOffline(props2.project);
            },
            get children() {
              return createComponent(Tooltip, {
                get label() {
                  return _4("Available offline");
                },
                get children() {
                  return createComponent(Icon, {
                    name: "fa-cloud-download"
                  });
                }
              });
            }
          }), null);
          insert(_el$5, createComponent(Show, {
            get when() {
              return props2.showTeam && props2.project.team;
            },
            get children() {
              const _el$7 = _tmpl$339.cloneNode(true);
              insert(_el$7, () => props2.project.team.name);
              return _el$7;
            }
          }), _el$11);
          insert(_el$5, createComponent(Show, {
            get when() {
              return props2.card && props2.card.path.length;
            },
            get children() {
              const _el$8 = _tmpl$339.cloneNode(true);
              insert(_el$8, () => _4("in"), null);
              insert(_el$8, createComponent(For, {
                get each() {
                  return props2.card.path;
                },
                children: (b3, index2) => (() => {
                  const _el$17 = _tmpl$913.cloneNode(true);
                  insert(_el$17, () => ` ${b3.title} ` + index2 <= props2.card.path.length ? "" : "/");
                  return _el$17;
                })()
              }), null);
              return _el$8;
            }
          }), _el$11);
          insert(_el$5, createComponent(Show, {
            get when() {
              return props2.project.last_activity_at;
            },
            get children() {
              return createComponent(Tooltip, {
                get label() {
                  return _4("Last updated at");
                },
                get children() {
                  const _el$9 = _tmpl$426.cloneNode(true), _el$10 = _el$9.firstChild;
                  insert(_el$9, createComponent(Icon, {
                    name: "fa-bolt"
                  }), _el$10);
                  insert(_el$9, () => fromNow(props2.project.last_activity_at), null);
                  return _el$9;
                }
              });
            }
          }), _el$11);
          insert(_el$11, createComponent(Show, {
            get when() {
              return remainingMembersCount();
            },
            get children() {
              const _el$12 = _tmpl$523.cloneNode(true), _el$13 = _el$12.firstChild;
              insert(_el$12, remainingMembersCount, null);
              return _el$12;
            }
          }), null);
          insert(_el$11, createComponent(For, {
            get each() {
              return members();
            },
            children: (m3) => createComponent(UserAvatar, {
              user: m3
            })
          }), null);
          insert(_el$5, createComponent(Icon, {
            "class": "project-tile-icon",
            get name() {
              return (props2.card && props2.card.parent_id ? "bi-check-circle" : "") || (!props2.card && props2.project.is_public ? "fa-globe" : "") || (!props2.card && props2.project.is_private ? "fa-lock" : "");
            }
          }), null);
          return _el$5;
        })()];
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return createMemo(() => !!props2.project.is_portfolio)() && !isScreensizeXS();
      },
      get children() {
        return [(() => {
          const _el$14 = _tmpl$257.cloneNode(true);
          const _ref$4 = portfolioShadowEl;
          typeof _ref$4 === "function" ? use(_ref$4, _el$14) : portfolioShadowEl = _el$14;
          return _el$14;
        })(), (() => {
          const _el$15 = _tmpl$257.cloneNode(true);
          const _ref$5 = portfolioShadowEl2;
          typeof _ref$5 === "function" ? use(_ref$5, _el$15) : portfolioShadowEl2 = _el$15;
          return _el$15;
        })()];
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return isAccessible();
      },
      get children() {
        const _el$16 = _tmpl$717.cloneNode(true);
        insert(_el$16, createComponent(Show, {
          get when() {
            return createMemo(() => !!(props2.showFavoriteBtn && !props2.card && isConnected()))() && isMember();
          },
          get children() {
            return createComponent(IconButton, {
              style: "text",
              onClick: (e3) => {
                toggleFavorite();
              },
              get icon() {
                return isFav() ? "fa-star" : "fa-star-o";
              }
            });
          }
        }), null);
        insert(_el$16, createComponent(Show, {
          get when() {
            return createMemo(() => !!!loading())() && isSettingsButtonVisible(props2.project);
          },
          get children() {
            return createComponent(NgComponent, {
              directive: "project-tile-options-button",
              get project() {
                return props2.project;
              }
            });
          }
        }), null);
        return _el$16;
      }
    }), null);
    return _el$;
  })();
}

// public/app/routes/global-home/GlobalHomePage.tsx
var _tmpl$129 = /* @__PURE__ */ template(`<div class="loader"><div class="header"></div><div><div class="tile"></div><div class="tile"></div></div></div>`, 10);
var _tmpl$258 = /* @__PURE__ */ template(`<div class="empty-notice"><i class="fa fa-warning"></i><div><h2></h2><p></p></div></div>`, 10);
var _tmpl$340 = /* @__PURE__ */ template(`<div class="page-container"><div class="topbar" id="topbar"></div><div id="global-home-view" class="page-container-view"></div></div>`, 6);
var _tmpl$427 = /* @__PURE__ */ template(`<span> / </span>`, 2);
var _tmpl$524 = /* @__PURE__ */ template(`<form class="hidden-xs"></form>`, 2);
var _tmpl$619 = /* @__PURE__ */ template(`<div class="alert alert-info trial-message alert-actionnable"><span> </span></div>`, 4);
var _tmpl$718 = /* @__PURE__ */ template(`<div class="alert alert-danger trial-message"> </div>`, 2);
var _tmpl$816 = /* @__PURE__ */ template(`<div class="alert alert-danger trial-message alert-actionnable"><span> </span></div>`, 4);
var _tmpl$914 = /* @__PURE__ */ template(`<span> </span>`, 2);
var _tmpl$1011 = /* @__PURE__ */ template(`<div class="empty"></div>`, 2);
var _tmpl$1111 = /* @__PURE__ */ template(`<div class="global-home-section"><div class="header"><h2><span class="title"></span></h2></div><div class="project-tile-list"></div></div>`, 10);
function GlobalHomePage() {
  const [showUseAsHomeBtn, setShowUseAsHomeBtn] = createSignal(!!get(currentUser2.app_params, "home", ""));
  const personalProjectStore2 = projectStore.scoped({
    dashboard_group: "user"
  });
  function useAsHome() {
    saveUserAppParams({
      "home": ""
    });
    setShowUseAsHomeBtn(false);
  }
  return (() => {
    const _el$ = _tmpl$340.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
    insert(_el$2, createComponent(NgComponent, {
      directive: "quick-global-search-toggle",
      "cover-toggle": "true"
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return showUseAsHomeBtn();
      },
      get children() {
        return createComponent(Tooltip, {
          get label() {
            return _4("Make this page your home when you click the Kantree logo in the upper left corner");
          },
          get children() {
            return createComponent(Button, {
              "class": "btn btn-topbar ms-auto hidden-xs",
              onClick: () => useAsHome(),
              get children() {
                return [createComponent(Icon, {
                  name: "bi-house"
                }), " ", createMemo(() => _4("Use as home"))];
              }
            });
          }
        });
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      get when() {
        return !isAppContextLoaded() && !appContext.projectsCount && !appContext.orgs.length;
      },
      get children() {
        return _tmpl$129.cloneNode(true);
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      get when() {
        return isAppContextLoaded() || appContext.projectsCount && appContext.orgs.length;
      },
      get children() {
        return [createComponent(Show, {
          get when() {
            return favoriteCardStore.count();
          },
          get children() {
            return createComponent(GlobalHomeSection, {
              store: favoriteCardStore,
              showTileTeam: true,
              icon: "bi-star-fill",
              get sectionTitle() {
                return _4("My favorites");
              }
            });
          }
        }), createComponent(Show, {
          get when() {
            return currentUser2.can_create_projects || personalProjectStore2.count();
          },
          get children() {
            return createComponent(GlobalHomeSection, {
              store: personalProjectStore2,
              get sectionTitle() {
                return _4("Personal workspaces");
              },
              id: "personal-workspaces",
              get showCreate() {
                return createMemo(() => !!currentUser2.can_create_projects)() ? _4("New personal workspace") : "";
              },
              showArchivesCheckbox: true
            });
          }
        }), createComponent(Show, {
          get when() {
            return sharedProjectStore.count();
          },
          get children() {
            return createComponent(GlobalHomeSection, {
              store: sharedProjectStore,
              showTileTeam: true,
              get sectionTitle() {
                return _4("Shared workspaces");
              },
              id: "shared-workspaces"
            });
          }
        }), createComponent(For, {
          get each() {
            return appContext.teams;
          },
          children: (spec) => createComponent(GlobalHomeSection, {
            get store() {
              return spec.store;
            },
            get org() {
              return spec.org;
            },
            get team() {
              return spec.team;
            },
            get showCreate() {
              return createMemo(() => !!(!isOrgLocked(spec.org) && spec.org.permission > 0 && (!spec.team && spec.org.permission > 1 || spec.team && spec.team.permission > 1)))() ? _4("New workspace") : "";
            }
          })
        })];
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      get when() {
        return isAppContextLoaded() && !appContext.projectsCount && !appContext.orgs.length && !currentUser2.can_create_projects && !currentUser2.can_create_organizations;
      },
      get children() {
        const _el$5 = _tmpl$258.cloneNode(true), _el$6 = _el$5.firstChild, _el$7 = _el$6.nextSibling, _el$8 = _el$7.firstChild, _el$9 = _el$8.nextSibling;
        insert(_el$8, () => _4("You haven't been invited to any workspaces"));
        insert(_el$9, () => _4("Your current permission settings do not allow you to create workspaces. Ask your team mates to invite you to an existing team or workspace."));
        return _el$5;
      }
    }), null);
    return _el$;
  })();
}
function GlobalHomeSection(props2) {
  const [showArchive, setShowArchive] = createSignal(false);
  const trialRemainingDays = createMemo(() => {
    return props2.org && props2.org.billing ? moment_default(props2.org.billing.trial_ends_at).diff(moment_default(), "days") : null;
  });
  const locked = createMemo(() => {
    return props2.org && isOrgLocked(props2.org);
  });
  const storeData = props2.store.react();
  const localProjects = createMemo(() => {
    return storeData().map((obj) => {
      if (obj.__type__ ? obj.__type__ === cardStore.options.typeName : obj.project_id) {
        return {
          project: projectStore.getForCard(obj),
          card: obj,
          id: `card-${obj.id}`
        };
      } else {
        return {
          project: obj,
          card: null,
          id: `project-${obj.id}`
        };
      }
    }).sort((a3, b3) => compare2(a3.card ? a3.card.title : a3.project.title, b3.card ? b3.card.title : b3.project.title));
  });
  const filteredProjects = createMemo(on([localProjects, showArchive], () => {
    return localProjects().filter(({
      project
    }) => !project.is_archived || showArchive());
  }));
  return (() => {
    const _el$10 = _tmpl$1111.cloneNode(true), _el$11 = _el$10.firstChild, _el$12 = _el$11.firstChild, _el$13 = _el$12.firstChild, _el$28 = _el$11.nextSibling;
    insert(_el$12, createComponent(Show, {
      get when() {
        return props2.icon;
      },
      get children() {
        return createComponent(Icon, {
          get name() {
            return props2.icon;
          },
          "class": "me-1 fs-4"
        });
      }
    }), _el$13);
    insert(_el$13, createComponent(Show, {
      get when() {
        return props2.sectionTitle;
      },
      get children() {
        return props2.sectionTitle;
      }
    }), null);
    insert(_el$13, createComponent(Show, {
      get when() {
        return !props2.sectionTitle && props2.org;
      },
      get children() {
        return [createComponent(Dynamic, {
          get component() {
            return props2.org && props2.org.permission >= 1 ? A3 : "span";
          },
          route: "org.hub",
          get routeParams() {
            return {
              slug: props2.org.slug
            };
          },
          get children() {
            return props2.org.name;
          }
        }), createComponent(Show, {
          get when() {
            return props2.team;
          },
          get children() {
            const _el$14 = _tmpl$427.cloneNode(true), _el$15 = _el$14.firstChild;
            insert(_el$14, createComponent(Dynamic, {
              get component() {
                return props2.org && props2.org.permission >= 1 ? A3 : "span";
              },
              route: "org.team.hub",
              get routeParams() {
                return {
                  slug: props2.org.slug,
                  teamSlug: props2.team.slug
                };
              },
              get children() {
                return props2.team.name;
              }
            }), null);
            return _el$14;
          }
        })];
      }
    }), null);
    insert(_el$12, createComponent(Show, {
      get when() {
        return props2.org && !props2.team && props2.org.permission >= 3;
      },
      get children() {
        return createComponent(A3, {
          "class": "btn btn-primary btn-ghost btn-sm ms-4",
          route: "org.members",
          get routeParams() {
            return {
              slug: props2.org.slug
            };
          },
          get children() {
            return _4("Invite members");
          }
        });
      }
    }), null);
    insert(_el$11, createComponent(Show, {
      get when() {
        return props2.showArchivesCheckbox;
      },
      get children() {
        const _el$16 = _tmpl$524.cloneNode(true);
        insert(_el$16, createComponent(CheckInput, {
          id: "projectListWithArchives",
          name: "projectListWithArchives",
          containerClass: "form-switch me-2 mb-2",
          get label() {
            return _4("Show archives");
          },
          get checked() {
            return showArchive();
          },
          onChange: (e3) => {
            setShowArchive(e3.target.checked);
          }
        }));
        return _el$16;
      }
    }), null);
    insert(_el$10, createComponent(Show, {
      get when() {
        return props2.org && !props2.team && props2.org.permission === 4 && props2.org.billing && props2.org.billing.status == "trialing";
      },
      get children() {
        const _el$17 = _tmpl$619.cloneNode(true), _el$18 = _el$17.firstChild, _el$19 = _el$18.firstChild;
        insert(_el$18, createComponent(Icon, {
          name: "bi-info-square-fill"
        }), _el$19);
        insert(_el$18, () => _4("Only {days} days left to take advantage of your free trial", {
          days: trialRemainingDays()
        }), null);
        insert(_el$17, createComponent(A3, {
          "class": "btn btn-info",
          route: "org.hub",
          get routeParams() {
            return {
              slug: props2.org.slug,
              "#": "billing"
            };
          },
          get children() {
            return _4("Upgrade now");
          }
        }), null);
        return _el$17;
      }
    }), _el$28);
    insert(_el$10, createComponent(Show, {
      get when() {
        return props2.org && !props2.team && props2.org.permission === 4 && locked() && (!props2.org.billing || !props2.org.billing.locked);
      },
      get children() {
        const _el$20 = _tmpl$718.cloneNode(true), _el$21 = _el$20.firstChild;
        insert(_el$20, createComponent(Icon, {
          name: "bi-x-circle-fill"
        }), _el$21);
        insert(_el$20, () => _4("Your organization has been locked."), null);
        return _el$20;
      }
    }), _el$28);
    insert(_el$10, createComponent(Show, {
      get when() {
        return props2.org && !props2.team && props2.org.permission === 4 && props2.org.billing && props2.org.billing.status === "unpaid";
      },
      get children() {
        const _el$22 = _tmpl$816.cloneNode(true), _el$23 = _el$22.firstChild, _el$24 = _el$23.firstChild;
        insert(_el$23, createComponent(Icon, {
          name: "bi-x-circle-fill"
        }), _el$24);
        insert(_el$23, () => _4("Your subscription has been suspended. Upgrade now to continue using this team"), null);
        insert(_el$22, createComponent(A3, {
          "class": "btn btn-danger",
          route: "org.hub",
          get routeParams() {
            return {
              slug: props2.org.slug,
              "#": "billing"
            };
          },
          get children() {
            return _4("Upgrade now");
          }
        }), null);
        return _el$22;
      }
    }), _el$28);
    insert(_el$10, createComponent(Show, {
      get when() {
        return createMemo(() => !!(props2.org && !props2.team && props2.org.permission === 4 && props2.org.billing))() && ["past_due", "incomplete"].includes(props2.org.billing.status);
      },
      get children() {
        const _el$25 = _tmpl$816.cloneNode(true), _el$26 = _el$25.firstChild, _el$27 = _el$26.firstChild;
        insert(_el$26, createComponent(Icon, {
          name: "bi-x-circle-fill"
        }), _el$27);
        insert(_el$26, () => _4("We haven't been able to charge the credit card."), null);
        insert(_el$25, createComponent(A3, {
          "class": "btn btn-danger",
          route: "org.hub",
          get routeParams() {
            return {
              slug: props2.org.slug,
              "#": "billing"
            };
          },
          get children() {
            return _4("Check your billing information");
          }
        }), null);
        return _el$25;
      }
    }), _el$28);
    insert(_el$28, createComponent(For, {
      get each() {
        return filteredProjects();
      },
      children: ({
        project,
        card
      }) => createComponent(ProjectTile, {
        project,
        card,
        get showTeam() {
          return props2.showTileTeam;
        }
      })
    }), null);
    insert(_el$28, createComponent(Show, {
      get when() {
        return props2.showCreate;
      },
      get children() {
        return createComponent(A3, {
          "class": "project-tile-list-create-btn create",
          route: "templates",
          get routeParams() {
            return {
              org: props2.org ? props2.org.id : "",
              team: props2.team ? props2.team.id : ""
            };
          },
          get children() {
            const _el$29 = _tmpl$914.cloneNode(true), _el$30 = _el$29.firstChild;
            insert(_el$29, createComponent(Icon, {
              name: "bi-plus-lg"
            }), _el$30);
            insert(_el$29, () => props2.showCreate, null);
            return _el$29;
          }
        });
      }
    }), null);
    insert(_el$10, createComponent(Show, {
      get when() {
        return createMemo(() => !!!props2.showCreate)() && !localProjects().length;
      },
      get children() {
        const _el$31 = _tmpl$1011.cloneNode(true);
        insert(_el$31, () => _4("You haven't joined any workspaces in this {space}.", {
          space: props2.team ? _4("team") : _4("organization")
        }), null);
        insert(_el$31, createComponent(Show, {
          get when() {
            return props2.org && props2.org.permission !== 0;
          },
          get children() {
            return createComponent(A3, {
              "class": "ms-2",
              route: "org.hub",
              get routeParams() {
                return {
                  slug: props2.org.slug
                };
              },
              get children() {
                return [createMemo(() => _4("Explore workspace")), createComponent(Icon, {
                  name: "bi-box-arrow-up-right",
                  "class": "ms-2"
                })];
              }
            });
          }
        }), null);
        return _el$31;
      }
    }), null);
    insert(_el$10, createComponent(Show, {
      get when() {
        return createMemo(() => !!(!props2.showCreate && localProjects().length))() && !filteredProjects().length;
      },
      get children() {
        const _el$32 = _tmpl$1011.cloneNode(true);
        insert(_el$32, () => _4("You haven't joined any active workspaces in this team. Look at the archives."));
        return _el$32;
      }
    }), null);
    return _el$10;
  })();
}

// public/app/routes/global-home/index.jsx
addRoute({
  name: "globalHome",
  path: "/all",
  component: () => createComponent(AuthenticatedPage, {
    get children() {
      return createComponent(GlobalHomePage, {});
    }
  })
});

// public/app/config/global-views.js
var globalViewsAvailableProps = [
  "filter",
  "filter_scopes",
  "mode",
  "mode_options",
  "group_by",
  "include_descendants",
  "include_archived",
  "locked"
];
var globalViewsDefaultProps = {
  mode: "list",
  include_archived: true,
  filter_scopes: pinnedOrgFilterScopes,
  mode_options: {
    showUngroupedCards: true
  }
};

// public/app/config/project/views.js
var projectViewsAvailableProps = [
  "project_id",
  "card_ref",
  "mode",
  "mode_options",
  "group_by",
  "filter",
  "include_descendants",
  "include_archived",
  "locked"
];
var projectViewsDefaultProps = {
  mode: "kanban",
  limit_to_ref: true,
  mode_options: {
    showUngroupedCards: true
  }
};
var portfolioViewAvailableProps = [
  "project_id",
  "mode",
  "mode_options",
  "group_by",
  "filter",
  "filter_scopes",
  "include_descendants",
  "include_archived",
  "locked"
];
var portfolioViewDefaultProps = {
  mode: "kanban",
  limit_to_ref: true,
  mode_options: {
    showUngroupedCards: true
  }
};

// public/app/apps/cards/common/group-by/registry.js
var GroupByRegistry = class extends Registry {
  get(...args) {
    const GroupByCls = super.get(...args);
    if (!GroupByCls) {
      return this.getDefault();
    }
    return GroupByCls;
  }
  getDefault() {
    return this.getAll().find((Cls) => !!Cls.default);
  }
};
var groupByRegistry = new GroupByRegistry();

// public/app/apps/cards/common/group-by/utils.js
function formatSpec(spec) {
  if (spec && spec.type === "name" && spec.id && spec.id.length) {
    return spec;
  }
  if (spec && spec.type === "group_type" && spec.id && cardGroupTypeStore.exists(spec.id)) {
    return spec;
  }
  if (spec && spec.type === "attribute" && spec.id && cardModelStore.getAttribute(spec.id)) {
    return spec;
  }
  if (spec && spec.type === "projects") {
    return spec;
  }
  if (spec && spec.type === "orgs") {
    return spec;
  }
  if (spec && spec.type === "teams") {
    return spec;
  }
  return { type: "nothing" };
}
function formatSpecFromView(view) {
  let specs = { type: "group_type" };
  if (view.group_by) {
    specs = view.group_by;
  } else if (view.group_type_id) {
    var gt = cardGroupTypeStore.tryGet(view.group_type_id);
    if (gt) {
      specs = { type: "group_type", id: gt.id };
    }
  } else if (view.group_by_attribute_id) {
    if (view.group_by_attribute_id === -1) {
      specs = {};
    } else {
      var attr = cardModelStore.getGroupableAttributes({ id: view.group_by_attribute_id })[0];
      if (attr) {
        specs = { type: "attribute", id: attr.id };
      }
    }
  }
  if (!specs) {
    specs = [{}, {}];
  } else if (!Array.isArray(specs)) {
    specs = [specs, {}];
  }
  return specs.map((spec) => formatSpec(spec));
}
function equals2(groupBy2, otherGroupBy) {
  if (!groupBy2 && !otherGroupBy) return true;
  if (!groupBy2 && otherGroupBy || groupBy2 && !otherGroupBy) return false;
  return groupBy2 === otherGroupBy;
}
function create2(specs, cardStore2, board, includeArchived, groupByGroups) {
  return (specs || [null, null]).map((s3, idx) => {
    const spec = formatSpec(s3);
    const GroupByCls = groupByRegistry.get(spec?.type);
    return new GroupByCls(
      spec,
      cardStore2,
      board,
      includeArchived,
      groupByGroups && groupByGroups.length ? groupByGroups[idx] : null
    );
  });
}
function formatSpecLabel(spec) {
  if (!Array.isArray(spec)) {
    spec = [spec];
  }
  return spec.map((spec2) => groupByRegistry.get(spec2?.type).formatSpecLabel(spec2)).join(_4(" and "));
}
function findBestGroupBy(project, attrType) {
  if (!project || project.is_portfolio) return null;
  if (!attrType) {
    const contexts = cardGroupTypeStore.scopedByEnabled(project).query({}, { sortBy: "name" });
    if (contexts.length) {
      return [{ type: "group_type", id: contexts[0].id }];
    }
    return null;
  }
  const attrs2 = cardModelStore.scopedByEnabled(project).getGroupableAttributes(attrType ? { type: attrType } : null).sort();
  if (attrs2.length) {
    return [{ type: "attribute", id: attrs2[0].id }];
  }
  return null;
}

// public/app/stores/utils/view.js
var modeOptionsKeepEmptyArray = ["visible_attributes"];
function formatModeOptions(modeOptions = {}) {
  var out = {};
  Object.entries(modeOptions).forEach(([key2, opt]) => {
    if (opt === null || opt === "" || opt === 0 || equals(opt, []) && !modeOptionsKeepEmptyArray.includes(key2) || equals(opt, {})) {
      return;
    }
    out[key2] = opt;
  });
  return out;
}
function filterAvailableViewProps(props2) {
  const availableProps = props2.project_id ? projectViewsAvailableProps : globalViewsAvailableProps;
  return availableProps.reduce((accu, propKey) => {
    accu[propKey] = props2[propKey];
    return accu;
  }, {});
}
function getContextParamsFromView(view) {
  const { name: name2, mode, filter: filter4, filter_scopes, mode_options, include_archived, include_descendants, locked } = view;
  const group_by = formatSpecFromView(view);
  let appName = mode;
  const appOptions = { ...mode_options, filter: filter4, name: name2, group_by, include_archived, include_descendants, locked };
  if (cardsAppRegistry.get(mode)) {
    appName = "cards";
    appOptions.mode = mode;
  }
  return { filterScopes: filter_scopes, appName, appOptions };
}
function transformAppChangesIntoViewProps(changes) {
  const newViewProps = {};
  const _changes = { ...changes };
  if (typeof _changes.options !== "undefined") {
    const modeOptions = { ..._changes.options };
    delete modeOptions.name;
    delete modeOptions.include_archived;
    delete modeOptions.include_descendants;
    delete modeOptions.group_by;
    delete modeOptions.filter;
    delete modeOptions.filter_scopes;
    delete modeOptions.mode;
    delete modeOptions.locked;
    if (Object.keys(modeOptions).length > 0 && typeof modeOptions === "object") {
      newViewProps.mode_options = modeOptions;
    }
    if (typeof _changes.options.name !== "undefined") {
      newViewProps.name = _changes.options.name;
    }
    if (typeof _changes.options.include_archived !== "undefined") {
      newViewProps.include_archived = _changes.options.include_archived;
    }
    if (typeof _changes.options.include_descendants !== "undefined") {
      newViewProps.include_descendants = _changes.options.include_descendants;
    }
    if (typeof _changes.options.group_by !== "undefined") {
      newViewProps.group_by = _changes.options.group_by;
    }
    if (typeof _changes.options.filter !== "undefined") {
      newViewProps.filter = _changes.options.filter;
    }
    if (typeof _changes.options.filter_scopes !== "undefined") {
      newViewProps.filter_scopes = _changes.options.filter_scopes;
    }
    if (typeof _changes.options.mode !== "undefined") {
      newViewProps.mode = _changes.options.mode;
    }
    if (typeof _changes.options.locked !== "undefined") {
      newViewProps.locked = _changes.options.locked;
    }
    delete _changes.options;
  }
  return { ..._changes, ...newViewProps };
}
function applyAppChangesToView(view, changes, defaultProps = {}, availableProps) {
  let viewProps = transformAppChangesIntoViewProps(changes);
  viewProps = {
    ...defaultProps,
    ...view,
    ...viewProps,
    mode_options: {
      ...defaultProps.mode_options,
      ...viewProps.mode_options,
      ...view?.mode === viewProps.mode ? view.mode_options : {}
    }
  };
  return availableProps ? { ...availableProps.reduce((accu, propName) => {
    accu[propName] = viewProps[propName];
    return accu;
  }, {}) } : viewProps;
}

// public/app/actions/view.ts
async function createFromLocalView(name2, view, isPublic) {
  const params = {
    name: name2,
    public: !!isPublic,
    icon: view.icon,
    mode: view.mode,
    mode_options: formatModeOptions(view.mode_options),
    card_ref: view.card_ref,
    limit_to_ref: true,
    group_by: view.group_by ? formatSpecFromView(view) : null,
    filter: view.filter,
    include_archived: view.include_archived,
    include_descendants: view.include_descendants,
    filter_scopes: view.filter_scopes
  };
  if (view.project_id) {
    params["project_id"] = view.project_id;
  }
  if (view.category_id) {
    params["category_id"] = view.category_id;
  }
  if (view.org_id) {
    params["org_id"] = view.org_id;
  }
  view = await api_default.views.create_view.post(params);
  view = viewStore.insert(view);
  return view;
}
async function createProjectView(name2, project, view, { isPublic = false, defaultProps = projectViewsDefaultProps } = {}) {
  view.project_id = project.id;
  if (project.is_portfolio) {
    defaultProps = portfolioViewDefaultProps;
  }
  if (view.filter_scopes && !isString_default(view.filter_scopes)) {
    view.filter_scopes = filterScopesToString(view.filter_scopes);
  }
  return createFromLocalView(name2, Object.assign({}, defaultProps, view), isPublic);
}
async function updateView(view, data2, withStoreUpdate = true) {
  view = await api_default.views.update_view.put(Object.assign({
    view_id: view.id,
    name: view.name,
    icon: view.icon,
    card_ref: view.card_ref,
    group_by: view.group_by ? formatSpecFromView(view) : null,
    // group_type_id: view.group_type_id,
    // group_by_attribute_id: view.group_by_attribute_id,
    filter: view.filter,
    mode: view.mode,
    mode_options: view.mode_options,
    include_archived: view.include_archived,
    include_descendants: view.include_descendants,
    locked: view.locked,
    filter_scopes: view.filter_scopes
  }, data2 || {}));
  if (withStoreUpdate) {
    return viewStore.update(view);
  }
  return view;
}
async function reorderView(view, relativeToView, positionStrategy, category) {
  let v3;
  const params = {
    view_id: view.id
  };
  if (relativeToView) {
    if (positionStrategy === "before") {
      params["before_view_id"] = relativeToView.id;
    }
    if (positionStrategy === "replace") {
      params["after_view_id"] = relativeToView.id;
    }
  }
  if (view.project_id) {
    v3 = await api_default.project_views.reorder_view.post(Object.assign(params, {
      project_id: view.project_id,
      category_id: category ? category.id : null
    }));
  } else {
    v3 = await api_default.views.reorder_view.post(params);
  }
  let store2;
  if (v3.project_id) {
    store2 = viewStore.scopedByProject({ id: v3.project_id });
  } else {
    store2 = viewStore.scopedByGlobal();
  }
  const oldCategoryId = view.category_id;
  const oldPosition = view.position;
  store2.transaction(() => {
    store2.update(v3);
    store2.reorderAfterChange(v3, oldPosition, oldCategoryId);
  });
}
async function makeViewPublic(view) {
  view = await api_default.views.update_view.put({
    view_id: view.id,
    public: true,
    reset_position: true
  });
  return viewStore.update(view);
}
async function toggleFavoriteView(view) {
  if (isFavorite("view", view.id)) {
    await api_default.views.unfavorite_view.delete({ view_id: view.id });
    removeFavorite("view", view.id);
  } else {
    await api_default.views.favorite_view.post({ view_id: view.id });
    addFavorite("view", view.id);
  }
  viewStore.broadcast("changed");
}
async function deleteView(view) {
  await api_default.views.delete_view.delete({ view_id: view.id });
  let store2;
  if (view.project_id) {
    store2 = viewStore.scopedByProject({ id: view.project_id });
  } else {
    store2 = viewStore.scopedByGlobal();
  }
  store2.remove(view);
}
async function createViewCategory(project, name2) {
  const category = await api_default.project_views.create_view_category.post({ project_id: project.id, name: name2 });
  return viewCategoryStore.insert(category);
}
async function createDefaultViewCategory(project, name2) {
  let categories = viewCategoryStore.scopedByProject(project).query();
  let category = await api_default.project_views.create_view_category.post({
    project_id: project.id,
    name: name2,
    attached_uncategorized_views: true,
    before_category_id: categories.length ? categories[0].id : null
  });
  viewCategoryStore.updateMany(categories, { position: (p4) => p4 + 1 });
  category = viewCategoryStore.insert(category);
  viewStore.scopedByProject(project).updateManyMatching({ category_id: query_exports.isFalsy() }, { category_id: category.id });
  return category;
}
async function renameViewCategory(category, name2) {
  category = await api_default.project_views.update_view_category.put(
    { project_id: category.project_id, category_id: category.id, name: name2 }
  );
  return viewCategoryStore.update(category);
}
async function reorderViewCategory(category, beforeCategory) {
  const c3 = await api_default.project_views.reorder_view_category.post({
    project_id: category.project_id,
    category_id: category.id,
    before_category_id: beforeCategory ? beforeCategory.id : null
  });
  viewCategoryStore.reorder(category, c3.position);
}
async function deleteViewCategory(category, deleteViews) {
  await api_default.project_views.delete_view_category.delete({
    project_id: category.project_id,
    category_id: category.id,
    delete_views: deleteViews
  });
  if (deleteViews) {
    viewStore.removeManyMatching({ category_id: category.id });
  } else {
    let lastView = viewStore.query({ project_id: category.project_id }, { sortBy: "-position" })?.[0];
    let position = lastView ? lastView.position + 1 : 0;
    for (const view of viewStore.query({ category_id: category.id }, { sortBy: "position" })) {
      viewStore.update(view, { position, category_id: null });
      position++;
    }
  }
  viewCategoryStore.remove(category);
}

// public/app/apps/context.js
var BaseContext = class extends mixin2(EventedMixin) {
  constructor(config3 = {}, app, appOptions) {
    super();
    this.initEventedMixin();
    if (config3) {
      for (const [key2, value2] of Object.entries(config3)) {
        this["_" + key2] = value2;
        Object.defineProperty(this, key2, {
          get() {
            return this["_" + key2];
          },
          set(newVal) {
            const oldVal = this["_" + key2];
            this["_" + key2] = newVal;
            this._afterChange(key2 + "Changed", this["_" + key2], oldVal);
          },
          enumerable: true
        });
      }
    }
    if (app) {
      this.app = app;
    }
    this.appOptions = appOptions || {};
  }
  updateConfig(config3) {
    for (const [key2, value2] of Object.entries(config3)) {
      if (!equals(this[key2], value2)) {
        this[key2] = value2;
      }
    }
  }
  update(config3, app, appOptions) {
    this.transaction(() => {
      if (!!config3 && !this.configEquals(config3)) {
        this.updateConfig(config3);
      }
      if (!!app && !this.appEquals(app.name)) {
        this.app = app;
      }
      if (!!appOptions && !this.appOptionsEquals(appOptions)) {
        this.appOptions = appOptions;
      }
    });
  }
  transaction(callback) {
    if (this._delayEventTriggering) {
      return callback();
    }
    this._delayEventTriggering = true;
    this._delayedEventTriggers = [];
    const r3 = callback();
    this._delayEventTriggering = false;
    this._delayedEventTriggers.map(this._delayedEventTriggers.pop, [...this._delayedEventTriggers]).filter((eventTriggerArgs, index2, self2) => {
      return index2 === self2.findIndex((tArgs) => tArgs[0] === eventTriggerArgs[0]);
    }).forEach((eventTriggerArgs) => {
      this.trigger(...eventTriggerArgs);
    });
    this._delayedEventTriggers = null;
    return r3;
  }
  _afterChange(eventName, ...args) {
    if (this._delayEventTriggering) {
      this._delayedEventTriggers.push([eventName, ...args]);
      return;
    }
    this.trigger(eventName, ...args);
  }
  configEquals(config3) {
    return Object.keys(config3).every((key2) => {
      return equals(this[key2], config3[key2]);
    });
  }
  appEquals(appName) {
    return this.app?.name === appName;
  }
  appOptionsEquals(appOptions) {
    return equals(this.appOptions, appOptions);
  }
  get app() {
    return this._app;
  }
  set app(app) {
    const old = this._app;
    this._app = app;
    this.appState = {};
    this.clearListeners("appOptionsChanged");
    this._afterChange("appChanged", this._app, old);
  }
  get appOptions() {
    return this._appOptions;
  }
  set appOptions(options2) {
    const old = this._appOptions;
    this._appOptions = options2;
    this._afterChange("appOptionsChanged", this._appOptions, old);
  }
  destroy() {
    this.clearListeners();
    this.trigger("destroy");
  }
};

// public/app/apps/reports/utils.ts
var onForceRefreshAllWidgets = createEvent();
function formatWidgetForDisplay(widget, charts = [], chartsData = []) {
  const _widget = Object.assign({}, widget);
  for (const chart of charts) {
    if (chart.name === widget.chart) {
      _widget.chart = chart;
      break;
    }
  }
  for (const data2 of chartsData) {
    if (equals(data2.position, widget.position)) {
      _widget.chartConfig = data2;
    }
  }
  return _widget;
}
function formatWidgetForStore(widget) {
  const _widget = Object.assign(
    {
      options: {},
      position: null
    },
    widget
  );
  delete _widget.chartConfig;
  if (_widget.chart && typeof _widget.chart !== "string") {
    _widget.title = _widget.title || _widget.chart.title;
    _widget.chart = _widget.chart.name;
  }
  return _widget;
}
function missingReqsForWidget(widget) {
  if (!widget || !widget.chart) return true;
  if (!widget.filter_scopes || widget.filter_scopes.length === 0) return true;
  if (typeof widget.chart == "string") return false;
  return widget.chart?.options?.some((opt) => {
    return opt.required && (widget.options?.[opt.name] === void 0 || widget.options?.[opt.name] === null);
  });
}

// public/app/apps/reports/context-mixin.js
var ReportContextMixin = {
  updateReportWidgets(widgets, title) {
    this.appOptions = {
      ...this.appOptions,
      widgets: this.formatReportWidgets(widgets),
      title
    };
  },
  formatReportWidgets(widgets = []) {
    if (!widgets.length) return;
    return widgets.map((widget) => {
      const _widget = formatWidgetForStore(widget);
      if (this.filterScopes) {
        delete _widget.filter_scopes;
      }
      return _widget;
    });
  }
};

// public/app/apps/cards/common/group-by-list-generator.js
function fetchGroupByChoices(filter4, filterScopes, options2) {
  filter4 = filter4?.trim();
  if (filterScopes?.[0]?.[0] === "portfolio") {
    return api_default.project_portfolio.list_group_by_possibilities.get(Object.assign(
      { project_id: filterScopes[0][1] },
      filter4 ? { filter: filter4 } : {}
    ), options2).then((groupBys) => {
      return groupBys.map((groupBy2) => ({ "type": "name", "id": groupBy2.name, "types": groupBy2.types }));
    });
  }
  return api_default.search.list_group_by_possibilities.get({
    filter: filter4,
    filter_scopes: filterScopesToString(filterScopes)
  }, options2).then((groupBys) => {
    return groupBys.map((groupBy2) => ({ "type": "name", "id": groupBy2.name, "types": groupBy2.types }));
  });
}
function fetchGroupByGroups(groupBy2, filter4, filterScopes, options2 = {}) {
  filter4 = filter4?.trim();
  if (filterScopes?.[0]?.[0] === "portfolio") {
    return api_default.project_portfolio.list_group_by_groups.get({
      project_id: filterScopes[0][1],
      filter: filter4,
      group_by: groupBy2.id
    }, options2);
  }
  return api_default.search.list_group_by_groups.get({
    filter: filter4,
    filter_scopes: filterScopesToString(filterScopes),
    group_by: groupBy2.id
  }, options2);
}

// public/app/apps/global/context.js
var GlobalContext = class extends extendWithMixin(BaseContext, ReportContextMixin) {
  constructor(config3 = {}, app, appOptions) {
    super({ ...config3, fetching: false, needFetchCards: false }, app, appOptions);
    this.on("fetchingChanged", () => {
      if (!this.fetching) {
        this.needFetchCards = false;
      }
    });
  }
  get cardStore() {
    return this._cardStore;
  }
  set cardStore(cards) {
    const oldStore = this._cardStore;
    const store2 = cards && cards.length > 0 ? cardStore.scoped({
      id: query_exports.any(cards.map((card) => card.id)),
      is_archived: (v3) => this.appOptions?.include_archived ? true : !v3,
      is_template: query_exports.isFalsy()
    }) : null;
    this._cardStore = store2;
    this._afterChange("cardStoreChanged", this._cardStore, oldStore);
  }
  get groupByChoices() {
    return this._groupByChoices;
  }
  set groupByChoices(choices) {
    const oldChoices = this._groupByChoices;
    this._groupByChoices = choices;
    this._afterChange("groupByChoicesChanged", this._groupByChoices, oldChoices);
  }
  get groupByGroups() {
    return this._groupByGroups;
  }
  set groupByGroups(groups) {
    const oldGroups = this._groupByGroups;
    this._groupByGroups = groups;
    this._afterChange("groupByGroupsChanged", this._groupByGroups, oldGroups);
  }
  get needsGroupByGroupRefreshWhenCardStoreChange() {
    return this.appOptions && this.appOptions.group_by.some(
      (groupBySpec) => groupBySpec && ["projects", "orgs", "teams"].includes(groupBySpec.type)
    );
  }
  async fetchCards() {
    if (this.filterScopes && this.filterScopes.length === 0) {
      if (!!this.cardStore) {
        this.cardStore = null;
      }
      return Promise.reject("Filter scopes is empty");
    }
    this.fetching = true;
    try {
      const cards = await searchCards(this.appOptions.filter, this.filterScopes, null, { ignoreErrorHandlers: true });
      this.cardStore = cards;
      return this.cardStore;
    } catch (reason) {
      if (!!this.cardStore) {
        this.cardStore = null;
      }
      return Promise.reject(reason);
    } finally {
      this.fetching = false;
    }
  }
  async fetchGroupByChoices() {
    if (this.filterScopes && !this.filterScopes.length) {
      if (this.groupByChoices) {
        this.groupByChoices = null;
      }
      return Promise.reject("Filter scopes is empty");
    }
    try {
      const groupByChoices = await fetchGroupByChoices(this.appOptions.filter, this.filterScopes);
      if (groupByChoices && groupByChoices.length > 0 || this.groupByChoices) {
        this.groupByChoices = groupByChoices;
      }
      return this.groupByChoices;
    } catch (reason) {
      if (this.groupByChoices) {
        this.groupByChoices = null;
      }
      return Promise.reject(reason);
    }
  }
  async fetchGroupByGroups() {
    if (!this.appOptions.group_by) {
      if (this.groupByGroups) {
        this.groupByGroups = null;
      }
      return Promise.reject("Group by is empty");
    }
    const groupByGroups = [];
    const reasons = [];
    for (const groupBySpec of this.appOptions.group_by) {
      if (groupBySpec && groupBySpec.type === "name") {
        const filter4 = this.appOptions.filter?.trim();
        if (this.filterScopes && !this.filterScopes.length) {
          groupByGroups.push(null);
          reasons.push("Filter scopes is empty");
          continue;
        }
        try {
          const groupsTitles = await fetchGroupByGroups(groupBySpec, filter4, this.filterScopes, { ignoreErrorHandlers: true });
          if (!groupsTitles || !groupsTitles.length) {
            groupByGroups.push(null);
            continue;
          }
          groupByGroups.push(groupsTitles.map((title) => ({ title })));
          continue;
        } catch (reason) {
          groupByGroups.push(null);
          reasons.push(reason);
          continue;
        }
      }
      if (!groupBySpec || !["projects", "orgs", "teams"].includes(groupBySpec.type)) {
        groupByGroups.push(null);
        continue;
      }
      const [groups, r3] = await this.getGroupByGroupsFromProjects(groupBySpec);
      groupByGroups.push(groups);
      if (r3) {
        reasons.push(r3);
      }
    }
    this.groupByGroups = groupByGroups;
    if (reasons.length) {
      return Promise.reject(reasons);
    }
    return this.groupByGroups;
  }
  async getGroupByGroupsFromProjects(groupBySpec) {
    if (!this.cardStore) {
      return [null, "Card store is empty"];
    }
    const projects = [];
    for (const projectId of uniq(pluck(this.cardStore.query(), "project_id"))) {
      try {
        const project = await getOrLoadProject(projectId, { ignoreErrorHandlers: true });
        projects.push(project);
      } catch (reason) {
        console.warn(reason);
      }
    }
    if (groupBySpec.type === "projects") {
      return [projects];
    }
    if (groupBySpec.type === "orgs") {
      const orgs = /* @__PURE__ */ new Map();
      for (const { owner: org2 } of projects) {
        if (!org2) continue;
        if (org2.type === "org") {
          const storedOrg = orgStore.tryGet(org2.id);
          if (storedOrg && Number.isInteger(storedOrg.permission)) {
            orgs.set(storedOrg.id, storedOrg);
          } else {
            orgs.set("shared", { id: "shared", type: "shared" });
          }
        }
        if (org2.type === "user") {
          if (org2.name !== currentUser2.username) {
            orgs.set("shared", { id: "shared", type: "shared" });
          } else {
            orgs.set("user", { id: "user", type: "user" });
          }
        }
      }
      return [[...orgs.values()]];
    }
    if (groupBySpec.type === "teams") {
      const teams = /* @__PURE__ */ new Map();
      for (const { team } of projects) {
        if (!team) continue;
        teams.set(`${team.id}_${team.name}`, team);
      }
      return [[...teams.values()]];
    }
    return [null];
  }
};

// public/app/apps/global/utils.ts
function setupContextAndFetch($scope2, view, updateViewCallback, preventFirstCallback = false) {
  const { filterScopes, appName, appOptions } = getContextParamsFromView(view);
  const app = globalAppRegistry.get(appName, true, true);
  const context = new GlobalContext({ filterScopes }, app, appOptions);
  const onChanges = updateViewCallback ? (changes) => {
    const props2 = transformAppChangesIntoViewProps(changes);
    if (viewStore.hasChanges(view, props2)) {
      const defaultProps = context.app.name === "cards" ? globalViewsDefaultProps : null;
      const availableProps = globalViewsAvailableProps;
      const formattedView = viewStore.formatDraftView(
        view,
        props2,
        defaultProps,
        availableProps
      );
      updateViewCallback(formattedView, changes);
    }
  } : void 0;
  return setupContextWatchers($scope2, context, onChanges, preventFirstCallback);
}
var fetchGroupByChoices2 = debounce2(
  (context) => context.fetchGroupByChoices(),
  60
);
var fetchGroupByGroups2 = debounce2(
  (context) => context.fetchGroupByGroups(),
  60
);
var fetchCards = debounce2((context) => context.fetchCards(), 60);
function fetchAll(context) {
  fetchCards(context);
  fetchGroupByChoices2(context);
  if (!context.needsGroupByGroupRefreshWhenCardStoreChange) {
    fetchGroupByGroups2(context);
  }
}
function setupContextWatchers($scope2, context, onChanges, preventFirstCallback = false) {
  let preventCallback = preventFirstCallback;
  const refreshUI = debounce2(() => $scope2.$applyAsync(), 60);
  context.watch(
    "cardStore",
    () => {
      if (context.needsGroupByGroupRefreshWhenCardStoreChange) {
        fetchGroupByGroups2(context);
      } else {
        refreshUI();
      }
    },
    false
  );
  context.watch("groupByChoices", refreshUI, false);
  context.watch("groupByGroups", refreshUI, false);
  let deregisterAppOptionsWatcher, deregisterFilterScopesWatcher, deregisterFetchAllWatcher, disposeOnForceRefreshAllWidgetsEventListener;
  context.watch("app", (newApp, oldApp) => {
    if (deregisterAppOptionsWatcher) deregisterAppOptionsWatcher();
    deregisterAppOptionsWatcher = context.watch(
      "appOptions",
      (newVal, oldVal) => {
        if (context.app.name === "cards") {
          if (!equals(newVal?.filter, oldVal?.filter)) {
            fetchAll(context);
          } else if (!equals(newVal?.group_by, oldVal?.group_by)) {
            fetchGroupByGroups2(context);
          }
        }
        if (!preventCallback && onChanges) {
          onChanges({ filter_scopes: context.filterScopes, options: newVal });
        }
        if (context.app.name !== "cards") {
          preventCallback = false;
        }
      },
      false
    );
    if (deregisterFilterScopesWatcher) {
      deregisterFilterScopesWatcher();
      deregisterFilterScopesWatcher = null;
    }
    if (deregisterFetchAllWatcher) {
      deregisterFetchAllWatcher();
      deregisterFetchAllWatcher = null;
    }
    if (disposeOnForceRefreshAllWidgetsEventListener) {
      disposeOnForceRefreshAllWidgetsEventListener();
      disposeOnForceRefreshAllWidgetsEventListener = null;
    }
    if (context.app.name === "cards" && context.app.name !== oldApp?.name) {
      deregisterFilterScopesWatcher = context.watch(
        "filterScopes",
        (newVal, oldVal) => {
          fetchAll(context);
          if (!preventCallback && onChanges) {
            onChanges({ filter_scopes: newVal, options: context.appOptions });
          }
          preventCallback = false;
        }
      );
      deregisterFetchAllWatcher = context.on(
        "fetchAll",
        () => fetchAll(context)
      );
    }
    if (context.app.name === "report" && context.app.name !== oldApp?.name) {
      disposeOnForceRefreshAllWidgetsEventListener = onForceRefreshAllWidgets.subscribe(() => {
        context.needFetchCards = false;
      });
    }
  });
  let disposeScopeDestroyEventListener = $scope2.$on("$destroy", () => {
    context.destroy();
  });
  context.on("destroy", () => {
    if (disposeOnForceRefreshAllWidgetsEventListener) {
      disposeOnForceRefreshAllWidgetsEventListener();
      disposeOnForceRefreshAllWidgetsEventListener = null;
    }
    if (disposeScopeDestroyEventListener) {
      disposeScopeDestroyEventListener();
      disposeScopeDestroyEventListener = null;
    }
    fetchGroupByChoices2.clear();
    fetchGroupByGroups2.clear();
    fetchCards.clear();
    refreshUI.clear();
  });
  return context;
}

// public/app/routes/global-search/ng-components/search.js
angular_default.module("kantree").directive("globalSearch", function() {
  return {
    //---act as component
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    replace: true,
    //---
    templateUrl: "/static/app/routes/global-search/ng-components/templates/search.html",
    controller: class extends AngularClass {
      static $inject = ["$scope", "$q", "$state"];
      $onInit() {
        injectI18nHelpersIntoScope(this.$scope);
        this.isScreensizeXS = isScreensizeXS;
        let view = { ...globalViewsDefaultProps, mode: "list", filter_scopes: [] };
        if (this.$state.params.q) {
          view["filter"] = this.$state.params.q;
        }
        let viewProps;
        this.context = setupContextAndFetch(this.$scope, view, (_viewProps) => {
          viewProps = _viewProps;
        });
        this.saveAsDashboard = () => {
          viewProps.icon = "bi-search";
          this.$q.when(createFromLocalView("", viewProps, false), (view2) => {
            this.$state.go("myWork.dashboard", { viewId: view2.id });
          });
        };
      }
    }
  };
});

// public/app/routes/global-search/index.jsx
addRoute({
  name: "search",
  path: "/search",
  component: () => createComponent(AuthenticatedPage, {
    get children() {
      return createComponent(NgComponent, {
        directive: "global-search"
      });
    }
  })
});

// public/app/loaders/view.js
var loader5 = new StoreLoader(viewStore);
function loadView(viewId) {
  return loader5.load(api_default.views.get_view, { view_id: viewId });
}
function getOrLoadView(viewId) {
  return loader5.getOrLoad(viewId, api_default.views.get_view, { view_id: viewId });
}
function loadMyWorkViews() {
  return loader5.loadMany(api_default.views.list_my_work_views);
}

// public/app/routes/my-work/MyWorkPage.jsx
var _tmpl$130 = /* @__PURE__ */ template(`<div class="page-container"></div>`, 2);
function MyWorkPage(props2) {
  loadMyWorkViews();
  const sidebarConfig = {
    header: [{
      type: "page-header",
      options: {
        title: _4("My work")
      }
    }],
    fixedContent: [{
      type: "link",
      options: {
        label: _4("Inbox"),
        icon: "bi-inbox-fill",
        href: routeHref("myWork.inbox")
      },
      active: () => ngApp.$injector.get("$state").is("myWork.inbox")
    }, {
      type: "link",
      options: {
        label: _4("Agenda"),
        icon: "bi-calendar",
        href: routeHref("myWork.agenda")
      },
      active: () => ngApp.$injector.get("$state").is("myWork.agenda")
    }, {
      type: "link",
      options: {
        label: _4("Cards assigned to me"),
        icon: "bi-check-circle",
        href: routeHref("myWork.assigned")
      },
      active: () => ngApp.$injector.get("$state").is("myWork.assigned")
    }, {
      type: "link",
      options: {
        label: _4("My requests"),
        icon: "kfi-form",
        href: routeHref("myWork.requests")
      },
      active: () => ngApp.$injector.get("$state").is("myWork.requests")
    }],
    content: [{
      type: "my-work-dashboard-list"
    }, {
      type: "my-work-project-view-list"
    }]
  };
  return [createComponent(NgComponent, {
    directive: "nav-sidebar",
    config: sidebarConfig
  }), (() => {
    const _el$ = _tmpl$130.cloneNode(true);
    insert(_el$, () => props2.children);
    return _el$;
  })()];
}

// public/app/routes/my-work/ng-components/agenda.js
angular_default.module("kantree").component("myWorkAgenda", {
  template: `
    <my-work-dashboard view="$ctrl.view" on-filter-scopes-change="$ctrl.saveFilterScopes($filterScopes)" with-empty-notice="false"></my-work-dashboard>
  `,
  controller: class extends AngularClass {
    static $inject = ["$q"];
    $onInit() {
      this.view = {
        ...globalViewsDefaultProps,
        filter_scopes: get(currentUser2.app_params, "myWorkFilterScopes", [["pinned"]]),
        mode: "calendar",
        filter: "@me {$date}!=empty",
        name: _4("Agenda")
      };
    }
    saveFilterScopes(filterScopes) {
      this.$q.digest(saveUserAppParams({ "myWorkFilterScopes": filterScopes }));
    }
  }
});

// public/app/routes/my-work/ng-components/assigned.js
angular_default.module("kantree").component("myWorkAssigned", {
  template: `
    <my-work-dashboard view="$ctrl.view" on-filter-scopes-change="$ctrl.saveFilterScopes($filterScopes)"></my-work-dashboard>
  `,
  controller: class extends AngularClass {
    static $inject = ["$q"];
    $onInit() {
      this.view = {
        ...globalViewsDefaultProps,
        filter_scopes: get(currentUser2.app_params, "myWorkFilterScopes", [["pinned"]]),
        mode: "list",
        filter: "@me state!=finished",
        group_by: [{ type: "projects" }, { id: "nothing", type: "nothing" }],
        name: _4("Assigned cards")
      };
    }
    saveFilterScopes(filterScopes) {
      this.$q.digest(saveUserAppParams({ "myWorkFilterScopes": filterScopes }));
    }
  }
});

// public/app/routes/my-work/ng-components/dashboard.js
angular_default.module("kantree").component("myWorkDashboard", {
  templateUrl: "/static/app/routes/my-work/ng-components/templates/dashboard.html",
  bindings: {
    originalView: "<?view",
    onFilterScopesChange: "&",
    withEmptyNotice: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isScreensizeXS = isScreensizeXS;
      if (this.withEmptyNotice === void 0) {
        this.withEmptyNotice = true;
      }
    }
    $onDestroy() {
      this.globalViewStore.removeManyMatching({ _draft: true });
    }
    $onChanges(changes) {
      if (changes.originalView) {
        if (this.context) {
          this.$onDestroy();
          this.unregisterWatchers();
          this.draftRemovalWatcher && this.draftRemovalWatcher();
        }
        this.view = this.originalView;
        if (!this.view._draft) {
          let draftView = this.globalViewStore.tryGetDraftView(this.view);
          if (draftView) {
            this.view = draftView;
          }
        }
        this.setupContext();
        this.unregisterWatchers = offMany([
          viewStore.$watch(this.$scope, this.originalView, "updated", (v3) => {
            this.view = v3;
          }, false),
          viewStore.$watch(this.$scope, this.originalView, "removed", () => {
            this.$state.go("myWork.inbox");
          }, false)
        ]);
      }
    }
    get globalViewStore() {
      return viewStore.scopedByGlobal();
    }
    setupContext() {
      this.draftRemovalWatcher = null;
      this.context = setupContextAndFetch(this.$scope, this.originalView, (viewProps) => {
        this.draftRemovalWatcher && this.draftRemovalWatcher();
        this.view = this.globalViewStore.upsertDraftView(viewProps, this.originalView);
        this.draftRemovalWatcher = viewStore.$watch(this.$scope, this.view, "removed", () => {
          this.view = this.originalView;
          this.draftRemovalWatcher();
          this.setupContext();
        }, false);
      }, this.originalView.mode !== "report");
      this.context.hideNav = !this.originalView.id;
      this.context.$watch(this.$scope, "filterScopes", () => this.onFilterScopesChange({ $filterScopes: this.context.filterScopes }), false);
    }
    saveAsDashboard() {
      this.$q.when(createFromLocalView(this.view.name || "", this.view, false), (view) => {
        this.$state.go("myWork.dashboard", { viewId: view.id });
      });
    }
  }
});

// public/app/ui/utils/page-title.js
var separator = " | ";
var isFirstChange = true;
var originalTitle;
var subtitleStack = [];
var _subtitle;
var _badge;
function update() {
  if (isFirstChange) {
    originalTitle = document.title;
    isFirstChange = false;
  }
  let title = originalTitle;
  if (_subtitle) {
    title = _subtitle + separator + title;
  }
  if (_badge !== null) {
    title = "(" + _badge + ") " + title;
  }
  document.title = title;
}
function updateSubtitle(subtitle) {
  if (_subtitle) {
    subtitleStack.push(_subtitle);
  }
  _subtitle = subtitle;
  update();
  return revertSubtitle;
}
function revertSubtitle() {
  if (subtitleStack.length > 0) {
    _subtitle = subtitleStack.pop();
  } else {
    _subtitle = null;
  }
  update();
}
function clearSubtitle() {
  subtitleStack = [];
  _subtitle = null;
  update();
}
function updateBadge(badge) {
  _badge = badge;
  update();
}
function clearBadge() {
  _badge = null;
  update();
}

// public/app/services/notifications.js
var store = new ActivityStore({ autoLoad: false });
var [unreadNotifications, setUnreadNotifications] = createSignal(null);
var onNewUnreadNotifications = createEvent();
createEffect(() => {
  if (isAuthenticated()) {
    checkNotifications();
    getPushConnection().then((conn) => {
      conn.on("notified", () => checkNotifications());
    });
  }
});
createEffect(on(
  () => appContext.org,
  () => updateUnreadCount()
));
var prevUnread;
var checkNotifications = debounce2(function() {
  prevUnread = unreadNotifications();
  api_default.user.list_notifications.get({}, { ignoreErrorHandlers: true }).then((activities) => {
    store.upsertMany(activities);
    updateUnreadCount();
    if (prevUnread !== null && unreadNotifications() > prevUnread) {
      onNewUnreadNotifications();
    }
    notifyConnectionRecovered();
  }, () => {
    notifyConnectionLost();
  });
}, 200);
function markNotificationsAsRead(activities) {
  return api_default.user.clear_notifications.delete({ activity_ids: activities.map((a3) => a3.id) }).then(() => {
    for (let activity of activities) {
      store.removeById(activity.id);
    }
    updateUnreadCount();
  });
}
function markAllNotificationsAsRead(scope, customStoreRemovalFn) {
  return api_default.user.clear_notifications.delete(scope).then(() => {
    if (scope && !customStoreRemovalFn) {
      store.removeManyMatching(scope);
    } else if (!customStoreRemovalFn) {
      store.removeAll();
    } else {
      customStoreRemovalFn(store);
    }
    updateUnreadCount();
  });
}
function updateUnreadCount() {
  const unread = store.query().length;
  setUnreadNotifications(unread);
  if (unread === 0) {
    clearBadge();
  } else {
    updateBadge(unread);
  }
}

// public/app/ui/inbox/utils.ts
function isCardFeedItem(feedItem) {
  return feedItem.card !== void 0;
}
function isActivitiesFeedItem(feedItem) {
  return Array.isArray(feedItem.activities);
}
function isDateSeparatorFeedItem(feedItem) {
  return typeof feedItem.separator === "string";
}
function processInboxFeedFetchedData(data2, feed, feedCardIds, feedDates, feedActivityStore) {
  let accuActivitiesWithoutCards = [];
  let today = moment_default().format("LL");
  function pushAccuActivitiesWithoutCards() {
    if (accuActivitiesWithoutCards.length) {
      feed.push({
        id: accuActivitiesWithoutCards[0].id,
        latest_activity_id: accuActivitiesWithoutCards[0].id,
        activities: accuActivitiesWithoutCards
      });
    }
    accuActivitiesWithoutCards = [];
  }
  const activities = feedActivityStore.upsertMany(data2.activities);
  for (let activity of activities) {
    if (!feedDates.has(activity.formatted_date)) {
      if (!feed.length || !isDateSeparatorFeedItem(feed[feed.length - 1])) {
        feed.push(activity.formatted_date === today ? { id: _4("Today"), separator: _4("Today"), today: true } : { id: activity.formatted_date, separator: activity.formatted_date });
        feedDates.add(activity.formatted_date);
      }
    }
    if (!activity.card_id) {
      accuActivitiesWithoutCards.push(activity);
    } else {
      pushAccuActivitiesWithoutCards();
      if (!feedCardIds.has(activity.card_id)) {
        const card = data2.cards[activity.card_id];
        if (card) {
          feed.push({
            id: activity.id,
            card,
            latest_activity_id: activity.id,
            activities: feedActivityStore.scoped({ card_id: activity.card_id })
          });
          if (card.subscribed) {
            cardSubscriptionStore.subscribeTo(card);
          }
          feedCardIds.add(card.id);
        }
      }
    }
  }
  pushAccuActivitiesWithoutCards();
  if (feed.length && isDateSeparatorFeedItem(feed[feed.length - 1])) {
    feed.pop();
  }
}
function getActivitiesPositionsInFeed(feed = []) {
  const activitiesPositionsInFeed = /* @__PURE__ */ new Map();
  for (let i3 = 0; i3 < feed.length; i3++) {
    let activities = [];
    let feedItem = feed[i3];
    if (isActivitiesFeedItem(feedItem)) {
      activities = feedItem.activities;
    } else if (isCardFeedItem(feedItem)) {
      activities = feedItem.activities.query();
    }
    for (const activity of activities) {
      activitiesPositionsInFeed.set(activity.id, i3);
    }
  }
  return activitiesPositionsInFeed;
}
function getEarliestUnreadFeedItemId(feed = [], unreadIds = []) {
  function findEarliestUnreadFeedItem(unreadIds2) {
    const earliestUnreadId = Math.min(...unreadIds2);
    if (activitiesPositionsInFeed.has(earliestUnreadId)) {
      const earliestUnreadFeedItemId = activitiesPositionsInFeed.get(earliestUnreadId);
      const earliestUnreadFeedItem = feed[earliestUnreadFeedItemId];
      if ("card" in earliestUnreadFeedItem) {
        const earlierUnreadIds = unreadIds2.filter(
          (id) => id !== earliestUnreadId && id < earliestUnreadFeedItem.latest_activity_id
        );
        if (earlierUnreadIds.length > 0) {
          return findEarliestUnreadFeedItem(unreadIds2.filter((id) => earliestUnreadId !== id));
        }
      }
      return earliestUnreadFeedItemId;
    }
    return null;
  }
  if (feed.length === 0 || unreadIds.length === 0) return null;
  const activitiesPositionsInFeed = getActivitiesPositionsInFeed(feed);
  return findEarliestUnreadFeedItem(unreadIds);
}

// public/app/routes/my-work/ng-components/inbox.js
angular_default.module("kantree").component("myWorkInbox", {
  templateUrl: "/static/app/routes/my-work/ng-components/templates/inbox.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "$rootScope", "iCalendarModal", "$q", "$element", "searchModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.loading = true;
      this.currentUser = currentUser2;
      this.filterScopes = get(currentUser2.app_params, "myWorkFilterScopes", [["pinned"]]);
      this.feedActivityStore = new ActivityStore({ autoLoad: false });
      this.refreshScoping();
      this.settingsMenu = { config: [
        {
          subheader: _4("Inbox options")
        },
        {
          checkbox: true,
          label: _4("Only show unread items"),
          offline: false,
          value: () => get(currentUser2.app_params, "inboxUnreadOnly", false),
          toggle: (isChecked) => {
            this.$q.digest(saveUserAppParams({ "inboxUnreadOnly": isChecked }));
            this.refreshFeed();
          }
        },
        {
          checkbox: true,
          label: _4("Hide activities initiated by yourself"),
          offline: false,
          value: () => get(currentUser2.app_params, "inboxIgnoreSelf", false),
          toggle: (isChecked) => {
            this.$q.digest(saveUserAppParams({ "inboxIgnoreSelf": isChecked }));
            this.refreshFeed();
          }
        },
        {
          label: "--"
        },
        {
          subheader: _4("Automatically mark as read")
        },
        {
          checkbox: true,
          switch: false,
          label: _4("When I scroll"),
          offline: false,
          value: () => get(currentUser2.app_params, "inboxMarkAsReadWhenScrolled", false),
          toggle: (isChecked) => this.$q.digest(saveUserAppParams({ "inboxMarkAsReadWhenScrolled": isChecked }))
        },
        {
          checkbox: true,
          switch: false,
          label: _4("When I comment"),
          offline: false,
          value: () => get(currentUser2.app_params, "inboxMarkAsReadWhenComment", false),
          toggle: (isChecked) => this.$q.digest(saveUserAppParams({ "inboxMarkAsReadWhenComment": isChecked }))
        }
      ] };
      this.showUseAsHomeBtn = get(currentUser2.app_params, "home", "") !== "inbox";
      this.TinyCalendar = TinyCalendar;
      this.queryCalendarCards = this.queryCalendarCards.bind(this);
      this.doCalendarSearch = this.doCalendarSearch.bind(this);
      this.showCalendarFeed = this.showCalendarFeed.bind(this);
    }
    $postLink() {
      const $sidebar = this.$element.find(".inbox-sidebar");
      const $main = this.$element.find(".inbox-main");
      let inboxHeight;
      this.windowResizeListener = () => {
        $sidebar.css("right", Math.round(($main.outerWidth(true) - $main.outerWidth()) / 2) + 30);
        inboxHeight = this.$element.height();
      };
      jquery_default(window).on("resize", this.windowResizeListener);
      this.windowResizeListener();
      const $viewport = jquery_default("#inbox-view");
      const $unreadBanner = $viewport.find(">a");
      $viewport.on("scroll", () => {
        requestAnimationFrame(() => $unreadBanner.css("top", $viewport[0].scrollTop));
        const deltaToBottom = $viewport[0].scrollHeight - $viewport[0].scrollTop - inboxHeight;
        if (deltaToBottom < 200) {
          this.loadNextFeedPage();
        }
      });
    }
    $onDestroy() {
      jquery_default(window).off("resize", this.windowResizeListener);
    }
    get isConnected() {
      return isConnected();
    }
    refreshFeed() {
      this.feed = [];
      this.feedCardIds = /* @__PURE__ */ new Set();
      this.feedDates = /* @__PURE__ */ new Set();
      this.refreshFeedNeeded = false;
      this.loading = true;
      this.feedPage = 1;
      this.feedReachedEnd = false;
      this.hasValidFilterScopes = true;
      this.unreadIds = pluck(this.scopedNotifsStore.query(), "id");
      this.loadNextFeedPage();
    }
    loadNextFeedPage() {
      if (this.feedReachedEnd || this.loadingFeedPage) {
        return;
      }
      if (this.filterScopes?.length === 0) {
        this.loading = false;
        this.hasValidFilterScopes = false;
        return;
      }
      this.loadingFeedPage = true;
      this.$q.when(api_default.user.get_inbox_feed.get({
        scope: this.getFilterScopesAsString(),
        page: this.feedPage++,
        unread_only: get(currentUser2.app_params, "inboxUnreadOnly", false),
        ignore_self: get(currentUser2.app_params, "inboxIgnoreSelf", false)
      }), (data2) => {
        if (!data2.activities.length) {
          this.loading = false;
          this.loadingFeedPage = false;
          this.feedReachedEnd = true;
          return;
        }
        processInboxFeedFetchedData(data2, this.feed, this.feedCardIds, this.feedDates, this.feedActivityStore);
        this.loading = false;
        this.loadingFeedPage = false;
      });
    }
    markAllAsRead() {
      markAllNotificationsAsRead({ scope: this.getFilterScopesAsString() }, (store2) => {
        store2.removeMany(this.scopedNotifsStore.query());
      });
    }
    markAllOtherOrgsAsRead() {
      markAllNotificationsAsRead({ scope: this.getFilterScopesAsString(), exclude_matching: true }, (store2) => {
        store2.removeMany(this.unscopedNotifsStore.query());
      });
    }
    markAsRead(activities) {
      markNotificationsAsRead(activities);
    }
    doCalendarSearch(day) {
      this.$searchModal.open(`@me in {$members} state!=done {$date}="${day.date.format("YYYY-MM-DD")}"`);
    }
    queryCalendarCards(start, end, callback) {
      const filter4 = '@me in {$members} state!=done {$date}>="' + start + '" {$date}<="' + end + '"';
      this.$q.when(searchCards(filter4, pinnedOrgFilterScopes, null, { ignoreErrorHandlers: true }), callback, () => callback([]));
    }
    showCalendarFeed() {
      this.$iCalendarModal.open(this.$q.when(api_default.user.get_calendar_url.get()));
    }
    refreshScoping() {
      if (this.deregisterNotifsWatcher) this.deregisterNotifsWatcher();
      const projectIds = getProjectsFromFilterScopes(this.filterScopes).map((p4) => p4.id);
      this.scopedNotifsStore = store.scoped({ project_id: (id) => projectIds.includes(id) });
      this.unscopedNotifsStore = store.scoped({ project_id: (id) => !projectIds.includes(id) });
      this.deregisterNotifsWatcher = this.scopedNotifsStore.$watchAll(this.$scope, () => {
        const newUnreadIds = pluck(this.scopedNotifsStore.query(), "id");
        if (newUnreadIds.some((id) => !this.unreadIds.includes(id))) {
          this.refreshFeedNeeded = true;
          this.refreshUnreadCount = newUnreadIds.filter((id) => !this.unreadIds.includes(id)).length;
        } else {
          this.unreadIds = newUnreadIds;
        }
      }, false);
      this.refreshFeed();
    }
    saveFilterScopes(filterScopes) {
      this.filterScopes = filterScopes;
      this.$q.digest(saveUserAppParams({ "myWorkFilterScopes": filterScopes }));
      this.refreshScoping();
    }
    getFilterScopesAsString() {
      return filterScopesToString(this.filterScopes);
    }
    useAsHome() {
      this.$q.digest(saveUserAppParams({ "home": "inbox" }));
      this.showUseAsHomeBtn = false;
    }
  }
});

// public/app/routes/my-work/ng-components/project-view.js
angular_default.module("kantree").factory("MyWorkProjectScopeManager", [
  "ProjectScopeManager",
  function(ProjectScopeManager) {
    return class MyWorkProjectScopeManager extends ProjectScopeManager {
      // No fallback here
      getDefaultView() {
        return null;
      }
      gotoView(view) {
        if (view) return super.goToView(view);
        return null;
      }
    };
  }
]);
angular_default.module("kantree").component("myWorkProjectView", {
  bindings: {
    viewId: "<"
  },
  templateUrl: "/static/app/routes/my-work/ng-components/templates/project-view.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "MyWorkProjectScopeManager", "$q", "$state"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      if (changes.viewId) {
        this.refreshView();
      }
    }
    refreshView() {
      if (this.scopeManager) {
        this.scopeManager.destroy();
        this.scopeManager = null;
      }
      this.loading = true;
      this.$q.when(getOrLoadView(this.viewId), (view) => {
        this.$MyWorkProjectScopeManager.init(this, this.$scope, view.project_id, view.card_ref).then((scopeManager) => {
          this.scopeManager = scopeManager;
          scopeManager.setActiveView(view.id);
          if (this.view) {
            scopeManager.fetchCards();
            bindToScope(this.$scope, setPageBackgroundImage(this.project.image_cover_url));
          } else {
            this.loadingErrorMessage = _4("This view is not available anymore. Ask Workspace admin for more information.");
          }
          this.loading = false;
          const routeParams = { projectId: this.project.id, view: view.id };
          this.projectUrl = this.board.parent_id ? this.$state.href("project_board", { ...routeParams, cardRef: this.board.ref }) : this.$state.href("project", routeParams);
        });
      });
    }
  }
});

// public/app/loaders/request.js
function loadRequest(token, options2) {
  return load(requestStore, api_default.request.get_request, { request_token: token }, options2);
}
function loadAllRequestsForUser() {
  requestStore.clear();
  return loadMany(requestStore, api_default.user.list_requests);
}

// public/app/routes/my-work/ng-components/requests.js
angular_default.module("kantree").component("myWorkRequests", {
  templateUrl: "/static/app/routes/my-work/ng-components/templates/requests.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.filters = [
        {
          label: _4("Opened requests"),
          predicate: (r3) => !r3.closed
        },
        {
          label: _4("Closed requests"),
          predicate: (r3) => !!r3.closed
        }
      ];
      this.filterMenu = {
        config: this.filters.map((f3) => ({
          label: f3.label,
          action: () => {
            this.filter = f3;
          }
        }))
      };
      this.filter = this.filters[0];
      requestStore.$watchAll(this.$scope, () => {
        this.refreshRequests();
      });
      this.$scope.$watch("$ctrl.filter", (newVal, oldVal) => {
        if (newVal === oldVal) return;
        this.refreshRequests();
      });
      this.loading = true;
      this.$q.when(loadAllRequestsForUser(), () => {
        this.loading = false;
      });
    }
    refreshRequests() {
      this.requests = requestStore.query({}, { sortBy: "-created_at" }).filter(this.filter.predicate);
    }
  }
});

// public/app/routes/my-work/ng-components/sidebar-dashboard-list.js
angular_default.module("kantree").component("navSidebarMyWorkDashboardList", {
  template: `
    <div class="list-header" ng-if="!$ctrl.mode">
      <button type="button" class="btn" ng-click="$ctrl.toggleContent()">
        <span>
          <i class="fa fa-chevron-down"></i>
          <span class="title">{{$ctrl.label}}</span>
          <span class="count">({{$ctrl.views.length}})</span>
        </span>
      </button>
    </div>
    <div class="list-content js-sortable" ui-sortable="$ctrl.sortableOptions" ng-model="$ctrl.views">
      <nav-sidebar-view class="js-sortable-item" ng-repeat="view in $ctrl.views track by view.id"
        view="view" mode="{{$ctrl.mode}}"></nav-sidebar-view>
    </div>
    <div class="nav-sidebar-item" hide-offline>
      <button class="nav-sidebar-btn btn-adder" type="button" ng-click="$ctrl.createView()">
        <i class="bi-plus-lg"></i>
        <span>{{::$ctrl.addBtnLabel}}</span>
      </button>
    </div>
  `,
  bindings: {
    options: "<",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$q", "navSidebar", "$state"];
    $onInit() {
      this.label = _4("Dashboards");
      this.addBtnLabel = _4("Add dashboard");
      this.views = [];
      this.storageKey = "my-work-dashboards";
      this.store = viewStore.scopedByGlobal().scoped({ _draft: query_exports.isFalsy() });
      this.store.$watchAll(this.$scope, () => {
        this.views = this.store.query({}, { sortBy: "position" });
      });
      this.sortableOptions = {
        appendTo: "body",
        helper: "original",
        items: ".js-sortable-item:not(.is-draft)",
        handle: ".js-sortable-item-handle",
        tolerance: "pointer",
        distance: 12,
        scroll: false,
        zIndex: 0,
        axis: "y",
        update: (event2, ui) => {
          const { cancel, droptarget, index: index2, dropindex } = ui.item.sortable;
          if (event2.originalEvent.target === null) {
            cancel();
          }
          if (!droptarget || !droptarget.length) {
            cancel();
          }
          if (index2 === dropindex) {
            cancel();
          }
        },
        stop: (e3, ui) => {
          const {
            isCanceled,
            // the dragged card has already been added by ng-sortable.js in the droptargetModel
            // See : L246 for connected lists sort and L260 for normal sort
            droptargetModel: droptargetViews,
            model: view,
            dropindex,
            index: index2
          } = ui.item.sortable;
          if (isCanceled()) return;
          if (!droptargetViews) return;
          let relativeToView = null;
          if (droptargetViews.length <= 1) {
            relativeToView = null;
          } else if (dropindex < index2) {
            relativeToView = droptargetViews.slice(dropindex + 1).find((v3) => v3.id !== view.id);
          } else if (dropindex > index2) {
            relativeToView = droptargetViews.slice(0, dropindex).reverse().find((v3) => v3.id !== view.id);
          }
          this.$q.digest(reorderView(view, nextView, "replace"));
        }
      };
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-list");
      if (this.storageKey) {
        this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.storageKey));
      }
      this.toggleSortable();
      this.$scope.$on("screensize:changed", () => this.toggleSortable());
    }
    toggleSortable() {
      const $sortableElement = jquery_default(this.$element).find(".js-sortable");
      if ($sortableElement && $sortableElement.sortable("instance")) {
        $sortableElement.sortable(!isScreensizeXS() ? "enable" : "disable");
      }
    }
    toggleContent() {
      if (this.$navSidebar.isListCollapsed(this.storageKey)) {
        this.$navSidebar.expandList(this.storageKey);
      } else {
        this.$navSidebar.collapseList(this.storageKey);
      }
      this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.storageKey));
    }
    createView() {
      let view = { mode: "report" };
      return this.$q.when(createFromLocalView("", view, false), (view2) => {
        this.$state.go("myWork.dashboard", { viewId: view2.id });
      });
    }
  }
});

// public/app/routes/my-work/ng-components/sidebar-project-view-list.js
angular_default.module("kantree").component("navSidebarMyWorkProjectViewList", {
  template: `
    <div class="list-header" ng-if="!$ctrl.mode">
      <button type="button" class="btn" ng-click="$ctrl.toggleContent()">
        <span>
          <i class="fa fa-chevron-down"></i>
          <span class="title">{{$ctrl.label}}</span>
          <span class="count">({{$ctrl.views.length}})</span>
        </span>
      </button>
    </div>
    <div class="list-content">
      <nav-sidebar-my-work-project-view ng-repeat="view in $ctrl.views track by view.id" view="view" mode="{{$ctrl.mode}}"></nav-sidebar-my-work-project-view>
    </div>
  `,
  bindings: {
    options: "<",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "navSidebar", "$state"];
    $onInit() {
      this.label = _4("Workspace views");
      this.storageKey = "my-work-project-views";
      this.views = [];
      this.store = viewStore.scoped({ id: (id) => isFavorite("view", id) });
      this.store.$watchAll(this.$scope, () => {
        this.views = this.store.query({}, { sortBy: "name" });
        this.$element.toggleClass("hidden", !this.views.length);
      });
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-list");
      if (this.storageKey) {
        this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.storageKey));
      }
    }
    toggleContent() {
      if (this.$navSidebar.isListCollapsed(this.storageKey)) {
        this.$navSidebar.expandList(this.storageKey);
      } else {
        this.$navSidebar.collapseList(this.storageKey);
      }
      this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.storageKey));
    }
  }
});
angular_default.module("kantree").component("navSidebarMyWorkProjectView", {
  template: `
    <a href class="nav-sidebar-btn" ng-class="{'untitled': !$ctrl.view.name}" uib-tooltip="{{$ctrl.name}}" tooltip-placement="right"
    tooltip-popup-delay="0" tooltip-enable="$ctrl.mode === 'icon'" ng-click="$ctrl.activate()">
      <i ng-if="$ctrl.view.icon || $ctrl.view.default_icon"
        ng-class="($ctrl.view.icon || $ctrl.view.default_icon)|iconClass"></i>
      <span class="title" ng-show="!$ctrl.mode || (!$ctrl.view.icon && !$ctrl.view.default_icon)"
        ng-bind="($ctrl.mode === 'icon' ? ($ctrl.name|limitTo:2) : $ctrl.name)"></span>
      <span class="project">{{$ctrl.project.title}}</span>
    </a>
    <button class="nav-sidebar-btn btn-settings" type="button" drop-menu="$ctrl.menuConfig"><i class="bi-three-dots"></i></button>
  `,
  bindings: {
    view: "<",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$state", "$q"];
    $onInit() {
      if (this.view.project_id) {
        this.project = projectStore.tryGet(this.view.project_id);
      }
      this.$scope.$watch(() => this.view.name, () => {
        this.name = this.view.name || _4("Untitled view");
      });
      this.menuConfig = { config: [
        {
          label: _4("Remove from my work"),
          action: () => {
            this.$q.digest(toggleFavoriteView(this.view));
            this.$state.go("myWork.inbox");
          }
        }
      ] };
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-item");
      this.$element.toggleClass("nav-sidebar-item-view");
      this.$element.toggleClass("active", !!this.active);
      this.$scope.$watch(() => this.active, (newVal, oldVal) => {
        this.$element.toggleClass("active", !!newVal);
      });
    }
    get active() {
      return this.$state.is("myWork.projectView") && parseInt(this.$state.params.viewId) === this.view.id;
    }
    activate() {
      if (!this.active) {
        this.$state.go("myWork.projectView", { viewId: this.view.id });
      }
    }
  }
});

// public/app/routes/my-work/index.jsx
addRoute({
  name: "myWork",
  component: (props2) => createComponent(AuthenticatedPage, {
    get children() {
      return createComponent(MyWorkPage, {
        get children() {
          return props2.children;
        }
      });
    }
  }),
  children: [{
    name: "inbox",
    path: "/inbox",
    component: () => createComponent(NgComponent, {
      directive: "my-work-inbox"
    })
  }, {
    name: "agenda",
    path: "/agenda",
    component: () => createComponent(NgComponent, {
      directive: "my-work-agenda"
    })
  }, {
    name: "assigned",
    path: "/assigned",
    component: () => createComponent(NgComponent, {
      directive: "my-work-assigned"
    })
  }, {
    name: "requests",
    path: "/requests",
    component: () => createComponent(NgComponent, {
      directive: "my-work-requests"
    })
  }, {
    name: "dashboard",
    path: "/d/:viewId",
    component: () => {
      const params = useParams();
      const view = createMemo(() => {
        return viewStore.scopedByGlobal().tryGet(params.viewId);
      });
      return createComponent(Show, {
        get when() {
          return view();
        },
        get children() {
          return createComponent(NgComponent, {
            directive: "my-work-dashboard",
            get view() {
              return view();
            }
          });
        }
      });
    }
  }, {
    name: "projectView",
    path: "/v/:viewId",
    component: () => {
      const params = useParams();
      return createComponent(NgComponent, {
        directive: "my-work-project-view",
        get viewId() {
          return params.viewId;
        }
      });
    }
  }]
});

// public/app/loaders/template-lib.js
function loadTemplates() {
  const templatesByTags = {};
  const locale = getCurrentLocale();
  return Promise.all([
    api_default.template_library.list_tags.get({ locale }),
    loadTemplatesPage(templatesByTags)
  ]).then((r3) => {
    const tags2 = r3[0];
    if (typeof templatesByTags["__untagged__"] !== "undefined") {
      tags2.push(_4("Untagged"));
      templatesByTags[tags2[tags2.length - 1].replace(/\s/g, "").toLowerCase()] = templatesByTags["__untagged__"];
    }
    return [tags2, templatesByTags];
  });
}
async function loadTemplatesPage(templatesByTags, page = 1) {
  const locale = getCurrentLocale();
  const [templates, resp] = await api_default.template_library.list_templates.get({ page, locale }, { resolveWithResponse: true });
  for (let tpl of templates) {
    for (let tag of tpl.tags.length ? tpl.tags : ["__untagged__"]) {
      tag = tag.replace(/\s/g, "").toLowerCase();
      if (!templatesByTags[tag]) {
        templatesByTags[tag] = [];
      }
      templatesByTags[tag].push(tpl);
    }
  }
  const nextPage = resp.headers.get("X-Kantree-NextPage");
  if (nextPage) {
    await loadTemplatesPage(templatesByTags, nextPage);
  }
  return templatesByTags;
}
function loadTemplateTags() {
  return api_default.template_library.list_tags.get({ locale: getCurrentLocale() });
}

// public/app/routes/onboarding/ng-components/onboarding.js
angular_default.module("kantree").component("onboardingFlow", {
  templateUrl: "/static/app/routes/onboarding/ng-components/templates/onboarding.html",
  controller: class extends AngularClass {
    static $inject = ["$state", "$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.appContext = appContext;
      this.currentUser = currentUser2;
      this.serverConfig = serverConfig;
      this.displayName = currentUser2.display_name_value;
      this.templateTag = currentUser2.preferred_template_library_tag;
      if (currentUser2.was_invited) {
        this.startInvite();
      } else {
        this.startOwner();
      }
    }
    startInvite() {
      this.flow = "invite";
      this.steps = ["customize-invite"];
      this.step = 0;
    }
    startOwner() {
      this.flow = "owner";
      if (currentUser2.can_create_projects) {
        this.steps = ["customize-owner"];
      } else if (currentUser2.can_create_organizations) {
        this.steps = ["create-org", "customize-owner"];
      } else {
        this.steps = ["customize-observer"];
      }
      this.step = 0;
      this.$q.when(loadTemplateTags(), (tags2) => {
        let featuredTag;
        if (isObject2(serverConfig.template_library_featured_tag)) {
          featuredTag = serverConfig.template_library_featured_tag[getCurrentLocale()] || null;
        } else {
          featuredTag = serverConfig.template_library_featured_tag;
        }
        this.templateTags = tags2.filter((t3) => t3 !== featuredTag);
      });
      if (appContext.orgs.length) {
        if (appContext.projectsCount) {
          this.markAsOnboarded().then(() => {
            this.$state.go("org.hub", { slug: appContext.org.slug });
          });
        } else {
          this.gotoStep("customize-owner");
        }
      }
    }
    handleOrgCreated(org2) {
      fetchAppContextData().then(() => this.$q.digest(saveUserAppParams({ "home": `org:${org2.slug}` })));
      this.nextStep();
    }
    submitCustomizations() {
      this.$q.when(api_default.user.update.post({
        display_name: this.displayName || null,
        preferred_template_library_tag: this.templateTag || null
      }), (user) => {
        setCurrentUser(user);
        if (appContext.org && appContext.orgs.length === 1 && !currentUser2.can_create_projects) {
          this.$q.digest(saveUserAppParams({ "home": `org:${appContext.org.slug}` }));
        }
        if (appContext.org && (appContext.org.has_projects || !appContext.org.can_create_projects || appContext.org.permission < 2)) {
          this.markAsOnboarded().then(() => {
            if (this.flow === "owner" && appContext.org.has_projects) {
              const project = appContext.orgs[0].projectStore.query({ is_portfolio: false })?.[0];
              if (project) {
                this.$state.go("project", { projectId: project.slug });
                return;
              }
            }
            this.$state.go("org.hub", { slug: appContext.org.slug });
          });
        } else if (appContext.projectsCount) {
          this.markAsOnboarded().then(() => {
            this.$state.go("/");
          });
        } else {
          this.markAsOnboarded();
          this.$state.go("templates", { onboarding: 1 });
        }
      });
    }
    finishInvite() {
      this.$q.when(api_default.user.update.post({
        display_name: this.displayName || null
      }), (user) => {
        setCurrentUser(user);
      });
      this.markAsOnboarded().then(() => {
        if (appContext.org && appContext.org.permission > 0) {
          if (appContext.orgs.length === 1 && !currentUser2.can_create_projects) {
            this.$q.digest(saveUserAppParams({ "home": `org:${appContext.org.slug}` }));
          }
          this.$state.go("org.projects", { slug: appContext.org.slug, onboarding: 1 });
        } else {
          this.$state.go("/");
        }
      });
    }
    nextStep() {
      this.step++;
    }
    gotoStep(step2) {
      this.step = this.steps.indexOf(step2);
    }
    markAsOnboarded() {
      return this.$q.when(api_default.user.mark_as_onboarded.post({ step: "user" }, { ignoreErrorHandlers: true }), (user) => {
        setCurrentUser(user);
        onAppContextUpdate();
      }).catch(() => this.$q.resolve());
    }
  }
});

// public/app/routes/onboarding/index.jsx
addRoute({
  name: "onboarding",
  path: "/onboarding",
  component: () => {
    return createComponent(AuthenticatedPage, {
      preventOnboardingRedirect: true,
      get children() {
        return createComponent(HideSystemSidebar, {
          get children() {
            return createComponent(NgComponent, {
              directive: "onboarding-flow"
            });
          }
        });
      }
    });
  }
});

// public/app/loaders/org.js
function formatOrg(org2) {
  if (org2.members) {
    orgMemberStore.scopedByOrg(org2).replace(org2.members.map((i3) => {
      i3.org_id = org2.id;
      return i3;
    }));
    delete org2.members;
  }
  if (org2.featured_items) {
    orgFeaturedItemStore.scopedByOrg(org2).replace(org2.featured_items.map((i3) => {
      i3.org_id = org2.id;
      return i3;
    }));
    delete org2.featured_items;
  }
  return org2;
}
var loader6 = new StoreLoader(orgStore, { format: formatOrg });
function loadOrg(id, options2) {
  return loader6.load(api_default.organizations.get_org, { org_id: id }, options2);
}
function loadOrgBySlug(slug, options2) {
  return loader6.load(api_default.organizations.get_org, { org_id: slug }, options2);
}

// public/app/loaders/team.js
function loadTeam(orgId, teamId, options2) {
  return load(teamStore, api_default.teams.get_team, { org_id: orgId, team_id: teamId }, options2);
}
async function loadAllTeams(org2, options2) {
  const teams = await loadMany(teamStore, api_default.teams.list_teams, { org_id: org2.id }, options2);
  teamStore.scopedByOrg(org2).removeAllNotMatching(teams);
  return teams;
}

// public/app/routes/org/ng-components/creator.js
angular_default.module("kantree").component("orgCreatorForm", {
  templateUrl: "/static/app/routes/org/ng-components/templates/creator-form.html",
  bindings: {
    onPaymentNeeded: "&",
    onSuccess: "&",
    onCancel: "&",
    showCancel: "<?",
    showFindOrg: "<?",
    isModal: "<?",
    withoutTitle: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$timeout", "$sce"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.activeStep = "create-org";
      this.joinHelpLinkText = this.$sce.trustAsHtml(_4('For more information, check out <a href="https://kantree.io/help/guides/organizations/#org-members" target="_blank">how to manage team members</a>'));
      this.invites = [null, null, null];
      this.showMessage = false;
      this.message = null;
    }
    create() {
      this.$q.when(api_default.organizations.create_org.post({ name: this.orgName }, { ignoreErrorHandlers: true }), (org2) => {
        this.createdOrg = org2;
        setCurrentUser("orgs", [...currentUser2.orgs, org2.id]);
        if (org2.billing && org2.billing.status === "unpaid") {
          this.onPaymentNeeded({ $org: org2 });
          return;
        }
        this.activeStep = "members-invite";
        fetchAppContextData();
      }, autoCatchAsRequestErrorDialog([400])).catch(() => {
        this.submitButton.prop("disabled", false).text(_4("Create"));
      });
    }
    sendInvites() {
      const invites = this.invites.reduce((accu, invite) => {
        if (invite !== null) {
          if (!accu.length) {
            return invite;
          }
          return accu + ", " + invite;
        }
        return accu;
      }, "");
      if (!invites.length) {
        this.finish();
        return;
      }
      this.$q.when(
        api_default.org_members.invite.post({ org_id: this.createdOrg.id, email_or_usernames: invites, message: this.message }, { ignoreErrorHandlers: true }),
        () => this.finish(),
        autoCatchAsRequestErrorDialog([400])
      );
    }
    finish() {
      if (this.onSuccess) {
        this.onSuccess({ $org: this.createdOrg });
      } else if (this.onCancel) {
        this.onCancel();
      }
    }
    onInviteInputChange(index2) {
      if (index2 === this.invites.length - 1) {
        $timeout(function() {
          this.invites.push(null);
        }, 0);
      }
    }
  }
});

// public/app/routes/org/ng-components/topbar.js
angular_default.module("kantree").directive("organizationTopbar", function() {
  return {
    //---act as component
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    //---
    templateUrl: "/static/app/routes/org/ng-components/templates/topbar.html",
    bindToController: {
      org: "<"
    },
    controller: class extends AngularClass {
      static $inject = ["$scope", "$q", "$state", "createTeamModal", "projectCreatorModal"];
      $onInit() {
        injectI18nHelpersIntoScope(this.$scope);
        this.filterScopes = [["org", this.org.id]];
        this.refreshShowUseAsHome();
        this.$scope.$on("$stateChangeSuccess", this.refreshShowUseAsHome.bind(this));
      }
      $onChanges() {
        this.notificationStore = store.scoped({ org_id: this.org.id });
        this.addNewMenu = { config: [
          {
            label: _4("New workspace"),
            action: () => {
              if (this.$state.includes("org.team")) {
                this.$state.go("templates", { org: this.org.id, team: teamStore.query({ slug: this.$state.params.teamSlug })?.[0].id });
              } else {
                this.$state.go("templates", { org: this.org.id });
              }
            }
          },
          {
            label: _4("New team"),
            featureFlag: [this.org, "teams"],
            action: () => fenceBehindFeatureFlag(this.org, "teams", () => this.$createTeamModal.open(this.org).then((team) => this.$state.go("org.team.hub", { slug: this.org.slug, teamSlug: team.slug })))
          },
          {
            label: _4("New portfolio"),
            enabled: () => hasFeatureFlag(this.org, "portfolios"),
            action: () => this.$projectCreatorModal.open({ org, createPortfolio: true }).then((portfolio) => this.$state.go("portfolio", { slug: portfolio.slug }))
          }
        ] };
      }
      markAllNotificationsAsRead() {
        markAllNotificationsAsRead({ org_id: this.org.id });
      }
      refreshShowUseAsHome() {
        this.useAsHomeValue = this.$state.includes("org.team") ? `org:${this.org.slug}:${this.$state.params.teamSlug}` : `org:${this.org.slug}`;
        this.showUseAsHomeBtn = get(currentUser2.app_params, "home") !== this.useAsHomeValue;
      }
      useAsHome() {
        this.$q.digest(saveUserAppParams({ "home": this.useAsHomeValue }));
        this.showUseAsHomeBtn = false;
      }
    }
  };
});

// public/app/actions/org.ts
async function updateOrg(org2, data2) {
  org2 = await api_default.organizations.update_org.put(Object.assign({}, data2, { org_id: org2.id }));
  org2 = orgStore.update(org2);
  fetchAppContextData();
  return org2;
}
async function deleteOrg(org2) {
  await api_default.organizations.delete_org.delete({ org_id: org2.id });
  const projectIds = pluck(projectStore.scopedByOrg(org2).query(), "id");
  cardStore.scoped({ project_id: query_exports.any(projectIds) }).removeAll();
  projectStore.scopedByOrg(org2, { withPortfolio: true, withTemplates: true }).removeAll();
  orgStore.remove(org2);
  fetchAppContextData();
}
async function addFeaturedOrgItem(org2, object_type, object_id) {
  const item = await api_default.organizations.add_featured_item.post({ org_id: org2.id, object_type, object_id });
  item.org_id = org2.id;
  return orgFeaturedItemStore.upsert(item);
}
async function deleteFeaturedOrgItem(org2, item) {
  await api_default.organizations.remove_featured_item.delete({ org_id: org2.id, item_id: item.id });
  orgFeaturedItemStore.remove(item);
}
function synchronizeFeaturedOrgItemsForType(org2, objectType, objects) {
  const matchingObjectIds = [];
  const actions2 = [];
  const store2 = orgFeaturedItemStore.scopedByOrg(org2).scoped({ type: objectType });
  for (const object2 of objects) {
    if (store2.query({ object: (obj) => obj.id === object2.id }).length === 0) {
      actions2.push(addFeaturedOrgItem(org2, objectType, object2.id));
    }
    matchingObjectIds.push(object2.id);
  }
  for (const unmatchedItem of store2.query({ object: (obj) => !matchingObjectIds.includes(obj.id) })) {
    actions2.push(deleteFeaturedOrgItem(org2, unmatchedItem));
  }
  return Promise.all(actions2);
}
async function enableOrgInviteLink(org2, refresh = false, defaultPerm = null) {
  let data2 = { org_id: org2.id, refresh };
  if (defaultPerm !== null) {
    data2["default_perm"] = defaultPerm;
  }
  org2 = await api_default.organizations.enable_org_invite_link.post(data2);
  return orgStore.update(org2);
}
async function disableOrgInviteLink(org2) {
  org2 = await api_default.organizations.disable_org_invite_link.delete({ org_id: org2.id });
  return orgStore.update(org2);
}
async function postOrgUpdate(org2, content2) {
  const acitivity = await api_default.organizations.post_update.post({ org_id: org2.id, content: content2 });
  return activityStore.insert(acitivity);
}

// public/app/routes/org/ng-components/hubAddFeaturedItemButton.js
angular_default.module("kantree").component("hubAddFeaturedItemButton", {
  bindings: {
    org: "<",
    featuredItems: "<"
  },
  template: `<button drop-menu="$ctrl.addFeaturedItemMenu"><i class="bi-plus-lg"></i> {{_('Add featured item')}}</button>`,
  controller: class extends AngularClass {
    static $inject = ["$scope", "fileSelectModal", "orgProjectSelectorModal", "requestFormSelectorModal", "$q"];
    $onInit() {
      this.addFeaturedItemMenu = {
        config: [
          {
            label: _4("Workspace"),
            action: () => {
              this.$orgProjectSelectorModal.open({
                org: this.org,
                selectedProjects: this.featuredItems.filter((i3) => i3.type === "project").map((i3) => i3.object),
                isMultiple: true
              }).then((projects) => {
                this.$q.when(
                  synchronizeFeaturedOrgItemsForType(this.org, "project", projects)
                );
              });
            }
          },
          {
            label: _4("Form"),
            action: () => {
              this.$requestFormSelectorModal.open(this.org).then((requestForm) => {
                this.$q.when(
                  api_default.organizations.add_featured_item.post({
                    org_id: this.org.id,
                    object_type: "request_form",
                    object_id: requestForm.id
                  }),
                  (item) => {
                    orgFeaturedItemStore.insert(Object.assign({ org_id: this.org.id }, item));
                  }
                );
              });
            }
          },
          {
            label: _4("File"),
            action: () => this.$fileSelectModal.open().then((file) => {
              upload({
                url: api_default.organizations.add_featured_item.url({ org_id: this.org.id }),
                data: { file }
              }, (evt) => {
                this.featuredFileUploadProgress = parseInt(100 * evt.loaded / evt.total);
              }).then(
                (r3) => {
                  this.featuredFileUploadProgress = false;
                  r3.data.org_id = this.org.id;
                  orgFeaturedItemStore.insert(r3.data);
                },
                (resp) => {
                  errorDialog(_4("An error occured while uploading your file"));
                  this.featuredFileUploadProgress = false;
                }
              );
            })
          },
          {
            label: _4("Link"),
            action: () => {
              inputDialog(_4("Website URL:")).then((url2) => {
                if (url2) {
                  this.$q.when(
                    api_default.organizations.add_featured_item.post({
                      org_id: this.org.id,
                      url: url2
                    }),
                    (item) => {
                      orgFeaturedItemStore.insert(Object.assign({ org_id: this.org.id }, item));
                    }
                  );
                }
              });
            }
          }
        ]
      };
    }
  }
});

// public/app/routes/org/ng-components/memberTileChangeRoleButton.js
angular_default.module("kantree").component("memberTileChangeRoleButton", {
  bindings: {
    menu: "<",
    name: "<"
  },
  template: `<button class="btn btn-default btn-text" drop-menu="$ctrl.menu">
      {{$ctrl.name}} <span class="bi-caret-down-fill"></span>
    </button>`
});

// public/app/routes/org/ng-components/headerSettingsButton.js
angular_default.module("kantree").directive("headerSettingsButton", function() {
  return {
    replace: true,
    scope: {
      menu: "<"
    },
    template: `
      <span class="ms-auto"><button class="btn"
        ng-class="{'btn-icon': isScreensizeXS()}"
        drop-menu="menu">
        <i class="bi-sliders2"></i>
        <span class="hidden-xs">{{::_("Settings")}}</span>
      </button></span>
    `,
    controller: ["$scope", ($scope2) => {
      injectI18nHelpersIntoScope($scope2);
      $scope2.isScreensizeXS = isScreensizeXS;
    }]
  };
});

// public/app/routes/org/ng-components/headerBannerCustomizationMenuButton.js
angular_default.module("kantree").component("headerBannerCustomizationMenuButton", {
  bindings: {
    menu: "<"
  },
  template: `<a class="edit hidden-xs" href drop-menu="$ctrl.menu" hide-offline>
              <i class="fa fa-pencil"></i>
            </a>`
});

// public/app/routes/org/ng-components/headerTeamCustomizationMenuConfigButton.js
angular_default.module("kantree").component("headerTeamCustomizationMenuConfigButton", {
  bindings: {
    teamCustomizationMenuConfig: "<",
    team: "<",
    canCustomize: "<"
  },
  template: `<div class="team" drop-menu="$ctrl.canCustomize && !$ctrl.isScreensizeXS() ? $ctrl.teamCustomizationMenuConfig : null">
              <div custom-bgcolor="{{$ctrl.team.color}}" bgcolor-hover="true">
                <i ng-class="$ctrl.team.icon|iconClass" ng-show="$ctrl.team.icon"></i>
                <span class="bi-caret-down-fill" ng-show="$ctrl.canCustomize"></span>
              </div>
            </div>`,
  controller: class extends AngularClass {
    $onInit() {
      this.isScreensizeXS = isScreensizeXS;
    }
  }
});

// public/app/routes/org/menus/selector.js
angular_default.module("kantree").service("orgSelectorMenu", class extends AngularClass {
  static $inject = ["$q"];
  getMenuItems(options2) {
    const { selected, org: org2, withTeams, select: select3 } = options2;
    let items = [];
    if (currentUser2.can_create_projects) {
      const myProjectsName = !currentUser2.can_create_private_projects ? _4("Your public workspaces") : _4("Your workspaces");
      items.push({
        label: myProjectsName,
        action: () => select3({
          org: { id: -1, name: myProjectsName, type: "user" }
        }),
        selected: () => selected && selected.org && selected.org.type === "user"
      });
    }
    if (currentUser2.is_kantree_admin) {
      items = items.concat(this.getItemsForKantreeAdmin(selected, org2, withTeams, select3));
    } else {
      items = items.concat(this.getItemsForUser(selected, withTeams, select3));
    }
    return items;
  }
  getItemsForUser(selected, withTeams, select3) {
    const items = [];
    for (let team of appContext.teams) {
      if (!withTeams && team.team) {
        continue;
      }
      items.push({
        label: team.name,
        selected: () => selected && this.isSelectedOrg(team.org, selected.org) && (!selected.team && !team.team || team.team && this.isSelectedTeam(team.team, selected.team)),
        action: () => {
          let selected2 = { org: { id: team.org.id, name: team.org.name, type: "org" } };
          if (team.team) {
            selected2.team = { id: team.team.id, name: team.team.name };
          }
          select3(selected2);
        }
      });
    }
    return items;
  }
  getItemsForKantreeAdmin(selected, org2, withTeams, select3) {
    const items = [{
      label: org2.name,
      selected: () => selected && this.isSelectedOrg(org2, selected.org) && !selected.team,
      action: () => select3({ org: { id: org2.id, name: org2.name, type: "org" } })
    }];
    for (let team of teamStore.scopedByOrg(org2).query()) {
      items.push({
        label: `${org2.name} / ${team.name}`,
        selected: () => selected && this.isSelectedOrg(org2, selected.org) && this.isSelectedTeam(team, selected.team),
        action: () => select3({
          org: { id: org2.id, name: org2.name, type: "org" },
          team: { id: team.id, name: team.name }
        })
      });
    }
    items.push({
      placeholder: _4("Org slug or id"),
      input: true,
      closeAfterSubmit: true,
      submit: (value2) => {
        this.$q.when(api_default.organizations.get_org.get({ org_id: value2 }, { ignoreErrorHandlers: true }), (org3) => {
          select3({ org: { id: org3.id, name: org3.name, type: "org" } });
        }, () => {
          errorDialog(_4("Unknown organization"));
        });
      }
    });
    return items;
  }
  isSelectedOrg(org2, selectedOrg) {
    return selectedOrg && selectedOrg.type === "org" && selectedOrg.id === org2.id;
  }
  isSelectedTeam(team, selectedTeam) {
    return selectedTeam && selectedTeam.name === team.name;
  }
  getMenu(options2) {
    return {
      config: () => () => this.getMenuItems(options2)
    };
  }
});

// public/app/loaders/org-member.js
function loadAllOrgMembers(orgId, options2) {
  return loadMany(orgMemberStore, api_default.org_members.list_members, { org_id: orgId }, options2, { format: (member) => {
    member.org_id = orgId;
    return member;
  } });
}

// public/app/routes/org/modals/add-members-to.js
angular_default.module("kantree").service("orgAddMembersToModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(org2, team, modalTitle, isMemberAddedFunc, onAddCallback, canManageMembers2) {
    return this.$uibModal.open({
      windowClass: "org-add-members-to-modal",
      component: "orgAddMembersToModal",
      resolve: {
        org: () => org2,
        team: () => team,
        modalTitle: () => modalTitle,
        isMemberAddedFunc: () => isMemberAddedFunc,
        onAddCallback: () => onAddCallback,
        canManageMembers: () => canManageMembers2
      }
    }).result;
  }
});
angular_default.module("kantree").component("orgAddMembersToModal", {
  templateUrl: "/static/app/routes/org/modals/templates/add-members-to-modal.html",
  bindings: {
    close: "&",
    dismiss: "&",
    resolve: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$state"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.filter = "";
      this.onlyShowTeamMember = !!this.resolve.team;
      this.refreshMemberStore();
      orgMemberStore.$watchAll(this.$scope, () => this.refreshMembers());
      this.$q.digest(loadAllOrgMembers(this.resolve.org.id));
      this.canManageMembers = this.resolve.canManageMembers();
    }
    refreshMemberStore() {
      if (this.resolve.team && this.onlyShowTeamMember) {
        this.memberStore = orgMemberStore.scopedByTeam(this.resolve.team);
      } else {
        this.memberStore = orgMemberStore.scopedByOrg(this.resolve.org);
      }
    }
    refreshMembers() {
      this.members = this.memberStore.query({}, { sortBy: "user.display_name" });
    }
    matchFilter(member) {
      if (this.filter) {
        return member.user.username.toLowerCase().indexOf(this.filter.toLowerCase()) !== -1 || member.user.display_name.toLowerCase().indexOf(this.filter.toLowerCase()) !== -1;
      }
      return true;
    }
    goToMembersPage() {
      if (this.resolve.team) {
        this.$state.go("org.team.members", { slug: this.resolve.org.slug, teamSlug: this.resolve.team.slug });
      } else {
        this.$state.go("org.members", { slug: this.resolve.org.slug });
      }
      this.dismiss({ $value: "navigate" });
    }
  }
});

// public/app/actions/team.ts
async function createTeam(org2, name2, color, icon) {
  let team = await api_default.teams.create_team.post({ org_id: org2.id, name: name2, color, icon });
  team = teamStore.insert(team);
  loadAllOrgMembers(org2.id);
  fetchAppContextData();
  return team;
}
async function updateTeam(team, data2) {
  team = await api_default.teams.update_team.put(Object.assign({ org_id: team.owner.id, team_id: team.id }, data2));
  team = teamStore.update(team);
  fetchAppContextData();
  return team;
}
async function deleteTeam(team) {
  await api_default.teams.delete_team.delete({ org_id: team.owner.id, team_id: team.id });
  teamStore.remove(team);
  fetchAppContextData();
}
async function addTeamMember(team, member) {
  member = await api_default.teams.add_team_member.post({ org_id: team.owner.id, team_id: team.id, org_member_id: member.id });
  member = orgMemberStore.update(member);
  return member;
}
async function updateTeamMemberPerm(team, member, permission) {
  member = await api_default.teams.update_team_member.put({
    org_id: team.owner.id,
    team_id: team.id,
    org_member_id: member.id,
    permission
  });
  member = orgMemberStore.update(member);
  return member;
}
async function removeTeamMember(team, member) {
  member = await api_default.teams.remove_team_member.delete({
    org_id: team.owner.id,
    team_id: team.id,
    org_member_id: member.id
  });
  member = orgMemberStore.update(member);
  return member;
}
async function joinTeam(team) {
  let member = await api_default.teams.add_team_member.post({ org_id: team.owner.id, team_id: team.id });
  member = orgMemberStore.update(member);
  teamStore.update(team, { is_member: true, permission: member.teams.find((t3) => t3.id === team.id).perm });
  fetchAppContextData();
  return member;
}

// public/app/routes/org/modals/create-team.js
angular_default.module("kantree").service("createTeamModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(org2) {
    return this.$uibModal.open({
      windowClass: "create-team-modal",
      component: "createTeamModal",
      resolve: {
        org: () => org2
      }
    }).result;
  }
});
angular_default.module("kantree").component("createTeamModal", {
  templateUrl: "/static/app/routes/org/modals/templates/create-team-modal.html",
  bindings: {
    resolve: "<",
    close: "&",
    dismiss: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.name = "";
      this.color = null;
      this.icon = null;
    }
    create() {
      this.$q.when(createTeam(this.resolve.org, this.name, this.color, this.icon), (team) => this.close({ $value: team }));
    }
  }
});

// public/app/routes/org/modals/creator.js
angular_default.module("kantree").service("orgCreatorModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open() {
    if (this.current) {
      this.current.dismiss();
    }
    this.current = this.$uibModal.open({
      windowClass: "org-creator-modal",
      backdrop: "static",
      keyboard: false,
      component: "orgCreatorModal"
    });
    const cb2 = () => {
      this.current = null;
    };
    return this.current.result.then(cb2, cb2);
  }
});
angular_default.module("kantree").component("orgCreatorModal", {
  templateUrl: "/static/app/routes/org/modals/templates/creator-modal.html",
  bindings: {
    close: "&",
    dismiss: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$state"];
    onCreated(org2) {
      this.close();
      this.$state.go("org.hub", { slug: org2.slug, "#": org2.billing && org2.billing.status === "unpaid" ? "billing" : "" });
    }
  }
});

// public/app/routes/org/modals/export.js
angular_default.module("kantree").service("orgExportModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(org2) {
    return this.$uibModal.open({
      windowClass: "org-export-modal",
      component: "orgExportModal",
      resolve: {
        org: () => org2
      }
    }).result;
  }
});
angular_default.module("kantree").component("orgExportModal", {
  templateUrl: "/static/app/routes/org/modals/templates/export-modal.html",
  bindings: {
    resolve: "<",
    close: "&",
    dismiss: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.org = this.resolve.org;
      this.withFiles = true;
      this.withUserOrgs = true;
    }
    export() {
      this.$q.when(api_default.organizations.export.post({
        org_id: this.org.id,
        bundle_files: this.withFiles,
        include_user_orgs: this.withUserOrgs
      }), () => {
        infoDialog(
          _4("You will receive an email with a link to download your exported file"),
          _4("Export in progress")
        );
        this.close();
      });
    }
  }
});

// public/app/routes/org/modals/invite-members.js
angular_default.module("kantree").service("orgInviteMembersModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(org2) {
    return this.$uibModal.open({
      windowClass: "org-invite-members-modal",
      component: "orgInviteMembersModal",
      resolve: {
        org: () => org2
      }
    }).result;
  }
});
angular_default.module("kantree").component("orgInviteMembersModal", {
  templateUrl: "/static/app/routes/org/modals/templates/invite-members-modal.html",
  bindings: {
    close: "&",
    dismiss: "&",
    resolve: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "manageBillingSeatsModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.MemberList = MemberList;
      this.serverConfig = serverConfig;
      this.org = this.resolve.org;
      this.newMembers = [];
      this.currentTab = "invites";
      this.availableOrgRoles = availableOrgRoles;
      this.isAdmin = isOrgAdmin(this.org);
      this.isOwner = isOrgOwner(this.org);
      this.$q.when(api_default.org_members.list_invites.get({ org_id: this.org.slug }), (invites) => {
        this.invites = invites;
        if (this.org.billing) {
          this.refreshBilling();
        } else {
          this.refreshMaxUsers();
        }
      });
      this.linkDefaultPermMenu = { config: availableOrgRoles.map((r3) => {
        return {
          label: r3.name,
          action: () => this.setLinkDefaultPerm(r3.id)
        };
      }) };
    }
    refreshBilling() {
      this.$q.when(api_default.billing.get_account.get({ account_id: this.org.billing.id }), (account) => {
        this.billing = account;
        if (!account.auto_adjust_seat_count) {
          this.canInvite = this.isOwner;
        }
        this.refreshMaxUsers();
      });
    }
    refreshMaxUsers() {
      this.nbUsers = this.org.nb_members + this.invites.length;
      if (!this.org.billing) {
        this.maxUserReached = this.org.max_allowed_users ? this.nbUsers >= this.org.max_allowed_users : false;
        this.maxUsers = this.org.max_allowed_users;
      } else if (this.billing) {
        if (this.billing.auto_adjust_seat_count) {
          this.nbUsers = this.org.nb_members;
          this.maxUserReached = false;
        } else {
          this.maxUserReached = this.nbUsers >= this.billing.seat_count;
        }
        this.maxUsers = this.billing.seat_count;
      }
    }
    invite(emailOrUsernames, message, callbacks2) {
      let confirmed;
      if (this.billing && this.billing.auto_adjust_seat_count && this.nbUsers === this.maxUsers && this.billing.plan_period === "yearly") {
        confirmed = confirmDialog({
          title: _4("Are you sure?"),
          text: _4("Adding users will add new seats to your billing plan for the remaining of the year.")
        });
      } else {
        confirmed = Promise.resolve();
      }
      confirmed.then(() => {
        this.$q.when(api_default.org_members.invite.post({ org_id: this.org.id, email_or_usernames: emailOrUsernames, message }, { ignoreErrorHandlers: true }), (invites) => {
          callbacks2.success();
          let nbUsers = 0;
          let nbMembers = this.org.nb_members;
          let nbInvites = this.org.nb_invites;
          for (const invite of invites) {
            if (invite.user) {
              invite.org_id = this.org.id;
              orgMemberStore.insert(invite);
              nbMembers++;
              this.newMembers.push(invite);
              nbUsers++;
            } else if (invite.email) {
              this.invites = this.invites.concat(invite);
              nbInvites++;
            }
          }
          this.org = orgStore.update(this.org, {
            nb_members: nbMembers,
            nb_invites: nbInvites
          });
          if (this.billing && this.billing.auto_adjust_seat_count) {
            let scheduledDeletion = this.billing.seat_count - this.billing.next_period_seat_count;
            let deltaSeatCount = nbUsers - scheduledDeletion;
            this.billing.next_period_seat_count += nbUsers;
            if (deltaSeatCount > 0) {
              this.billing.seat_count += deltaSeatCount;
            }
          }
          this.refreshMaxUsers();
        }, autoCatchAsRequestErrorDialog([400, 403])).catch((r3) => callbacks2.error && callbacks2.error(r3));
      });
    }
    resendInvite = (invite) => {
      this.$q.digest(api_default.org_members.invite.post({ org_id: this.org.id, email_or_usernames: invite.email }));
    };
    removeInvite = (invite) => {
      this.$q.when(api_default.org_members.remove_member.delete({ org_id: this.org.id, member_id: invite.id }), () => {
        this.invites = this.invites.filter((i3) => i3.id !== invite.id);
        this.org.nb_invites--;
        this.refreshMaxUsers();
      });
    };
    openManageSeatsModal() {
      this.$manageBillingSeatsModal.open(this.billing).then(() => this.refreshBilling());
    }
    updateInvitePerm = (invite, roleId) => {
      this.$q.when(api_default.org_members.update_member_permission.put({ org_id: this.org.id, member_id: invite.id, perm: roleId }, { ignoreErrorHandlers: true }), (m3) => {
        this.invites = this.invites.map((i3) => m3.id === i3.id ? m3 : i3);
      }, autoCatchAsRequestErrorDialog([400, 403]));
    };
    get linkDefaultPermLabel() {
      return availableOrgRoles.find((r3) => r3.id === this.org.invite_token_default_perm).name;
    }
    toggleLink() {
      if (this.org.invite_link) {
        confirmDialog({
          title: _4("Are you sure?"),
          text: _4("Re-enabling the link will generate a new one. The current one will become unusable.")
        }).then(() => {
          this.$q.digest(disableOrgInviteLink(this.org));
        });
      } else {
        this.$q.digest(enableOrgInviteLink(this.org));
      }
    }
    resetLink() {
      confirmDialog({
        title: _4("Are you sure?"),
        text: _4("Resetting the link will make the current one unusable")
      }).then(() => {
        this.$q.digest(enableOrgInviteLink(this.org, true));
      });
    }
    setLinkDefaultPerm(defaultPerm) {
      this.$q.digest(enableOrgInviteLink(this.org, false, defaultPerm));
    }
  }
});

// public/app/routes/org/modals/team-add-member.js
angular_default.module("kantree").service("teamAddMemberModal", class extends AngularClass {
  static $inject = ["orgAddMembersToModal", "$q"];
  open(team) {
    const org2 = orgStore.getFromTeam(team);
    return this.$orgAddMembersToModal.open(
      org2,
      null,
      _4("Add members to team"),
      (member) => !!member.teams.find((t3) => t3.id === team.id),
      (member) => this.$q.digest(addTeamMember(team, member)),
      () => isOrgAdmin(org2)
    );
  }
});

// public/app/routes/org/modals/team-settings.js
angular_default.module("kantree").service("teamSettingsModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(team) {
    return this.$uibModal.open({
      windowClass: "team-settings-modal",
      component: "teamSettingsModal",
      resolve: {
        team: () => team
      }
    }).result;
  }
});
angular_default.module("kantree").component("teamSettingsModal", {
  templateUrl: "/static/app/routes/org/modals/templates/team-settings-modal.html",
  bindings: {
    close: "&",
    dismiss: "&",
    resolve: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "processingStatus"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.team = this.resolve.team;
      this.name = this.team.name;
      this.color = this.team.color;
      this.icon = this.team.icon;
      this.description = this.team.description || "";
      this.orgMembersCanObserve = this.team.org_members_can_observe;
      this.orgMembersCanAutoJoin = this.team.org_members_can_autojoin;
    }
    update() {
      this.updateStatus = this.$processingStatus.saver(() => {
        this.$q.digest(updateTeam(this.team, {
          name: this.name,
          color: this.color,
          icon: this.icon,
          description: this.description
        }));
      });
    }
    delete() {
      confirmDeleteDialog2().then(() => {
        this.$q.digest(deleteTeam(this.team));
        this.close();
      });
    }
    updateAccessSettings() {
      this.$q.digest(updateTeam(this.team, {
        org_members_can_observe: this.orgMembersCanObserve,
        org_members_can_autojoin: this.orgMembersCanAutoJoin
      }));
    }
  }
});

// public/app/routes/org/components/Header.jsx
var _tmpl$131 = /* @__PURE__ */ template(`<span class="team"> / </span>`, 2);
var _tmpl$259 = /* @__PURE__ */ template(`<span class="name"></span>`, 2);
var _tmpl$341 = /* @__PURE__ */ template(`<span>+</span>`, 2);
var _tmpl$428 = /* @__PURE__ */ template(`<div id="org-page-header"><div><div class="logo"></div><div class="spacer"></div></div><nav class="hidden-xs"></nav></div>`, 10);
var [orgPageHeaderTeam, setOrgPageHeaderTeam] = createSignal();
var [orgPageHeaderActionsMenu, setOrgPageHeaderActionsMenu] = createSignal();
var [orgPageHeaderCustomizable, setOrgPageHeaderCustomizable] = createSignal(false);
var [orgPageHeaderSectionTitle, setOrgPageHeaderSectionTitle] = createSignal();
function OrgPageHeader(props2) {
  props2 = mergeProps({
    showMembers: true
  }, props2);
  const navigate2 = useNavigate2();
  const org2 = useRouteData();
  const locked = createMemo(() => isOrgLocked(org2()));
  const isOwner = createMemo(() => isOrgOwner(org2()));
  const canCustomize = createMemo(() => !locked() && !!orgPageHeaderTeam() && isTeamAdmin(orgPageHeaderTeam()));
  const canJoinTeam = createMemo(() => {
    return !locked() && isCurrentUserMemberOf(org2(), orgPageHeaderTeam(), false) && orgPageHeaderTeam() && !isTeamMember(orgPageHeaderTeam()) && orgPageHeaderTeam().org_members_can_autojoin;
  });
  const canInvite = createMemo(() => {
    return !locked() && (orgPageHeaderTeam() && isTeamAdmin(orgPageHeaderTeam()) || isOrgAdmin(org2()));
  });
  const members = createMemo(() => (orgPageHeaderTeam() ? orgPageHeaderTeam().members_preview : org2().members_preview) || []);
  const remainingMembersCount = createMemo(() => Math.max(0, members().length - 6));
  const navItems = createMemo(() => {
    let items;
    if (orgPageHeaderTeam()) {
      items = [{
        label: _4("Workspaces"),
        route: "org.team.hub",
        routeParams: {
          slug: org2().slug,
          teamSlug: orgPageHeaderTeam().slug
        }
      }, {
        label: _4("Portfolios"),
        route: "org.team.portfolios",
        routeParams: {
          slug: org2().slug,
          teamSlug: orgPageHeaderTeam().slug
        },
        hide: !hasFeatureFlag(org2(), "portfolios")
      }, {
        label: _4("Members"),
        route: "org.team.members",
        routeParams: {
          slug: org2().slug,
          teamSlug: orgPageHeaderTeam().slug
        }
      }];
    } else {
      items = [{
        label: _4("Overview"),
        route: "org.hub",
        routeParams: {
          slug: org2().slug
        }
      }, {
        label: _4("Updates"),
        route: "org.updates",
        routeParams: {
          slug: org2().slug
        },
        hide: !hasFeatureFlag(org2(), "org_updates")
      }, {
        label: _4("Workspaces"),
        route: "org.projects",
        routeParams: {
          slug: org2().slug
        }
      }, {
        label: _4("Portfolios"),
        route: "org.portfolios",
        routeParams: {
          slug: org2().slug
        },
        hide: !hasFeatureFlag(org2(), "portfolios")
      }, {
        label: _4("Teams"),
        route: "org.teams",
        routeParams: {
          slug: org2().slug
        },
        hide: !hasFeatureFlag(org2(), "teams")
      }, {
        label: _4("Forms"),
        route: "org.forms",
        routeParams: {
          slug: org2().slug
        },
        hide: !hasFeatureFlag(org2(), "org_hub")
      }, {
        label: _4("Members"),
        route: "org.members",
        routeParams: {
          slug: org2().slug
        }
      }];
    }
    return items.filter((i3) => !i3.hide);
  });
  const navMenuForXSScreen = createMemo(() => navItems().map((navItem) => ({
    label: navItem.label,
    action: () => navigate2(navItem.route, navItem.routeParams),
    enabled: () => isScreensizeXS()
  })));
  const bannerStyle = createMemo(() => {
    let localStyle;
    if (org2().image_cover_url) {
      localStyle = {
        background: `url(${org2().image_cover_url}) no-repeat top center`,
        "background-size": "cover"
      };
      if (org2().cover_color) {
        localStyle["background-color"] = org2().cover_color;
      }
    } else if (org2().cover_color) {
      localStyle = {
        background: org2().cover_color
      };
    }
    return localStyle;
  });
  const settingsMenu = createMemo(() => {
    let menu;
    if (orgPageHeaderTeam() && isTeamAdmin(orgPageHeaderTeam())) {
      menu = {
        config: [
          // --- only on XS screen
          {
            subheader: _4("Team navigation"),
            enabled: () => isScreensizeXS()
          },
          ...navMenuForXSScreen(),
          {
            label: "--",
            enabled: () => isScreensizeXS()
          },
          // ---
          {
            label: _4("Team settings"),
            action: () => $invoke(["teamSettingsModal", (teamSettingsModal) => teamSettingsModal.open(orgPageHeaderTeam())])
          },
          // --- only in XS screen
          {
            label: "--",
            enabled: () => isScreensizeXS() && (canJoinTeam() || canInvite())
          },
          {
            label: _4("Join this team"),
            action: () => joinTeam(orgPageHeaderTeam()),
            enabled: () => isScreensizeXS() && canJoinTeam()
          },
          {
            label: _4("Add member"),
            action: () => inviteMembers(),
            enabled: () => isScreensizeXS() && canInvite()
          }
          // ---
        ]
      };
    } else if (isOrgAdmin(org2())) {
      menu = {
        config: [
          // --- only on XS screen
          {
            subheader: _4("Organization navigation"),
            enabled: () => isScreensizeXS()
          },
          ...navMenuForXSScreen(),
          {
            label: "--",
            enabled: () => isScreensizeXS()
          },
          // ---
          {
            label: _4("Organization settings"),
            action: () => $invoke(["orgSettingsModal", (orgSettingsModal) => orgSettingsModal.open(org2())])
          },
          {
            label: _4("Billing & invoices"),
            action: () => $invoke(["orgSettingsModal", (orgSettingsModal) => orgSettingsModal.open(org2(), "billing")]),
            enabled: () => isOrgOwner(org2()) && serverConfig.payments_enabled
          },
          // --- only in XS screen
          {
            label: "--",
            enabled: () => isScreensizeXS() && canInvite()
          },
          {
            label: _4("Invite"),
            action: () => inviteMembers(),
            enabled: () => isScreensizeXS() && canInvite()
          }
          // ---
        ]
      };
    }
    if (orgPageHeaderActionsMenu()) {
      if (!menu) {
        menu = {
          config: []
        };
      } else {
        menu.config.push({
          label: "--"
        });
      }
      menu.config.push(...orgPageHeaderActionsMenu());
    }
    return menu;
  });
  let uploadProgress;
  const bannerCustomizationMenu = createMemo(() => {
    const menu = {
      config: [{
        subheader: _4("Logo")
      }, {
        filepicker: true,
        initialFile: org2().logo_url,
        getProgress: () => uploadProgress,
        noCloseAfterAction: true,
        action: async (event2, pickedFile) => {
          if (pickedFile) {
            uploadProgress = 1;
            upload({
              url: api_default.organizations.update_org.url({
                org_id: org2().id
              }),
              data: {
                logo: pickedFile
              }
            }, (evt) => {
              uploadProgress = parseInt(100 * evt.loaded / evt.total);
            }).then((r3) => {
              uploadProgress = false;
              setTimeout(() => {
                orgStore.update(org2(), r3.data);
              }, 500);
            }, (resp) => {
              errorDialog(_4("An error occured while uploading your file"));
            });
          } else {
            await updateOrg(org2(), {
              logo: null
            });
          }
        }
      }],
      options: {
        title: _4("Banner customization")
      }
    };
    if (hasFeatureFlag(org2(), "org_hub")) {
      menu.config.push({
        subheader: _4("Image")
      }, {
        filepicker: true,
        initialFile: org2().image_cover_url,
        getProgress: () => uploadProgress,
        noCloseAfterAction: true,
        action: async (event2, pickedFile) => {
          if (pickedFile) {
            uploadProgress = 1;
            upload({
              url: api_default.organizations.update_org.url({
                org_id: org2().id
              }),
              data: {
                image_cover: pickedFile
              }
            }, (evt) => {
              uploadProgress = parseInt(100 * evt.loaded / evt.total);
            }).then((r3) => {
              uploadProgress = false;
              setTimeout(() => {
                orgStore.update(org2(), r3.data);
              }, 500);
            }, (resp) => {
              errorDialog(_4("An error occured while uploading your file"));
            });
          } else {
            await updateOrg(org2(), {
              image_cover: null
            });
          }
        }
      }, {
        subheader: _4("Color")
      }, {
        colorpicker: true,
        getValue: () => org2().cover_color || null,
        action: async (event2, color) => {
          color = color || "";
          if (org2().cover_color === color) {
            return;
          }
          await updateOrg(org2(), {
            cover_color: color
          });
        },
        hasColorPalette: true,
        offline: false
      });
    } else {
      menu.config.push({
        label: "--"
      }, {
        label: _4("More customization available"),
        featureFlag: [org2(), "org_hub"],
        action: () => fenceBehindFeatureFlag(org2(), "org_hub", () => {
        })
      });
    }
    return menu;
  });
  const teamCustomizationMenuConfig = createMemo(() => ({
    config: [{
      subheader: _4("Customize your team")
    }, {
      colorpicker: true,
      getValue: () => orgPageHeaderTeam().color || null,
      action: (event2, color) => {
        color = color || "";
        if (orgPageHeaderTeam().color === color) {
          return;
        }
        updateTeam(orgPageHeaderTeam(), {
          color
        });
      },
      noColorColor: "#eee",
      hasColorPalette: true,
      offline: false
    }, {
      subheader: _4("Icon")
    }, {
      iconpicker: true,
      emptyIcon: true,
      getValue: () => orgPageHeaderTeam().icon,
      action: (event2, icon) => {
        if (orgPageHeaderTeam().icon === icon) {
          return;
        }
        updateTeam(orgPageHeaderTeam(), {
          icon
        });
      },
      noCloseAfterAction: true,
      extended: true
    }]
  }));
  function inviteMembers() {
    if (orgPageHeaderTeam()) {
      $invoke(["teamAddMemberModal", (teamAddMemberModal) => teamAddMemberModal.open(orgPageHeaderTeam())]);
    } else {
      $invoke(["orgInviteMembersModal", (orgInviteMembersModal) => orgInviteMembersModal.open(org2())]);
    }
  }
  ;
  return (() => {
    const _el$ = _tmpl$428.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$7 = _el$3.nextSibling, _el$10 = _el$2.nextSibling;
    insert(_el$3, createComponent(A3, {
      route: "org.hub",
      get routeParams() {
        return {
          slug: org2().slug
        };
      },
      get style() {
        return {
          "background-image": org2().logo_url ? "url(" + org2().logo_url + ")" : ""
        };
      },
      get children() {
        return createComponent(Show, {
          get when() {
            return !org2().logo_url;
          },
          get children() {
            return createComponent(Icon, {
              name: "bi-building"
            });
          }
        });
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      get when() {
        return createMemo(() => !!(!locked() && isOwner()))() && !orgPageHeaderTeam();
      },
      get children() {
        return createComponent(NgComponent, {
          directive: "header-banner-customization-menu-button",
          get menu() {
            return bannerCustomizationMenu();
          }
        });
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      get when() {
        return !!orgPageHeaderTeam();
      },
      get children() {
        return createComponent(NgComponent, {
          directive: "header-team-customization-menu-config-button",
          get teamCustomizationMenuConfig() {
            return teamCustomizationMenuConfig();
          },
          get team() {
            return orgPageHeaderTeam();
          },
          get canCustomize() {
            return canCustomize();
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(ReadableTextColor, {
      get bgColor() {
        return org2().cover_color;
      },
      get children() {
        const _el$4 = _tmpl$259.cloneNode(true);
        insert(_el$4, createComponent(A3, {
          route: "org.hub",
          get routeParams() {
            return {
              slug: org2().slug
            };
          },
          get children() {
            return org2().name;
          }
        }), null);
        insert(_el$4, createComponent(Show, {
          get when() {
            return orgPageHeaderTeam();
          },
          get children() {
            const _el$5 = _tmpl$131.cloneNode(true), _el$6 = _el$5.firstChild;
            insert(_el$5, createComponent(A3, {
              route: "organization",
              get routeParams() {
                return {
                  slug: org2().slug,
                  teamSlug: orgPageHeaderTeam().slug
                };
              },
              get children() {
                return orgPageHeaderTeam().name;
              }
            }), null);
            return _el$5;
          }
        }), null);
        createRenderEffect(() => _el$4.style.setProperty("text-shadow", org2().image_cover_url ? "0 0 2px #fff" : null));
        return _el$4;
      }
    }), _el$7);
    insert(_el$2, createComponent(Show, {
      get when() {
        return canJoinTeam();
      },
      get children() {
        return createComponent(Button, {
          onClick: () => joinTeam(orgPageHeaderTeam()),
          "class": "btn-cta btn-lg hidden-xs",
          get label() {
            return _4("Join this team");
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return canInvite();
      },
      get children() {
        return createComponent(Button, {
          onClick: () => inviteMembers(),
          style: "cta",
          size: "lg",
          "class": "hidden-xs",
          get children() {
            return [createComponent(Icon, {
              name: "bi-person-plus-fill"
            }), " ", createMemo(() => createMemo(() => !!orgPageHeaderTeam())() ? _4("Add member") : _4("Invite"))];
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props2.showMembers;
      },
      get children() {
        return createComponent(A3, {
          "class": "members stacked-members-avatar hidden-xs",
          get route() {
            return orgPageHeaderTeam() ? "org.team.members" : "org.members";
          },
          get routeParams() {
            return {
              slug: org2().slug,
              teamSlug: orgPageHeaderTeam()?.slug
            };
          },
          get children() {
            return [createComponent(Show, {
              get when() {
                return remainingMembersCount();
              },
              get children() {
                const _el$8 = _tmpl$341.cloneNode(true), _el$9 = _el$8.firstChild;
                insert(_el$8, remainingMembersCount, null);
                return _el$8;
              }
            }), createComponent(For, {
              get each() {
                return members().slice(0, 6);
              },
              children: (m3) => createComponent(Tooltip, {
                get label() {
                  return m3.display_name || m3.username;
                },
                get children() {
                  return createComponent(UserAvatar, {
                    user: m3
                  });
                }
              })
            })];
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return createMemo(() => !!(isOwner() && org2().billing && org2().billing.status !== "trialing"))() && !org2().billing.plan?.includes("business");
      },
      get children() {
        return createComponent(Button, {
          "class": "btn-ghost hidden-xs",
          onClick: () => {
            $invoke(["orgSettingsModal", (orgSettingsModal) => orgSettingsModal.open(org2(), "billing")]);
          },
          get children() {
            return [createComponent(Icon, {
              name: "bi-stars"
            }), " ", createMemo(() => _4("Update to Business"))];
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return createMemo(() => !!settingsMenu())() && isScreensizeXS();
      },
      get children() {
        return createComponent(NgComponent, {
          directive: "header-settings-button",
          get menu() {
            return settingsMenu();
          }
        });
      }
    }), null);
    insert(_el$10, createComponent(For, {
      get each() {
        return navItems();
      },
      children: (item) => createComponent(A3, {
        get route() {
          return item.route;
        },
        get routeParams() {
          return item.routeParams;
        },
        end: true,
        get children() {
          return item.label;
        }
      })
    }), null);
    insert(_el$10, createComponent(Show, {
      get when() {
        return settingsMenu();
      },
      get children() {
        return createComponent(NgComponent, {
          directive: "header-settings-button",
          get menu() {
            return settingsMenu();
          }
        });
      }
    }), null);
    createRenderEffect((_$p) => style(_el$, bannerStyle(), _$p));
    return _el$;
  })();
}

// public/app/routes/org/OrganizationPage.jsx
var _tmpl$134 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$260 = /* @__PURE__ */ template(`<button class="btn"></button>`, 2);
function OrganizationPage(props2) {
  const org2 = useRouteData();
  setPageColor(org2().color);
  onMount(() => {
    onCleanup(updateSubtitle(org2().name));
    onCleanup(ngApp.$injector.get("coach").setupContext({
      org: org2().id
    }));
    if (isOrgOwner(org2())) {
      const orgBannerProps = getOrgBannerProps(org2());
      if (orgBannerProps) {
        const orgBanner = showBanner(OrgStatusBanner, orgBannerProps);
        onCleanup(() => orgBanner.close());
      }
    }
    if (!isOrgMember(org2()) && currentUser2.is_kantree_admin) {
      const adminBanner = showBanner(AccessingAsSystemAdminBanner);
      onCleanup(() => adminBanner.close());
    }
  });
  return createComponent(PageContainer, {
    get children() {
      return [createComponent(NgComponent, {
        directive: "organization-topbar",
        get org() {
          return org2();
        }
      }), createComponent(PageContainerView, {
        id: "org-view",
        get children() {
          return [createComponent(OrgPageHeader, {
            get org() {
              return org2();
            }
          }), createMemo(() => props2.children)];
        }
      })];
    }
  });
}
function getOrgBannerProps(org2) {
  let message, color, btnLabel = _4("Upgrade now");
  if (org2.billing && org2.billing.status === "trialing") {
    message = _4("Only {days} days left to take advantage of your free trial", {
      days: moment_default(org2.billing.trial_ends_at).diff(moment_default(), "days")
    });
    color = "#d9edf7";
  } else if (org2.billing && org2.billing.status === "unpaid") {
    message = _4("Your subscription has been suspended. Upgrade now to continue using Kantree");
    color = "#fcf8e3";
  } else if (org2.billing && ["past_due", "incomplete"].includes(org2.billing.status)) {
    message = _4("We haven't been able to charge the credit card");
    color = "#fcf8e3";
    btnLabel = _4("Check your billing information");
  } else if (org2.billing && org2.billing.status === "canceled") {
    message = _4("The subscription has been canceled");
    color = "#fcf8e3";
    btnLabel = _4("Re-activate");
  } else if (isOrgLocked(org2)) {
    message = _4("The team has been locked");
    btnLabel = null;
  } else {
    return null;
  }
  return {
    org: org2,
    message,
    color,
    btnLabel
  };
}
function OrgStatusBanner(props2) {
  function onClick() {
    $digest(["orgSettingsModal", function(orgSettingsModal) {
      orgSettingsModal.open(props2.org, "billing");
    }]);
  }
  return createComponent(SystemBanner, {
    get color() {
      return props2.color;
    },
    get children() {
      return [(() => {
        const _el$ = _tmpl$134.cloneNode(true);
        insert(_el$, () => props2.message);
        return _el$;
      })(), (() => {
        const _el$2 = _tmpl$260.cloneNode(true);
        _el$2.$$click = onClick;
        insert(_el$2, () => props2.btnLabel);
        return _el$2;
      })()];
    }
  });
}
function AccessingAsSystemAdminBanner() {
  return createComponent(SystemBanner, {
    "class": "dark-theme",
    color: "#941212",
    get children() {
      const _el$3 = _tmpl$134.cloneNode(true);
      insert(_el$3, () => _4("You are accessing this content as a Kantree admin"));
      return _el$3;
    }
  });
}
delegateEvents(["click"]);

// public/app/utils/file-base64-converter.js
function convertFileToBase64(file) {
  return new Promise((resolve2, reject2) => {
    const reader = new FileReader();
    reader.onload = () => resolve2(reader.result);
    reader.readAsDataURL(file);
  });
}
async function convertManyFilesToBase64(data2) {
  await Promise.all(Object.entries(data2).map(([key2, value2]) => {
    if (value2 instanceof File) {
      return convertFileToBase64(value2).then((b64) => {
        data2[key2] = [value2.name, b64];
      });
    } else if (isObject2(value2)) {
      return convertManyFilesToBase64(value2).then(() => {
        data2[key2] = value2;
      });
    }
  }));
  return data2;
}

// public/app/actions/form.ts
async function saveRequestForm(form) {
  const data2 = {
    project_id: form.project_id,
    name: form.name,
    description: form.description || "",
    header_color: form.header_color || null,
    email_required: form.email_required || false,
    unlisted: form.unlisted || false,
    send_confirmation_email: form.send_confirmation_email || false,
    request_page: form.request_page || false,
    email_message: form.email_message || "",
    email_sender: form.email_sender || "",
    public_permission: form.public_permission,
    allow_comments: form.allow_comments || false,
    editable_after_submit: form.editable_after_submit || false,
    allow_request_via_email: form.allow_request_via_email || false,
    anonymous_email_field_idx: form.anonymous_email_field_idx >= 0 ? form.anonymous_email_field_idx : null,
    email_subject_field_idx: form.email_subject_field_idx >= 0 ? form.email_subject_field_idx : null,
    email_body_field_idx: form.email_body_field_idx >= 0 ? form.email_body_field_idx : null,
    email_attachments_field_idx: form.email_attachments_field_idx >= 0 ? form.email_attachments_field_idx : null,
    tracking_group_type_id: form.tracking_group_type_id || null,
    tracking_group_ids: form.tracking_group_ids || [],
    notify_requester_of_group_change: form.notify_requester_of_group_change || false,
    add_card_to_group_id: form.add_card_to_group_id || null,
    card_model_id: form.card_model_id || null,
    add_to_parent_id: form.add_to_parent_id || null,
    fields: form.fields || []
  };
  if (form.id) {
    form = await api_default.project_request_forms.update_request_form.put(Object.assign({
      request_form_id: form.id
    }, data2));
  } else {
    form = await api_default.project_request_forms.create_request_form.post(data2);
  }
  return requestFormStore.upsert(form);
}
async function deleteRequestForm(form) {
  await api_default.project_request_forms.delete_request_form.delete({ project_id: form.project_id, request_form_id: form.id });
  cardStore.transaction(() => {
    cardStore.query({ project_id: form.project_id, from_request: query_exports.objMatch({ form_id: form.id }) }).forEach((card) => {
      cardStore.update(card, { from_request: null });
    });
  });
  requestFormStore.remove(form);
}
async function submitRequestForm(form, data2, email2) {
  data2 = await convertManyFilesToBase64(data2);
  let request2 = await api_default.request_form.post_request.post({ request_form_id: form.id, data: data2, email: email2 }, { signal: AbortSignal.timeout(6e4) });
  if (request2.id) {
    request2 = requestStore.insert(request2);
  }
  return request2;
}
async function unlistRequestForm(form) {
  form = await api_default.project_request_forms.update_request_form.put({
    project_id: form.project_id,
    request_form_id: form.id,
    unlisted: true
  });
  return requestFormStore.update(form);
}

// public/app/routes/org/components/Forms.jsx
var _tmpl$135 = /* @__PURE__ */ template(`<div class="org-view-empty-tab"><div></div><p></p></div>`, 6);
var _tmpl$261 = /* @__PURE__ */ template(`<div class="org-view-page" id="org-forms"><div class="org-view-page-controls"></div><div class="form-list"></div></div>`, 6);
var _tmpl$342 = /* @__PURE__ */ template(`<div class="indicator"></div>`, 2);
var _tmpl$429 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$525 = /* @__PURE__ */ template(`<span> <!> / </span>`, 3);
var _tmpl$620 = /* @__PURE__ */ template(`<a href="#"></a>`, 2);
var _tmpl$719 = /* @__PURE__ */ template(`<div><div class="main"><div class="name"></div></div></div>`, 6);
function formsRouteData() {
  const org2 = useRouteData();
  const [data2] = createResource(() => org2(), async (org3) => {
    await loadAllRequestFormsForOrg(org3);
    return org3;
  });
  return data2;
}
function FormsTab() {
  const navigate2 = useNavigate2();
  const org2 = useRouteData();
  const [filterForm, setFilterForm] = createSignal("");
  const data2 = requestFormStore.scopedByOrg(org2).react({
    unlisted: query_exports.isFalsy()
  }, {
    sortBy: "name"
  });
  return (() => {
    const _el$ = _tmpl$261.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
    insert(_el$2, createComponent(TextInput, {
      type: "text",
      get placeholder() {
        return _4("Filter forms");
      },
      get value() {
        return filterForm();
      },
      onInput: (e3) => setFilterForm(e3.target.value)
    }));
    insert(_el$3, createComponent(For, {
      get each() {
        return data2().filter((e3) => e3.name.toLowerCase().includes(filterForm().toLowerCase()));
      },
      children: (form) => (() => {
        const _el$7 = _tmpl$719.cloneNode(true), _el$9 = _el$7.firstChild, _el$10 = _el$9.firstChild;
        _el$7.$$click = (e3) => {
          e3.stopPropagation();
          navigate2("request_form", {
            formSlug: form.slug
          });
        };
        insert(_el$7, createComponent(ColorizeElement, {
          get bgColor() {
            return form.header_color || form.project.color || org2().cover_color || "#0a846c";
          },
          get children() {
            return _tmpl$342.cloneNode(true);
          }
        }), _el$9);
        insert(_el$10, () => form.name);
        insert(_el$9, createComponent(A3, {
          "class": "path",
          route: "project",
          get routeParams() {
            return {
              projectId: form.project.slug
            };
          },
          onClick: (e3) => e3.stopPropagation(),
          get children() {
            return [createComponent(Show, {
              get when() {
                return form.team;
              },
              get children() {
                const _el$11 = _tmpl$525.cloneNode(true), _el$13 = _el$11.firstChild, _el$15 = _el$13.nextSibling, _el$14 = _el$15.nextSibling;
                insert(_el$11, createComponent(ColorizeElement, {
                  get fgColor() {
                    return form.team.color || "#aaa";
                  },
                  get children() {
                    const _el$12 = _tmpl$429.cloneNode(true);
                    insert(_el$12, createComponent(Icon, {
                      get name() {
                        return form.team.icon || "bi-circle-fill";
                      }
                    }));
                    return _el$12;
                  }
                }), _el$13);
                insert(_el$11, () => form.team.name, _el$15);
                return _el$11;
              }
            }), createMemo(() => form.project.title)];
          }
        }), null);
        insert(_el$7, createComponent(Show, {
          get when() {
            return isOrgAdmin(org2());
          },
          get children() {
            return createComponent(Tooltip, {
              get label() {
                return _4("Remove from this list");
              },
              get children() {
                const _el$16 = _tmpl$620.cloneNode(true);
                _el$16.$$click = (e3) => {
                  e3.stopPropagation();
                  unlistRequestForm(form);
                };
                insert(_el$16, createComponent(Icon, {
                  name: "bi-x-lg"
                }));
                return _el$16;
              }
            });
          }
        }), null);
        return _el$7;
      })()
    }));
    insert(_el$, createComponent(Show, {
      get when() {
        return createMemo(() => !!!data2().length)() && !filterForm();
      },
      get children() {
        const _el$4 = _tmpl$135.cloneNode(true), _el$5 = _el$4.firstChild, _el$6 = _el$5.nextSibling;
        insert(_el$5, () => _4("You don't have any forms yet"));
        insert(_el$6, () => _4("Forms can be created inside workspaces to collect information and start processes"));
        return _el$4;
      }
    }), null);
    return _el$;
  })();
}
delegateEvents(["click"]);

// public/app/loaders/activity.js
async function loadAllActivitiesForCard(card, options2 = {}) {
  const activities = await loadMany(activityStore, api_default.card_stream.list_stream, { card_id: card.id }, options2);
  activityStore.scopedForCard(card).removeAllNotMatching(activities);
  return activities;
}
function loadAllActivitiesForProject(project, params) {
  return loadMany(activityStore, api_default.projects.list_activities, Object.assign({
    project_id: project.id
  }, params || {}));
}
function loadAllActivitiesForProjectBetweenDates(project, fromDate, toDate) {
  return loadAllActivitiesForProject(project, { from_date: fromDate, to_date: toDate });
}
function loadLogsForProject(project, logType) {
  return loadMany(activityStore, api_default.project_log_types.list_logs, {
    project_id: project.id,
    type_id: logType.id
  });
}
async function loadUpdatesForOrg(org2, options2) {
  return loadPaginated(activityStore, api_default.organizations.list_updates, { org_id: org2.id }, options2);
}

// public/app/routes/org/components/Project/ProjectsFilterContext.jsx
var OrgProjectsFiltersContext = createContext();
function OrgProjectsFiltersContextProvider(props2) {
  const [filter4, setFilter] = createSignal("");
  const [sortByFilter, setSortByFilter] = createSignal("title");
  const [showArchive, setShowArchive] = createSignal(false);
  const data2 = {
    filter: filter4,
    setFilter,
    sortByFilter,
    setSortByFilter,
    showArchive,
    setShowArchive
  };
  return createComponent(OrgProjectsFiltersContext.Provider, {
    value: data2,
    get children() {
      return props2.children;
    }
  });
}
var useOrgProjectsFilterContext = () => useContext(OrgProjectsFiltersContext);

// public/app/config/project/available-sorts.js
var projectAvailableSorts = [
  {
    title: "A-Z",
    predicate: "title"
  },
  {
    title: "Z-A",
    predicate: "-title"
  },
  {
    title: _lazy("Recently created"),
    predicate: "-created_at"
  },
  {
    title: _lazy("Recently active"),
    predicate: "-last_activity_at"
  }
];

// public/app/routes/org/components/Project/ProjectList.jsx
var _tmpl$136 = /* @__PURE__ */ template(`<span class="input-group me-2 mb-2"><span class="input-group-text" for="projectListSort"></span></span>`, 4);
var _tmpl$262 = /* @__PURE__ */ template(`<form></form>`, 2);
var _tmpl$343 = /* @__PURE__ */ template(`<div class="empty"></div>`, 2);
var _tmpl$430 = /* @__PURE__ */ template(`<div class="project-tile-list"></div>`, 2);
var _tmpl$526 = /* @__PURE__ */ template(`<div class="project-tile-list-placeholder"></div>`, 2);
var _tmpl$621 = /* @__PURE__ */ template(`<div class="org-project-list"></div>`, 2);
function OrgProjectList(props2) {
  props2 = mergeProps({
    emptyMessage: _4("No workspaces found"),
    filterPlaceholder: _4("Filter workspaces"),
    createBtnLabel: props2.org.can_create_private_projects ? _4("New workspace") : _4("New public workspace"),
    placeholderProjects: [],
    showCreate: true,
    showSort: true,
    isPortfolios: false,
    showArchivesCheckbox: false,
    onSortChange: () => {
    },
    onArchivesChecked: () => {
    }
  }, props2);
  const resolved = children(() => props2.children);
  const canCreateProjects = currentUser2.is_kantree_admin || props2.org.can_create_projects && !isOrgLocked(props2.org) && (isOrgAdmin(props2.org) || !props2.team && isOrgManager(props2.org) || props2.team && isTeamManager(props2.team));
  const {
    filter: filter4,
    setFilter,
    sortByFilter,
    setSortByFilter,
    showArchive,
    setShowArchive
  } = useOrgProjectsFilterContext();
  if (props2.sortBy) setSortByFilter(props2.sortBy);
  const localProjects = props2.store ? props2.store.react() : () => props2.projects;
  let sortingBy = props2.sortBy;
  if (!sortingBy) {
    props2.onSortChange(sortByFilter());
  }
  const filteredProjects = createMemo(() => {
    let filteredProjects2 = localProjects().filter((project) => (!project.is_archived || showArchive()) && (!filter4() || project.title.toLowerCase().indexOf(filter4().toLowerCase()) !== -1));
    filteredProjects2 = sortBy2(filteredProjects2, sortByFilter());
    return filteredProjects2;
  });
  const placeholderProjects = createMemo(() => {
    if (props2.showPlaceholder && localProjects().length === 0) {
      const now = moment().unix();
      return [{
        title: _4("Project management"),
        last_activity_at: now,
        color: "#cbbaf5",
        icon: "bi-check2-square"
      }, {
        title: _4("CRM"),
        last_activity_at: now,
        color: "#fde7a8",
        icon: "bi-person-rolodex"
      }, {
        title: _4("Marketing"),
        last_activity_at: now,
        color: "#93e9ba",
        icon: "bi-megaphone"
      }, {
        title: _4("Recruiting"),
        last_activity_at: now,
        color: "#9ee3ed",
        icon: "bi-person-badge"
      }, {
        title: _4("Event planner"),
        last_activity_at: now,
        color: "#f7dcf4",
        icon: "bi-calendar"
      }, {
        title: _4("Issue tracker"),
        last_activity_at: now,
        color: "#f3bfbf",
        icon: "bi-bug"
      }];
    }
    return props2.placeholderProjects;
  });
  const onCreateClick = (e3) => {
    if (props2.onCreateClick) {
      e3.preventDefault();
      props2.onCreateClick();
    }
  };
  return (() => {
    const _el$ = _tmpl$621.cloneNode(true);
    insert(_el$, createComponent(Show, {
      get when() {
        return (canCreateProjects || localProjects().length) && (props2.showSort || props2.showArchivesCheckbox);
      },
      get children() {
        const _el$2 = _tmpl$262.cloneNode(true);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props2.showCreate && canCreateProjects;
          },
          get children() {
            return createComponent(A3, {
              "class": "btn me-2 mb-2",
              get classList() {
                return {
                  "btn-cta": props2.highlightCreate,
                  "btn-default btn-ghost": !props2.highlightCreate
                };
              },
              route: "templates",
              get routeParams() {
                return {
                  org: props2.org.id,
                  team: props2.team?.id
                };
              },
              "hide-offline": true,
              onClick: onCreateClick,
              get children() {
                return [createComponent(Icon, {
                  name: "bi-plus-lg"
                }), " ", createMemo(() => props2.createBtnLabel)];
              }
            });
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props2.exploreProjectsLink;
          },
          get children() {
            return createComponent(A3, {
              "class": "btn btn-default btn-ghost me-2 mb-2",
              get route() {
                return props2.exploreProjectsLink;
              },
              get children() {
                return [createComponent(Icon, {
                  name: "fa-binoculars"
                }), " ", createMemo(() => _4("Explore"))];
              }
            });
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return props2.filterable;
          },
          get children() {
            return createComponent(TextInput, {
              type: "text",
              "class": "me-2 mb-2",
              get placeholder() {
                return props2.filterPlaceholder;
              },
              get value() {
                return filter4();
              },
              onInput: (e3) => setFilter(e3.target.value)
            });
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return createMemo(() => !!props2.showSort)() && localProjects().length;
          },
          get children() {
            const _el$3 = _tmpl$136.cloneNode(true), _el$4 = _el$3.firstChild;
            insert(_el$4, createComponent(Icon, {
              name: "bi-sort-down"
            }));
            insert(_el$3, createComponent(SelectInput2, {
              get options() {
                return projectAvailableSorts.map((e3) => ({
                  ...e3,
                  value: e3.predicate
                }));
              },
              get selected() {
                return sortByFilter();
              },
              onChange: (e3) => {
                props2.onSortChange(e3.target.value);
                setSortByFilter(e3.target.value);
              },
              id: "projectListSort"
            }), null);
            return _el$3;
          }
        }), null);
        insert(_el$2, createComponent(Show, {
          get when() {
            return createMemo(() => !!props2.showArchivesCheckbox)() && localProjects().length;
          },
          get children() {
            return createComponent(CheckInput, {
              id: "projectListWithArchives",
              name: "projectListWithArchives",
              containerClass: "form-switch me-2 mb-2",
              get label() {
                return _4("Show archives");
              },
              get checked() {
                return showArchive();
              },
              onChange: (e3) => {
                props2.onArchivesChecked(e3.target.checked);
                setShowArchive(e3.target.checked);
              }
            });
          }
        }), null);
        insert(_el$2, resolved, null);
        return _el$2;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return !placeholderProjects().length;
      },
      get children() {
        const _el$5 = _tmpl$430.cloneNode(true);
        insert(_el$5, createComponent(Show, {
          get when() {
            return filteredProjects().length === 0;
          },
          get children() {
            const _el$6 = _tmpl$343.cloneNode(true);
            insert(_el$6, () => props2.emptyMessage);
            return _el$6;
          }
        }), null);
        insert(_el$5, createComponent(For, {
          get each() {
            return filteredProjects();
          },
          children: (project) => createComponent(ProjectTile, {
            project,
            get showTeam() {
              return props2.showTileTeam;
            }
          })
        }), null);
        return _el$5;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return placeholderProjects().length;
      },
      get children() {
        const _el$7 = _tmpl$526.cloneNode(true);
        insert(_el$7, createComponent(For, {
          get each() {
            return placeholderProjects();
          },
          children: (project) => createComponent(ProjectTile, {
            project
          })
        }), null);
        insert(_el$7, createComponent(Show, {
          get when() {
            return props2.org.nb_projects === 0 && canCreateProjects;
          },
          get children() {
            return createComponent(A3, {
              route: "templates",
              get children() {
                return [createMemo(() => _4("Discover the endless possibilities of Kantree using our templates")), createComponent(Icon, {
                  name: "bi-arrow-right-circle-fill"
                })];
              }
            });
          }
        }), null);
        insert(_el$7, createComponent(Show, {
          get when() {
            return props2.org.nb_projects === 0 && !canCreateProjects;
          },
          get children() {
            return createComponent(A3, {
              route: "templates",
              get children() {
                return _4("No workspaces have been created yet");
              }
            });
          }
        }), null);
        insert(_el$7, createComponent(Show, {
          get when() {
            return !localProjects().length && props2.org.nb_projects > 0;
          },
          get children() {
            return createComponent(A3, {
              route: "org.projects",
              get routeParams() {
                return {
                  slug: props2.org.slug
                };
              },
              get children() {
                return [createMemo(() => _4("Explore all available workspaces from your organization")), createComponent(Icon, {
                  name: "bi-arrow-right-circle-fill"
                })];
              }
            });
          }
        }), null);
        insert(_el$7, createComponent(Show, {
          get when() {
            return localProjects().length;
          },
          get children() {
            return createComponent(A3, {
              route: "org.projects",
              get routeParams() {
                return {
                  slug: props2.org.slug
                };
              },
              get children() {
                return [createMemo(() => _4("Explore more use cases")), createComponent(Icon, {
                  "class": "bi-arrow-right-circle-fill"
                })];
              }
            });
          }
        }), null);
        createRenderEffect(() => _el$7.classList.toggle("blur-more", !!(!localProjects().length && props2.org.nb_projects > 0)));
        return _el$7;
      }
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Project/Projects.jsx
var _tmpl$137 = /* @__PURE__ */ template(`<div class="onboarding-notice"><span>\u{1F389}</span><div><h2></h2><p></p></div></div>`, 10);
var _tmpl$263 = /* @__PURE__ */ template(`<div class="hub-section"></div>`, 2);
var _tmpl$344 = /* @__PURE__ */ template(`<div class="org-view-page"></div>`, 2);
var _tmpl$431 = /* @__PURE__ */ template(`<div class="hub-section"><div class="hub-title"></div></div>`, 4);
function projectsRouteData() {
  const org2 = useRouteData();
  const [data2] = createResource(() => org2(), async (org3) => {
    await loadAllTeams(org3);
    await loadProjectsForOrg(org3, false, true);
    return org3;
  });
  return data2;
}
function OrgProjects() {
  const searchParams = useSearchParams();
  const org2 = useRouteData();
  const isAdmin = () => isOrgAdmin(org2());
  const teams = teamStore.scopedByOrg(org2).react({}, {
    sortBy: "name"
  });
  const projects = projectStore.scopedByTeam(false, org2());
  const getTeamStore = (team) => projectStore.scopedByTeam(team, org2());
  return (() => {
    const _el$ = _tmpl$344.cloneNode(true);
    insert(_el$, createComponent(Show, {
      get when() {
        return searchParams.onboarding;
      },
      get children() {
        const _el$2 = _tmpl$137.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.nextSibling, _el$5 = _el$4.firstChild, _el$6 = _el$5.nextSibling;
        insert(_el$5, () => _4("Welcome to Kantree! Checkout workspaces from your organization"));
        insert(_el$6, () => _4("Workspaces are where work happens. Whether you are organizing data, building a product, planning an event, etc... workspaces will let you work the way you want with your team mates"));
        return _el$2;
      }
    }), null);
    insert(_el$, createComponent(OrgProjectsFiltersContextProvider, {
      get children() {
        return [(() => {
          const _el$7 = _tmpl$263.cloneNode(true);
          insert(_el$7, createComponent(OrgProjectList, {
            store: projects,
            get org() {
              return org2();
            },
            filterable: true,
            get showArchivesCheckbox() {
              return isAdmin();
            },
            onArchivesChecked: (checked) => !!checked && isAdmin() && loadAllArchivedProjectsForOrg(org2())
          }));
          return _el$7;
        })(), createComponent(For, {
          get each() {
            return teams();
          },
          children: (team) => (() => {
            const _el$8 = _tmpl$431.cloneNode(true), _el$9 = _el$8.firstChild;
            insert(_el$9, createComponent(A2, {
              get href() {
                return "/o/" + org2().slug + "/" + team.slug;
              },
              get children() {
                return [createComponent(Icon, {
                  get name() {
                    return team.icon || "bi-circle-fill";
                  },
                  get style() {
                    return {
                      color: team.color || "#aaa"
                    };
                  }
                }), createMemo(() => team.name)];
              }
            }));
            insert(_el$8, createComponent(OrgProjectList, {
              get store() {
                return getTeamStore(team);
              },
              get org() {
                return org2();
              },
              team,
              showSort: false
            }), null);
            return _el$8;
          })()
        })];
      }
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Team/TeamTile.jsx
var _tmpl$138 = /* @__PURE__ */ template(`<div class="name mb-2"></div>`, 2);
var _tmpl$264 = /* @__PURE__ */ template(`<span>+</span>`, 2);
var _tmpl$345 = /* @__PURE__ */ template(`<div class="members stacked-members-avatar"></div>`, 2);
function OrgTeamTile(props2) {
  const [members, setMembers] = createSignal([]);
  const [remainingMembersCount, setRemainingMembersCount] = createSignal(0);
  createEffect(() => {
    if (props2.team.members_preview?.length) {
      setMembers(props2.team.members_preview.slice(0, 6));
      setRemainingMembersCount(Math.max(0, props2.team.members_preview.length - 6));
    }
  });
  return createComponent(A3, {
    get style() {
      return {
        "border-left-color": props2.team.color
      };
    },
    "class": "team-tile",
    route: "org.team.hub",
    get routeParams() {
      return {
        slug: props2.org.slug,
        teamSlug: props2.team.slug
      };
    },
    get children() {
      return [createComponent(Show, {
        get when() {
          return props2.team.icon;
        },
        get children() {
          return createComponent(Icon, {
            get name() {
              return props2.team.icon;
            },
            get style() {
              return {
                color: props2.team.color
              };
            }
          });
        }
      }), createComponent(VStack, {
        "class": "ms-4",
        get children() {
          return [(() => {
            const _el$ = _tmpl$138.cloneNode(true);
            insert(_el$, () => props2.team.name);
            return _el$;
          })(), (() => {
            const _el$2 = _tmpl$345.cloneNode(true);
            insert(_el$2, createComponent(Show, {
              get when() {
                return remainingMembersCount();
              },
              get children() {
                const _el$3 = _tmpl$264.cloneNode(true), _el$4 = _el$3.firstChild;
                insert(_el$3, remainingMembersCount, null);
                return _el$3;
              }
            }), null);
            insert(_el$2, createComponent(For, {
              get each() {
                return members();
              },
              children: (m3) => createComponent(Tooltip, {
                get label() {
                  return m3.display_name || m3.username;
                },
                get children() {
                  return createComponent(UserAvatar, {
                    user: m3
                  });
                }
              })
            }), null);
            return _el$2;
          })()];
        }
      })];
    }
  });
}

// public/app/routes/org/components/Updates.jsx
var _tmpl$139 = /* @__PURE__ */ template(`<div class="org-view-page" id="org-news"></div>`, 2);
var _tmpl$265 = /* @__PURE__ */ template(`<div></div>`, 2);
var _tmpl$346 = /* @__PURE__ */ template(`<div class="activity-update"><div class="activity-update-header"></div><div class="activity-update-body"></div></div>`, 6);
function updatesRouteData() {
  const org2 = useRouteData();
  const [data2] = createResource(() => org2(), async (org3) => {
    await loadUpdatesForOrg(org3);
    return org3;
  });
  return data2;
}
function UpdatesTab() {
  const org2 = useRouteData();
  const updates = activityStore.scopedByOrg(org2).scopedByUpdates().react({}, {
    sortBy: "-date"
  });
  return (() => {
    const _el$ = _tmpl$139.cloneNode(true);
    insert(_el$, createComponent(Button, {
      onClick: () => openModal(() => createComponent(PostUpdateModal, {
        get org() {
          return org2();
        }
      })),
      get children() {
        return _4("Post an update");
      }
    }), null);
    insert(_el$, createComponent(UpdatesTimeline, {
      get updates() {
        return updates();
      },
      "class": "mt-3"
    }), null);
    return _el$;
  })();
}
function UpdatesTimeline(props2) {
  return (() => {
    const _el$2 = _tmpl$265.cloneNode(true);
    insert(_el$2, createComponent(For, {
      get each() {
        return props2.updates;
      },
      children: (activity) => createComponent(UpdatePost, {
        activity
      })
    }));
    createRenderEffect(() => className(_el$2, "org-updates-timeline " + (props2.class || "")));
    return _el$2;
  })();
}
function UpdatePost(props2) {
  const contentHtml = createMemo(() => convertMarkdownToHTML(props2.activity.message));
  return (() => {
    const _el$3 = _tmpl$346.cloneNode(true), _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling;
    insert(_el$4, createComponent(UserAvatar, {
      get user() {
        return props2.activity.actor;
      }
    }), null);
    insert(_el$4, () => _4("Posted by {author} {ago}", {
      author: props2.activity.actor.display_name,
      ago: fromNow(props2.activity.date)
    }), null);
    createRenderEffect(() => _el$5.innerHTML = contentHtml());
    return _el$3;
  })();
}
function PostUpdateModal(props2) {
  const modal = useModal();
  const [form, {
    Form: Form3,
    TextAreaField
  }] = createForm2();
  const postUpdate = async (values2) => {
    await postOrgUpdate(props2.org, values2.content);
    modal.close();
  };
  return createComponent(Modal, {
    get children() {
      return [createComponent(ModalHeader, {
        get title() {
          return _4("Post an update to {org}", {
            org: props2.org.name
          });
        }
      }), createComponent(ModalBody, {
        get children() {
          return createComponent(Form3, {
            of: form,
            onSubmit: postUpdate,
            get children() {
              return [createComponent(TextAreaField, {
                of: form,
                name: "content",
                get placeholder() {
                  return _4("Your message");
                },
                rows: "4"
              }), createComponent(Button, {
                type: "submit",
                style: "primary",
                get disabled() {
                  return form.submitting;
                },
                get children() {
                  return _4("Post update");
                }
              })];
            }
          });
        }
      })];
    }
  });
}

// public/app/routes/org/components/Hub.jsx
var _tmpl$140 = /* @__PURE__ */ template(`<div class="featured-items"></div>`, 2);
var _tmpl$266 = /* @__PURE__ */ template(`<button></button>`, 2);
var _tmpl$347 = /* @__PURE__ */ template(`<div class="hub-section"><div class="hub-title"></div><div class="team-tile-list"></div></div>`, 6);
var _tmpl$432 = /* @__PURE__ */ template(`<div class="hub-section"><div class="hub-title"></div></div>`, 4);
var _tmpl$527 = /* @__PURE__ */ template(`<span class="counter"></span>`, 2);
var _tmpl$622 = /* @__PURE__ */ template(`<div class="hub-section joined-projects"><div class="hub-title"></div></div>`, 4);
var _tmpl$720 = /* @__PURE__ */ template(`<div class="hub-section page-description"></div>`, 2);
var _tmpl$817 = /* @__PURE__ */ template(`<div class="hub-section promo-section"><h4> </h4><p></p><a class="btn btn-cta" target="_blank"></a></div>`, 8);
var _tmpl$915 = /* @__PURE__ */ template(`<div class="hub-section promo-section" hide-offline><h4> </h4><p></p><ul><li> </li><li> </li><li> </li><li> </li><li> </li></ul></div>`, 18);
var _tmpl$1012 = /* @__PURE__ */ template(`<div class="hub-sidebar"></div>`, 2);
var _tmpl$1112 = /* @__PURE__ */ template(`<div class="org-view-page"><div class="hub-container"><div class="hub-main"><div class="hub-section links hidden-xs"><a target="_blank"> </a><a target="_blank"> </a><a href="https://kantree.io/leave-review" target="_blank"> </a></div></div></div></div>`, 14);
var _tmpl$1210 = /* @__PURE__ */ template(`<span> </span>`, 2);
var _tmpl$1310 = /* @__PURE__ */ template(`<span><img alt=""> </span>`, 3);
var _tmpl$144 = /* @__PURE__ */ template(`<div><a></a></div>`, 4);
var _tmpl$154 = /* @__PURE__ */ template(`<div><h3></h3></div>`, 4);
function OrgHub(props2) {
  const org2 = useRouteData();
  const locked = () => isOrgLocked(org2());
  const isAdmin = () => isOrgAdmin(org2());
  const isOwner = () => isOrgOwner(org2());
  ensureConnectivity(() => {
    loadAllTeams(org2()), loadProjectsForOrg(org2());
  });
  const [joinedProjectsGroupedByTeams, setJoinedProjectsGroupedByTeams] = createSignal(get(currentUser2.app_params, "org_hub_group_by_teams", false));
  const [joinedTeams, setJoinedTeams] = createSignal([]);
  const [joinedProjectsSort, setJoinedProjectsSort] = createSignal(get(currentUser2.app_params, "org_hub_sort"));
  const [hasJoinedTeams, setHasJoinedTeams] = createSignal(false);
  const [joinedProjectsCount, setJoinedProjectsCount] = createSignal(0);
  const [joinedProjects, setJoinedProjects] = createSignal([]);
  const [featuredItemEditing, setFeaturedItemEditing] = createSignal(false);
  const toggleFeaturedItemEditing = () => {
    setFeaturedItemEditing((prev) => !prev);
  };
  const orgSpec = createMemo(() => appContext.orgs.find((o3) => o3.org.id === org2().id));
  const teams = teamStore.scopedByOrg(org2).react({
    is_member: true
  }, {
    sortBy: "name"
  });
  const updates = activityStore.scopedByOrg(org2).scopedByUpdates().react({}, {
    sortBy: "-date",
    limit: 4
  });
  const featuredItemStore = orgFeaturedItemStore.scopedByOrg(org2);
  const featuredItems = featuredItemStore.react({}, {
    sortBy: "name"
  });
  const [favoriteProjects, setFavoriteProjects] = createSignal([]);
  onCleanup(favoriteProjectStore.subscribe("favorites", () => {
    setFavoriteProjects(favoriteProjectStore.scopedByOrg(org2()).query({
      is_template: false
    }));
  }, true));
  const favoriteProjectIds = createHardMemo(() => pluck(favoriteProjects(), "id"));
  setOrgPageHeaderCustomizable(true);
  createEffect(() => {
    if (!isAdmin()) {
      return;
    }
    setOrgPageHeaderActionsMenu([{
      label: _4("Manage featured items"),
      featureFlag: [org2(), "org_hub"],
      action: () => fenceBehindFeatureFlag(org2(), "org_hub", () => toggleFeaturedItemEditing())
    }]);
  });
  onCleanup(() => {
    setOrgPageHeaderCustomizable(false);
    setOrgPageHeaderActionsMenu(null);
  });
  createEffect(() => {
    const joinedProjectsLocal = orgSpec()?.projectStore.scoped({
      id: query_exports.not(query_exports.any(favoriteProjectIds())),
      is_template: false,
      is_portfolio: false
    });
    const projectTeamIds = joinedProjectsLocal && uniq(pluck(joinedProjectsLocal.query(), "team").map((t3) => t3?.id).filter(Boolean));
    const joinedTeamsLocal = projectTeamIds && teamStore.query({
      is_member: true,
      id: query_exports.any(projectTeamIds)
    });
    setHasJoinedTeams(!!joinedTeamsLocal?.length);
    let _joinedProjects;
    if (joinedProjectsGroupedByTeams() && joinedTeamsLocal?.length) {
      const joinedTeamIds = pluck(joinedTeamsLocal, "id");
      _joinedProjects = joinedProjectsLocal.query({
        team: query_exports.or(query_exports.isFalsy(), query_exports.objMatch({
          id: (id) => !joinedTeamIds.includes(id)
        }))
      });
      let _joinedTeams = joinedTeamsLocal.map((team) => {
        return {
          team,
          projects: joinedProjectsLocal.query({
            team: query_exports.objMatch({
              id: team.id
            })
          })
        };
      });
      setJoinedProjects(_joinedProjects);
      setJoinedTeams(_joinedTeams);
      setJoinedProjectsCount(parseInt(_joinedProjects.length) + _joinedTeams.reduce((acc, obj) => acc + obj.projects.length, 0));
    } else {
      _joinedProjects = joinedProjectsLocal?.query() || [];
      setJoinedProjects(_joinedProjects);
      setJoinedTeams(null);
      setJoinedProjectsCount(_joinedProjects.length);
    }
  });
  const validateGetStartedOnboarding = async () => {
    const user = await api_default.user.mark_as_onboarded.post({
      step: "get_started"
    });
    setCurrentUser(user);
  };
  const toggleJoinedProjectsGroupedByTeam = (value2) => {
    saveUserAppParams({
      org_hub_group_by_teams: value2
    });
    setJoinedProjectsGroupedByTeams(value2);
  };
  const onProjectSortChange = (sortBy3) => {
    saveUserAppParams({
      org_hub_sort: sortBy3
    });
    setJoinedProjectsSort(sortBy3);
  };
  const showUpgradeAd = () => isOwner() && org2().billing && org2().billing.plan?.includes("team") && org2().billing.status === "trialing" && isOnline();
  const showGetStartedAd = () => !currentUser2.onboarded.includes("get_started");
  const openOrgSettingsModal = (anchor) => {
    $invoke(["orgSettingsModal", (orgSettingsModal) => {
      orgSettingsModal.open(org2(), anchor);
    }]);
  };
  const htmlDescription = createMemo(() => convertMarkdownToHTML(org2().description));
  return (() => {
    const _el$ = _tmpl$1112.cloneNode(true), _el$5 = _el$.firstChild, _el$6 = _el$5.firstChild, _el$15 = _el$6.firstChild, _el$16 = _el$15.firstChild, _el$17 = _el$16.firstChild, _el$18 = _el$16.nextSibling, _el$19 = _el$18.firstChild, _el$20 = _el$18.nextSibling, _el$21 = _el$20.firstChild;
    insert(_el$, createComponent(Show, {
      get when() {
        return createMemo(() => !!featuredItems().length)() && !featuredItemEditing();
      },
      get children() {
        const _el$2 = _tmpl$140.cloneNode(true);
        insert(_el$2, createComponent(For, {
          get each() {
            return featuredItems();
          },
          children: (item) => createComponent(A3, {
            get href() {
              return item.url;
            },
            get title() {
              return item.name;
            },
            get target() {
              return item.type === "url" || item.type === "file" ? "_blank" : void 0;
            },
            get children() {
              return [createComponent(Show, {
                get when() {
                  return item.type !== "url";
                },
                get children() {
                  const _el$46 = _tmpl$1210.cloneNode(true), _el$47 = _el$46.firstChild;
                  insert(_el$46, createComponent(Show, {
                    get when() {
                      return item.icon;
                    },
                    get children() {
                      return createComponent(Icon, {
                        get name() {
                          return item.icon;
                        }
                      });
                    }
                  }), _el$47);
                  insert(_el$46, () => item.name, null);
                  return _el$46;
                }
              }), createComponent(Show, {
                get when() {
                  return item.type === "url";
                },
                get children() {
                  const _el$48 = _tmpl$1310.cloneNode(true), _el$49 = _el$48.firstChild, _el$50 = _el$49.nextSibling;
                  insert(_el$48, () => item.title, null);
                  createRenderEffect(() => setAttribute(_el$49, "src", item.favicon));
                  return _el$48;
                }
              })];
            }
          })
        }));
        return _el$2;
      }
    }), _el$5);
    insert(_el$, createComponent(Show, {
      get when() {
        return featuredItemEditing();
      },
      get children() {
        const _el$3 = _tmpl$140.cloneNode(true);
        insert(_el$3, createComponent(For, {
          get each() {
            return featuredItems();
          },
          children: (item) => (() => {
            const _el$51 = _tmpl$144.cloneNode(true), _el$57 = _el$51.firstChild;
            insert(_el$51, createComponent(Show, {
              get when() {
                return item.type !== "url";
              },
              get children() {
                const _el$52 = _tmpl$1210.cloneNode(true), _el$53 = _el$52.firstChild;
                insert(_el$52, createComponent(Show, {
                  get when() {
                    return item.icon;
                  },
                  get children() {
                    return createComponent(Icon, {
                      get name() {
                        return item.icon;
                      }
                    });
                  }
                }), _el$53);
                insert(_el$52, () => item.name, null);
                return _el$52;
              }
            }), _el$57);
            insert(_el$51, createComponent(Show, {
              get when() {
                return item.type === "url";
              },
              get children() {
                const _el$54 = _tmpl$1310.cloneNode(true), _el$55 = _el$54.firstChild, _el$56 = _el$55.nextSibling;
                insert(_el$54, () => item.title, null);
                createRenderEffect(() => setAttribute(_el$55, "src", item.favicon));
                return _el$54;
              }
            }), _el$57);
            _el$57.$$click = () => deleteFeaturedOrgItem(org2(), item);
            insert(_el$57, createComponent(Icon, {
              name: "fa-trash"
            }));
            return _el$51;
          })()
        }), null);
        insert(_el$3, createComponent(NgComponent, {
          directive: "hub-add-featured-item-button",
          get org() {
            return org2();
          },
          get featuredItems() {
            return featuredItems();
          }
        }), null);
        insert(_el$3, createComponent(Tooltip, {
          get label() {
            return _4("Finish editing featured items");
          },
          get children() {
            const _el$4 = _tmpl$266.cloneNode(true);
            _el$4.$$click = () => toggleFeaturedItemEditing();
            insert(_el$4, createComponent(Icon, {
              name: "fa-check"
            }));
            return _el$4;
          }
        }), null);
        return _el$3;
      }
    }), _el$5);
    insert(_el$6, createComponent(Show, {
      get when() {
        return teams().length;
      },
      get children() {
        const _el$7 = _tmpl$347.cloneNode(true), _el$8 = _el$7.firstChild, _el$9 = _el$8.nextSibling;
        insert(_el$8, () => _4("My teams"));
        insert(_el$9, createComponent(For, {
          get each() {
            return teams();
          },
          children: (team) => createComponent(OrgTeamTile, {
            get org() {
              return org2();
            },
            team
          })
        }));
        return _el$7;
      }
    }), _el$15);
    insert(_el$6, createComponent(OrgProjectsFiltersContextProvider, {
      get children() {
        return [createComponent(Show, {
          get when() {
            return createMemo(() => !!favoriteProjects())() && favoriteProjects().length;
          },
          get children() {
            const _el$10 = _tmpl$432.cloneNode(true), _el$11 = _el$10.firstChild;
            insert(_el$11, createComponent(Icon, {
              name: "bi-star-fill"
            }), null);
            insert(_el$11, () => _4("Favorite workspaces"), null);
            insert(_el$10, createComponent(OrgProjectList, {
              get projects() {
                return favoriteProjects();
              },
              get org() {
                return org2();
              },
              showTileTeam: true,
              showSort: false,
              showCreate: false
            }), null);
            return _el$10;
          }
        }), (() => {
          const _el$12 = _tmpl$622.cloneNode(true), _el$13 = _el$12.firstChild;
          insert(_el$13, (() => {
            const _c$ = createMemo(() => !!(joinedProjectsCount() === 0 && favoriteProjects().length === 0));
            return () => _c$() ? _4("You haven't joined any workspace yet") : (() => {
              const _c$2 = createMemo(() => !!teams().length);
              return () => _c$2() ? _4("My workspaces across all teams") : _4("My workspaces");
            })();
          })(), null);
          insert(_el$13, createComponent(Show, {
            get when() {
              return joinedProjectsCount();
            },
            get children() {
              const _el$14 = _tmpl$527.cloneNode(true);
              insert(_el$14, joinedProjectsCount);
              return _el$14;
            }
          }), null);
          insert(_el$12, createComponent(OrgProjectList, {
            get projects() {
              return joinedProjects();
            },
            get org() {
              return org2();
            },
            showTileTeam: true,
            highlightCreate: true,
            get exploreProjectsLink() {
              return createMemo(() => !!org2().nb_projects)() ? routeHref("org.projects", {
                slug: org2().slug
              }) : null;
            },
            get sortBy() {
              return joinedProjectsSort();
            },
            onSortChange: onProjectSortChange,
            get showPlaceholder() {
              return favoriteProjects().length === 0;
            },
            get emptyMessage() {
              return createMemo(() => favoriteProjects().length > 0)() ? _4("You have favorited everything!") : null;
            },
            get children() {
              return createComponent(Show, {
                get when() {
                  return hasJoinedTeams();
                },
                get children() {
                  return createComponent(CheckInput, {
                    containerClass: "form-switch me-2 mb-2",
                    get checked() {
                      return joinedProjectsGroupedByTeams();
                    },
                    onChange: (e3) => toggleJoinedProjectsGroupedByTeam(e3.target.checked),
                    id: "projectListGroupedByTeam",
                    get label() {
                      return _4("Group by team");
                    }
                  });
                }
              });
            }
          }), null);
          insert(_el$12, createComponent(Show, {
            get when() {
              return createMemo(() => joinedTeams() !== null)() && joinedTeams().length;
            },
            get children() {
              return createComponent(For, {
                get each() {
                  return joinedTeams();
                },
                children: (team) => (() => {
                  const _el$58 = _tmpl$154.cloneNode(true), _el$59 = _el$58.firstChild;
                  insert(_el$59, createComponent(Icon, {
                    get name() {
                      return team.team.icon || "bi-circle-fill";
                    },
                    get style() {
                      return {
                        color: team.team.color || "#aaa"
                      };
                    }
                  }), null);
                  insert(_el$59, () => team.team.name, null);
                  insert(_el$58, createComponent(OrgProjectList, {
                    get projects() {
                      return team.projects;
                    },
                    get org() {
                      return org2();
                    },
                    get team() {
                      return team.team;
                    },
                    showCreate: false,
                    showSort: false,
                    get sortBy() {
                      return joinedProjectsSort();
                    }
                  }), null);
                  return _el$58;
                })()
              });
            }
          }), null);
          return _el$12;
        })()];
      }
    }), _el$15);
    insert(_el$16, createComponent(Icon, {
      name: "fa-life-ring"
    }), _el$17);
    insert(_el$16, () => _4("Help center"), null);
    insert(_el$18, createComponent(Icon, {
      name: "bi-rss-fill"
    }), _el$19);
    insert(_el$18, () => _4("Product blog"), null);
    insert(_el$20, createComponent(Icon, {
      name: "bi-stars"
    }), _el$21);
    insert(_el$20, () => _4("Leave us a review"), null);
    insert(_el$5, createComponent(Show, {
      get when() {
        return org2().description || showGetStartedAd() || showUpgradeAd() || updates().length;
      },
      get children() {
        const _el$22 = _tmpl$1012.cloneNode(true);
        insert(_el$22, createComponent(Show, {
          get when() {
            return org2().description;
          },
          get children() {
            const _el$23 = _tmpl$720.cloneNode(true);
            createRenderEffect(() => _el$23.innerHTML = htmlDescription());
            return _el$23;
          }
        }), null);
        insert(_el$22, createComponent(Show, {
          get when() {
            return showGetStartedAd();
          },
          get children() {
            const _el$24 = _tmpl$817.cloneNode(true), _el$25 = _el$24.firstChild, _el$26 = _el$25.firstChild, _el$27 = _el$25.nextSibling, _el$28 = _el$27.nextSibling;
            insert(_el$25, createComponent(Icon, {
              name: "bi-mortarboard-fill"
            }), _el$26);
            insert(_el$25, () => _4("Learn how to master Kantree"), null);
            insert(_el$27, () => _4("Check out our guide and video tutorials to learn how to use Kantree to boost your collaboration"));
            _el$28.$$click = validateGetStartedOnboarding;
            insert(_el$28, () => _4("Go to our guides"));
            insert(_el$24, createComponent(Button, {
              "class": "btn-link",
              onClick: validateGetStartedOnboarding,
              get children() {
                return _4("Dismiss");
              }
            }), null);
            createRenderEffect(() => setAttribute(_el$28, "href", getHelpSiteUrl()));
            return _el$24;
          }
        }), null);
        insert(_el$22, createComponent(Show, {
          get when() {
            return showUpgradeAd();
          },
          get children() {
            const _el$29 = _tmpl$915.cloneNode(true), _el$30 = _el$29.firstChild, _el$31 = _el$30.firstChild, _el$32 = _el$30.nextSibling, _el$33 = _el$32.nextSibling, _el$34 = _el$33.firstChild, _el$35 = _el$34.firstChild, _el$36 = _el$34.nextSibling, _el$37 = _el$36.firstChild, _el$38 = _el$36.nextSibling, _el$39 = _el$38.firstChild, _el$40 = _el$38.nextSibling, _el$41 = _el$40.firstChild, _el$42 = _el$40.nextSibling, _el$43 = _el$42.firstChild;
            insert(_el$30, createComponent(Icon, {
              name: "fa-trophy"
            }), _el$31);
            insert(_el$30, () => _4("Take advantage of your trial period to test Kantree Business"), null);
            insert(_el$32, () => _4("Upgrade your trial to get the most out of Kantree:"));
            insert(_el$34, createComponent(Icon, {
              name: "fa-check"
            }), _el$35);
            insert(_el$34, () => _4("All Team plan benefits"), null);
            insert(_el$36, createComponent(Icon, {
              name: "fa-check"
            }), _el$37);
            insert(_el$36, () => _4("Unlimited teams"), null);
            insert(_el$38, createComponent(Icon, {
              name: "fa-check"
            }), _el$39);
            insert(_el$38, () => _4("Cross-team collaboration"), null);
            insert(_el$40, createComponent(Icon, {
              name: "fa-check"
            }), _el$41);
            insert(_el$40, () => _4("Customized company page"), null);
            insert(_el$42, createComponent(Icon, {
              name: "fa-check"
            }), _el$43);
            insert(_el$42, () => _4("SSO"), null);
            insert(_el$29, createComponent(Button, {
              style: "cta",
              onClick: () => openOrgSettingsModal("billing"),
              get children() {
                return _4("Try Kantree Business");
              }
            }), null);
            return _el$29;
          }
        }), null);
        insert(_el$22, createComponent(Show, {
          get when() {
            return updates().length;
          },
          get children() {
            const _el$44 = _tmpl$432.cloneNode(true), _el$45 = _el$44.firstChild;
            insert(_el$45, () => _4("Latest updates"));
            insert(_el$44, createComponent(UpdatesTimeline, {
              get updates() {
                return updates();
              }
            }), null);
            insert(_el$44, createComponent(A3, {
              route: "org.updates",
              get routeParams() {
                return {
                  slug: org2().slug
                };
              },
              "class": "hub-link mt-4 d-block text-end",
              get children() {
                return _4("View more");
              }
            }), null);
            return _el$44;
          }
        }), null);
        return _el$22;
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = getHelpSiteUrl("help"), _v$2 = getLocalizedUrl("blog");
      _v$ !== _p$._v$ && setAttribute(_el$16, "href", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && setAttribute(_el$18, "href", _p$._v$2 = _v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$;
  })();
}
delegateEvents(["click"]);

// public/app/routes/org/components/Members/MemberTile.jsx
var _tmpl$141 = /* @__PURE__ */ template(`<div class="username">@</div>`, 2);
var _tmpl$267 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$348 = /* @__PURE__ */ template(`<div class="role"></div>`, 2);
var _tmpl$433 = /* @__PURE__ */ template(`<div class="teams"></div>`, 2);
var _tmpl$528 = /* @__PURE__ */ template(`<div class="organization-member-tile"><div class="identity"><div><div class="name"></div></div></div><div class="meta"></div></div>`, 10);
var _tmpl$623 = /* @__PURE__ */ template(`<div></div>`, 2);
function OrgMemberTile(props2) {
  const teams = createMemo(() => (props2.member.teams || []).map((team) => teamStore.tryGet(team.id)).filter(Boolean));
  const roleName = createMemo(() => {
    const role = props2.roles.find((role2) => role2.id === props2.member.permission);
    return role?.name.toString() || _4("None");
  });
  const removeMember = async () => {
    await confirmDeleteDialog2();
    props2.onRemove(props2.member);
  };
  const roleMenu = {
    config: [{
      subheader: _4("Organization role")
    }].concat(props2.roles.map((role) => ({
      label: role.name,
      small: role.description,
      action: () => props2.onRoleChange(props2.member, role)
    })))
  };
  return (() => {
    const _el$ = _tmpl$528.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$7 = _el$2.nextSibling;
    insert(_el$2, createComponent(UserAvatar, {
      get user() {
        return props2.member.user;
      }
    }), _el$3);
    insert(_el$4, () => props2.member.user.display_name);
    insert(_el$3, createComponent(Show, {
      get when() {
        return props2.member.user.username != props2.member.user.display_name;
      },
      get children() {
        const _el$5 = _tmpl$141.cloneNode(true), _el$6 = _el$5.firstChild;
        insert(_el$5, () => props2.member.user.username, null);
        return _el$5;
      }
    }), null);
    insert(_el$7, createComponent(Show, {
      get when() {
        return props2.roles && props2.roles.length;
      },
      get children() {
        const _el$8 = _tmpl$348.cloneNode(true);
        insert(_el$8, createComponent(Show, {
          get when() {
            return props2.editable;
          },
          get children() {
            return createComponent(NgComponent, {
              directive: "member-tile-change-role-button",
              menu: roleMenu,
              get name() {
                return roleName();
              }
            });
          }
        }), null);
        insert(_el$8, createComponent(Show, {
          get when() {
            return !props2.editable;
          },
          get children() {
            const _el$9 = _tmpl$267.cloneNode(true);
            insert(_el$9, roleName);
            return _el$9;
          }
        }), null);
        return _el$8;
      }
    }), null);
    insert(_el$7, createComponent(Show, {
      get when() {
        return teams().length > 0;
      },
      get children() {
        const _el$10 = _tmpl$433.cloneNode(true);
        insert(_el$10, createComponent(For, {
          get each() {
            return teams();
          },
          children: (team) => createComponent(Tooltip, {
            get label() {
              return team.name;
            },
            get children() {
              return createComponent(ColorizeElement, {
                get bgColor() {
                  return team.color;
                },
                get children() {
                  const _el$11 = _tmpl$623.cloneNode(true);
                  insert(_el$11, createComponent(Show, {
                    get when() {
                      return team.icon;
                    },
                    get children() {
                      return createComponent(Icon, {
                        get name() {
                          return team.icon;
                        }
                      });
                    }
                  }));
                  return _el$11;
                }
              });
            }
          })
        }));
        return _el$10;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return props2.editable;
      },
      get children() {
        return createComponent(Tooltip, {
          get label() {
            return _4("Remove this member");
          },
          get children() {
            return createComponent(IconButton, {
              onClick: () => removeMember(),
              icon: "fa-trash"
            });
          }
        });
      }
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Members/Members.jsx
var _tmpl$145 = /* @__PURE__ */ template(`<div class="org-view-page"><div class="org-view-page-controls"><span></span></div></div>`, 6);
function orgMembersRouteData() {
  const org2 = useRouteData();
  const [data2] = createResource(() => org2(), async (org3) => {
    await loadAllOrgMembers(org3.id);
    return org3;
  });
  return data2;
}
function OrgMembersTab(props2) {
  const org2 = useRouteData();
  const [filterForm, setFilterForm] = createSignal("");
  const roles = availableOrgRoles;
  const isAdmin = () => isOrgAdmin(org2());
  const memberStore = orgMemberStore.scopedByOrg(org2);
  const members = memberStore.react({}, {
    sortBy: "user.display_name"
  });
  const removeMember = async (member) => {
    try {
      await api_default.org_members.remove_member.delete({
        org_id: org2().id,
        member_id: member.id
      }, {
        ignoreErrorHandlers: true
      });
      memberStore.remove(member);
      orgStore.update(org2(), {
        nb_members: org2().nb_members - 1
      });
      if (member.user.id === currentUser2.id) {
        window.location = "/";
      }
    } catch (err) {
      autoCatchAsRequestErrorDialog([400, 403]);
    }
  };
  const updateMemberPerm = async (member, role) => {
    try {
      const m3 = await api_default.org_members.update_member_permission.put({
        org_id: org2().id,
        member_id: member.id,
        perm: role.id
      }, {
        ignoreErrorHandlers: true
      });
      if (m3.user) {
        memberStore.update(m3);
      } else {
      }
    } catch (err) {
      autoCatchAsRequestErrorDialog([400, 403]);
    }
  };
  const leaveOrg = async () => {
    const req = await confirmDeleteDialog2(null, _4("Are you sure you want to leave this organization ?"), _4("Leave"));
    if (req) {
      const leaving = await leaveOrg(org2());
      if (leaving) {
        window.location = "/";
      }
    }
  };
  const filterMembers = (member) => {
    return !filterForm() || (member.user.email || "").toLowerCase().includes(filterForm().toLowerCase()) || member.user.display_name.toLowerCase().includes(filterForm().toLowerCase());
  };
  const canInvite = () => !org2().locked && org2().isAdmin;
  const invite = () => {
    $invoke(["orgInviteMembersModal", (orgInviteMembersModal) => orgInviteMembersModal.open(org2())]);
  };
  createEffect(() => {
    setOrgPageHeaderActionsMenu([{
      label: _4("Manage workspace roles"),
      action: () => $invoke(["orgSettingsModal", (orgSettingsModal) => orgSettingsModal.open(org2(), "roles")]),
      enabled: () => !isOrgLocked(org2()) && isOrgAdmin(org2())
    }, {
      label: _4("Leave organization"),
      action: () => leaveOrg()
    }]);
  });
  onCleanup(() => setOrgPageHeaderActionsMenu(null));
  return (() => {
    const _el$ = _tmpl$145.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild;
    insert(_el$2, createComponent(Show, {
      get when() {
        return canInvite();
      },
      get children() {
        return createComponent(Button, {
          "class": "btn-ghost me-2",
          onClick: () => invite(),
          get children() {
            return [createComponent(Icon, {
              name: "fa-user-plus"
            }), " ", createMemo(() => _4("Invite new members"))];
          }
        });
      }
    }), _el$3);
    insert(_el$2, createComponent(TextInput, {
      "class": "me-2",
      type: "text",
      get placeholder() {
        return _4("Filter members");
      },
      get value() {
        return filterForm();
      },
      onInput: (e3) => setFilterForm(e3.target.value)
    }), _el$3);
    insert(_el$3, () => _4("{count} members", {
      count: members().length
    }));
    insert(_el$, createComponent(For, {
      get each() {
        return members().filter(filterMembers);
      },
      children: (member) => createComponent(OrgMemberTile, {
        get org() {
          return org2();
        },
        member,
        get editable() {
          return isAdmin();
        },
        onRemove: removeMember,
        roles,
        onRoleChange: updateMemberPerm
      })
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Team/TeamHub.jsx
var _tmpl$146 = /* @__PURE__ */ template(`<div class="hub-sidebar"><div class="hub-section page-description"> </div></div>`, 4);
var _tmpl$268 = /* @__PURE__ */ template(`<div class="org-view-page"><div class="hub-container"><div class="hub-main"><div class="hub-section"><div class="hub-title"></div></div></div></div></div>`, 10);
function OrgTeam(props2) {
  const routeData = useRouteData();
  const [org2, team] = routeData();
  createEffect(() => {
    setOrgPageHeaderTeam(team);
  });
  onCleanup(() => setOrgPageHeaderTeam(null));
  return props2.children;
}
function OrgTeamHub() {
  const routeData = useRouteData();
  const [org2, team] = routeData();
  const isAdmin = () => !isOrgLocked(org2) && (isOrgAdmin(org2) || isTeamAdmin(team));
  const projects = () => projectStore.scopedByTeam(team, org2);
  ensureConnectivity(() => {
    loadAllProjectsForTeam(team);
  });
  return (() => {
    const _el$ = _tmpl$268.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.firstChild;
    insert(_el$5, () => _4("Workspaces"));
    insert(_el$4, createComponent(OrgProjectsFiltersContextProvider, {
      get children() {
        return createComponent(OrgProjectList, {
          get store() {
            return projects();
          },
          org: org2,
          team,
          get showArchivesCheckbox() {
            return isAdmin();
          },
          highlightCreate: true
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return team.description;
      },
      get children() {
        const _el$6 = _tmpl$146.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.firstChild;
        createRenderEffect(() => _el$8.data = team.description);
        return _el$6;
      }
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Team/TeamMembers.jsx
var _tmpl$147 = /* @__PURE__ */ template(`<div class="org-view-page"><div class="hub-section"><div class="hub-title"></div></div></div>`, 6);
function teamMembersRouteData() {
  const parent = useRouteData();
  const [data2] = createResource(() => parent(), async ([org2, team]) => {
    await loadAllOrgMembers(org2.id);
    return team;
  });
  return data2;
}
function OrgTeamMembers() {
  const team = useRouteData();
  const navigate2 = useNavigate2();
  const isAdmin = () => isTeamAdmin(team());
  const roles = () => availableTeamRoles;
  const results2 = orgMemberStore.scopedByTeam(team()).react({}, {
    sortBy: "user.display_name"
  });
  const members = createMemo(() => {
    const localMembers = results2().map((m3) => {
      const member = unwrap(m3);
      return {
        ...member,
        permission: member.teams.find((t3) => t3.id === team().id).perm
      };
    });
    return localMembers;
  });
  const updateMemberPerm = (member, perm) => {
    updateTeamMemberPerm(team(), member, perm);
  };
  const removeMember = (member) => {
    removeTeamMember(team(), member);
  };
  const leaveTeam = async () => {
    await confirmDeleteDialog2(null, _4("Are you sure you want to leave this team ?"), _4("Leave"));
    await leaveTeam(team());
    navigate2("/");
  };
  createEffect(() => {
    setOrgPageHeaderActionsMenu([{
      label: _4("Leave team"),
      action: () => leaveTeam()
    }]);
    setOrgPageHeaderSectionTitle(_4("Members"));
  });
  onCleanup(() => {
    setOrgPageHeaderSectionTitle(null);
    setOrgPageHeaderActionsMenu(null);
  });
  return (() => {
    const _el$ = _tmpl$147.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild;
    insert(_el$3, () => _4("Members in {org}", {
      org: team().name
    }));
    insert(_el$2, createComponent(MemberList, {
      get members() {
        return members();
      },
      filterable: true,
      get editable() {
        return isAdmin();
      },
      showRemove: true,
      onRemove: removeMember,
      defaultViewMode: "tiles",
      get roles() {
        return roles();
      },
      onRoleChange: updateMemberPerm
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Team/TeamPortfolios.jsx
var _tmpl$148 = /* @__PURE__ */ template(`<div class="hub-section"></div>`, 2);
var _tmpl$269 = /* @__PURE__ */ template(`<div class="org-view-page"></div>`, 2);
function teamPortfoliosRouteData() {
  const parent = useRouteData();
  const [data2] = createResource(() => parent(), async ([org2, team]) => {
    await loadPortfoliosForOrg(org2);
    return [org2, team];
  });
  return data2;
}
function OrgTeamPortfolios() {
  const routeData = useRouteData();
  const [org2, team] = routeData();
  const isAdmin = () => isTeamAdmin(team);
  createEffect(() => {
    setOrgPageHeaderSectionTitle(_4("Portfolios"));
  });
  onCleanup(() => {
    setOrgPageHeaderSectionTitle(null);
  });
  const projects = projectStore.scopedByTeam(team, org2, {
    withPortfolios: true
  }).scoped({
    is_portfolio: true
  });
  const onCreateClick = () => {
    $invoke(["projectCreatorModal", (projectCreatorModal) => {
      projectCreatorModal.open({
        org: org2,
        team,
        createPortfolio: true
      }).then((portfolio) => navigateTo("portfolio", {
        slug: portfolio.slug
      }));
    }]);
  };
  return (() => {
    const _el$ = _tmpl$269.cloneNode(true);
    insert(_el$, createComponent(OrgProjectsFiltersContextProvider, {
      get children() {
        const _el$2 = _tmpl$148.cloneNode(true);
        insert(_el$2, createComponent(OrgProjectList, {
          store: projects,
          org: org2,
          team,
          filterable: true,
          get showArchivesCheckbox() {
            return isAdmin();
          },
          get emptyMessage() {
            return _4("No portfolios found");
          },
          get createBtnLabel() {
            return createMemo(() => !!org2.can_create_private_projects)() ? _4("New portfolio") : _4("New public portfolio");
          },
          onCreateClick
        }));
        return _el$2;
      }
    }));
    return _el$;
  })();
}

// public/app/routes/org/components/Teams.jsx
var _tmpl$149 = /* @__PURE__ */ template(`<div class="org-view-empty-tab"><div></div><p></p><p></p></div>`, 8);
var _tmpl$270 = /* @__PURE__ */ template(`<div class="org-view-page" id="org-teams"><div class="org-view-page-controls"></div><div class="team-tile-list"></div></div>`, 6);
function teamsRouteData() {
  const org2 = useRouteData();
  const [data2] = createResource(() => org2(), async (org3) => {
    await loadAllTeams(org3);
    return org3;
  });
  return data2;
}
function TeamsTab() {
  const navigate2 = useNavigate2();
  const org2 = useRouteData();
  const locked = () => isOrgLocked(org2());
  const isAdmin = () => isOrgAdmin(org2());
  const [filterTeam, setFilterTeam] = createSignal("");
  const teams = teamStore.scopedByOrg(org2).react({}, {
    sortBy: "name"
  });
  const filteredTeams = createMemo(() => teams().filter((e3) => e3.name.toLowerCase().includes(filterTeam().toLowerCase())));
  const createTeam2 = () => {
    fenceBehindFeatureFlag(org2(), "teams", () => {
      $invoke(["createTeamModal", (createTeamModal) => {
        createTeamModal.open(org2()).then((team) => navigate2("org.team.hub", {
          slug: org2().slug,
          teamSlug: team.slug
        }));
      }]);
    });
  };
  return (() => {
    const _el$ = _tmpl$270.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.nextSibling;
    insert(_el$2, createComponent(Show, {
      get when() {
        return createMemo(() => !!(isAdmin() && !locked() && isConnected()))() && hasFeatureFlag(org2(), "teams");
      },
      get children() {
        return createComponent(Button, {
          "class": "btn-ghost me-2",
          onClick: () => createTeam2(),
          get children() {
            return [createComponent(Icon, {
              name: "bi-plus"
            }), " ", createMemo(() => _4("Create new team"))];
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(TextInput, {
      type: "text",
      get placeholder() {
        return _4("Filter teams");
      },
      get value() {
        return filterTeam();
      },
      onInput: (e3) => setFilterTeam(e3.target.value)
    }), null);
    insert(_el$3, createComponent(For, {
      get each() {
        return filteredTeams();
      },
      children: (team) => createComponent(OrgTeamTile, {
        get org() {
          return org2();
        },
        team
      })
    }));
    insert(_el$, createComponent(Show, {
      get when() {
        return createMemo(() => !!!teams().length)() && !filterTeam();
      },
      get children() {
        const _el$4 = _tmpl$149.cloneNode(true), _el$5 = _el$4.firstChild, _el$6 = _el$5.nextSibling, _el$7 = _el$6.nextSibling;
        insert(_el$5, () => _4("You don't have any teams yet"));
        insert(_el$6, () => _4("Teams can have their own list of members and workspaces"));
        insert(_el$7, createComponent(Button, {
          "class": "btn-ghost me-2",
          onClick: () => createTeam2(),
          get children() {
            return [createComponent(Icon, {
              name: "bi-plus"
            }), " ", createMemo(() => _4("Create your first team"))];
          }
        }));
        return _el$4;
      }
    }), null);
    return _el$;
  })();
}

// public/app/routes/org/components/Portfolios.jsx
var _tmpl$150 = /* @__PURE__ */ template(`<div class="hub-section"></div>`, 2);
var _tmpl$271 = /* @__PURE__ */ template(`<div class="org-view-page"></div>`, 2);
function portfoliosRouteData() {
  const org2 = useRouteData();
  const [data2] = createResource(() => org2(), async (org3) => {
    await loadPortfoliosForOrg(org3);
    return org3;
  });
  return data2;
}
function PortfoliosTab() {
  const navigateTo2 = useNavigate2();
  const org2 = useRouteData();
  const isAdmin = () => isOrgAdmin(org2());
  const projects = projectStore.scopedByTeam(false, org2(), {
    withPortfolios: true
  }).scoped({
    is_portfolio: true
  });
  const onCreateClick = () => {
    $invoke(["projectCreatorModal", (projectCreatorModal) => {
      projectCreatorModal.open({
        org: org2(),
        createPortfolio: true
      }).then((portfolio) => navigateTo2("portfolio", {
        slug: portfolio.slug
      }));
    }]);
  };
  return (() => {
    const _el$ = _tmpl$271.cloneNode(true);
    insert(_el$, createComponent(OrgProjectsFiltersContextProvider, {
      get children() {
        const _el$2 = _tmpl$150.cloneNode(true);
        insert(_el$2, createComponent(OrgProjectList, {
          store: projects,
          get org() {
            return org2();
          },
          filterable: true,
          get showArchivesCheckbox() {
            return isAdmin();
          },
          get emptyMessage() {
            return _4("No portfolios found");
          },
          get createBtnLabel() {
            return createMemo(() => !!org2().can_create_private_projects)() ? _4("New portfolio") : _4("New public portfolio");
          },
          onCreateClick
        }));
        return _el$2;
      }
    }));
    return _el$;
  })();
}

// public/app/routes/org/index.jsx
function orgRouteData() {
  const params = useParams();
  const [org2, {
    refetch
  }] = createResource(() => params.slug, (slug) => {
    if (isConnected()) {
      return loadOrgBySlug(slug, {
        ignoreErrorHandlers: true
      });
    }
    return orgStore.query({
      slug
    })?.[0];
  });
  onEvent(onConnectivityRecovered, refetch);
  return org2;
}
function teamRouteData() {
  const params = useParams();
  const org2 = useRouteData();
  const [team, {
    refetch
  }] = createResource(() => org2() ? params.teamSlug : null, (slug) => {
    if (isConnected()) {
      return loadTeam(org2().id, slug, {
        ignoreErrorHandlers: true
      }).then((team2) => [org2(), team2]);
    }
    return [org2(), teamStore.query({
      slug
    })?.[0]];
  });
  onEvent(onConnectivityRecovered, refetch);
  return team;
}
function orgRouteLoaderError(e3) {
  const navigate2 = useNavigate2();
  if (!isConnected() || isAuthenticated()) {
    errorDialog(_4("This team does not exist or is not available offline!"));
    navigate2("myWork.inbox");
  } else {
    authSession.login();
  }
}
addRoute({
  name: "org",
  path: "/o/:slug",
  colorized: true,
  component: (props2) => createComponent(AuthenticatedPage, {
    get children() {
      return createComponent(ColorizedPage, {
        get children() {
          return createComponent(RouteData, {
            loader: orgRouteData,
            onError: orgRouteLoaderError,
            get children() {
              return createComponent(OrganizationPage, {
                get children() {
                  return props2.children;
                }
              });
            }
          });
        }
      });
    }
  }),
  children: [{
    name: "hub",
    path: "/",
    colorized: true,
    component: OrgHub
  }, {
    name: "updates",
    path: "/updates",
    colorized: true,
    component: () => createComponent(RouteData, {
      loader: updatesRouteData,
      get children() {
        return createComponent(UpdatesTab, {});
      }
    })
  }, {
    name: "projects",
    path: "/projects",
    colorized: true,
    component: () => createComponent(RouteData, {
      loader: projectsRouteData,
      get children() {
        return createComponent(OrgProjects, {});
      }
    })
  }, {
    name: "forms",
    path: "/forms",
    colorized: true,
    component: () => createComponent(RouteData, {
      loader: formsRouteData,
      get children() {
        return createComponent(FormsTab, {});
      }
    })
  }, {
    name: "portfolios",
    path: "/portfolios",
    colorized: true,
    component: () => createComponent(RouteData, {
      loader: portfoliosRouteData,
      get children() {
        return createComponent(PortfoliosTab, {});
      }
    })
  }, {
    name: "teams",
    path: "/teams",
    colorized: true,
    component: () => createComponent(RouteData, {
      loader: teamsRouteData,
      get children() {
        return createComponent(TeamsTab, {});
      }
    })
  }, {
    name: "members",
    path: "/members",
    colorized: true,
    component: () => createComponent(RouteData, {
      loader: orgMembersRouteData,
      get children() {
        return createComponent(OrgMembersTab, {});
      }
    })
  }, {
    name: "team",
    path: "/:teamSlug",
    colorized: true,
    component: (props2) => createComponent(RouteData, {
      loader: teamRouteData,
      onError: orgRouteLoaderError,
      get children() {
        return createComponent(OrgTeam, {
          get children() {
            return props2.children;
          }
        });
      }
    }),
    children: [{
      name: "hub",
      path: "",
      colorized: true,
      component: OrgTeamHub
    }, {
      name: "portfolios",
      path: "/portfolios",
      colorized: true,
      component: () => createComponent(RouteData, {
        loader: teamPortfoliosRouteData,
        onError: orgRouteLoaderError,
        get children() {
          return createComponent(OrgTeamPortfolios, {});
        }
      })
    }, {
      name: "members",
      path: "/members",
      colorized: true,
      component: () => createComponent(RouteData, {
        loader: teamMembersRouteData,
        onError: orgRouteLoaderError,
        get children() {
          return createComponent(OrgTeamMembers, {});
        }
      })
    }]
  }]
});

// public/app/routes/portfolio/ng-components/nav.js
angular_default.module("kantree").component("portfolioNav", {
  templateUrl: "/static/app/routes/portfolio/ng-components/templates/nav.html",
  bindings: {
    context: "<",
    view: "<",
    withSettings: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$interval", "cardModal", "$state", "projectPage", "mobileMenuFactory"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isAuthenticated = isAuthenticated;
      this.canAddCard = canAddCard(this.$projectPage.project);
      this.isScreensizeXS = isScreensizeXS;
      this.refresh();
      this.refreshMobileMenuDebounced = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshMobileMenu();
        });
      });
      this.refreshMobileMenu();
      ["app", "appOptions", "cardStore", "groupByChoices"].map((prop2) => {
        return this.context.$watch(this.$scope, prop2, () => {
          this.refreshMobileMenuDebounced();
        }, false);
      });
    }
    $onChanges(changes) {
      if (changes.view && this.view) {
        this.viewMode = portfolioAppRegistry.get(this.view.mode);
        this.showSaveBtn = viewStore.isDraftView(this.view);
      }
    }
    _onClickTitle() {
      if (this.onClickTitle) {
        this.onClickTitle();
      } else {
        jquery_default(this.$element.find(".js-settings")).trigger("click");
      }
    }
    refresh() {
      if (this.deregisterBoardWatcher) this.deregisterBoardWatcher();
      this.deregisterBoardWatcher = cardStore.$watch(this.$scope, this.$projectPage.board.id, (board) => {
        this.path = board.path.slice(1);
        this.pathMenuSpec = {
          config: () => this.path.map((parent) => {
            return {
              label: parent.title,
              action: () => this.$state.go("project_board", { projectId: this.$projectPage.project.slug, cardRef: parent.ref })
            };
          })
        };
      });
      this.notApprovedDomainMembers = [];
      const notApprovedDomainMembersStore = projectMemberStore.scopedByProject(this.$projectPage.project).scoped({
        user: query_exports.objMatch({ is_from_approved_domain: false })
      });
      notApprovedDomainMembersStore.$watchAll(this.$scope, () => {
        this.notApprovedDomainMembers = notApprovedDomainMembersStore.query();
      });
      this.projectNotificationStore = store.scoped({ project_id: this.$projectPage.project.id });
    }
    refreshMobileMenu() {
      this.mobileMenu = this.$mobileMenuFactory.get(this.context);
    }
    $postLink() {
      if (typeof ResizeObserver === "undefined") return;
      const resizeObserver = new ResizeObserver((entries2) => {
        for (let entry of entries2) {
          if (entry.target === innerEl) {
            innerWidth = entry.contentRect.width;
            if (!this.shrinked) {
              lastUnshrinkedInnerWidth = innerWidth;
            }
          }
          if (entry.target === outerEl) {
            outerWidth = entry.contentRect.width;
          }
          if (outerWidth && innerWidth) {
            if (lastUnshrinkedInnerWidth) {
              const shrinked = lastUnshrinkedInnerWidth + 150 > outerWidth;
              if (shrinked != this.shrinked) {
                this.$scope.$applyAsync(() => {
                  this.shrinked = shrinked;
                });
              }
            }
            jquery_default(this.$element).find(".board-nav-view-component").toggleClass("shrinked", innerWidth > outerWidth);
          }
        }
      });
      let innerEl, outerEl, innerWidth, lastUnshrinkedInnerWidth, outerWidth;
      let initOuterElPromise = this.$interval(() => {
        outerEl = jquery_default(this.$element).find(".board-nav-view-component-outer")[0];
        if (outerEl) {
          resizeObserver.observe(outerEl);
          this.$interval.cancel(initOuterElPromise);
        }
      }, 100, 40, false);
      initOuterElPromise.then(() => {
        console.warn("nav-view resize can't be observed");
      }).catch(() => {
      }).finally(() => {
        initOuterElPromise = null;
      });
      this.$scope.$on("$destroy", () => {
        if (initOuterElPromise) {
          this.$interval.cancel(initOuterElPromise);
          initOuterElPromise = null;
        }
        if (resizeObserver && outerEl) {
          resizeObserver.unobserve(outerEl);
        }
      });
      const initInnerElResizeObserver = () => {
        let initInnerElPromise = this.$interval(() => {
          innerEl = jquery_default(this.$element).find(".board-nav-view-component-inner")[0];
          if (innerEl) {
            resizeObserver.observe(innerEl);
            this.$interval.cancel(initInnerElPromise);
          }
        }, 100, 40, false);
        initInnerElPromise.then(() => {
          console.warn("nav-view resize can't be observed");
        }).catch(() => {
        }).finally(() => {
          initInnerElPromise = null;
        });
        return () => {
          if (initInnerElPromise) {
            this.$interval.cancel(initInnerElPromise);
          }
          if (resizeObserver && innerEl) {
            resizeObserver.unobserve(innerEl);
          }
        };
      };
      this.deregisterAppWatcher = this.context.watch("app", () => {
        if (this.deregisterInnerElResizeObserver) this.deregisterInnerElResizeObserver();
        this.deregisterInnerElResizeObserver = initInnerElResizeObserver();
      });
    }
    $onDestroy() {
      if (this.deregisterBoardWatcher) this.deregisterBoardWatcher();
      if (this.deregisterAppWatcher) this.deregisterAppWatcher();
      if (this.deregisterInnerElResizeObserver) this.deregisterInnerElResizeObserver();
    }
    openCreateCardModal() {
      this.$cardModal.openEmpty(this.$projectPage.board);
    }
    markAllNotifsAsRead() {
      markAllNotificationsAsRead({ project_id: this.$projectPage.project.id });
    }
  }
});

// public/app/loaders/charts.js
var loadCharts = memoize2(() => {
  return api_default.chart_types.list_charts.get({}, { ignoreErrorHandlers: true }).catch(() => []);
});

// public/app/routes/portfolio/ng-components/page.js
angular_default.module("kantree").component("portfolioPage", {
  bindings: {
    projectId: "<",
    viewId: "<"
  },
  templateUrl: "/static/app/routes/portfolio/ng-components/templates/page.html",
  controller: class extends AngularClass {
    static $inject = [
      "$scope",
      "$state",
      "$timeout",
      "$location",
      "$q",
      "projectPage",
      "portfolioNavSidebarFactory",
      "projectTheme",
      "PortfolioScopeManager",
      "cardModal",
      "navSidebar"
    ];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      document.body.classList.toggle("body-board-view", true);
      loadCharts();
      this.embedded = isEmbedded;
      this.isScreensizeXS = isScreensizeXS;
      this.isAuthenticated = isAuthenticated;
      this.$scope.$watch("$ctrl.viewId", (newView, oldView) => {
        if (oldView === newView || this.projectId !== this.project.slug) return;
        this.scopeManager.setActiveView(this.viewId);
      });
      this.$scope.$watch("$ctrl.view", (newView, oldView) => {
        if (oldView === newView) return;
        this.$projectPage.clearSelectedCards();
      });
      this.$scope.$on("$destroy", () => {
        document.body.classList.toggle("body-board-view", false);
        this.clearScopeManager();
      });
      this.$scope.$on("$locationChangeSuccess", () => {
        this.handleLocationHash();
      });
      this.$scope.$watch("$ctrl.projectId", () => this.initScopeManager());
    }
    initScopeManager() {
      if (this.scopeManager) {
        this.clearScopeManager();
      }
      this.$PortfolioScopeManager.init(this, this.$scope, this.projectId).then((scopeManager) => {
        this.scopeManager = scopeManager;
        this.$projectPage.activate(this.$scope, scopeManager);
        this.$projectTheme.activate(this.$scope, this.project);
        updateSubtitle(this.project.title);
        this.sidebar = this.$portfolioNavSidebarFactory.get(this.project, this.board);
        cardStore.$watch(this.$scope, this.board, (board) => updateSubtitle(board.title));
        this.projectPlaceholderVisible = true;
        this.lockedOwner = isOrgLocked(this.project.owner);
        this.isOwnerOfProjectOwner = isCurrentUserOwnerOf(this.project);
        return this.handleLocationHash(true);
      }).then(() => {
        this.projectPlaceholderVisible = false;
        this.scopeManager.setActiveView(this.viewId);
        this.$scope.$on("appUnlocked", () => this.$q.digest(updateView(this.view, { locked: false })));
        this.scopeManager.fetchProjectsForPortfolio();
        this.scopeManager.fetchCards();
        if (isAuthenticated() && !this.project.is_archived) {
          addToRecentlyOpenedBoards(this.board);
        }
        if (isEmbedded()) {
          this.$navSidebar.close($("nav-sidebar-system > nav-sidebar"));
        }
      }).catch((r3) => {
        if (typeof r3 === "string") {
          errorDialog(
            _4("An error occured"),
            _4(`Something went wrong while fetching Portfolio data: ${r3} please reload the page`)
          );
          this.loadingErrorMessage = _4("An error occured");
        } else if (r3.status === 404 || r3.status === 400) {
          this.loadingErrorMessage = _4("Not Found!");
        } else if (r3.status === 403) {
          if (isAuthenticated()) {
            this.loadingErrorMessage = _4("Not Authorized!");
          } else {
            authSession.login();
          }
        } else {
          errorDialog(
            _4("An error occured"),
            _4("Something went wrong while fetching Portfolio data: please reload the page")
          );
          this.loadingErrorMessage = _4("An error occured");
        }
      });
    }
    clearScopeManager() {
      if (this.scopeManager) {
        this.scopeManager.destroy();
      }
      clearSubtitle();
    }
    handleLocationHash(pageLoad) {
      let hash = this.$location.hash();
      if (hash.match(/[0-9]+/)) {
        if (!this.$cardModal.current || hash != this.$cardModal.currentLocationHash) {
          let wasDocked;
          if (pageLoad) {
            wasDocked = this.$cardModal.isDocked();
            this.$cardModal.toggleDocked(false);
          }
          const modalOptions = pageLoad && isEmbedded() ? { showClose: false, cssClass: "card-modal-full-screen" } : {};
          this.$cardModal.currentLocationHash = hash;
          return this.$cardModal.loadByRef(this.project, hash, modalOptions, true).then(() => {
            if (wasDocked) {
              this.$cardModal.toggleDocked(true);
            }
          });
        }
      } else if (!hash && this.$cardModal.current && this.$cardModal.currentLocationHash !== null) {
        return this.$cardModal.close();
      }
      return this.$q.resolve();
    }
    joinPortfolio() {
      this.$q.when(joinProject(this.project), () => {
        fetchAppContextData();
        this.$state.reload();
      });
    }
  }
});

// public/app/routes/portfolio/services/nav-sidebar.js
angular_default.module("kantree").service("portfolioNavSidebarFactory", class extends AngularClass {
  static $inject = ["$state", "projectPage", "projectSidePanel"];
  getFixedContentItems(project, board) {
    const items = [];
    if (isAuthenticated()) {
      items.push(...portfolioAppRegistry.getAll().filter((app) => !!app.noView && !app.hideFromSidebar).map((app) => {
        return {
          type: "button",
          options: {
            label: app.title,
            icon: app.icon,
            action: (event2) => {
              this.$projectPage.gotoApp(app.name);
            }
          },
          active: () => this.$projectPage.context && this.$projectPage.context.app && this.$projectPage.context.app.name === app.name,
          enabled: () => !isScreensizeXS() && isConnected() && !board.parent_id && projectStore.get(project.id).system_apps.includes(app.name)
        };
      }));
    }
    return items;
  }
  getContentItems(project, board) {
    const items = [];
    const categoryStore = viewCategoryStore.scopedByProject(project);
    const boardViewStore = viewStore.scopedByBoard(project, board, true);
    const canEdit = isAuthenticated() && canManageViews(project);
    items.push({
      type: "view-categories",
      options: {
        categoryStore,
        viewStore: boardViewStore.scoped({ is_public: true, filter_scopes: query_exports.isTruthy() }),
        storageKey: `sharedMultiWorkspaceView-${project.id}-$CATID`,
        project,
        board,
        filterScopes: [["portfolio", project.id]],
        showCreateCategory: canEdit,
        showCreateView: canEdit,
        createView: canEdit,
        createPublicView: true,
        showNoCategoryViews: true
      }
    }, {
      type: "view-list",
      options: {
        label: _4("Private views"),
        indicator: "lock",
        store: boardViewStore.scoped({ is_public: false, filter_scopes: query_exports.isTruthy() }),
        storageKey: `privateMultiWorkspaceView-${project.id}`,
        project,
        board,
        filterScopes: [["portfolio", project.id]],
        showCreate: isAuthenticated(),
        create: isAuthenticated(),
        hideWhenEmpty: !isAuthenticated()
      }
    });
    return items;
  }
  getHeaderItems(project, board) {
    return [{
      type: "project-page-header",
      options: {
        project,
        board
      }
    }];
  }
  get(project, board) {
    const header = { header: this.getHeaderItems(project, board) };
    if (project.status) {
      return { ...header };
    }
    return {
      ...header,
      fixedContent: this.getFixedContentItems(project, board),
      content: this.getContentItems(project, board)
    };
  }
});

// public/app/loaders/project-member.js
function loadAllProjectMembers(project, withRole, options2) {
  const format2 = (member) => {
    member.project_id = project.id;
    return member;
  };
  return loadMany(projectMemberStore, api_default.project_members.list_members, { project_id: project.id, with_role: withRole ? 1 : 0 }, options2, { format: format2 }).then((members) => {
    projectMemberStore.scopedByProject(project).removeAllNotMatching(members);
    if (project.fromUserOrg) {
      members.push(projectMemberStore.upsertUserOrgOwner(project));
    }
    return members;
  });
}
async function loadMembersForProjects(projects, batchSize = 3, withRole = false, options2 = {}) {
  if (!projects || projects.length === 0) {
    return [];
  }
  const results2 = [];
  for (let i3 = 0; i3 < projects.length; i3 += batchSize) {
    const batch4 = projects.slice(i3, i3 + batchSize);
    const batchPromises = batch4.map(
      (project) => loadAllProjectMembers(project, withRole, options2).catch((err) => {
        console.error(`Failed to load members for project ${project.id}:`, err);
        return [];
      })
    );
    const batchResults2 = await Promise.all(batchPromises);
    results2.push(...batchResults2);
  }
  return results2;
}

// public/app/routes/portfolio/services/scope-manager.js
angular_default.module("kantree").factory("PortfolioScopeManager", [
  "ProjectScopeManager",
  function(ProjectScopeManager) {
    return class PortfolioScopeManager extends ProjectScopeManager {
      constructor(...args) {
        super(...args);
        this.viewDefaultProps = portfolioViewDefaultProps;
        this.viewAvailableProps = portfolioViewAvailableProps;
        this.portfolioProjectsPushRooms = /* @__PURE__ */ new Map();
        this.portfolioProjectsEventListeners = /* @__PURE__ */ new Map();
      }
      get appRegistry() {
        return portfolioAppRegistry;
      }
      fetchProjectsForPortfolio() {
        const projectsPromise = loadAllProjectsForPortfolio(this.project, false);
        this.$q.digest(projectsPromise.then((projects) => {
          loadMembersForProjects(projects, 3, false).catch((err) => {
            console.error("Failed to load portfolio project members:", err);
          });
          return projects;
        }));
      }
      get cardStore() {
        return cardStore.scoped({
          is_template: query_exports.isFalsy(),
          is_archived: (v3) => this.context.appOptions?.include_archived ? true : !v3,
          parent_id: (id) => !id,
          project_id: (id) => this.project.portfolio_project_ids.includes(id)
        });
      }
      createContext() {
        super.createContext();
        this.ctrl.portfolioContext = this.portfolioContext = this.context;
      }
      setupPush() {
        return super.setupPush().then(() => this.setupPushForPortfolioProjects());
      }
      closePushConnection() {
        if (!this.keepPushRoomOpenedOnDestroy) {
          this.pushRoom?.leave();
        }
        this.pushRoom = null;
        this.closePushConnectionForPortfolioProjects();
      }
      setupPushForPortfolioProjects() {
        return this.$q.all(
          this.project.portfolio_project_ids.map((projectId) => projectStore.tryGet(projectId)).filter(Boolean).map((project) => this.setupPushForPortfolioProject(project))
        ).then(() => {
          this.scope.$watch(() => this.project.portfolio_project_ids, (newVal, oldVal) => {
            if (!equals([...newVal]?.sort(), [...oldVal]?.sort())) {
              this.synchronizePushRoomForPortfolioProjects(this.project.portfolio_project_ids);
            }
          });
        });
      }
      setupPushForPortfolioProject(project) {
        return getPushConnection().then((conn) => conn.join(project.push_id)).then((room) => {
          if (this.destroyed) {
            room.leave();
            return;
          }
          this.portfolioProjectsPushRooms.set(project.id, room);
          new this.$ProjectPushListener(room, project);
          return room;
        });
      }
      synchronizePushRoomForPortfolioProjects(newProjectsIds) {
        for (const newProjectId of newProjectsIds) {
          if (!this.portfolioProjectsPushRooms.has(newProjectId)) {
            const project = projectStore.tryGet(newProjectId);
            if (project) {
              this.setupPushForPortfolioProject(project);
            }
          }
        }
        for (const [projectId, room] of this.portfolioProjectsPushRooms.entries()) {
          if (!newProjectsIds.includes(projectId)) {
            room.leave();
            this.portfolioProjectsPushRooms.delete(projectId);
          }
        }
      }
      closePushConnectionForPortfolioProjects() {
        for (const room of this.portfolioProjectsPushRooms.values()) {
          room.leave();
        }
        this.portfolioProjectsPushRooms.clear();
      }
      setupGlobalContext() {
        if (this.unregisterMatchingCardsListeners) {
          this.unregisterMatchingCardsListeners();
          this.unregisterMatchingCardsListeners = null;
        }
        if (this.unregisterFilterScopesListener) this.unregisterFilterScopesListener();
        if (this.disposeOnForceRefreshAllWidgetsEventListener) this.disposeOnForceRefreshAllWidgetsEventListener();
        this.ctrl.context = this.context = setupContextAndFetch(this.scope, this.view, (viewProps, changes) => {
          if (this.preventNextAppOptionsChange) {
            this.preventNextAppOptionsChange = false;
            return;
          }
          this.updateViewFromAppOptionsChanges(changes);
        }, true);
        this.setupEventListenersForPortfolioProjects();
        this.context.on("fetchingChanged", () => {
          if (!this.context.fetching) {
            this.synchronizeEventListenersForPortfolioProjects(this.project.portfolio_project_ids);
          }
        });
        this.disposeOnForceRefreshAllWidgetsEventListener = onForceRefreshAllWidgets.subscribe(() => {
          this.synchronizeEventListenersForPortfolioProjects(this.project.portfolio_project_ids);
        });
        this.unregisterContextAppOptionsWatcher = () => {
        };
        this.unregisterFilterScopesListener = this.scope.$watch(() => this.project.portfolio_project_ids, (newVal, oldVal) => {
          if (!equals([...newVal]?.sort(), [...oldVal]?.sort())) {
            this.context.needFetchCards = true;
            this.synchronizeEventListenersForPortfolioProjects(this.project.portfolio_project_ids);
          }
        });
      }
      switchBackToPortfolioContext() {
        if (this.unregisterFilterScopesListener) this.unregisterFilterScopesListener();
        if (this.disposeOnForceRefreshAllWidgetsEventListener) this.disposeOnForceRefreshAllWidgetsEventListener();
        this.disposeEventListenersForPortfolioProjects();
        this.context.destroy();
        this.ctrl.context = this.context = this.portfolioContext;
        if (this.context.app?.filterable || this.context.app.name === "cards" && this.appRegistry.get(this.context.appOptions.mode, true, true)?.filterable) {
          if (!this.unregisterMatchingCardsListeners) {
            this.registerMatchingCardsListeners();
          }
        }
      }
      setupEventListenersForPortfolioProjects() {
        for (const projectId of this.project.portfolio_project_ids) {
          const project = projectStore.tryGet(projectId);
          if (project) {
            this.setupEventListenersForPortfolioProject(project);
          }
        }
      }
      setupEventListenersForPortfolioProject(project) {
        const listener = () => {
          if (this.context.fetching || !this.cardsHaveBeenLoadedOnce) return;
          this.context.needFetchCards = true;
          this.disposeEventListenersForPortfolioProjects();
        };
        const dispose2 = offMany([
          cardStore.scopedByProject(project).subscribe(listener, false),
          cardGroupStore.scopedByAvailableForChildren(project.top_level_card).subscribe(listener, false),
          cardModelStore.scopedByEnabled(project).subscribe(listener, false),
          cardGroupTypeStore.scopedByEnabled(project).subscribe(listener, false),
          requestFormStore.scopedByProject(project).subscribe(listener, false)
          // cardSubscriptionStore.subscribe(listener, false)
        ]);
        this.portfolioProjectsEventListeners.set(project.id, dispose2);
      }
      synchronizeEventListenersForPortfolioProjects(newProjectsIds) {
        for (const newProjectId of newProjectsIds) {
          if (!this.portfolioProjectsEventListeners.has(newProjectId)) {
            const project = projectStore.tryGet(newProjectId);
            if (project) {
              this.setupEventListenersForPortfolioProject(project);
            }
          }
        }
        for (const [projectId, dispose2] of this.portfolioProjectsEventListeners.entries()) {
          if (!newProjectsIds.includes(projectId)) {
            dispose2();
            this.portfolioProjectsEventListeners.delete(projectId);
          }
        }
      }
      disposeEventListenersForPortfolioProjects() {
        for (const dispose2 of this.portfolioProjectsEventListeners.values()) {
          if (dispose2) dispose2();
        }
        this.portfolioProjectsEventListeners.clear();
      }
      getDefaultView() {
        return null;
      }
      _beforeSetActiveView(view, oldView, noViewAppFallback) {
        if (!noViewAppFallback && !view) {
          noViewAppFallback = "overview";
        }
        return { view, oldView, noViewAppFallback };
      }
      _afterSetActiveView(newView, oldView) {
        if (!newView) {
          if (this.context !== this.portfolioContext) {
            this.switchBackToPortfolioContext();
          }
          return;
        }
        const { filterScopes, appName } = getContextParamsFromView(newView);
        if (filterScopes?.[0]?.[0] === "portfolio" && (this.context === this.portfolioContext || appName !== this.context.app?.name)) {
          if (this.context instanceof GlobalContext) this.context.destroy();
          this.setupGlobalContext();
        } else {
          if (!filterScopes && this.context !== this.portfolioContext) {
            this.switchBackToPortfolioContext();
          }
          this.updateContextWithActiveView(true);
        }
      }
      gotoNoViewApp(appName) {
        if (this.context !== this.portfolioContext) {
          this.switchBackToPortfolioContext();
        }
        $navigateToProject(this.project, null, { id: appName });
      }
    };
  }
]);

// public/app/routes/portfolio/index.jsx
function PortfolioPage() {
  const params = useParams();
  const [searchParams] = useSearchParams();
  return createComponent(ColorizedPage, {
    get children() {
      return createComponent(NgComponent, {
        directive: "portfolio-page",
        get projectId() {
          return params.projectId;
        },
        get viewId() {
          return searchParams.view;
        }
      });
    }
  });
}
addRoute({
  name: "portfolio",
  path: "/po/:projectId",
  colorized: true,
  noSidebarForAnonymous: true,
  component: PortfolioPage
});

// public/app/config/suggested-views.js
var assignedTo = {
  title: _lazy("Cards which I'm assigned to"),
  icon: "bi-person-fill",
  create(project, board) {
    return {
      mode: "list",
      filter: "@me"
    };
  }
};
var recentUpdates = {
  title: _lazy("Recently updated cards"),
  icon: "clock-o",
  create(project, board) {
    return {
      mode: "table",
      filter: '{updated at} > ago("2 days")'
    };
  }
};
var recentActivities = {
  title: _lazy("Activities from last week"),
  icon: "history",
  create(project, board) {
    return {
      mode: "activities",
      mode_options: { filters: { dates: "last_week" } }
    };
  }
};
var workload = {
  title: _lazy("Workload"),
  icon: "kfi-timeline",
  create(project, board) {
    return {
      mode: "timeline",
      group_by: findBestGroupBy(project, "members")
    };
  }
};
var archives = {
  title: _lazy("Archived cards"),
  icon: "archive",
  create(project, board) {
    return {
      mode: "table",
      filter: "archived=yes",
      include_archived: true
    };
  }
};
var projectSuggestedViews = [
  assignedTo,
  recentUpdates,
  recentActivities,
  workload,
  archives
];
var portfolioSuggestedViews = [
  assignedTo,
  recentUpdates,
  archives
];
function getProjectSuggestedViews(project) {
  if (project.is_portfolio) {
    return portfolioSuggestedViews;
  }
  return projectSuggestedViews;
}

// public/app/stores/utils/project.ts
function getProjectTypeLabel(project) {
  if (!project) return _4("Workspace");
  if (project.is_portfolio) {
    if (project.is_template) {
      return _4("Portfolio template");
    } else {
      return _4("Portfolio");
    }
  } else if (project.is_template) {
    return _4("Workspace template");
  }
  return _4("Workspace");
}

// public/app/routes/project/modals/add-view.js
angular_default.module("kantree").factory("projectAddViewModal", [
  "$uibModal",
  function($uibModal) {
    return {
      open: function({ project, board, category, filterScopes, isPublic } = {}) {
        return $uibModal.open({
          windowClass: "project-add-view-modal",
          component: "projectAddViewModal",
          resolve: {
            options: () => {
              return { project, board, category, filterScopes, isPublic };
            }
          }
        }).result;
      }
    };
  }
]);
angular_default.module("kantree").component("projectAddViewModal", {
  templateUrl: "/static/app/routes/project/modals/templates/add-view-modal.html",
  bindings: {
    resolve: "<",
    close: "&",
    dismiss: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$injector"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.project = this.resolve.options.project;
      this.board = this.resolve.options.board;
      this.org = orgStore.tryGetForProject(this.project);
      this.cardsApps = getAvailableCardsApps(this.project);
      this.apps = getAvailableApps(this.project, this.resolve.options.filterScopes).filter((app) => !app.noView && app.name !== "cards");
      this.suggestions = getProjectSuggestedViews(this.project);
      this.typeLabel = getProjectTypeLabel(this.project);
      this.showCardsApps = false;
    }
    addView(mode) {
      this.createView("", {
        icon: mode.icon,
        mode: mode.name,
        group_by: mode.useDefaultGroupByOnCreateView ? findBestGroupBy(this.project) : null
      });
    }
    useSuggestion(suggestion) {
      const viewProps = suggestion.create(this.project, this.board);
      this.createView(suggestion.title, Object.assign({ icon: suggestion.icon }, viewProps));
    }
    createView(title, options2) {
      this.$q.when(
        createProjectView(title, this.project, Object.assign({}, options2, {
          card_ref: this.board.ref,
          category_id: this.resolve.options.category?.id,
          filter_scopes: this.resolve.options.filterScopes
        }), { isPublic: this.resolve.options.isPublic }),
        (view) => this.close({ $value: view })
      );
    }
  }
});

// public/app/actions/group-type.ts
function formatData2(groupType) {
  return {
    name: groupType.name,
    singular_name: groupType.singular_name,
    plural_name: groupType.plural_name,
    description: groupType.description,
    icon: groupType.icon,
    one_group_per_card: groupType.one_group_per_card,
    auto_random_color: groupType.auto_random_color,
    auto_assign_period: groupType.auto_assign_period
  };
}
function saveGroupType(groupType, org2, project) {
  if (groupType.id) {
    return updateGroupType(groupType, formatData2(groupType));
  }
  return createGroupType(groupType, org2, project);
}
async function createGroupType(groupType, org2, project) {
  const data2 = formatData2(Object.assign({
    singular_name: null,
    plural_name: null,
    description: null,
    icon: null,
    one_group_per_card: false,
    auto_random_color: false,
    auto_assign_period: null,
    auto_enabled_on_new_projects: false
  }, groupType));
  data2.scope = project && groupType.scope === "org" ? "project" : groupType.scope;
  if (org2) {
    data2["org_id"] = org2.id;
  }
  let props2;
  if (project) {
    data2["project_id"] = project.id;
    if (project.owner.type === "org") {
      data2["org_id"] = project.owner.id;
    }
    props2 = await api_default.project_group_types.create_group_type_in_project.post(data2);
  } else {
    props2 = await api_default.card_group_types.create.post(data2);
  }
  return cardGroupTypeStore.insert(Object.assign(groupType, props2));
}
var onGroupTypeRenamed = createEvent();
async function updateGroupType(groupType, data2) {
  const gt = await api_default.card_group_types.update.put({ type_id: groupType.id, ...data2 });
  const oldGt = cardGroupTypeStore.get(groupType.id);
  if (oldGt.name !== gt.name) {
    onGroupTypeRenamed(gt.name, oldGt.name);
  }
  return cardGroupTypeStore.update(gt);
}
async function changeGroupTypeScope(groupType, scope, groupsToDelete) {
  const gt = await api_default.card_group_types.update.put({
    type_id: groupType.id,
    scope,
    groups_to_delete: groupsToDelete
  });
  return cardGroupTypeStore.update(gt);
}
async function deleteGroupType(groupType) {
  await api_default.card_group_types.delete.delete({ type_id: groupType.id });
  cardGroupTypeStore.remove(groupType);
  cardGroupStore.removeManyMatching({ type_id: groupType.id });
}
async function enableGroupType(groupType, project) {
  const gt = await api_default.project_group_types.enable_group_type.put({ project_id: project.id, type_id: groupType.id });
  return cardGroupTypeStore.update(gt);
}
async function disableOrDeleteGroupType(groupType, project) {
  await confirmDeleteDialog2(
    _4("Are you sure?"),
    _4("All groups of this type in the current workspace will be removed."),
    groupType.is_project_specific ? _4("Delete") : _4("Disable")
  );
  const deleted = await api_default.project_group_types.disable_or_delete_group_type.delete({
    project_id: project.id,
    type_id: groupType.id
  });
  await loadProject(project.id);
  if (deleted) {
    if (cardGroupTypeStore.exists(groupType.id)) {
      cardGroupTypeStore.remove(groupType);
    }
    cardGroupStore.removeManyMatching({ type_id: groupType.id });
  } else {
    if (groupType.used_by.includes(project.id)) {
      cardGroupTypeStore.upsert(groupType, { used_by: groupType.used_by.filter((id) => id !== project.id) });
    }
  }
  cardStore.scopedByProject(project).clearGroupsAfterGroupTypeDisabled(groupType);
  return deleted;
}

// public/app/loaders/group-type.js
var loader7 = new StoreLoader(cardGroupTypeStore);
function getOrLoadGroupType(project, id, options2) {
  if (project && typeof project.id !== "undefined") {
    return loader7.getOrLoad(id, api_default.project_group_types.get_group_type, {
      project_id: project.id,
      type_id: id
    }, options2);
  }
  return loader7.getOrLoad(id, api_default.card_group_types.get, { type_id: id }, options2);
}
function loadAllGroupTypesForProject(project) {
  return loader7.loadMany(api_default.project_group_types.list_group_types_in_project, {
    project_id: project.id
  });
}
function loadAllGroupTypesForProjectOwner(project) {
  if (project.owner.type === "org") {
    return this.loadAllForOrg(project.owner);
  } else {
    return this.loadAllForUser();
  }
}
function loadAllGroupTypesForOrg(org2) {
  return loader7.loadMany(api_default.organizations.list_group_types, { org_id: org2.id });
}

// public/app/loaders/group.js
function sideLoadGroup(group2, ctx) {
  if (typeof ctx.loaded === "undefined") {
    ctx.loaded = [];
  }
  if (!cardGroupTypeStore.exists(group2.type_id) && !ctx.loaded.includes(group2.type_id)) {
    ctx.loaded.push(group2.type_id);
    const loadGroupType = (parent) => {
      let project = null;
      if (parent) {
        project = { id: parent.project_id };
      }
      getOrLoadGroupType(project, group2.type_id);
    };
    if (cardStore.exists(group2.parent_id)) {
      loadGroupType(cardStore.get(group2.parent_id));
    } else if (group2.parent_id === void 0 || group2.parent_id === null) {
      loadGroupType();
    } else {
      getOrLoadCard(group2.parent_id).then((parent) => loadGroupType(parent));
    }
  }
}
var loader8 = new StoreLoader(cardGroupStore, { sideload: sideLoadGroup });
function loadGroupByParent(parent, id, options2) {
  return loader8.load(id, api_default.card_groups.get, {
    card_id: parent.id,
    group_id: id
  }, options2);
}
function loadGroupByCard(card, id, options2) {
  return loader8.load(api_default.card_groups.get, {
    card_id: card.id,
    group_id: id
  }, options2);
}
function loadAllGroupsForTypeAndParent(groupType, parent, options2) {
  return loader8.loadMany(api_default.card_groups.list_all, {
    card_id: parent.id,
    type_id: groupType.id
  }, options2);
}
function loadAllArchivedGroupsForTypeAndParent(groupType, parent, options2) {
  return loader8.loadMany(api_default.card_groups.list_archived, {
    card_id: parent.id,
    type_id: groupType.id
  }, options2);
}
function loadAllArchivedAvailableGroupsForCard(card, options2) {
  return loader8.loadMany(api_default.card_groups.list_archived, { card_id: card.id }, options2);
}
function loadAllAvailableGroupsForCard(card, options2) {
  return loader8.loadMany(api_default.card_groups.list_all, { card_id: card.id }, options2);
}
function loadAllGroupsForType(groupType) {
  return loader8.loadMany(api_default.card_group_types.get_groups, { type_id: groupType.id });
}

// public/app/routes/project/modals/convert-context-scope.js
angular_default.module("kantree").factory("convertContextScopeModal", [
  "$uibModal",
  "$rootScope",
  "$q",
  function($uibModal, $rootScope, $q) {
    return {
      open: function(project) {
        var scope = $rootScope.$new();
        scope.project = project;
        scope.groupTypes = cardGroupTypeStore.scopedByEnabled(scope.project).scoped({ scope: "card" }).query();
        var instance;
        $q.all(scope.groupTypes.map((gt) => loadAllGroupsForType(gt))).then(() => {
          instance = $uibModal.open({
            templateUrl: "/static/app/routes/project/modals/templates/convert-context-scope-modal.html",
            windowClass: "convert-context-scope-modal",
            controller: "convertContextScopeModalCtrl",
            scope,
            backdrop: "static"
          });
          instance.result.finally(function() {
            scope.$destroy();
          });
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("convertContextScopeModalCtrl", [
  "$scope",
  "$document",
  "$sce",
  "$q",
  "$sanitize",
  function($scope2, $document, $sce, $q, $sanitize) {
    injectI18nHelpersIntoScope($scope2);
    $scope2.loading = false;
    $scope2.convertScopeGroupTypes = [];
    function formatGroup(group2) {
      var classes = [];
      var icon;
      if (group2.convert_status === "delete") {
        classes.push("is-deleted");
        icon = "minus";
      } else if (group2.convert_status === "merge") {
        classes.push("is-merged");
        icon = "share-alt fa-flip-horizontal";
      } else if (group2.convert_status === "add") {
        classes.push("is-added");
        icon = "plus";
      }
      if (group2.is_archived) {
        classes.push("is-archived");
      }
      return '<span class="' + classes.join(" ") + '">' + (icon ? '<i class="fa fa-' + icon + '"></i>' : "") + $sanitize(group2.title) + (group2.is_archived ? "<span>" + _4("archived") + "</span>" : "") + "</span>";
    }
    function mergedGroupHasCards(group2) {
      return [group2.id].concat(group2.merged_group_ids).some(function(groupId) {
        return cardStore.scopedByProject($scope2.project).scoped({ groups: matchGroup(groupId) }).count() > 0;
      });
    }
    function belongsToTopBoard(group2) {
      return !group2.parent_id || group2.parent_id === $scope2.project.top_level_card_id;
    }
    function getConvertStatus(group2, mode) {
      if (mode === "deleteEmpty") {
        if (belongsToTopBoard(group2)) {
          if (group2.merged_group_ids.length) return "merge";
        } else {
          if (mergedGroupHasCards(group2)) {
            if (group2.merged_group_ids.length) return "merge";
            else return "add";
          } else return "delete";
        }
        return;
      }
      if (mode === "deleteAll") {
        if (!belongsToTopBoard(group2)) return "delete";
        return;
      }
      if (belongsToTopBoard(group2)) {
        if (group2.merged_group_ids.length) return "merge";
      } else {
        if (group2.merged_group_ids.length) return "merge";
        else return "add";
      }
    }
    function getGroupsToDelete(mergedGroups, mode) {
      if (mode === "deleteEmpty") {
        return mergedGroups.reduce(function(accu, group2) {
          if (belongsToTopBoard(group2)) return accu;
          if (mergedGroupHasCards(group2)) return accu;
          return accu.concat([group2.id].concat(group2.merged_group_ids));
        }, []);
      }
      if (mode === "deleteAll") {
        return mergedGroups.reduce(function(accu, group2) {
          return accu.concat((belongsToTopBoard(group2) ? [] : [group2.id]).concat(group2.merged_group_ids));
        }, []);
      }
      return [];
    }
    function getMergedGroups(groupType) {
      var topLevelBoardGroups = cardGroupStore.scoped({
        type_id: groupType.id,
        parent_id: query_exports.or(query_exports.isNull(), function(propVal) {
          return propVal === $scope2.project.top_level_card_id;
        })
      }).query({}, { sortBy: "position" }).map(function(group2) {
        return Object.assign({}, group2, { merged_group_ids: [] });
      });
      return cardGroupStore.scoped({
        type_id: groupType.id
      }).query({}, { sortBy: "position" }).reduce(function(accu, group2) {
        var alreadyAddedGroupWithSameName = accu.find(function(g3) {
          return g3.title === group2.title;
        });
        if (alreadyAddedGroupWithSameName) {
          if (group2.id !== alreadyAddedGroupWithSameName.id && alreadyAddedGroupWithSameName.merged_group_ids.indexOf(group2.id) === -1) {
            alreadyAddedGroupWithSameName.merged_group_ids.push(group2.id);
          }
        } else {
          accu.push(Object.assign({}, group2, { merged_group_ids: [] }));
        }
        return accu;
      }, topLevelBoardGroups);
    }
    $scope2.changeConvertScopeMode = function(mode, convertScopeGt) {
      var mergedGroups = getMergedGroups(convertScopeGt);
      convertScopeGt.convertScopeMode = mode;
      convertScopeGt.groupsToDelete = getGroupsToDelete(mergedGroups, mode);
      convertScopeGt.groupCount = mergedGroups.length;
      convertScopeGt.resultingGroupsRecap = $sce.trustAsHtml(mergedGroups.map(function(group2) {
        return formatGroup(Object.assign({}, group2, { convert_status: getConvertStatus(group2, mode) }));
      }).join(" "));
    };
    $scope2.changeAllConvertScopeMode = function(mode) {
      $scope2.convertScopeGroupTypes.forEach(function(convertScopeGt) {
        $scope2.changeConvertScopeMode(mode, convertScopeGt);
      });
    };
    cardGroupStore.$watchAll($scope2, function() {
      $scope2.convertScopeGroupTypes = $scope2.groupTypes.map(function(groupType) {
        var convertScopeGroupType = Object.assign({}, groupType);
        $scope2.changeConvertScopeMode("deleteEmpty", convertScopeGroupType);
        return convertScopeGroupType;
      });
    });
    $scope2.showBulkActions = function() {
      return $scope2.convertScopeGroupTypes.filter(function(groupType) {
        return groupType.groupCount;
      }).length > 1;
    };
    $scope2.merge = function() {
      $scope2.loading = true;
      Promise.all($scope2.convertScopeGroupTypes.map(
        (groupType) => changeGroupTypeScope(groupType, "project", groupType.groupsToDelete)
      )).then(() => {
        $document[0].location.reload(true);
      });
    };
  }
]);

// public/app/config/export-formats.js
var exportFormats = [
  {
    name: "xlsx",
    title: "Excel",
    attributes: true,
    tabular: true
  },
  {
    name: "ods",
    title: "OpenOffice Calc",
    attributes: true,
    tabular: true
  },
  {
    name: "csv",
    title: "CSV",
    attributes: true,
    tabular: true
  },
  {
    name: "json",
    title: "JSON",
    attributes: false,
    tabular: false
  },
  {
    name: "jsontab",
    title: _lazy("Tabular JSON"),
    attributes: true,
    tabular: false
  }
];

// public/app/routes/project/modals/export.js
angular_default.module("kantree").factory("projectExportModal", [
  "$rootScope",
  "$uibModal",
  function($rootScope, $uibModal) {
    return {
      open: function(project, filter4, attributes, parent, includeDescendants, cardIds) {
        var scope = $rootScope.$new();
        scope.project = project;
        scope.filter = filter4;
        scope.defaultAttributes = attributes;
        scope.parent = parent;
        scope.includeDescendants = includeDescendants === void 0 ? true : includeDescendants;
        scope.cardIds = cardIds;
        var instance = $uibModal.open({
          templateUrl: "/static/app/routes/project/modals/templates/export-modal.html",
          controller: "ProjectExportModalCtrl",
          windowClass: "project-export-modal",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("ProjectExportModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.formats = exportFormats;
    $scope2.format = $scope2.formats[0];
    $scope2.onlyMatchingCards = $scope2.showOnyMatchingCards = !!$scope2.filter || !!$scope2.cardIds;
    $scope2.templates = [];
    $q.when(api_default.project_export_templates.list_templates.get({ project_id: $scope2.project.id }), (templates) => {
      $scope2.templates = templates;
    });
    var attributeNames = [];
    $scope2.attributes = [
      { id: "_1", label: _4("ID"), name: "id" },
      { id: "_2", label: _4("Card ref"), name: "card ref" },
      { id: "_3", label: _4("URL"), name: "url" },
      { id: "_4", label: _4("Parent ID"), name: "parent id" },
      { id: "_5", label: _4("Creation date"), name: "created at" },
      { id: "_6", label: _4("Created by"), name: "created by" },
      { id: "_7", label: _4("Is link?"), name: "is link" },
      { id: "_8", label: _4("Link ID"), name: "link id" },
      { id: "_9", label: _4("Title"), name: "title" },
      { id: "_10", label: _4("Full title"), name: "full title" },
      { id: "_11", label: _4("Is archived?"), name: "is archived" },
      { id: "_12", label: _4("Number of children"), name: "nb children" },
      { id: "_13", label: _4("Progress"), name: "progress" },
      { id: "_14", label: _4("State"), name: "state" },
      { id: "_15", label: _4("Number of comments"), name: "nb comments" },
      { id: "_16", label: _4("Image cover URL"), name: "image cover url" },
      { id: "_17", label: _4("Past groups"), name: "past groups" },
      { id: "_18", label: _4("Type name"), name: "model" }
    ].concat(cardGroupTypeStore.scopedByEnabled($scope2.project, false).query({}, { sortBy: "name" }).map(function(gt) {
      return { id: -gt.id, label: gt.name, name: gt.name };
    })).concat(cardModelStore.scopedByEnabled($scope2.project).getAttributesFromModels().map(function(attr) {
      return { id: attr.id, label: attr.name, name: attr.name };
    })).filter(function(attr) {
      if (attributeNames.indexOf(attr.name) === -1) {
        attributeNames.push(attr.name);
        return true;
      }
      return false;
    });
    if (!$scope2.defaultAttributes) {
      $scope2.defaultAttributes = $scope2.attributes.map(function(attr) {
        return attr.id;
      });
    } else {
      var orderedAttributes = [];
      for (let id of $scope2.defaultAttributes) {
        let i3 = $scope2.attributes.findIndex((a3) => a3.id === id);
        orderedAttributes.push($scope2.attributes[i3]);
        $scope2.attributes.splice(i3, 1);
      }
      $scope2.attributes = orderedAttributes.concat($scope2.attributes);
    }
    var skipResetTemplate = false;
    $scope2.useTemplate = function(tpl) {
      if (!tpl) return;
      $scope2.format = $scope2.formats.find(function(f3) {
        return f3.name === tpl.format;
      });
      $scope2.defaultAttributes = tpl.attributes.map(function(name2) {
        var attr = $scope2.attributes.find(function(a3) {
          return a3.name === name2;
        });
        if (attr) {
          return attr.id;
        }
      });
      skipResetTemplate = true;
    };
    $scope2.resetTemplate = function() {
      $scope2.template = null;
    };
    $scope2.saveTemplate = function() {
      inputDialog("Choose a name for this template:", { required: true }).then((name2) => {
        $q.when(api_default.project_export_templates.create_template.post({
          project_id: $scope2.project.id,
          name: name2,
          format: $scope2.format.name,
          attributes: $scope2.selected
        }), (tpl) => {
          $scope2.templates.push(tpl);
          $scope2.template = tpl;
        });
      });
    };
    $scope2.deleteTemplate = function(tpl) {
      $q.when(api_default.project_export_templates.delete_template.delete({ project_id: $scope2.project.id, template_id: tpl.id }), () => {
        $scope2.templates.splice($scope2.templates.indexOf(tpl), 1);
      });
    };
    $scope2.updateSelectedAttributes = function(values2) {
      $scope2.selected = values2.map(function(a3) {
        return a3.name;
      });
      if (!skipResetTemplate) {
        $scope2.resetTemplate();
      }
      skipResetTemplate = false;
    };
    $scope2.export = function() {
      $scope2.exporting = true;
      const attributes = $scope2.selected;
      let filter4 = $scope2.onlyMatchingCards ? $scope2.filter : "";
      if ($scope2.parent) {
        filter4 = "parent=" + $scope2.parent + " AND (" + filter4 + ")";
      }
      $q.when(exportProject(
        $scope2.project,
        $scope2.format.name,
        filter4,
        attributes,
        $scope2.includeDescendants,
        $scope2.cardIds
      ), (id) => {
        $q.when(waitForAsyncDownload(id), (url2) => {
          $scope2.exporting = false;
          $scope2.url = url2;
        }, () => $uibModalInstance.dismiss());
      });
    };
  }
]);

// public/app/routes/project/modals/import-errors.js
angular_default.module("kantree").factory("projectImportErrorsModal", [
  "$rootScope",
  "$uibModal",
  function($rootScope, $uibModal) {
    return {
      open: function(project) {
        var scope = $rootScope.$new();
        scope.project = project;
        scope.errors = scope.project.import_errors;
        projectStore.update(scope.project, { "import_errors": null });
        var instance = $uibModal.open({
          templateUrl: "/static/app/routes/project/modals/templates/import-errors-modal.html",
          controller: "ProjectImportErrorsModalCtrl",
          windowClass: "project-import-errors-modal",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("ProjectImportErrorsModalCtrl", [
  "$scope",
  "$uibModalInstance",
  function($scope2, $uibModalInstance) {
  }
]);

// public/app/routes/project/modals/importer.js
angular_default.module("kantree").factory("projectImportModal", [
  "$rootScope",
  "$uibModal",
  function($rootScope, $uibModal) {
    return {
      open: function(project) {
        var scope = $rootScope.$new();
        scope.project = project;
        var instance = $uibModal.open({
          templateUrl: "/static/app/routes/project/modals/templates/import-modal.html",
          controller: "ProjectImportModalCtrl",
          windowClass: "project-import-modal",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("ProjectImportModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.onImportReady = function(data2) {
      if (!data2) {
        $scope2.importData = null;
      } else {
        $scope2.importData = Object.assign({ project_id: $scope2.project.id }, data2);
      }
    };
    $scope2.import = async function() {
      $scope2.importing = true;
      let req;
      try {
        if (Object.values($scope2.importData.mapping).find(({ type }) => type === "delete")) {
          await confirmDeleteDialog2(
            _4("Are you sure?"),
            _4("Be careful, your import might <strong>DELETE CARDS</strong>."),
            _4("Import")
          );
        }
        if ($scope2.importData.file) {
          req = upload({
            url: api_default.importers.import_project.url($scope2.importData),
            data: $scope2.importData,
            arrayKey: ""
          });
        } else {
          req = api_default.importers.import_project.post($scope2.importData);
        }
        $q.when(req).then(() => {
          $uibModalInstance.close();
        }, () => {
          $scope2.importing = false;
        });
      } catch (e3) {
        console.error(e3);
      }
    };
  }
]);

// public/app/config/card-group-sort-by.js
var cardGroupStaticSortBy = [
  { value: "ref", label: _lazy("Reference") },
  { value: "title", label: _lazy("Title") },
  { value: "state", label: _lazy("State") },
  { value: "nb_children", label: _lazy("Number of sub-cards") },
  { value: "created_at", label: _lazy("Creation date") },
  { value: "-updated_at", label: _lazy("Last modification date") }
];

// public/app/actions/automations.ts
async function saveAutomationRule(project, rule) {
  const data2 = Object.assign({ project_id: project.id }, rule);
  let isNewButton = false;
  if (rule.id) {
    data2.rule_id = rule.id;
    rule = await api_default.project_automations.update_automation_rule.put(data2);
  } else {
    rule = await api_default.project_automations.create_automation_rule.post(data2);
    isNewButton = rule.trigger_event === "manual_card";
  }
  rule = automationRuleStore.upsert(rule);
  if (isNewButton) {
    loadProject(project.id);
  }
  return rule;
}
async function deleteAutomationRule(project, rule) {
  await api_default.project_automations.delete_automation_rule.delete({ project_id: project.id, rule_id: rule.id });
  automationRuleStore.remove(rule);
  if (rule.trigger_event === "manual_card") {
    loadProject(project.id);
  }
}
async function duplicateAutomationRule(project, rule) {
  rule = await api_default.project_automations.copy_automation_rule.post({ project_id: project.id, rule_id: rule.id });
  rule = automationRuleStore.insert(rule);
  if (rule.trigger_event === "manual_card") {
    loadProject(project.id);
  }
  return rule;
}
function runAutomationRule(project, rule, card) {
  return api_default.project_automations.trigger_automation_rule.post({
    project_id: project.id,
    rule_id: rule.id,
    card_id: card?.id
  });
}
function createAutomationRunToken(project, rule, card) {
  return api_default.project_automations.create_automation_rule_run_token.post({ project_id: project.id, rule_id: rule.id, card_id: card ? card.id : null });
}
function invalidAutomationRunTokens(project, rule) {
  return api_default.project_automations.invalidate_all_automation_rule_run_tokens.delete(
    { project_id: project.id, rule_id: rule.id }
  );
}
async function clearAllAutomationRuleErrors(project, rule) {
  await api_default.project_automations.clear_all_automation_error_states.delete({ project_id: project.id, rule_id: rule.id });
  automationRuleStore.update(rule, { is_erroring: false });
}

// public/app/routes/project/menus/mobile.js
angular_default.module("kantree").factory("mobileMenuFactory", [
  "cardsAppModesMenu",
  "cardFilterMenuFactory",
  "projectActivitiesAppFilterMenu",
  "projectLogsAppFilterMenu",
  "projectSettingsModal",
  "membersListMenuFactory",
  "cardsAppGroupByMenu",
  "projectPage",
  "$q",
  "$timeout",
  function(cardsAppModesMenu, cardFilterMenuFactory, projectActivitiesAppFilterMenu, projectLogsAppFilterMenu, projectSettingsModal, membersListMenuFactory, cardsAppGroupByMenu, projectPage, $q, $timeout2) {
    var getItems = function(context) {
      const items = [];
      if (context.app.name === "cards") {
        items.push(...getCardsMenuItems(context), { label: "--" });
      } else if (context.app.name === "activities") {
        items.push(...getActivitiesItems(context), { label: "--" });
      } else if (context.app.name === "logs") {
        items.push(...getLogsItems(context), { label: "--" });
      }
      items.push(...getNavMembersItems(context));
      return items;
    };
    var getCardsMenuItems = function(context) {
      var items = [];
      var addReset = function(item) {
        item.resetAfterAction = true;
        if (item.submenu) {
          item.submenu.forEach(addReset);
        }
        return item;
      };
      const locked = context.appOptions.locked;
      const mode = cardsAppRegistry.get(context.appOptions.mode);
      const cardsApps = getAvailableCardsApps(context.project, context.filterScopes);
      const org2 = orgStore.tryGetForProject(context.project);
      if (!locked) {
        const modeMenu = {
          config: cardsAppModesMenu.getMenu(mode.name, cardsApps, org2, (mode2) => {
            context.appOptions = {
              ...context.appOptions,
              mode: mode2.name
            };
          }).config,
          options: {
            classes: "menu-big-icon",
            title: _4("Switch")
          }
        };
        items.push({
          label: mode.title,
          icon: mode.icon,
          submenu: modeMenu.config,
          options: modeMenu.options,
          classes: "mod-mobile-project-view-mode",
          buttons: [{
            label: _4("Switch"),
            action: "openSubmenu"
          }]
        }, {
          label: "--"
        });
      } else {
        items.push({
          label: _4("Viewing cards as {title}", { title: mode.title }),
          icon: mode.icon
        });
      }
      if (!locked) {
        const cardFilterMenu = cardFilterMenuFactory.get(
          context.project,
          context.board,
          context.appOptions.include_archived,
          (query2) => {
            context.appOptions = {
              ...context.appOptions || {},
              filter: $.trim(context.appOptions.filter ? context.appOptions.filter + " " + query2 : query2)
            };
          }
        );
        items.push({
          subheader: _4("Filters")
        }, {
          input: true,
          placeholder: _4("Add filter"),
          submit: (value2) => {
            context.appOptions = { ...context.appOptions || {}, filter: value2 };
          },
          submitOnBlur: true,
          defaultValue: context.appOptions.filter || null,
          allowEmptyValue: true,
          reset: () => {
            context.appOptions = { ...context.appOptions || {}, filter: null };
          },
          icon: "filter",
          classes: !context.appOptions.filter && context.appOptions.filter !== "" ? "active" : null,
          // filter submenu
          submenu: () => () => cardFilterMenu.config.map(addReset),
          options: {
            title: _4("Filters")
          },
          buttons: [{
            icon: "plus",
            action: "openSubmenu"
          }]
        });
      } else {
        let filterText = null;
        if (!context.filterRepr) {
          filterText = _4("some fields");
        } else {
          filterText = context.filterRepr;
        }
        items.push({
          label: !filterText ? _4("Not filtered") : _4("Filtered by {filter}", { filter: filterText })
        });
      }
      let groupByChoices;
      if (context.project) {
        groupByChoices = cardGroupTypeStore.scopedByEnabled(context.project).query({}, { sortBy: "name" }).map((gt) => {
          return {
            id: gt.id,
            obj: gt,
            type: "group_type"
          };
        }).concat(cardModelStore.scopedByEnabled(context.project).getGroupableAttributes().sort().map((attr) => {
          return {
            id: attr.id,
            obj: attr,
            type: "attribute"
          };
        }));
      } else {
        groupByChoices = context.groupByChoices;
      }
      let groupBy2;
      const screenizeConstraint = isScreensizeXS() && context.appOptions && context.appOptions.group_by && context.appOptions.group_by.length > 1 && formatSpec(context.appOptions.group_by[1]).type !== "nothing";
      let spec;
      if (screenizeConstraint) {
        spec = [context.appOptions.group_by[0], {}];
      } else {
        spec = context.appOptions.group_by || [{}, {}];
      }
      if (!context.board && !context.cardStore) {
        groupBy2 = null;
      } else {
        groupBy2 = create2(spec, context.cardStore, context.board, context.appOptions.include_archived);
      }
      if (!locked) {
        items.push({
          subheader: _4("Group by:")
        }, {
          label: groupBy2[0].getLabel(),
          submenu: () => {
            return [{
              component: "group-by-editor-menu-component",
              params: {
                board: context.board,
                groupBy: groupBy2,
                groupableTwice: mode.groupableTwice,
                choices: groupByChoices,
                onChange: (spec2) => context.appOptions = { ...context.appOptions, group_by: spec2 }
              }
            }];
          },
          options: {
            title: _4("Group by...")
          }
        });
      } else {
        items.push({
          label: _4("Grouped by {groupby}", { groupby: groupBy2[0].getLabel() })
        });
      }
      if (locked) {
        const sortChoices = getSortableAttributes(context.project, context.store, true);
        const sortBy3 = getSortBy(context.appOptions);
        let sortText = _4("Sorted by Custom ordering");
        if (sortBy3) {
          let value2 = sortBy3.value;
          const builtin = cardGroupStaticSortBy.find((item) => item.value === value2);
          if (builtin) {
            value2 = builtin.label.toLowerCase();
          } else if (typeof value2 === "number") {
            value2 = sortChoices.find((item) => item.id === value2);
            if (value2) {
              value2 = value2.label.toLowerCase();
            } else {
              value2 = "?";
            }
          }
          let sortText2 = _4("Sorted by {value}", { value: value2 });
          if (sortBy3.reverse) sortText2 = sortText2 + " " + _4("reversed");
        }
        items.push({
          label: sortText
        });
      }
      if (locked && canManageViews(context.project)) {
        items.push({ label: "--" }, {
          desc: _4("The configuration of this view has been locked"),
          classes: "warning"
        }, {
          buttons: [{
            label: _4("Unlock"),
            icon: "unlock",
            classes: "btn btn-default",
            action: () => updateView(projectPage.view, { locked: false })
          }]
        });
      }
      const actions2 = loadActions(context);
      if (locked && actions2.length > 0) {
        items.push({ label: "--" });
        for (const action of actions2) {
          items.push(action);
        }
      }
      if (!locked) {
        items.push({ label: "--" }, {
          label: mode.title + " " + _4("options"),
          submenu: () => mode.menu(
            context.cardStore,
            context.board,
            groupBy2,
            context.appOptions,
            (changes) => context.appOptions = { ...context.appOptions || {}, ...changes }
          ).config
        });
      }
      return items;
    };
    var loadActions = (context) => {
      const rules = automationRuleStore.scopedByProject(context.project).query({ trigger_event: "manual" });
      const _actions = [];
      if (rules.length) {
        for (const ruleId of context.appOptions.automations_rules || []) {
          const rule = rules.find((rule2) => rule2.id === ruleId);
          if (rule) _actions.push({
            icon: rule.icon || "play-circle",
            label: rule.name,
            bgColor: rule.background_color ? rule.background_color : null,
            classes: "mobile-action",
            action: () => {
              $q.when(runAutomationRule(context.project, rule), () => {
                $timeout2(() => {
                  toastNotify(_4("Triggered automation"), "success");
                }, 500);
              });
            }
          });
        }
      }
      return _actions;
    };
    var getActivitiesItems = function(context) {
      const menu = projectActivitiesAppFilterMenu.get(context.project, (context.appOptions || {}).filters, (filters) => {
        context.appOptions = { ...context.appOptions || {}, filters };
      });
      const label = projectActivitiesAppFilterMenu.getButtonLabel(true, context.project, (context.appOptions || {}).filters);
      return [{
        label,
        submenu: menu.config,
        options: Object.assign({}, menu.options, {
          title: () => projectActivitiesAppFilterMenu.getButtonLabel(
            true,
            context.project,
            (context.appOptions || {}).filters
          ),
          watch: (cb2, scope) => context.watch("appOptions", () => {
            cb2();
            scope.$applyAsync();
          })
        })
      }];
    };
    var getLogsItems = function(context) {
      const activeDateRange = dateRangeToActiveRange(context.appOptions.filters && context.appOptions.filters.dates);
      const logTypes = projectLogTypeStore.scopedByProject(context.project).query();
      let logType;
      if (logTypes || logTypes.length === 0) {
        logType = null;
      } else if (context.appOptions.logsTypeId && logTypes.some((l3) => l3.id === context.appOptions.logsTypeId)) {
        logType = projectLogTypeStore.tryGet(context.appOptions.logsTypeId);
      } else {
        logType = logTypes.find((logType2) => {
          return activityStore.scoped({ project_id: context.project.id, stream_type: "log", type_id: logType2.id }).query({
            date: (date) => {
              return !activeDateRange || parseTimestamp(date).isBetween(activeDateRange.start, activeDateRange.end, "day", "[]");
            }
          }).length > 0;
        });
      }
      let menu;
      if (logType) {
        menu = projectLogsAppFilterMenu.get(context.project, logType.id, (logsTypeId) => {
          context.appOptions = { ...context.appOptions || {}, logsTypeId };
        });
      }
      if (logType) {
        return [{
          label: logType.label,
          submenu: menu.config,
          options: menu.options
        }];
      }
      return [];
    };
    var getNavMembersItems = function(context) {
      if (projectPage.isActive && !!projectPage.scopeManager.portfolioContext) {
        context = projectPage.scopeManager.portfolioContext;
      }
      var membersListMenuSpec = membersListMenuFactory.get(context.project, true);
      var items = [];
      const typeLabel = getProjectTypeLabel(context.project);
      items.push({
        subheader: _4("{projectType} members", { projectType: typeLabel })
      });
      items.push({
        component: "nav-members-menu-component",
        params: { context },
        submenu: membersListMenuSpec.config,
        label: _4("Members"),
        options: membersListMenuSpec.options
      });
      if (canManageMembers(context.project) && !isEmbedded() && isConnected()) {
        items.push({
          label: _4("Invite new members"),
          icon: "user-plus",
          action: function() {
            return projectSettingsModal.open(context.project, "members");
          }
        });
      }
      return items;
    };
    return {
      getItems,
      get: (context) => {
        return {
          config: () => getItems(context)
        };
      }
    };
  }
]);

// public/app/ui/utils/blink.js
function makeElementBlink(selector, duration = 3e3) {
  const nodes2 = document.querySelectorAll(selector);
  nodes2.forEach((node) => node.classList.add("blink"));
  setTimeout(() => nodes2.forEach((node) => node.classList.remove("blink")), duration);
}

// public/app/actions/role.ts
function formatData3(role) {
  return {
    name: role.name,
    description: role.description,
    permissions: role.permissions || []
  };
}
var getAvailableRoleActions = singleton(() => {
  return api_default.roles.get_available_actions.get();
});
async function createRoleInOrg(role, org2) {
  role = await api_default.roles.create.post(Object.assign({ org_id: org2.id }, formatData3(role)));
  return roleStore.insert(role);
}
async function updateRole(role) {
  role = await api_default.roles.update.put(Object.assign({ role_id: role.id }, formatData3(role)));
  return roleStore.upsert(role);
}
async function updateProjectRolePermissions(role, project, permissions) {
  role = await api_default.roles.update_project_permissions.put({
    role_id: role.id,
    project_id: project.id,
    permissions
  });
  return roleStore.upsert(role);
}
async function addRolePermission(role, object_type, actions2, project, object2) {
  role = await api_default.roles.add_permission.post({
    role_id: role.id,
    object_type,
    actions: actions2,
    project_id: project ? project.id : null,
    object_id: object2 ? object2.id : null
  });
  return roleStore.upsert(role);
}
async function deleteRolePermission(role, permission) {
  role = await api_default.roles.delete_permission.delete({
    role_id: role.id,
    permission_id: permission.id
  });
  return roleStore.upsert(role);
}
async function duplicateRole(role) {
  const newRole = await api_default.roles.duplicate.post({ role_id: role.id });
  return roleStore.insert(newRole);
}
async function deleteRole(role) {
  try {
    await api_default.roles.delete.delete({ role_id: role.id });
    roleStore.remove(role);
  } catch (r3) {
    if (r3.status === 412) {
      await new Promise((r4) => setTimeout(r4, 500));
      errorDialog(
        _4("This role cannot be deleted"),
        _4("This role is being used. You cannot delete it.")
      );
    }
    throw r3;
  }
}
async function resetRoleForProject(role, project) {
  role = await api_default.roles.reset.put({
    role_id: role.id,
    project_id: project.id
  });
  return roleStore.upsert(role);
}

// public/app/routes/project/menus/view.js
angular_default.module("kantree").directive("viewMenuToggle", [
  "viewMenuFactory",
  "menuDropdown",
  "$q",
  function(viewMenuFactory, menuDropdown, $q) {
    return {
      restrict: "A",
      scope: {
        view: "<viewMenuToggle",
        options: "<viewMenuOptions",
        dropConfig: "<"
      },
      link: function(scope, element2, attr) {
        var menu;
        var drop;
        scope.$watchGroup(["view", "options"], () => {
          if (scope.view) {
            menu = viewMenuFactory.get(scope.view, scope.options);
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu) {
            drop = menuDropdown.toggle(drop, element2[0], menu, scope, {
              classes: "drop-theme-menu drop-theme-arrow drop-theme-project-view",
              ...scope.dropConfig || {},
              tetherOptions: {
                targetAttachment: "middle right",
                attachment: "top left",
                offset: "19px 0",
                constraints: [
                  {
                    to: "window",
                    pin: true,
                    attachment: "none"
                  }
                ],
                resizable: false,
                ...(scope.dropConfig || {}).tetherOptions || {}
              }
            }, event2);
            if (!scope.view.name) {
              drop.on("close", () => {
                let view = viewStore.tryGet(scope.view.id);
                if (view && view.id && !view._draft && !view.name) {
                  const name2 = getAppForView(view).title;
                  $q.digest(updateView(view, { name: name2 }));
                }
              });
            }
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("viewMenuFactory", [
  "projectPage",
  "projectExportModal",
  "$state",
  "$q",
  function(projectPage, projectExportModal, $state, $q) {
    function getViewStore(view) {
      if (viewStore.isGlobalView(view)) return viewStore.scopedByGlobal();
      if (viewStore.isProjectView(view)) return viewStore.scopedByProject({ id: view.project_id });
      return viewStore;
    }
    function onViewUpdated(v3) {
      $navigateToView(v3);
    }
    var getItemsForDraftView = function(view, { showPrivateOptions = true, showExportOptions = true, customLabels = {} } = {}) {
      const defaultLabels = {
        defaultName: (viewMode2, number3) => _4("{viewmode} {number}", { viewmode: viewMode2.title, number: number3 }),
        overwrite: (originalName) => _4("Overwrite {viewname}", { viewname: originalName }),
        overwritePublic: (originalName) => _4("Overwrite {viewname} for everybody", { viewname: originalName }),
        saveAsNew: () => _4("Save as new private view"),
        saveAsNewPublic: () => _4("Save as new public view")
      };
      const viewMode = getAppForView(view);
      const project = view.project_id ? projectStore.tryGet(view.project_id) : null;
      if (!view.project_id && $state.includes("myWork")) {
        customLabels = Object.assign({
          saveAsNew: () => _4("Save as new dashboard")
        }, customLabels);
      } else if (projectPage.isProjectActive(project) && !!view.filter_scopes) {
        showPrivateOptions = false;
        showExportOptions = false;
      }
      const labels = Object.assign({}, defaultLabels, customLabels);
      var store2 = getViewStore(view).scoped({ _draft: query_exports.isFalsy() });
      if (project && projectPage.isProjectActive(project)) {
        store2 = store2.scoped({
          is_public: (isPublic) => !isPublic || canManageViews(project),
          card_ref: (ref) => ref === view.card_ref || query_exports.isFalsy()
        });
      }
      function replaceView(original) {
        const props2 = filterAvailableViewProps(view);
        return $q.when(updateView(original, props2, false), (v3) => {
          viewStore.transaction(() => {
            viewStore.remove(view);
            viewStore.update(v3);
          });
        });
      }
      function saveAsNew(isPublic = false, viewTitle) {
        return $q.when(createFromLocalView(viewTitle || "", view, isPublic), (v3) => {
          viewStore.remove(view);
          onViewUpdated(v3);
        });
      }
      const items = [];
      if (view.from_view_id && viewStore.exists(view.from_view_id)) {
        const original = viewStore.get(view.from_view_id);
        items.push(
          {
            label: original.is_public ? labels.overwritePublic(original.name) : labels.overwrite(original.name),
            icon: "bi-save",
            action: () => replaceView(original),
            enabled: () => !projectPage.isActive || !original.is_public || project && canManageViews(project)
          },
          {
            label: _4("Discard changes"),
            icon: "trash",
            action: () => viewStore.remove(view)
          },
          {
            label: labels.saveAsNew(),
            icon: "clone",
            action: () => saveAsNew(false),
            enabled: () => showPrivateOptions && (!projectPage.isActive || project && project.is_member)
          },
          {
            label: labels.saveAsNewPublic(),
            icon: "clone",
            action: () => saveAsNew(true),
            enabled: () => projectPage.isActive && project && original.is_public && project && canManageViews(project)
          }
        );
      } else {
        items.push(
          { subheader: showPrivateOptions ? labels.saveAsNew() : labels.saveAsNewPublic() },
          {
            input: true,
            defaultValue: labels.defaultName(viewMode, store2.query({ mode: viewMode.name }).length + 1),
            allowUnchangedDefaultValue: true,
            placeholder: _4("Title"),
            focusOnLoad: true,
            selectOnLoad: true,
            submit: (viewTitle) => saveAsNew(!showPrivateOptions, viewTitle),
            closeAfterSubmit: true
          }
        );
      }
      if (viewMode.convertToImage && showExportOptions) {
        const project2 = view.project_id ? projectStore.tryGet(view.project_id) : null;
        items.push({
          label: _4("Download as image"),
          icon: "download",
          action: () => {
            viewMode.convertToImage(project2 ? project2.title : view.name);
          }
        });
      }
      return items;
    };
    var getItems = function(view, {
      showPrivateOptions = true,
      showSubBoardOptions = true,
      showMyWorkOptions = true,
      showShareOptions = true,
      showExportOptions = true,
      customLabels = {}
    } = {}) {
      const defaultLabels = {
        viewAvailable: () => _4("This view is available for every member of the workspace"),
        duplicate: () => _4("Duplicate as private view"),
        duplicateAsPublic: () => _4("Duplicate as public view")
      };
      const viewMode = getAppForView(view);
      const project = view.project_id ? projectStore.tryGet(view.project_id) : null;
      const canManageView = !view.is_public || project && canManageViews(project);
      if (!view.project_id && $state.includes("myWork")) {
        customLabels = Object.assign({
          duplicate: () => _4("Duplicate")
        }, customLabels);
      } else if (projectPage.isProjectActive(project) && !!view.filter_scopes) {
        customLabels = Object.assign({
          viewAvailable: () => _4("This view is available for every member of the portfolio"),
          duplicateAsPublic: () => _4("Duplicate")
        }, customLabels);
        showPrivateOptions = false;
        showExportOptions = false;
        showSubBoardOptions = false;
      }
      const labels = Object.assign({}, defaultLabels, customLabels);
      var items = [];
      items.push({
        desc: labels.viewAvailable(),
        enabled: () => view.is_public
      });
      if (canManageView) {
        items.push(
          { subheader: _4("Name") },
          {
            input: true,
            defaultValue: view && view.name ? view.name : viewMode.title,
            allowUnchangedDefaultValue: true,
            submit: (name2) => {
              if (view.name === name2 || !name2) {
                return;
              }
              return $q.digest(updateView(view, { name: name2 }));
            },
            focusOnLoad: true,
            selectOnLoad: true
          },
          { subheader: _4("Icon") },
          {
            iconpicker: true,
            getValue: () => view ? view.icon : null,
            action: (event2, icon) => {
              if (view.icon === icon) {
                return;
              }
              return $q.digest(updateView(view, { icon }));
            },
            emptyIcon: true,
            maxIcons: 7,
            noCloseAfterAction: true,
            extended: true,
            options: {
              watch: watch.bind(this, view)
            }
          }
        );
        if (project) {
          const roles = roleStore.scopedByOrg(project.owner).query({});
          items.push({
            label: _4("Who can see this view?"),
            icon: "person",
            enabled: () => view.is_public,
            submenu: roles.map((role) => {
              let permission = role.permissions.find(
                (perm) => perm.object_type === "view" && perm.object_id === view.id && perm.project_id === project.id
              );
              return {
                checkbox: true,
                value: () => permission && permission.actions.indexOf("HIDDEN") > -1 ? false : true,
                label: role.name,
                help: role.description,
                disabled: () => role.is_builtin,
                toggle: (value2) => {
                  if (!value2) {
                    $q.when(addRolePermission(role, "view", ["HIDDEN"], project, view), (role2) => {
                      permission = role2.permissions.find(
                        (perm) => perm.object_type === "view" && perm.object_id === view.id && perm.project_id === project.id
                      );
                    });
                  }
                  if (value2) {
                    $q.when(deleteRolePermission(role, permission), () => {
                      permission = null;
                    });
                  }
                }
              };
            })
          });
        }
        items.push(
          { label: "--" },
          {
            checkbox: true,
            label: _4("Lock view"),
            offline: true,
            mobile: true,
            help: _4("When locked, no additionnal configuration can be made on the view. Its toolbar is hidden"),
            value: () => view.locked,
            toggle: () => $q.digest(updateView(view, { locked: !view.locked }))
          }
        );
      }
      if (canManageView && project && showSubBoardOptions) {
        items.push(
          {
            checkbox: true,
            value: view.card_ref !== null,
            label: view.card_ref === null || projectPage.isActive && projectPage.board.ref === view.card_ref ? _4("Only applies to the current board") : _4("Only applies to board #{ref}", { ref: view.card_ref }),
            toggle: function(isChecked) {
              if (isChecked && view.card_ref !== null || !isChecked && view.card_ref === null) {
                return;
              }
              return $q.digest(updateView(view, { card_ref: isChecked ? parseInt(projectPage.board.ref, 10) : null }));
            },
            enabled: () => projectPage.isProjectActive(project) && view.card_ref === null
          },
          {
            checkbox: true,
            value: !view.limit_to_ref,
            label: _4("Available from any board"),
            help: _4("Make this view available from anyboard even if it only applies to one board. Will open the target board when activated"),
            enabled: () => view.card_ref !== null && !view.limit_to_ref,
            toggle: function(isChecked) {
              if (isChecked && !view.limit_to_ref || !isChecked && view.limit_to_ref) {
                return;
              }
              return $q.digest(updateView(view, { limit_to_ref: !isChecked }));
            }
          },
          { label: "--" }
        );
      }
      if (project) {
        items.push(
          {
            label: _4("Make this view available for everybody"),
            icon: "unlock",
            noCloseAfterAction: true,
            action: () => $q.digest(makeViewPublic(view)),
            enabled: () => !view.is_public && canManageView
          },
          {
            label: _4("Share this view"),
            icon: "bi-share-fill",
            offline: false,
            submenu: () => [{
              component: "sharing-editor-menu-component",
              backAfterAction: true,
              params: {
                object_id: view.id,
                object_type: "view"
              }
            }],
            enabled: () => showShareOptions && (viewMode.shareable === void 0 || viewMode.shareable) && !project.is_portfolio && !project.is_template && (view.share_token && isCurrentUserMemberOfProject(project) || canManageMembers(project))
          },
          {
            label: _4("Add to my work"),
            icon: "bi-clipboard-check",
            offline: false,
            action: () => $q.when(toggleFavoriteView(view), () => makeElementBlink("#nav-sidebar-my-work")),
            enabled: () => showMyWorkOptions && !isFavorite("view", view.id) && !project.is_portfolio && !project.is_template
          },
          {
            label: _4("Export"),
            icon: "download",
            action: () => {
              const opts = view.mode_options || {};
              const availableColumns = cardModelStore.scopedByEnabled(project).getAttributesFromModels().map((a3) => [a3.name, a3.id]).concat(cardGroupTypeStore.scopedByEnabled(project, false).query().map((gt) => [gt.name, -gt.id]));
              let columns2 = [];
              if (opts.visible_attributes) {
                for (let name2 of opts.visible_attributes) {
                  let col = availableColumns.find((c3) => c3[0] === name2);
                  if (col) {
                    columns2.push(col[1]);
                  }
                }
              } else if (view.mode === "table") {
                columns2 = columns2.concat(availableColumns.filter((col) => {
                  if (typeof opts["table_cols_" + col[1]] !== "undefined") {
                    return !!opts["table_cols_" + col[1]];
                  }
                  return true;
                }).map((col) => col[1]));
              }
              if (columns2.length) {
                columns2 = [
                  "_2",
                  "_9"
                  /* title */
                ].concat(columns2);
              }
              projectExportModal.open(project, view.filter, columns2, null, view.include_descendants);
            },
            enabled: () => showExportOptions && canExportData(project) && (view.mode === "table" || !!view.filter || !!view.mode_options.visible_attributes)
          }
        );
      }
      if (viewMode.convertToImage) {
        items.push({
          label: _4("Download as image"),
          icon: "download",
          action: () => viewMode.convertToImage(view.name),
          enabled: () => showExportOptions
        });
      }
      items.push(
        {
          label: _4("Duplicate"),
          icon: "clone",
          submenu: [
            {
              label: labels.duplicateAsPublic(),
              action: () => $q.when(createFromLocalView(view.name, view, true), (v3) => onViewUpdated(v3))
            },
            {
              label: labels.duplicate(),
              action: () => $q.when(createFromLocalView(view.name, view, false), (v3) => onViewUpdated(v3))
            }
          ],
          enabled: () => !!view.project_id && showPrivateOptions && canManageView
        },
        {
          label: labels.duplicateAsPublic(),
          icon: "clone",
          action: () => $q.when(createFromLocalView(view.name, view, true), (v3) => onViewUpdated(v3)),
          enabled: () => !!view.project_id && !showPrivateOptions && canManageView
        },
        {
          label: labels.duplicate(),
          icon: "clone",
          action: () => $q.when(createFromLocalView(view.name, view, false), (v3) => onViewUpdated(v3)),
          enabled: () => !view.project_id && showPrivateOptions && !canManageView
        },
        {
          label: _4("Delete"),
          icon: "trash",
          action: () => {
            let p4;
            if (viewMode.category !== "cards") {
              p4 = confirmDeleteDialog2();
            } else {
              p4 = $q.resolve();
            }
            p4.then(() => {
              $q.digest(deleteView(view));
            });
          },
          enabled: () => canManageView
        }
      );
      return items;
    };
    var watch = function(view, cb2, $scope2) {
      var store2 = getViewStore(view);
      if (store2.isDraftView(view)) {
        return store2.$watchAll($scope2, cb2, false);
      }
      return store2.$watch($scope2, view, ["updated", "removed"], cb2, false);
    };
    return {
      getItems,
      watch,
      get: function(view, options2) {
        var isDraftView = viewStore.isDraftView(view);
        var menuConfig = function() {
          if (isDraftView) {
            return getItemsForDraftView.bind(this, view, options2);
          }
          return getItems.bind(this, view, options2);
        };
        var menuOpts = {
          watch: watch.bind(this, view),
          title: isDraftView ? null : function() {
            return _4("Edit {title}", { title: view.name });
          },
          help: {
            guide: "customization",
            anchor: "save-views",
            label: _4("Learn more about views")
          }
        };
        return {
          config: menuConfig,
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/routes/project/ng-components/batch-popover.js
angular_default.module("kantree").component("projectBatchPopover", {
  templateUrl: "/static/app/routes/project/ng-components/templates/batch-popover.html",
  bindings: {
    context: "<",
    view: "<",
    selectedCards: "<",
    onClear: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "cardBatchEditMenuFactory", "projectExportModal", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.canExport = canExportData(this.context.project);
      this.actionsMenuConfig = { config: () => () => {
        return this.$cardBatchEditMenuFactory.getItems({
          project: this.context.project,
          parent: this.context.board,
          batchParams: {
            card_ids: this.selectedCards
          }
        });
      } };
      this.dropConfig = {
        _fixDropAfterMenuInit: true
      };
    }
    $postLink() {
      this.$scope.$watch(() => this.selectedCards && this.selectedCards.length, (hasSelection3) => {
        this.$element.toggleClass("visible", !!hasSelection3);
      });
    }
    export() {
      this.$projectExportModal.open(this.context.project, null, null, null, null, this.selectedCards);
      this.$scope.$emit("projectBatchEnd");
    }
  }
});

// public/app/services/assistant.js
var onAssistantFeedback = createEvent();
function initAssistant() {
  getPushConnection().then((conn) => {
    conn.on("assistant", (data2) => {
      onAssistantFeedback(data2);
    });
  });
}

// public/app/routes/project/ng-components/nav.js
angular_default.module("kantree").component("projectNav", {
  templateUrl: "/static/app/routes/project/ng-components/templates/nav.html",
  bindings: {
    context: "<",
    view: "<",
    withSettings: "<"
  },
  controller: class extends AngularClass {
    static $inject = [
      "$scope",
      "projectActionsMenuFactory",
      "projectPage",
      "cardActionsMenuFactory",
      "$element",
      "$interval",
      "cardModal",
      "$state",
      "$timeout",
      "projectAddViewModal",
      "mobileMenuFactory",
      "assistantModal"
    ];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isAuthenticated = isAuthenticated;
      this.canAddCard = canAddCard(this.context.project);
      this.isScreensizeXS = isScreensizeXS;
      this.canRunAutomations = this.context.project ? canRunAutomations(this.context.project) : false;
      this.pathMenuDropConfig = {
        classes: "drop-theme-menu drop-theme-arrow",
        tetherOptions: {
          attachment: "top left",
          offset: "0 22px"
        }
      };
      this.context.$watch(this.$scope, "board", () => {
        this.refresh();
      });
      this.projectNotificationStore = store.scoped({ project_id: this.context.project.id });
      this.projectNotificationStore.$watchAll(this.$scope, () => {
        this.hasNewNotif = this.projectNotificationStore.count();
      });
      cardModelStore.scopedByEnabled(this.context.project).subscribeQuery({ base_model_id: query_exports.isUndefined() }, { sortBy: "name" }, (models) => {
        this.setupCreateMenu(models);
      });
      this.refreshMobileMenuDebounced = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshMobileMenu();
        });
      });
      this.refreshMobileMenu();
      ["board", "project", "app", "appOptions", "cardStore"].map((prop2) => {
        return this.context.$watch(this.$scope, prop2, () => {
          this.refreshMobileMenuDebounced();
        }, false);
      });
      const org2 = orgStore.tryGetForProject(this.context.project);
      this.assistantEnabled = org2?.ai_assistant_enabled ?? false;
      if (this.assistantEnabled) {
        this.assistantRunning = false;
        $onEvent(this.$scope, onAssistantFeedback, (data2) => {
          if (data2.project_id !== this.context.project.id) {
            return;
          }
          this.assistantRunning = !["completed", "confirm"].includes(data2.status);
          this.$scope.$applyAsync();
        });
      }
    }
    $onChanges(changes) {
      if (changes.view && this.view) {
        this.viewMode = projectAppRegistry.get(this.view.mode);
        this.showSaveBtn = viewStore.isDraftView(this.view);
      }
    }
    _onClickTitle() {
      if (this.onClickTitle) {
        this.onClickTitle();
      } else {
        jquery_default(this.$element.find(".js-settings")).trigger("click");
      }
    }
    refresh() {
      if (this.deregisterBoardWatcher) this.deregisterBoardWatcher();
      this.deregisterBoardWatcher = cardStore.$watch(this.$scope, this.context.board.id, (board) => {
        this.path = board.path.slice(1);
        this.pathMenuSpec = {
          config: () => this.path.map((parent) => {
            return {
              label: parent.title,
              action: () => this.$state.go("project_board", { projectId: this.context.project.slug, cardRef: parent.ref })
            };
          })
        };
      });
      this.notApprovedDomainMembers = [];
      const notApprovedDomainMembersStore = projectMemberStore.scopedByProject(this.context.project).scoped({
        user: query_exports.objMatch({ is_from_approved_domain: false })
      });
      notApprovedDomainMembersStore.$watchAll(this.$scope, () => {
        this.notApprovedDomainMembers = notApprovedDomainMembersStore.query();
      });
    }
    refreshMobileMenu() {
      this.mobileMenu = this.$mobileMenuFactory.get(this.context);
    }
    setupCreateMenu(models = []) {
      const createItems = [];
      if (this.canAddCard) {
        if (models.length) {
          createItems.push(
            { subheader: _4("Cards") },
            {
              label: _4("No type"),
              action: () => this.openCreateCardModal()
            }
          );
          for (const model of models) {
            createItems.push({
              label: model.name,
              action: () => this.openCreateCardModal({ model_id: model.id })
            });
          }
          createItems.push({ label: "--" });
        } else {
          createItems.push({
            label: _4("Card"),
            action: () => this.openCreateCardModal()
          });
        }
      }
      if (canManageViews(this.context.project)) {
        const createView = (options2) => {
          createFromLocalView("", Object.assign(options2, {
            project_id: this.context.project.id,
            card_ref: this.context.board.ref,
            limit_to_ref: true
          }), true, (view) => this.$projectPage.gotoView(view.id));
        };
        createItems.push(
          {
            label: _4("View"),
            action: () => this.$projectAddViewModal.open(this.context.project, this.context.board, true).then((view) => this.$projectPage.gotoView(view.id))
          },
          {
            label: _4("Form"),
            action: () => createView({ mode: "form" })
          },
          {
            label: _4("Dashboard"),
            action: () => createView({ mode: "report" })
          }
        );
      }
      if (canManageAutomations(this.context.project)) {
        createItems.push(
          {
            label: _4("Automation rule"),
            action: () => {
              this.$projectPage.gotoApp("automations");
              this.$timeout(() => this.$projectPage.trigger("addRule"), 200);
            }
          }
        );
      }
      if (createItems.length) {
        if (createItems[createItems.length - 1].label === "--") {
          createItems.pop();
        }
        this.createMenu = { config: [
          { subheader: _4("Add to the workspace") },
          ...createItems
        ] };
      }
    }
    $postLink() {
      if (typeof ResizeObserver === "undefined") return;
      const resizeObserver = new ResizeObserver((entries2) => {
        for (let entry of entries2) {
          if (entry.target === innerEl) {
            innerWidth = entry.contentRect.width;
            if (!this.shrinked) {
              lastUnshrinkedInnerWidth = innerWidth;
            }
          }
          if (entry.target === outerEl) {
            outerWidth = entry.contentRect.width;
          }
          if (outerWidth && innerWidth) {
            if (lastUnshrinkedInnerWidth) {
              const shrinked = lastUnshrinkedInnerWidth + 150 > outerWidth;
              if (shrinked != this.shrinked) {
                this.$scope.$applyAsync(() => {
                  this.shrinked = shrinked;
                });
              }
            }
            jquery_default(this.$element).find(".board-nav-view-component").toggleClass("shrinked", innerWidth > outerWidth);
          }
        }
      });
      let innerEl, outerEl, innerWidth, lastUnshrinkedInnerWidth, outerWidth;
      let initOuterElPromise = this.$interval(() => {
        outerEl = jquery_default(this.$element).find(".board-nav-view-component-outer")[0];
        if (outerEl) {
          resizeObserver.observe(outerEl);
          this.$interval.cancel(initOuterElPromise);
        }
      }, 100, 40, false);
      initOuterElPromise.then(() => {
        console.warn("nav-view resize can't be observed");
      }).catch(() => {
      }).finally(() => {
        initOuterElPromise = null;
      });
      this.$scope.$on("$destroy", () => {
        if (initOuterElPromise) {
          this.$interval.cancel(initOuterElPromise);
          initOuterElPromise = null;
        }
        if (resizeObserver && outerEl) {
          resizeObserver.unobserve(outerEl);
        }
      });
      const initInnerElResizeObserver = () => {
        let initInnerElPromise = this.$interval(() => {
          innerEl = jquery_default(this.$element).find(".board-nav-view-component-inner")[0];
          if (innerEl) {
            resizeObserver.observe(innerEl);
            this.$interval.cancel(initInnerElPromise);
          }
        }, 100, 40, false);
        initInnerElPromise.then(() => {
          console.warn("nav-view resize can't be observed");
        }).catch(() => {
        }).finally(() => {
          initInnerElPromise = null;
        });
        return () => {
          if (initInnerElPromise) {
            this.$interval.cancel(initInnerElPromise);
          }
          if (resizeObserver && innerEl) {
            resizeObserver.unobserve(innerEl);
          }
        };
      };
      this.deregisterAppWatcher = this.context.watch("app", () => {
        if (this.deregisterInnerElResizeObserver) this.deregisterInnerElResizeObserver();
        this.deregisterInnerElResizeObserver = initInnerElResizeObserver();
      });
    }
    $onDestroy() {
      if (this.deregisterBoardWatcher) this.deregisterBoardWatcher();
      if (this.deregisterAppWatcher) this.deregisterAppWatcher();
      if (this.deregisterInnerElResizeObserver) this.deregisterInnerElResizeObserver();
    }
    openCreateCardModal(card) {
      this.$cardModal.openEmpty(this.context.board, card);
    }
    markAllNotifsAsRead() {
      markAllNotificationsAsRead({ project_id: this.context.project.id });
    }
    openAssistant() {
      this.$assistantModal.open(this.context.project.owner, { project: this.context.project, view: this.view });
    }
  }
});

// public/app/config/project/onboarding-tour-steps.js
var onboardingTourSteps = [];
(async () => {
  await loadServerConfig();
  if (serverConfig.payments_enabled) {
    onboardingTourSteps.push(
      {
        icon: "bi-chat-quote-fill",
        body: _lazy("Hi! Get a free 15 minutes demo to see how Kantree can help your team organize, collaborate and accelerate their work."),
        cta: {
          actionLabel: _lazy("Schedule a Demo"),
          continueLabel: _lazy("No Thanks"),
          action: () => window.open(getLocalizedUrl("demo"))
        },
        back: false,
        dots: false
      },
      {
        icon: "rocket",
        body: _lazy("We have great guides and video tutorials to get you started. Request a demo call at anytime from the Help menu"),
        cta: {
          actionLabel: _lazy("Discover our guides"),
          continueLabel: _lazy("Close"),
          action: () => window.open(getHelpSiteUrl("guides"))
        },
        back: false,
        dots: false
      }
    );
  } else {
    onboardingTourSteps.push(
      {
        title: _lazy("Welcome to your first workspace!"),
        body: _lazy("Add cards and lists to your board. Click on a card to open it."),
        media: prependBaseUrl("/static/assets/tour/videos/tour1.webm")
      },
      {
        title: _lazy("Try different ways to display cards"),
        body: _lazy("Change the visualization mode, grouping, filtering, etc... You can save your settings as a view in the sidebar"),
        media: prependBaseUrl("/static/assets/tour/videos/tour2.webm")
      },
      {
        title: _lazy("Customize fields on cards"),
        body: _lazy("Add or remove fields on cards like you would with columns in a spreadsheet. Adding and removing fields on one card affects all the other cards."),
        media: prependBaseUrl("/static/assets/tour/videos/tour3.webm")
      },
      {
        title: _lazy("Get help and follow Kantree updates"),
        body: _lazy("You will find the help button at the bottom left of the screen. Discover our blog and product updates from the same menu."),
        media: prependBaseUrl("/static/assets/tour/videos/tour4.webm")
      }
    );
  }
})();

// public/app/routes/project/ng-components/onboarding.js
angular_default.module("kantree").service("onboardingTour", class extends AngularClass {
  static $inject = ["$compile", "$rootScope"];
  start() {
    this.stop();
    this.tourScope = this.$rootScope.$new(true);
    this.tourScope.close = () => {
      if (this.tourScope) this.tourScope.$destroy();
      if (this.tourElement) this.tourElement.remove();
      this.tourElement = null;
    };
    this.tourElement = this.$compile('<onboarding-tour on-close="close()"></onboarding-tour>')(this.tourScope);
    this.tourElement.appendTo(jquery_default(document.body));
  }
  stop() {
    if (this.tourScope) this.tourScope.$destroy();
    if (this.tourElement) this.tourElement.remove();
  }
});
angular_default.module("kantree").component("onboardingTour", {
  templateUrl: "/static/app/routes/project/ng-components/templates/onboarding.html",
  bindings: {
    onClose: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$sce", "$q", "$injector"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.steps = onboardingTourSteps;
      this.activeStep(0);
    }
    activeStep(index2) {
      this.stepIndex = index2;
      this.step = this.steps[index2];
      this.titleHtml = this.step.title ? this.$sce.trustAsHtml(this.step.title.toString()) : null;
      this.bodyHtml = this.step.body ? this.$sce.trustAsHtml(this.step.body.toString()) : null;
    }
    nextStep(cta = false) {
      if (this.step.cta?.action && cta) {
        this.$injector.invoke(this.step.cta.action, this.step.cta);
      }
      if (this.stepIndex + 1 === this.steps.length) {
        this.close();
        return;
      }
      this.activeStep(this.stepIndex + 1);
    }
    prevStep() {
      this.activeStep(this.stepIndex - 1);
    }
    close() {
      this.markAsOnboarded();
      this.onClose();
    }
    markAsOnboarded() {
      if ((currentUser2.onboarded || []).includes("project")) {
        return this.$q.resolve();
      }
      return this.$q.when(api_default.user.mark_as_onboarded.post({ step: "project" }), (user) => {
        setCurrentUser(user);
      }).catch(() => this.$q.resolve());
    }
    toggleBig() {
      if (this.backdrop) {
        this.$element.removeClass("big");
        this.backdrop.remove();
        this.backdrop = null;
      } else {
        this.$element.addClass("big");
        this.backdrop = jquery_default('<div class="onboarding-tour-backdrop"></div>').insertBefore(this.$element);
        this.backdrop.on("click", () => this.toggleBig());
      }
    }
    $onDestroy() {
      if (this.backdrop) {
        this.backdrop.remove();
        this.backdrop = null;
      }
    }
  }
});

// public/app/routes/project/ng-components/page.js
angular_default.module("kantree").component("projectPage", {
  bindings: {
    projectId: "<",
    cardRef: "<",
    viewId: "<"
  },
  templateUrl: "/static/app/routes/project/ng-components/templates/page.html",
  controller: class extends AngularClass {
    static $inject = [
      "$scope",
      "$state",
      "projectSidePanel",
      "$element",
      "projectPage",
      "demoSignupModal",
      "projectNavSidebarFactory",
      "$timeout",
      "$location",
      "cardModal",
      "onboardingTour",
      "projectImportErrorsModal",
      "projectCreatorModal",
      "hotkeys",
      "projectTheme",
      "ProjectScopeManager",
      "$q",
      "navSidebar",
      "coach",
      "cardsSelector",
      "assistantModal"
    ];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      document.body.classList.toggle("body-board-view", true);
      loadCharts();
      this.embedded = isEmbedded;
      this.isScreensizeXS = isScreensizeXS;
      this.isAuthenticated = isAuthenticated;
      this.$scope.$watchGroup(["$ctrl.projectId", "$ctrl.cardRef", "$ctrl.viewId"], (newSearchParams, oldSearchParams) => {
        if (oldSearchParams === newSearchParams) this.initScopeManager();
        const [newProjectId, newCardRef, newViewId] = newSearchParams;
        const [oldProjectId, oldCardRef, oldViewId] = oldSearchParams;
        if (newProjectId !== oldProjectId || newCardRef !== oldCardRef) {
          this.initScopeManager();
        } else if (newViewId !== oldViewId) {
          this.scopeManager.setActiveView(newViewId);
        }
      });
      this.$scope.$watch("$ctrl.view", (newView, oldView) => {
        if (oldView === newView) return;
        this.$projectPage.clearSelectedCards();
      });
      this.$scope.$on("projectBatchEnd", () => {
        this.$projectPage.clearSelectedCards();
      });
    }
    $onDestroy() {
      document.body.classList.toggle("body-board-view", false);
      this.clearScopeManager();
    }
    initScopeManager() {
      const project = projectStore.query({ slug: this.projectId });
      if (project.length) {
        this.sidebar = { header: [{
          type: "project-page-header",
          options: { project: project[0] }
        }] };
      } else {
        this.sidebar = null;
      }
      this.loadingErrorMessage = null;
      if (this.scopeManager) {
        this.projectPlaceholderVisible = true;
        this.$element.find("fake-nav-sidebar").show();
        this.clearScopeManager().then(() => {
          this.initScopeManager();
        });
        return;
      }
      this.$ProjectScopeManager.init(this, this.$scope, this.projectId, this.cardRef).then((scopeManager) => {
        this.scopeManager = scopeManager;
        this.$scope.$on("$locationChangeSuccess", () => this.handleLocationHash());
        this.$projectPage.activate(this.$scope, scopeManager);
        this.$projectTheme.activate(this.$scope, this.project);
        updateSubtitle(this.project.title);
        this.sidebar = this.$projectNavSidebarFactory.get(this.project, this.board);
        if (this.project.status) {
          return this.$q.reject("importing");
        }
        cardStore.$watch(this.$scope, this.board, (board) => updateSubtitle(board.title));
        this.projectPlaceholderVisible = true;
        this.lockedOwner = isOrgLocked(this.project.owner);
        this.isOwnerOfProjectOwner = isCurrentUserOwnerOf(this.project);
        return this.handleLocationHash(true);
      }).then(() => {
        this.projectPlaceholderVisible = false;
        this.canCreateProjectFromTemplate = this.project && !this.project.is_archived && (canCurrentUserCreateProjectsIn(this.project.owner) || this.project.is_public || this.project.include_in_template_library);
        this.scopeManager.setActiveView(this.viewId);
        this.$scope.$on("appUnlocked", () => this.$q.digest(updateView(this.view, { locked: false })));
        this.scopeManager.fetchCards();
        if (isAuthenticated() && !this.project.is_template && !this.project.is_archived) {
          addToRecentlyOpenedBoards(this.board);
        }
        if (!!this.project.import_errors) {
          this.$projectImportErrorsModal.open(this.project);
        }
        const firstTimeKey = "firstTimeVisit:" + this.project.id;
        if (jsonLocalStorage.getItem(firstTimeKey) === null) {
          jsonLocalStorage.setItem(firstTimeKey, true);
        } else if (jsonLocalStorage.getItem(firstTimeKey)) {
          jsonLocalStorage.setItem(firstTimeKey, false);
        }
        if (!isEmbedded() && serverConfig.onboarding_tour_enabled && isAuthenticated() && isCurrentUserOwnerOf(this.project) && !currentUser2.onboarded.includes("project") && !this.project.is_template && !(this.project.is_public && !this.editable)) {
          this.$onboardingTour.start();
        }
        this.$coach.setupContextOnScope(this.$scope, {
          org: this.project.owner.id,
          project: this.project.id
        });
        if (isEmbedded()) {
          this.$navSidebar.close($("nav-sidebar-system > nav-sidebar"));
        }
        const org2 = orgStore.tryGetForProject(this.project);
        if (org2?.ai_assistant_enabled) {
          this.$hotkeys.bindTo(this.$scope).add(
            {
              combo: "ctrl+alt+i",
              description: _4("Ask Kantree Assistant"),
              callback: () => {
                this.$assistantModal.open(org2, {
                  project: this.project,
                  card: this.$cardsSelector.top()?.selected
                });
              }
            }
          );
        }
      }).catch((r3) => {
        if (r3 === "importing") {
          this.reloadTimeoutPromise = this.$timeout(() => {
            if (this.project.status && this.project.status !== "error") {
              this.$state.reload();
            }
          }, 5e3);
          return;
        }
        if (typeof r3 === "string") {
          errorDialog(
            _4("An error occured"),
            _4(`Something went wrong while fetching workspace data: ${r3} please reload the page`)
          );
          this.loadingErrorMessage = _4("An error occured");
        } else if (r3.status === 404 || r3.status === 400) {
          this.loadingErrorMessage = _4("Not Found!");
        } else if (r3.status === 403) {
          if (isAuthenticated()) {
            this.loadingErrorMessage = _4("Not Authorized!");
          } else {
            authSession.login();
          }
        } else {
          errorDialog(
            _4("An error occured"),
            _4("Something went wrong while fetching workspace data: please reload the page")
          );
          this.loadingErrorMessage = _4("An error occured");
        }
      });
    }
    clearScopeManager() {
      return this.$q((resolve2) => {
        this.loadingErrorMessage = null;
        clearSubtitle();
        if (this.releaseAnnouncement) {
          this.releaseAnnouncement.close(false);
        }
        this.$onboardingTour.stop();
        if (this.reloadTimeoutPromise) {
          this.$timeout.cancel(this.reloadTimeoutPromise);
        }
        if (this.scopeManager) {
          this.project = null;
          this.board = null;
          this.context = null;
          this.scopeManager.destroy().then(() => {
            this.scopeManager = null;
            resolve2();
          });
        } else {
          resolve2();
        }
      });
    }
    handleLocationHash(pageLoad) {
      let hash = this.$location.hash();
      if (hash.match(/[0-9]+/)) {
        if (!this.$cardModal.current || hash != this.$cardModal.currentLocationHash) {
          let wasDocked;
          if (pageLoad) {
            wasDocked = this.$cardModal.isDocked();
            this.$cardModal.toggleDocked(false);
          }
          const modalOptions = pageLoad && isEmbedded() ? { showClose: false, cssClass: "card-modal-full-screen" } : {};
          this.$cardModal.currentLocationHash = hash;
          return this.$cardModal.loadByRef(this.project, hash, modalOptions, true).then(() => {
            if (wasDocked) {
              this.$cardModal.toggleDocked(true);
            }
          });
        }
      } else if (!hash && this.$cardModal.current && this.$cardModal.currentLocationHash !== null) {
        return this.$cardModal.close();
      }
      return this.$q.resolve();
    }
    joinProject() {
      this.$q.when(joinProject(this.project), () => {
        fetchAppContextData();
        this.$state.reload();
      });
    }
    // TODO: remove this when board-scoped contexts are completely converted to project-scoped
    openConvertContextScopeModal() {
      if (isAllowedInProject(this.project, "card_group_type", ["CREATE", "EDIT", "DELETE"]) && cardGroupTypeStore.scopedByEnabled(this.project).scoped({ scope: "card" }).count() && isConnected() && projectMemberStore.scopedByProject(this.project).getByUserId(currentUser2.id)) {
        this.$convertContextScopeModal.open(this.project);
      }
    }
    openCreateProjectFromTplModal() {
      if (!isAuthenticated()) {
        if (this.$state.params.demo) {
          this.$demoSignupModal.open(this.project, this.$state.params.demo);
        } else {
          document.location = "/signup?utm_source=kantree&utm_campaign=workspace&create_project_from=" + this.project.id;
        }
        return;
      }
      if (!isCurrentUserOwnerOf(this.project) || isCurrentUserPersonalOrg(this.project.owner)) {
        this.$projectCreatorModal.open({ template: this.project });
      } else {
        this.$q.when(loadOrg(this.project.owner.id, { ignoreErrorHandlers: true }), (org2) => {
          this.$projectCreatorModal.open({ org: org2, template: this.project });
        }, (r3) => {
          console.warn(r3);
        });
      }
    }
    importKeepProject() {
      this.$q.digest(updateProject(this.project, { keep_failed_import: true }));
    }
    importDeleteProject() {
      this.$q.digest(deleteProject(this.project));
      this.$state.go("globalHome");
    }
  }
});

// public/app/routes/project/ng-components/placeholder.js
angular_default.module("kantree").component("projectPlaceholder", {
  template: `
    <div class="column-placeholder" ng-repeat="column in $ctrl.columns track by $index"
      ng-style="{height: column.height}"></div>
  `,
  controller: class extends AngularClass {
    $onInit() {
      this.columns = new Array(this.createRandomInt(5, 10)).fill(0).map((v3) => this.createColumn());
    }
    createColumn() {
      return {
        height: this.createRandomInt(200, 800)
      };
    }
    createRandomInt(min3, max3) {
      min3 = Math.ceil(min3);
      max3 = Math.floor(max3);
      return Math.floor(Math.random() * (max3 - min3 + 1)) + min3;
    }
  }
});

// public/app/routes/project/ng-components/side-panel.js
angular_default.module("kantree").component("projectSidePanel", {
  template: `
    <div class="project-side-panel-header">
      <span class="project-side-panel-header-title">{{$ctrl.$projectSidePanel.panel.title}}</span>
      <a href ng-click="$ctrl.closeSidebar()" class="btn btn-icon"><i class="fa fa-times"></i></a>
    </div>
    <div class="project-side-panel-content" ng-class="$ctrl.$projectSidePanel.panel.name">
      <dynamic-directive project="$ctrl.context.project" board="$ctrl.context.board"
        directive="{{$ctrl.$projectSidePanel.panel.component}}"></dynamic-directive>
    </div>
  `,
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "projectSidePanel", "$rootScope"];
    $onInit() {
      this.context.$watch(this.$scope, "project", () => this.refreshSidebar());
    }
    refreshSidebar() {
      this.$projectSidePanel.panel = jsonLocalStorage.getItem("project:" + this.context.project.id + ":sidebar-panel");
      this.$projectSidePanel.$on(this.$scope, "panelChanged", (panel) => {
        jsonLocalStorage.setItem("project:" + this.context.project.id + ":sidebar-panel", panel ? panel.name : null);
        this.$rootScope.$broadcast("projectSidePanelToggled");
      });
    }
    closeSidebar() {
      this.$projectSidePanel.panel = null;
    }
  }
});
angular_default.module("kantree").component("projectSidePanelGuide", {
  templateUrl: "/static/app/routes/project/ng-components/templates/panel-guide.html",
  bindings: {
    project: "<",
    board: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    get localStorageDraftKey() {
      return `${this.project.id}-project-guide`;
    }
    edit(discard) {
      if (discard) {
        this.draft = null;
        jsonLocalStorage.setItem(this.localStorageDraftKey, null);
      }
      this.editing = true;
    }
    async save(content2) {
      if ((this.project.guide || "") !== content2) {
        return this.$q.when(updateProjectGuide(this.project, content2), () => {
          this.editing = false;
        });
      } else {
        this.editing = false;
        return Promise.resolve();
      }
    }
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isConnected = isConnected;
      this.refreshProject();
    }
    $onChanges(changes) {
      if (changes.project && !changes.project.isFirstChange()) {
        this.refreshProject();
      }
    }
    refreshProject() {
      this.draft = jsonLocalStorage.getItem(this.localStorageDraftKey);
      this.guideOptions = { draftDelay: 1e3, uuid: this.localStorageDraftKey };
      if (this.deregisterProjectWatcher) this.deregisterProjectWatcher();
      this.deregisterProjectWatcher = projectStore.$watch(this.$scope, this.project, (project) => {
        this.project = project;
        this.canEdit = canManageSettings(this.project);
        this.refreshGuide();
      });
    }
    refreshDraft() {
      this.draft = jsonLocalStorage.getItem(this.localStorageDraftKey);
    }
    refreshGuide() {
      if (!this.project.has_guide || this.project.guide) return;
      this.loading = true;
      this.$q.when(loadProjectGuide(this.project), () => {
        this.loading = false;
      }, () => {
        console.warn("Workspace guide couldn't be loaded", e);
        this.error = true;
        this.loading = false;
      });
    }
  }
});

// public/app/routes/project/services/nav-sidebar.js
angular_default.module("kantree").service("projectNavSidebarFactory", class extends AngularClass {
  static $inject = ["$state", "projectPage", "projectSidePanel"];
  getFixedContentItems(project, board) {
    const items = [];
    if (board.parent_id) {
      items.push({
        type: "link",
        options: {
          label: _4("Go to parent board"),
          icon: "bi-arrow-90deg-up",
          href: board.path.length > 1 ? this.$state.href("project_board", { projectId: project.slug, cardRef: board.path[board.path.length - 1].ref }) : this.$state.href("project", { projectId: project.slug })
        }
      });
    }
    items.push({
      type: "button",
      options: {
        label: _4("Workspace guide"),
        icon: "bi-book",
        action: (event2) => {
          this.$projectSidePanel.panel = (this.$projectSidePanel.panel || {}).name === "guide" ? null : "guide";
        }
      },
      enabled: () => project.has_guide && !isScreensizeXS()
    });
    if (isAuthenticated()) {
      items.push(...projectAppRegistry.getAll().filter((app) => !!app.noView && !app.hideFromSidebar).sort((a3, b3) => (a3.priority || 100) - (b3.priority || 100)).map((app) => {
        return {
          type: "button",
          options: {
            label: app.title,
            icon: app.icon,
            action: (event2) => {
              this.$projectPage.gotoApp(app.name);
            }
          },
          active: () => this.$projectPage.context && this.$projectPage.context.app && this.$projectPage.context.app.name === app.name,
          enabled: () => !isScreensizeXS() && isConnected() && !board.parent_id && projectStore.tryGet(project.id)?.system_apps?.includes(app.name)
        };
      }));
    }
    return items;
  }
  getContentItems(project, board) {
    const items = [];
    const categoryStore = viewCategoryStore.scopedByProject(project);
    const boardViewStore = viewStore.scopedByBoard(project, board, true);
    const subBoardStore = cardStore.scoped({
      project_id: project.id,
      parent_id: query_exports.notNull(),
      board_created: query_exports.isTruthy()
    });
    const canEdit = isAuthenticated() && canManageViews(project);
    items.push(
      {
        type: "view-categories",
        options: {
          categoryStore,
          viewStore: boardViewStore.scoped({ is_public: true }),
          storageKey: `sharedViews-${project.id}-$CATID`,
          project,
          board,
          showCreateCategory: canEdit,
          showCreateView: canEdit,
          createView: canEdit,
          createPublicView: true,
          showNoCategoryViews: true
        }
      },
      {
        type: "view-list",
        options: {
          label: _4("Private views"),
          store: boardViewStore.scoped({ is_public: false }),
          indicator: "lock",
          storageKey: `privateViews-${project.id}`,
          project,
          board,
          showCreate: isAuthenticated(),
          create: isAuthenticated(),
          hideWhenEmpty: !isAuthenticated()
        }
      },
      {
        type: "board-list",
        options: {
          label: _4("Sub-boards"),
          store: subBoardStore,
          storageKey: `subBoards-${project.id}`,
          icon: "sitemap",
          hideWhenEmpty: true
        }
      }
    );
    return items;
  }
  getHeaderItems(project, board) {
    return [{
      type: "project-page-header",
      options: {
        project,
        board
      }
    }];
  }
  get(project, board) {
    const header = { header: this.getHeaderItems(project, board) };
    if (project.status) {
      return { ...header };
    }
    return {
      ...header,
      fixedContent: this.getFixedContentItems(project, board),
      content: this.getContentItems(project, board)
    };
  }
});

// public/app/routes/project/services/side-panel.js
var projectSidePanels = [
  {
    name: "guide",
    title: _lazy("Workspace guide"),
    icon: "fa-book",
    component: "project-side-panel-guide"
  }
];
angular_default.module("kantree").service("projectSidePanel", class extends angularClassMixin(AngularClass, EventedMixin) {
  constructor(...args) {
    super(...args);
    this.initEventedMixin();
  }
  get panel() {
    return this._panel;
  }
  set panel(panel) {
    this._panel = !!panel ? projectSidePanels.find((p4) => p4.name === panel) : null;
    this.trigger("panelChanged", this._panel);
  }
});

// public/app/routes/project/index.jsx
function ProjectPage() {
  const params = useParams();
  const [searchParams] = useSearchParams();
  return createComponent(ColorizedPage, {
    get children() {
      return createComponent(NgComponent, {
        directive: "project-page",
        get projectId() {
          return params.projectId;
        },
        get cardRef() {
          return params.cardRef;
        },
        get viewId() {
          return searchParams.view;
        }
      });
    }
  });
}
addRoute({
  name: "project",
  path: "/p/:projectId",
  colorized: true,
  noSidebarForAnonymous: true,
  component: ProjectPage
});
addRoute({
  name: "project_board",
  path: "/p/:projectId/:cardRef",
  colorized: true,
  noSidebarForAnonymous: true,
  component: ProjectPage
});

// public/app/routes/request/ng-components/request.js
angular_default.module("kantree").directive("requestPage", function() {
  return {
    //---act as component
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    replace: true,
    //---
    templateUrl: "/static/app/routes/request/ng-components/templates/request-page.html",
    controller: class extends AngularClass {
      static $inject = ["$scope", "$state", "$sce", "$q"];
      $onInit() {
        injectI18nHelpersIntoScope(this.$scope);
        this.loading = true;
        if (this.$state.params.confirm) {
          this.confirmMessage = _4('<p class="d-inline-block"><strong>Your request has been successfully submitted.</strong></p><p>This is a recap of your request as well as its tracking page. You will also receive a confirmation email with the link to this page.</p>');
          if (this.$state.params.confirm === "support") {
            this.confirmMessage += _4("<p>One of our support agent will contact you shortly</p>");
          }
          this.confirmMessage = this.$sce.trustAsHtml(this.confirmMessage);
          this.requestJustCreated = true;
        }
        this.$q.when(loadRequest(this.$state.params.requestToken, { ignoreErrorHandlers: true }), (request2) => {
          this.request = request2;
          this.loading = false;
        }, (r3) => {
          if (r3.status === 401) {
            authSession.login();
            return;
          }
          if (r3.status === 403) {
            this.error = _4("Not authorized");
          } else {
            this.error = _4("Not found");
          }
          this.loading = false;
        });
      }
    }
  };
});

// public/app/routes/request/index.jsx
addRoute({
  name: "request",
  path: "/r/:requestToken",
  component: () => createComponent(HideSystemSidebar, {
    get children() {
      return createComponent(UnavailableOffline, {
        get children() {
          return createComponent(NgComponent, {
            directive: "request-page"
          });
        }
      });
    }
  })
});

// public/app/apps/cards/common/context-mixin.js
var CardsContextMixin = {
  get cardStore() {
    throw new NotImplementedError();
  },
  set cardStore(store2) {
    throw new NotImplementedError();
  },
  // get modelStore() {
  //   throw new NotImplementedError();
  // },
  // set modelStore(store) {
  //   throw new NotImplementedError();
  // },
  // get groupTypeStore() {
  //   throw new NotImplementedError();
  // },
  // set groupTypeStore(store) {
  //   throw new NotImplementedError();
  // },
  // get groupStore() {
  //   throw new NotImplementedError();
  // },
  // set groupStore(store) {
  //   throw new NotImplementedError();
  // },
  get matchingCardIds() {
    throw new NotImplementedError();
  },
  set matchingCardIds(ids) {
    throw new NotImplementedError();
  },
  updateMatchingCardIdsWithCard(card, isMatching) {
    throw new NotImplementedError();
  }
};

// public/app/apps/project/context.js
var ProjectContext2 = class extends extendWithMixin(BaseContext, CardsContextMixin, ReportContextMixin) {
  constructor(config3, app, appOptions) {
    super(config3, app, appOptions);
  }
  get cardStore() {
    return this._cardStore;
  }
  set cardStore(store2) {
    const oldStore = this._cardStore;
    this._cardStore = store2.scopedByProject(this.project);
    this._afterChange("cardStoreChanged", this._cardStore, oldStore);
  }
  // Project filtering
  get matchingCardIds() {
    return this._matchingCardIds;
  }
  set matchingCardIds(ids) {
    this._matchingCardIds = ids;
    this._afterChange("matchingCardIdsChanged", ids);
  }
  updateMatchingCardIdsWithCard(card, isMatching) {
    const wasMatching = this._matchingCardIds.includes(card.id);
    if (isMatching && !wasMatching) {
      this._matchingCardIds = this._matchingCardIds.concat([card.id]);
      this._afterChange("matchingCardIdsChanged", this._matchingCardIds);
    } else if (!isMatching && wasMatching) {
      this._matchingCardIds = this._matchingCardIds.filter((i3) => i3 !== card.id);
      this._afterChange("matchingCardIdsChanged", this._matchingCardIds);
    }
  }
  get shouldRenderFilteredCards() {
    return this._shouldRenderFilteredCards;
  }
  set shouldRenderFilteredCards(newVal) {
    const oldVal = this._shouldRenderFilteredCards;
    if (!oldVal && oldVal !== newVal) {
      this._shouldRenderFilteredCards = true;
      this._afterChange("shouldRenderFilteredCardsChanged", true, false);
    }
  }
};

// public/app/loaders/shared-obj.ts
function sideloadBase(object2) {
  if (object2.mode_options?.visible_attributes && object2.shareOptions.only_show_fields_from_view_settings) {
    object2.project.attributes = object2.project.attributes?.filter((attr) => {
      return object2.mode_options?.visible_attributes.includes(attr.name);
    });
    object2.org.attributes = object2.org.attributes?.filter((attr) => {
      return object2.mode_options?.visible_attributes.includes(attr.name);
    });
  }
  object2.org = orgStore.upsert(object2.org);
  object2.project = projectStore.upsert(sideLoadProject(object2.project));
  object2.board = sideLoadBoard(object2.project);
  object2.activities.forEach(function(el2) {
    if (!object2.shareOptions.only_show_request_comments || el2.stream_type === "comment" && el2.show_in_request) {
      activityStore.upsert(el2);
    }
  });
  object2.group_types.forEach(function(el2) {
    cardGroupTypeStore.upsert(el2);
  });
}
function sideloadCard(card, {
  visible_attributes = null,
  with_groups = false,
  with_card_update = false,
  only_show_request_comments = false
} = {}) {
  if (with_card_update) {
    cardStore.insert(card);
  }
  if (card.parent && card.parent.id && !cardStore.exists(card.parent.id)) {
    cardStore.insert(card.parent);
  }
  if (card.model && card.model.id && !cardModelStore.exists(card.model.id)) {
    if (visible_attributes) {
      card.model.attributes = card.model.attributes?.filter((attr) => {
        return visible_attributes.includes(attr.name);
      });
    }
    cardModelStore.insert(card.model);
  }
  if (with_groups) {
    card.groups.forEach(function(el2) {
      if (!el2.id || !cardGroupStore.exists(el2.id)) {
        cardGroupStore.insert(el2);
      }
    });
  }
  card.log_types.forEach(function(el2) {
    if (!el2.id || !projectLogTypeStore.exists(el2.id)) {
      projectLogTypeStore.insert(el2);
    }
  });
  card.stream.forEach(function(el2) {
    if (!el2.id || !activityStore.exists(el2.id)) {
      if (!only_show_request_comments || el2.stream_type === "comment" && el2.show_in_request) {
        activityStore.insert(el2);
      }
    }
  });
  card.attributes.forEach(function(el2) {
    if (el2.type == "members") {
      el2.value.forEach(function(m3) {
        projectMemberStore.upsert(projectMemberStore.format({ project_id: card.project_id, user: unwrap(m3) }));
      });
    }
  });
  if (card.related_cards) {
    for (const related_card of card.related_cards) {
      if (!cardStore.exists(related_card.id)) {
        cardStore.insert({ ...related_card, ref: null });
      }
    }
  }
}
var loader9 = new StoreLoader(cardStore);
function loadCardsInSharedView(token, widgetId, sideloadOptions = {}) {
  loader9.callbacks.sideload = (card) => {
    sideloadCard(unwrap(card), sideloadOptions);
  };
  return loader9.loadPaginated(api_default.share_objects.list_cards, {
    token,
    widget_id: widgetId,
    sort: "smart"
  }, {
    sideload: (card) => {
      sideloadCard(unwrap(card), sideloadOptions);
    }
  });
}

// public/app/routes/share/ng-components/share-view.js
function mayUpdateGroupByAfterUpdatingCards(view, context) {
  const group_by = formatSpecFromView(view);
  if (group_by.some((spec) => spec.type === "attribute") && context) {
    context.appOptions = Object.assign({}, context.appOptions, { group_by });
  }
}
angular_default.module("kantree").directive("shareView", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        view: "<",
        project: "<",
        board: "<"
      },
      template: `
        <div class="share-body">
          <div class="project-view-container" ng-if="$ctrl.view">
            <dynamic-directive directive="{{$ctrl.context.app.component}}" context="$ctrl.context"></dynamic-directive>
          </div>
        </div>
      `,
      controller: class extends AngularClass {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element"]);
        }
        mayUpdateGroupByAfterUpdatingCardsDebounced = debounce2(() => this.$scope.$applyAsync(() => {
          mayUpdateGroupByAfterUpdatingCards(this.view, this.context);
        }), 100);
        $onChanges(changes) {
          if (this.view) {
            sideloadBase(this.view);
            viewStore.upsert(Object.keys(this.view).filter((key2) => {
              return ["project", "activities", "analytics", "group_types", "board"].indexOf(key2) === -1;
            }).reduce((accu, key2) => {
              accu[key2] = this.view[key2];
              return accu;
            }, {}));
            if (this.view.cards) {
              this.mayUpdateGroupByAfterUpdatingCardsDebounced();
            } else {
              if (this.cardWatcherOff) this.cardWatcherOff();
              this.cardWatcherOff = cardStore.$watchAll(this.$scope, () => {
                this.mayUpdateGroupByAfterUpdatingCardsDebounced();
              });
            }
            const { appName, appOptions } = getContextParamsFromView(this.view);
            const app = projectAppRegistry.get(appName, true, true);
            if (this.context) this.context.destroy();
            if ((!this.view.project || this.view.project.is_portfolio) && this.view.filter_scopes) {
              this.context = new GlobalContext({ filterScopes: this.view.filter_scopes }, app, appOptions);
              this.context.cardStore = [];
              throw Error("WIP: Not working");
            } else {
              this.context = new ProjectContext2({
                project: this.view.project,
                board: this.view.board,
                cardStore: cardStore.scoped({
                  is_template: query_exports.isFalsy(),
                  is_archived: (v3) => this.context.appOptions?.include_archived ? true : !v3,
                  path: (path) => this.context.appOptions?.include_descendants ? query_exports.matchArray(path, (card) => card.id === this.view.board.id.toString()) : true,
                  parent_id: (id) => this.context.appOptions?.include_descendants ? true : this.view.board.id === id
                }),
                readonly: true
              }, app, appOptions);
            }
            this.context.shareMode = true;
            this.context.shareModeData = this.view;
            if (!!this.view.is_filtered) {
              if (this.view.cards) {
                this.context.matchingCardIds = this.view.cards.map((c3) => c3.id);
              } else {
                this.$scope.$on("updateSharedViewMatchingCardIds", (event2, ids) => {
                  this.context.matchingCardIds = ids;
                  this.$scope.$broadcast("shouldRenderFilteredCards", false);
                });
              }
            }
          }
        }
        $onDestroy() {
          if (this.context) this.context.destroy();
        }
      }
    };
  }
]);

// public/app/routes/share/ng-components/share-card.js
angular_default.module("kantree").directive("shareCard", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        card: "<"
      },
      template: `
        <div class="share-body">
          <div class="card-view-container" ng-if="$ctrl.card">
            <card-view card="$ctrl.card"></card-view>
          </div>
        </div>
      `,
      controller: class extends AngularClass {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element"]);
        }
        $onChanges(changes) {
          if (this.card) {
            sideloadBase(this.card);
            sideloadCard(this.card, {
              with_groups: true,
              with_card_update: true,
              only_show_request_comments: this.card.shareOptions.only_show_request_comments
            });
            for (const card of this.card.children) {
              sideloadCard(card, {
                with_groups: true,
                with_card_update: true,
                only_show_request_comments: this.card.shareOptions.only_show_request_comments
              });
            }
          }
        }
      }
    };
  }
]);

// public/app/routes/share/ng-components/share-page.js
angular_default.module("kantree").component("sharePage", {
  bindings: {
    token: "<"
  },
  templateUrl: "/static/app/routes/share/ng-components/templates/share-page.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "$q", "$rootScope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      disableConnectionManager();
    }
    $onChanges() {
      this.loading = true;
      this.currentUser = currentUser2;
      this.sharedCard = null;
      this.sharedView = null;
      this.$q.when(api_default.share_objects.get.get({ token: this.token }, { ignoreErrorHandlers: true }), (sharing) => {
        var projectId = sharing.object.project_id;
        this.loading = false;
        if (isAuthenticated()) {
          this.$q.when(api_default.projects.get_board.get({ project_id: projectId }, { ignoreErrorHandlers: true }), (project) => {
            if (sharing.object_type === "card") {
              this.$state.go("project", { projectId: project.slug, "#": sharing.object.ref });
            } else if (sharing.object_type === "view") {
              this.$state.go("project", { projectId: project.slug, view: sharing.object.id });
            }
          }, (r3) => {
            this.openSharedLink(sharing);
          });
        } else {
          this.openSharedLink(sharing);
        }
      }, (r3) => {
        this.loading = false;
        if (isEmbedded()) {
          if (r3.status === 403) {
            this.error = _4("Not authorized");
          } else {
            this.error = _4("Not found");
          }
          return;
        }
        if (isAuthenticated()) {
          this.$state.go("/");
        } else {
          authSession.login();
        }
      });
    }
    openSharedLink(sharing) {
      cardStore.resetWithoutLocalStorage();
      projectStore.resetWithoutLocalStorage();
      cardModelStore.resetWithoutLocalStorage();
      cardGroupStore.resetWithoutLocalStorage();
      projectLogTypeStore.resetWithoutLocalStorage();
      projectMemberStore.resetWithoutLocalStorage();
      sharing.object.shareOptions = sharing.options || {};
      if (sharing.object_type == "card") {
        this.sharedCard = sharing.object;
        jquery_default(".kantree-logo").css("display", "block");
      } else if (sharing.object_type == "view") {
        jquery_default(".kantree-logo").css("display", "block");
        sharing.object.forms = sharing.forms;
        this.sharedView = sharing.object;
        const sideloadOptions = {
          only_show_request_comments: this.sharedView.shareOptions.only_show_request_comments,
          visible_attributes: this.sharedView.shareOptions.only_show_fields_from_view_settings && this.sharedView.mode_options?.visible_attributes
        };
        if (this.sharedView.mode == "report") {
          sharing.object.analytics.forEach((widget, index2) => {
            if (widget.type === "cards") {
              sharing.object.analytics[index2] = { ...widget, processing: true };
              this.$q.when(loadCardsInSharedView(this.token, index2, sideloadOptions), (cards) => {
                sharing.object.analytics[index2] = { ...widget, cards };
              });
            }
          });
        } else {
          this.$q.when(loadCardsInSharedView(this.token, null, sideloadOptions), (cards) => {
            sharing.object.cards = cards || [];
            this.$rootScope.$broadcast("updateSharedViewMatchingCardIds", cards?.map((c3) => c3.id));
          });
        }
      }
    }
    openForm(form) {
      window.open(makeUrlAbsolute(this.$state.href("request_form", { formSlug: form.slug })));
    }
    login() {
      authSession.login();
    }
    signup() {
      authSession.signup();
    }
  }
});

// public/app/routes/share/index.jsx
addRoute({
  name: "share",
  path: "/share/:token",
  component: () => {
    const params = useParams();
    return createComponent(HideSystemSidebar, {
      get children() {
        return createComponent(NgComponent, {
          directive: "share-page",
          get token() {
            return params.token;
          }
        });
      }
    });
  }
});

// public/app/routes/template-lib/ng-components/library.js
angular_default.module("kantree").component("templateLibrary", {
  bindings: {
    tag: "<"
  },
  templateUrl: "/static/app/routes/template-lib/ng-components/templates/library.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "$q", "projectCreatorModal", "navSidebar"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      bindToScope(this.$scope, updateSubtitle(_4("Template library")));
      this.isOrgManager = isOrgManager;
      this.onboarding = !!this.$state.params.onboarding;
      this.preferredTag = currentUser2.preferred_template_library_tag;
      if (isObject2(serverConfig.template_library_featured_tag)) {
        this.featuredTag = serverConfig.template_library_featured_tag[getCurrentLocale()] || null;
      } else {
        this.featuredTag = serverConfig.template_library_featured_tag;
      }
      if (this.$state.params.org) {
        this.org = orgStore.tryGet(parseInt(this.$state.params.org));
      }
      if (this.$state.params.team) {
        this.team = teamStore.tryGet(parseInt(this.$state.params.team));
      }
      if (this.org) {
        this.canUse = isAuthenticated() && (currentUser2.is_kantree_admin || appContext.orgs.some((spec) => spec.org.id === this.org.id && spec.canCreate));
        if (!this.canUse) {
          this.org = null;
        }
      }
      if (!this.org) {
        this.canUse = !isAuthenticated() || currentUser2.is_kantree_admin || currentUser2.can_create_projects || appContext.orgs.some((spec) => spec.canCreate);
      }
      this.loading = true;
      this.tags = [];
      this.templatesByTags = {};
      this.orgs = {};
      this.currentTag = null;
      if (this.canUse && isAuthenticated()) {
        this.addBlankTag();
      }
      this.setupSidebar();
    }
    $onChanges() {
      this.refreshTemplates();
    }
    refreshTemplates() {
      this.tags = [];
      this.orgs = {};
      this.featuredOrgTemplates = null;
      const loaders = [
        loadTemplates().then(([tags2, templatesByTags]) => {
          this.tags = tags2;
          Object.assign(this.templatesByTags, templatesByTags);
        })
      ];
      if (isAuthenticated()) {
        loaders.push(api_default.template_library.list_used.get().then((data2) => {
          this.templatesByTags["__recent__"] = data2;
        }));
        const addOrgTemplates = (org2, templates) => {
          const tag = `__org${org2.id}__`;
          this.orgs[tag] = org2;
          templates = templates.map((t3) => Object.assign(t3, { noview: true }));
          this.templatesByTags[tag] = templates;
          if (this.org?.id === org2.id && templates.length) {
            this.featuredOrgTemplates = templates;
          }
          return templates;
        };
        if (currentUser2.can_create_projects) {
          loaders.push(api_default.template_library.list_from_user.get().then((data2) => {
            addOrgTemplates({ id: "private", name: _4("Your private templates"), isManager: true }, data2);
          }));
        }
        let orgs = appContext.orgs.filter((org2) => !!appContext.pinnedOrgs.find((o3) => org2.id === o3.id)).map((o3) => o3.org);
        if (this.org && !appContext.pinnedOrgs.find((o3) => o3.id === this.org.id)) {
          orgs.unshift(this.org);
        }
        orgs.forEach((org2) => {
          loaders.push(api_default.template_library.list_from_org.get({ org_id: org2.id }).then((data2) => addOrgTemplates(org2, data2)));
        });
      }
      this.$q.all(loaders).then(() => {
        this.loading = false;
        if (this.featuredTag && this.tags.includes(this.featuredTag)) {
          this.tags.splice(this.tags.indexOf(this.featuredTag), 1);
        }
        if (this.blankTag) {
          this.tags.push(this.blankTag);
        }
        this.setupSidebar();
        if (this.tag) {
          const defaultTag = this.tags.find((t3) => t3.replace(/\s/g, "").toLowerCase() === this.tag.replace(/\s/g, "").toLowerCase());
          if (defaultTag) {
            this.selectTag(defaultTag);
          }
        }
        if (this.$state.params.tpl) {
          for (let templates of Object.values(this.templatesByTags)) {
            for (let template3 of templates) {
              if (template3.id == this.$state.params.tpl) {
                this.onTileClick(template3);
                return;
              }
            }
          }
        }
      }).catch((r3) => {
        console.log(r3);
        this.loading = false;
      });
    }
    addBlankTag() {
      this.blankTag = _4("From scratch");
      this.templatesByTags[this.blankTag.replace(/\s/g, "").toLowerCase()] = serverConfig.base_project_templates.map((tpl) => {
        return {
          id: tpl.name,
          color: "#b3ecd2",
          title: _4(tpl.title),
          icon: tpl.icon,
          description: _4(tpl.desc),
          noview: true,
          fromScratch: true
        };
      }).concat([
        {
          color: "#b3ece4",
          title: _4("Import from spreadsheet"),
          icon: "file-excel-o",
          description: _4("Import from XSLX, CSV, and ODT files"),
          importer: "spreadsheet"
        },
        {
          color: "#b3ece4",
          title: _4("Import from other apps"),
          icon: "cloud-download",
          description: _4("Import your existing workspace from third-party apps"),
          importer: "1"
        },
        {
          color: "#e1e6eb",
          title: _4("Empty"),
          description: _4("Creates an empty workspace"),
          noview: true
        }
      ]);
    }
    setupSidebar() {
      const content2 = [{
        type: "button",
        options: {
          label: this.canUse && isAuthenticated() ? _4("Start") : _4("Featured"),
          icon: "rocket",
          action: () => this.selectTag(null)
        },
        active: () => !this.currentTag
      }];
      if (this.templatesByTags["__recent__"] && this.templatesByTags["__recent__"].length) {
        content2.push({
          type: "button",
          options: {
            label: _4("Recently used"),
            icon: "clock-o",
            action: () => this.selectTag("__recent__")
          },
          active: () => this.currentTag === "__recent__"
        });
      }
      content2.push({ type: "separator" });
      if (this.orgs) {
        Object.values(this.orgs).sort((o3) => o3.name).forEach((org2) => {
          const tag = `__org${org2.id}__`;
          content2.push({
            type: "button",
            options: {
              label: org2.name,
              icon: org2.id === "private" ? "user" : "bi-building",
              action: () => this.selectTag(tag)
            },
            active: () => this.currentTag === tag
          });
        });
        if (Object.keys(this.orgs).length) {
          content2.push({ type: "separator" });
        }
      }
      for (let tag of this.tags) {
        content2.push({
          type: "button",
          options: {
            label: tag,
            action: () => this.selectTag(tag)
          },
          active: () => this.currentTag && this.currentTag.replace(/\s/g, "").toLowerCase() === tag.replace(/\s/g, "").toLowerCase()
        });
      }
      this.sidebarConfig = {
        header: [{
          type: "page-header",
          options: { title: isAuthenticated() ? _4("Template library") : _4("Kantree Templates") }
        }],
        content: content2
      };
    }
    selectTag(tag) {
      this.currentTag = tag;
      this.template = null;
      if (isScreensizeXS()) {
        this.$navSidebar.close();
      }
    }
    getTagTemplates(tag, sorted = true) {
      let templates = this.templatesByTags[tag.replace(/\s/g, "").toLowerCase()] || [];
      if (sorted && tag !== this.blankTag) {
        return templates.sort((a3, b3) => a3.title.localeCompare(b3.title));
      }
      return templates;
    }
    onTileClick(template3) {
      this.$scope.$applyAsync(() => {
        if (this.orgs[this.currentTag]) {
          this.$state.go("project", { projectId: template3.slug });
        } else if (template3.viewMode) {
          this.$projectCreatorModal.open({ org: this.org, team: this.team, defaultViewMode: template3.viewMode.name });
        } else if (template3.importer) {
          this.$projectCreatorModal.open({ org: this.org, team: this.team, importer: template3.importer });
        } else if (template3.noview && this.canUse) {
          this.$projectCreatorModal.open({ org: this.org, team: this.team, template: template3 });
        } else {
          this.template = template3;
        }
      });
    }
    createTemplate(org2) {
      this.$projectCreatorModal.open({ org: org2.id === "private" ? null : org2, createTemplate: true });
    }
  }
});
angular_default.module("kantree").component("templateLibraryTile", {
  template: `
    <div ng-style="{'background-image': $ctrl.template.image_cover_url ? ('url(' + $ctrl.template.image_cover_url + ')') : '',
      'background-color': $ctrl.template.color}" class="cover"><i ng-class="$ctrl.template.icon|iconClass" ng-if="$ctrl.template.icon"></i></div>
    <div class="body">
      <div class="title">{{$ctrl.template.title}}</div>
      <div class="desc">{{$ctrl.template.description|ellipsis:65}}</div>
    </div>
    <button ng-click="$event.stopPropagation(); $ctrl.delete()" ng-show="$ctrl.canDelete"><i class="bi-trash"></i></button>
  `,
  bindings: {
    template: "<",
    onTileClick: "&",
    canDelete: "<?",
    onDelete: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$q"];
    $postLink() {
      this.$element.on("click", () => this.onTileClick());
    }
    delete() {
      confirmDeleteDialog2().then(() => {
        this.$q.when(deleteProject(this.template), () => this.onDelete());
      });
    }
  }
});

// public/app/routes/template-lib/ng-components/view.js
angular_default.module("kantree").component("templateView", {
  templateUrl: "/static/app/routes/template-lib/ng-components/templates/view.html",
  bindings: {
    template: "<",
    org: "<?",
    team: "<?",
    canUse: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "demoSignupModal", "projectCreatorModal", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    createProject() {
      if (!isAuthenticated()) {
        if (this.$state.params.demo) {
          this.$demoSignupModal.open(this.template, this.$state.params.demo);
        } else {
          document.location = "/signup?utm_source=kantree&utm_campaign=template_lib&create_project_from=" + this.template.id;
        }
        return;
      }
      if (this.$state.params.nocreatemodal && this.org) {
        this.$q.when(api_default.organizations.create_project.post({
          org_id: this.org.id,
          team_id: this.team ? this.team.id : null,
          title: this.template.title,
          is_public: false,
          team_members_can_observe: true,
          team_members_can_autojoin: true,
          template_id: this.template.id
        }), (project) => {
          projectStore.upsertAfterCreation(project);
          this.$state.go("project", { "projectId": project.slug });
        });
      } else {
        this.$projectCreatorModal.open({ org: this.org, team: this.team, template: this.template });
      }
    }
  }
});

// public/app/routes/template-lib/index.jsx
addRoute({
  name: "templates",
  path: "/templates",
  component: () => createComponent(UnavailableOffline, {
    get children() {
      return createComponent(HideSystemSidebar, {
        anonymousOnly: true,
        get children() {
          return createComponent(NgComponent, {
            directive: "template-library"
          });
        }
      });
    }
  })
});
addRoute({
  name: "templates_tag",
  path: "/templates/:tag",
  component: () => {
    const params = useParams();
    return createComponent(UnavailableOffline, {
      get children() {
        return createComponent(HideSystemSidebar, {
          anonymousOnly: true,
          get children() {
            return createComponent(NgComponent, {
              directive: "template-library",
              get tag() {
                return params.tag;
              }
            });
          }
        });
      }
    });
  }
});

// public/app/routes/index.jsx
var _tmpl$151 = /* @__PURE__ */ template(`<div></div>`, 2);
addRoute({
  path: "/",
  component() {
    const navigate2 = useNavigate2();
    useAuthenticated(() => {
      const homeLink = get(currentUser2.app_params, "home", "");
      if (homeLink === "inbox") {
        navigate2("myWork.inbox");
      } else if (homeLink.indexOf("org:") === 0) {
        let parts = homeLink.split(":");
        if (parts.length > 2) {
          navigate2("org.team.hub", {
            slug: parts[1],
            teamSlug: parts[2]
          });
        } else {
          navigate2("org.hub", {
            slug: parts[1]
          });
        }
      } else {
        navigate2("globalHome");
      }
    });
  }
});
addRoute({
  path: "/p",
  redirectTo: "templates"
});
addRoute({
  path: "/dashboard",
  redirectTo: "globalHome"
});
addRoute({
  path: "/logout",
  component() {
    return _tmpl$151.cloneNode(true);
  }
});

// public/app/extensions/dropbox/index.js
var DropboxExtension = class {
  constructor() {
    fileProviders.push({
      label: _lazy("Attach from Dropbox"),
      execute: [
        "finishCallback",
        function(finishCallback) {
          Dropbox.choose({
            multiselect: true,
            folderselect: false,
            success: function(files) {
              finishCallback(files.map(function(file) {
                return {
                  name: file.name,
                  url: file.link
                };
              }));
            }
          });
        }
      ]
    });
    createEffect(() => {
      if (serverConfig.dropbox_app_key) {
        $('<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="' + serverConfig.dropbox_app_key + '"><\/script>').appendTo("head");
      }
    });
  }
};

// public/app/extensions/emailing/option-widget.js
angular_default.module("kantree").component("optionsWidgetEmailTemplate", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.onSelect()"
      items="$ctrl.items" is-required="$ctrl.items.length > 1" is-disabled="$ctrl.isDisabled"></options-widget-select-ref>
    <div class="mt-2 text-end">
      <a href ng-click="$ctrl.editTemplate()" ng-show="$ctrl.value && $ctrl.value.id">Edit template</a>
    </div>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "emailTemplateEditorModal", "$q", "$timeout"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refresh();
    }
    onSelect() {
      if (this.value && this.value.id === -1) {
        this.$emailTemplateEditorModal.open(this.options.project, { "attachments": [] }).then((tpl) => {
          if (tpl && tpl.id) {
            this.refresh().then(() => this.$timeout(() => {
              this.ngModel.$setViewValue({ id: tpl.id, name: tpl.name });
            }));
          } else {
            return this.$q.reject();
          }
        }).catch(() => {
          this.refresh().then(() => this.$timeout(() => {
            this.ngModel.$setViewValue(null);
          }));
        });
      } else {
        this.ngModel.$setViewValue(this.value);
      }
    }
    refresh() {
      if (this.options.project) {
        return this.$q.when(api_default.emailing_templates.list_email_templates.get({ project_id: this.options.project.id }), (templates) => {
          this.items = templates.sort((a3, b3) => {
            return a3.name.localeCompare(b3.name, currentUser2.locale, { sensitivity: "base", ignorePunctuation: true, numeric: true });
          }).concat([{ id: -1, name: _4("[Create new email template]") }]).map((tpl) => [tpl.id, tpl.name]);
        });
      }
      return this.$q.resolve();
    }
    editTemplate() {
      this.$q.when(api_default.emailing_templates.get_email_template.get({ project_id: this.options.project.id, email_template_id: this.value.id }), (template3) => {
        this.$emailTemplateEditorModal.open(this.options.project, template3).then((tpl) => {
          this.refresh().then(() => this.$timeout(() => {
            if (!tpl) {
              this.ngModel.$setViewValue(null);
            }
          }));
        });
      });
    }
  }
});

// public/app/extensions/emailing/project-settings.js
angular_default.module("kantree").directive("projectSettingsEmailingPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/extensions/emailing/templates/project-settings.html",
    controller: [
      "$scope",
      "$q",
      "processingStatus",
      function($scope2, $q, processingStatus) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.defaultSender = serverConfig.emailing_sender;
        $scope2.maxEmailTemplateSendPerDay = serverConfig.max_email_template_send_per_day;
        $scope2.canSendFromKantree = true;
        if (serverConfig.payments_enabled && $scope2.project.owner.type === "org") {
          const org2 = orgStore.tryGet($scope2.project.owner.id);
          $scope2.canSendFromKantree = !org2.billing || org2.billing.flags.includes("emailing") && ["active", "past_due"].includes(org2.billing.status);
        }
        $scope2.useSmtpConnection = !$scope2.canSendFromKantree;
        $q.when(api_default.emailing_templates.get_smtp_connection.get({ project_id: $scope2.project.id }), (smtp) => {
          $scope2.smtp = smtp || {};
          if (smtp) {
            $scope2.useSmtpConnection = true;
          }
        });
        $scope2.refresh = function() {
          $q.when(api_default.emailing_templates.list_email_templates.get({ project_id: $scope2.project.id }), (templates) => {
            $scope2.templates = templates.sort((a3, b3) => {
              return a3.name.localeCompare(b3.name, currentUser2.locale, { sensitivity: "base", ignorePunctuation: true, numeric: true });
            });
          });
        };
        $scope2.refresh();
        $scope2.add = function() {
          $scope2.selected = { "attachments": [] };
        };
        $scope2.edit = function(template3) {
          $scope2.selected = angular_default.copy(template3);
        };
        $scope2.delete = function(template3) {
          confirmDeleteDialog2().then(() => {
            $q.when(api_default.emailing_templates.delete_email_template.delete({
              project_id: $scope2.project.id,
              email_template_id: template3.id
            }), $scope2.refresh);
          });
        };
        $scope2.updateSmtpConnection = function() {
          $scope2.smtpUpdateStatus = processingStatus.saver((cb2) => {
            $q.when(api_default.emailing_templates.configure_smtp_connection.post(Object.assign({
              project_id: $scope2.project.id
            }, $scope2.useSmtpConnection ? $scope2.smtp : { server: null })), cb2);
          });
        };
      }
    ]
  };
});
angular_default.module("kantree").factory("ProsemirrorEmailTemplateMarkersToolbarItem", [
  "ProsemirrorPrettyMenuItem",
  "$q",
  function(ProsemirrorPrettyMenuItem, $q) {
    return function(scope, data2, schema7) {
      return new ProsemirrorPrettyMenuItem({
        title: _4("Insert template marker"),
        icon: "tags",
        dropConfig: {
          classes: "drop-theme-menu drop-theme-arrow drop-theme-prosemirror"
        },
        getMenu: function(view) {
          let markers = [];
          return {
            config: () => {
              return () => markers.map(([attrName, markerName]) => {
                return {
                  label: attrName,
                  action: () => {
                    view.dispatch(view.state.tr.replaceSelectionWith(schema7.text("${" + markerName + "}")));
                    view.focus();
                  }
                };
              });
            },
            options: {
              title: _4("Insert template marker"),
              fetchData: (cb2) => {
                $q.when(api_default.emailing_templates.list_template_markers.get({ project_id: data2.project_id }), (markers_) => {
                  markers = markers_;
                  cb2();
                });
              }
            }
          };
        }
      }, scope);
    };
  }
]);

// public/app/extensions/emailing/template-editor.js
angular_default.module("kantree").directive("emailTemplateEditor", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/extensions/emailing/templates/template-editor.html",
    scope: {
      project: "<",
      template: "<",
      onCancel: "&?",
      onSave: "&",
      onDelete: "&"
    },
    controller: [
      "$scope",
      "$q",
      "ProsemirrorEmailTemplateMarkersToolbarItem",
      function($scope2, $q, ProsemirrorEmailTemplateMarkersToolbarItem) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.newAttachments = [];
        $scope2.deletedAttachments = [];
        $scope2.contentEditorData = {
          project_id: $scope2.project.id,
          toolbarItems: [ProsemirrorEmailTemplateMarkersToolbarItem]
        };
        $scope2.addAttachment = (files) => {
          $scope2.newAttachments = $scope2.newAttachments.concat(files);
        };
        $scope2.deleteNewAttachment = (file) => {
          $scope2.newAttachments.splice($scope2.newAttachments.indexOf(file), 1);
        };
        $scope2.deleteAttachment = (attachment) => {
          $scope2.deletedAttachments.push(attachment.id);
          $scope2.template.attachments.splice($scope2.template.attachments.indexOf(attachment), 1);
        };
        $scope2.save = async () => {
          const data2 = {
            "project_id": $scope2.project.id,
            "name": $scope2.template.name,
            "subject": $scope2.template.subject,
            "sender": $scope2.template.sender || "",
            "reply_to": $scope2.template.reply_to || "",
            "body": $scope2.template.body
          };
          if ($scope2.deletedAttachments.length) {
            data2["delete_attachments"] = $scope2.deletedAttachments;
          }
          let service, method = "post";
          if ($scope2.template.id) {
            data2["email_template_id"] = $scope2.template.id;
            service = api_default.emailing_templates.update_email_template;
            method = "put";
          } else {
            service = api_default.emailing_templates.create_email_template;
          }
          try {
            let r3;
            if ($scope2.newAttachments.length > 0) {
              data2["attachments"] = $scope2.newAttachments;
              r3 = await upload({
                url: service.url(data2),
                method: method.toUpperCase(),
                data: data2
              });
              r3 = r3.data;
            } else {
              r3 = await service[method](data2);
            }
            if (r3.error) {
              errorDialog(r3.error);
            } else {
              $scope2.onSave({ $template: r3 });
            }
          } catch (r3) {
            errorDialog();
          }
        };
        $scope2.delete = () => {
          $q.when(confirmDeleteDialog2(), () => {
            $q.when(api_default.emailing_templates.delete_email_template.delete({ project_id: $scope2.project.id, email_template_id: $scope2.template.id }), () => {
              $scope2.onDelete();
            });
          });
        };
        $scope2.sendTest = () => {
          $q.when(inputDialog("Send the test email to the following address:", { required: true }), (value2) => {
            $q.when(
              api_default.emailing_templates.send_test_email.post({ project_id: $scope2.project.id, email_template_id: $scope2.template.id, recipient: value2 }),
              angular_default.noop,
              autoCatchAsRequestErrorDialog([403, 400])
            );
          });
        };
      }
    ]
  };
});
angular_default.module("kantree").factory("emailTemplateEditorModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(project, template3) {
        var scope = $rootScope.$new();
        scope.project = project;
        scope.template = angular_default.copy(template3);
        var instance = $uibModal.open({
          templateUrl: "/static/app/extensions/emailing/templates/template-editor-modal.html",
          windowClass: "email-template-editor-modal",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance.result;
      }
    };
  }
]);

// public/app/modals/project-settings/panels.js
var projectSettingsPanels = [
  {
    name: "options",
    title: _lazy("General"),
    directive: "project-settings-options-panel",
    enabled: function(project) {
      return canManageSettings(project);
    }
  },
  {
    name: "appearance",
    title: _lazy("Appearance"),
    directive: "project-settings-appearance-panel",
    enabled: function(project) {
      return canManageSettings(project);
    }
  },
  {
    name: "members",
    title: _lazy("Members & guests"),
    directive: "project-settings-members-panel",
    enabled: (project) => !project.is_template
  },
  {
    name: "roles",
    title: _lazy("Roles"),
    directive: "project-settings-roles-panel",
    enabled: function(project) {
      return !project.is_portfolio && project.owner.type === "org" && canManageMembers(project);
    }
  },
  {
    name: "models",
    title: _lazy("Card types"),
    directive: "project-settings-models-panel",
    enabled: function(project) {
      return !project.is_portfolio && (isAllowedInProject(project, "card_model", ["CREATE", "EDIT", "DELETE"]) || canManageAttributes(project));
    }
  },
  {
    name: "contexts",
    title: _lazy("Contexts"),
    directive: "project-settings-group-types-panel",
    enabled: function(project) {
      var org2 = orgStore.query({ id: project.owner.id })?.[0];
      return org2 && typeof org2.no_org_context !== "undefined" && !org2.no_org_context && !project.is_portfolio && isAllowedInProject(project, "card_group_type", ["CREATE", "EDIT", "DELETE"]);
    }
  },
  {
    name: "recurringCards",
    title: _lazy("Recurring cards"),
    directive: "project-settings-recurring-cards-panel",
    enabled: function(project) {
      return !project.is_portfolio && canManageRecurring(project) && !project.is_template;
    }
  },
  {
    name: "ai",
    title: _lazy("AI"),
    directive: "project-settings-ai-panel",
    enabled: function(project) {
      var org2 = orgStore.tryGetForProject(project);
      return org2?.ai_enabled ?? false;
    }
  },
  {
    name: "pii",
    title: _lazy("Privacy Compliance"),
    directive: "project-settings-pii-panel",
    enabled: function(project) {
      return !project.is_template && !project.is_portfolio && canManagePIIData(project);
    }
  }
];

// public/app/extensions/emailing/index.js
var EmailExtension = class {
  constructor() {
    rolePermissionMap.find((o3) => o3.key === "project").actions.push({
      label: _lazy("Manage emailing"),
      map: [
        { object_type: "project", actions: ["MANAGE_EMAIL_TEMPLATES"] }
      ]
    });
    projectSettingsPanels.push({
      name: "emailTemplates",
      title: _lazy("Emailing"),
      directive: "project-settings-emailing-panel",
      enabled: function(project) {
        return !project.is_template && !project.is_portfolio && isAllowedInProject(project, "project", "MANAGE_EMAIL_TEMPLATES", project.id);
      }
    });
  }
};

// public/app/ui/utils/browser-popup.js
var WebBrowserPopupHandler = class {
  getCallbackUrl() {
    return makeUrlAbsolute("/static/popup-callback.html");
  }
  open(url2, options2) {
    options2 = Object.assign({
      width: 800,
      height: 600
    }, options2 || {});
    const left = (screen.width - options2.width) / 2, top2 = (screen.height - options2.height) / 2;
    this.popup = window.open(url2, "", "top=" + top2 + ",left=" + left + ",width=" + options2.width + ",height=" + options2.height);
    this.deferred = deferredPromise();
    return this.deferred.promise;
  }
  callback(success) {
    this.popup.close();
    if (success) {
      this.deferred.resolve();
    } else {
      this.deferred.reject();
    }
  }
};
var browserPopup = createProxyHandler(new WebBrowserPopupHandler());
window.kantreePopupCallback = function(success) {
  browserPopup.callback(success);
};

// public/app/extensions/google/index.js
var GoogleExtension = class {
  constructor() {
    fileTypes.push(
      [new RegExp("^application\\/vnd\\.google-apps\\.document$", "i"), "fa-file-word-o"],
      [new RegExp("^application\\/vnd\\.google-apps\\.spreadsheet$", "i"), "fa-file-excel-o"],
      [new RegExp("^application\\/vnd\\.google-apps\\.presentation$", "i"), "fa-file-powerpoint-o"]
    );
    fileProviders.push({
      label: _lazy("Attach from Google Drive"),
      requireAuth: true,
      execute: [
        "finishCallback",
        function(finishCallback) {
          const showPicker = (tokens) => {
            var docsView = new google.picker.DocsView();
            docsView.setIncludeFolders(true);
            var picker = new google.picker.PickerBuilder().addView(docsView).setOAuthToken(tokens.access_token).setCallback((data2) => {
              var files = [];
              if (data2[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
                files = data2[google.picker.Response.DOCUMENTS].map(function(doc4) {
                  return {
                    name: doc4.name,
                    mimetype: doc4.mimeType,
                    url: doc4.url
                  };
                });
              }
              finishCallback(files);
            }).build();
            picker.setVisible(true);
          };
          Promise.all([
            new Promise((resolve2) => gapi.load("picker", () => resolve2())),
            api_default.google_integration.get_tokens.get({}, { ignoreErrorHandlers: true }).catch(() => {
              return browserPopup.open(prependBaseUrl("/login/google?next=" + browserPopup.getCallbackUrl())).then(() => {
                return api_default.google_integration.get_tokens.get();
              });
            })
          ]).then(([_5, tokens]) => {
            if (tokens.access_token) {
              showPicker(tokens);
            } else {
              errorDialog(_5("It seems there is an error connecting to Google. Please re-authentify your account from the Third Party Accounts section of your Account page"));
            }
          });
        }
      ]
    });
  }
};

// public/app/extensions/onedrive/index.js
var OneDriveExtension = class {
  constructor() {
    $('<script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js"><\/script>').appendTo("head");
    fileProviders.push({
      label: _lazy("Attach from OneDrive"),
      execute: [
        "finishCallback",
        (finishCallback) => {
          OneDrive.open({
            clientId: serverConfig.ms365_client_id,
            action: "share",
            multiSelect: true,
            advanced: {
              redirectUri: makeUrlAbsolute("/login/ms365/filepicker")
            },
            success: (resp) => {
              finishCallback(resp.value.map((file) => {
                return {
                  name: file.name,
                  url: file.webUrl || file["@microsoft.graph.downloadUrl"],
                  mimetype: "file" in file ? file.file["mimeType"] || null : null
                };
              }));
            }
          });
        }
      ]
    });
  }
};

// public/app/modals/org-settings/panels.js
var orgSettingsPanels = [
  {
    name: "options",
    title: _lazy("General"),
    component: "org-settings-options-panel",
    enabled: (org2) => {
      return (org2.permission === 4 || currentUser2.is_kantree_admin) && isConnected();
    }
  },
  {
    name: "appearance",
    title: _lazy("Appearance"),
    component: "org-settings-appearance-panel",
    featureFlag: "org_hub",
    upgradeForFeatureFlag: true,
    enabled: (org2) => {
      return (org2.permission === 4 || currentUser2.is_kantree_admin) && isConnected();
    }
  },
  {
    name: "roles",
    title: _lazy("Workspace roles"),
    component: "org-settings-roles-panel",
    enabled: (org2) => {
      return (org2.permission !== null || currentUser2.is_kantree_admin) && isConnected();
    }
  },
  {
    name: "templates",
    title: _lazy("Templates"),
    component: "org-settings-templates-panel",
    enabled: (org2) => {
      return currentUser2.is_kantree_admin;
    }
  },
  // {
  //   name: 'project-attrs',
  //   title: _lazy('Workspace fields'),
  //   component: 'org-settings-project-attrs-panel',
  //   enabled: (org) => {
  //     return (org.permission === 4 || currentUser.is_kantree_admin) && isConnected();
  //   }
  // },
  {
    name: "models",
    title: _lazy("Card types"),
    component: "org-settings-models-panel",
    enabled: (org2) => {
      return org2.permission !== null || currentUser2.is_kantree_admin;
    }
  },
  {
    name: "contexts",
    title: _lazy("Contexts"),
    component: "org-settings-group-types-panel",
    enabled: (org2) => {
      return (org2.permission !== null || currentUser2.is_kantree_admin) && !org2.no_org_context;
    }
  },
  {
    name: "integrations",
    title: _lazy("Integrations"),
    component: "org-settings-integrations-panel",
    enabled: (org2) => {
      return org2.permission !== null || currentUser2.is_kantree_admin;
    }
  },
  {
    name: "pii",
    title: _lazy("Privacy Compliance"),
    component: "org-settings-pii-panel",
    enabled: (org2) => {
      return (org2.permission >= 3 || currentUser2.is_kantree_admin) && isConnected();
    }
  },
  {
    name: "ai",
    title: _lazy("AI"),
    component: "org-settings-ai-panel",
    featureFlag: "ai",
    beta: true,
    enabled: (org2) => {
      return org2.permission !== null || currentUser2.is_kantree_admin;
    }
  },
  {
    name: "billing",
    title: _lazy("Billing"),
    component: "org-settings-billing-panel",
    enabled: (org2) => {
      return (org2.permission >= 3 && org2.billing || currentUser2.is_kantree_admin) && isConnected();
    }
  },
  {
    name: "admin",
    title: _lazy("Admin"),
    component: "org-settings-admin-panel",
    enabled: (org2) => {
      return currentUser2.is_kantree_admin && isConnected();
    }
  }
];

// public/app/extensions/sso/index.js
var SSOExtension = class {
  constructor() {
    orgSettingsPanels.push({
      name: "sso",
      title: _lazy("SSO"),
      featureFlag: "sso",
      upgradeForFeatureFlag: true,
      component: "org-settings-sso-panel",
      enabled: (org2) => {
        return (org2.permission >= 3 || currentUser2.is_kantree_admin) && isConnected();
      }
    });
  }
};
angular_default.module("kantree").component("orgSettingsSsoPanel", {
  templateUrl: "/static/app/extensions/sso/templates/org-settings.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.domainLogin = false;
      this.ssoType = null;
      this.$q.when(api_default.sso.get_sso_config.get({ org_id: this.org.id }), (info) => this.refresh(info));
      this.$q.when(api_default.sso.get_available_providers.get({ org_id: this.org.id }), (providers) => {
        this.providers = providers.filter((p4) => p4.name !== "saml");
      });
      this.$scope.$on("userEmailValidated", () => {
        this.info.domain_ownership_validated = true;
      });
    }
    refresh(info) {
      this.info = info;
      this.domainLogin = !!info.auto_join_from_domain;
      if (info.provider && info.provider.name === "saml") {
        if (info.idp_metadata_url) {
          this.ssoType = "$metadata";
          this.data = { idp_metadata_url: info.idp_metadata_url };
        } else {
          this.ssoType = "$params";
          this.data = {
            entity_id: info.entity_id,
            login_url: info.login_url,
            x509_cert: info.x509_cert
          };
        }
      } else if (info.provider) {
        this.ssoType = info.provider.name;
      } else {
        this.ssoType = null;
        this.data = {};
      }
    }
    submit() {
      if (!this.ssoType) {
        this.$q.when(api_default.sso.clear_sso_config.delete({ org_id: this.org.id }), (info) => this.refresh(info));
      } else if (this.ssoType === "$metadata") {
        this.$q.when(api_default.sso.update_sso_config.post({
          org_id: this.org.id,
          provider: "saml",
          idp_metadata_url: this.data.idp_metadata_url
        }), (info) => this.refresh(info));
      } else if (this.ssoType === "$params") {
        this.$q.when(api_default.sso.update_sso_config.post({
          org_id: this.org.id,
          provider: "saml",
          entity_id: this.data.entity_id,
          login_url: this.data.login_url,
          x509_cert: this.data.x509_cert
        }), (info) => this.refresh(info));
      } else {
        const provider = this.providers.find((p4) => p4.name === this.ssoType);
        if (provider.needs_setup) {
          browserPopup.open(api_default.sso.setup_sso_provider.url({ org_id: this.org.id }) + `?provider=${provider.name}`).then(() => {
            this.$q.when(api_default.sso.get_sso_config.get({ org_id: this.org.id }), (info) => this.refresh(info));
          });
        } else {
          this.$q.when(api_default.sso.update_sso_config.post({
            org_id: this.org.id,
            provider: provider.name
          }), (info) => this.refresh(info));
        }
      }
    }
    updateDomainLogin() {
      this.$q.when(api_default.sso.update_sso_config.post({
        org_id: this.org.id,
        auto_join_from_domain: this.domainLogin ? this.info.domain : null
      }), (info) => this.refresh(info));
    }
    validateDomain() {
      this.$q.when(api_default.user.send_email_validation.post(), () => {
        infoDialog(_4("We have sent you an email to confirm your email address. Please follow the link inside."));
      });
    }
  }
});

// public/app/extensions/index.js
var EXTENSIONS = {
  dropbox: DropboxExtension,
  emailing: EmailExtension,
  google: GoogleExtension,
  onedrive: OneDriveExtension,
  sso: SSOExtension
};
async function initExtensions() {
  await loadServerConfig();
  for (const ext of serverConfig.extensions) {
    if (EXTENSIONS[ext]) {
      new EXTENSIONS[ext]();
    }
  }
}

// virtual-ns:handlebars
var handlebars_default = Handlebars;

// public/app/utils/handlebars.js
init_icons();
handlebars_default.registerHelper("markdownToPlainText", function(options2) {
  return convertMarkdownToPlainText(options2.fn(this) || "");
});
handlebars_default.registerHelper("iconClass", function(icon) {
  return iconClass(icon);
});

// public/app/app.jsx
var _tmpl$155 = /* @__PURE__ */ template(`<span></span>`, 2);
var _tmpl$272 = /* @__PURE__ */ template(`<a href="https://kantree.io/help/guides/user#browser-support" class="btn" target="_blank"> </a>`, 2);
var _tmpl$349 = /* @__PURE__ */ template(`<a class="btn"></a>`, 2);
var _tmpl$434 = /* @__PURE__ */ template(`<a href="https://kantree.io/help/guides/collaboration#realtime" class="btn" target="_blank"> </a>`, 2);
var _tmpl$529 = /* @__PURE__ */ template(`<div id="app-container"><div id="app-main"><div></div></div></div>`, 6);
api_default.registerErrorHandler(autoCatchAsRequestErrorDialog([400, 403]));
if (isEmbedded()) {
  document.body.classList.add("embedded", "embedded-page-only");
  document.documentElement.style.setProperty("--system-sidebar-width", "0px");
  let accessToken;
  try {
    accessToken = window.parent.kantreeAccessToken;
  } catch {
  }
  if (accessToken) {
    api_default.setAuthToken(accessToken);
  }
}
window.addEventListener("hashchange", () => {
  var loc = window.location;
  if (loc.hash === "") {
    window.history.replaceState("", document.title, loc.pathname + loc.search);
  }
});
initExtensions();
loadCurrentUser().then(() => {
  loadAppContext();
  if (isAuthenticated()) {
    setLocaleFromUser();
    initAssistant();
    getPushConnection().then((conn) => {
      conn.on("logout", () => authSession.logout());
      conn.on("project_error", (data2) => {
        toastNotify(data2.error, "error");
      });
      conn.on("email_validated", () => {
        setCurrentUser("email_validated", true);
      });
    });
  } else {
    setLocale();
  }
});
function DeprecatedBrowserBanner() {
  return createComponent(SystemBanner, {
    "class": "dark-theme",
    get onClose() {
      return props.onClose;
    },
    color: "#941212",
    get children() {
      return [createComponent(Icon, {
        name: "warning"
      }), (() => {
        const _el$ = _tmpl$155.cloneNode(true);
        insert(_el$, () => _4("Your browser is not fully compatible with Kantree. We recommend using the latest versions of current browsers."));
        return _el$;
      })(), (() => {
        const _el$2 = _tmpl$272.cloneNode(true), _el$3 = _el$2.firstChild;
        insert(_el$2, () => _4("Learn more"), _el$3);
        insert(_el$2, createComponent(Icon, {
          name: "bi-box-arrow-up-right",
          "class": "right"
        }), null);
        return _el$2;
      })()];
    }
  });
}
function ImpersonateBanner() {
  function onClick() {
    clearStorageBeforeLogout();
    document.location = prependBaseUrl("/admin/impersonate/cancel");
  }
  return createComponent(SystemBanner, {
    "class": "dark-theme",
    color: "#941212",
    get children() {
      return [(() => {
        const _el$4 = _tmpl$155.cloneNode(true);
        insert(_el$4, () => _4("You are impersonating the current user as a super admin."));
        return _el$4;
      })(), (() => {
        const _el$5 = _tmpl$349.cloneNode(true);
        _el$5.$$click = onClick;
        insert(_el$5, () => _4("Stop impersonation"));
        return _el$5;
      })()];
    }
  });
}
function RealTimeIssueBanner() {
  return createComponent(SystemBanner, {
    "class": "dark-theme",
    color: "#941212",
    get children() {
      return [createComponent(Icon, {
        name: "warning"
      }), (() => {
        const _el$6 = _tmpl$155.cloneNode(true);
        insert(_el$6, () => _4("Cannot connect to Kantree servers. Please check your Internet connection or contact support."));
        return _el$6;
      })(), (() => {
        const _el$7 = _tmpl$434.cloneNode(true), _el$8 = _el$7.firstChild;
        insert(_el$7, () => _4("Learn more"), _el$8);
        insert(_el$7, createComponent(Icon, {
          name: "bi-box-arrow-up-right",
          "class": "right"
        }), null);
        return _el$7;
      })()];
    }
  });
}
function OfflineBanner() {
  return createComponent(SystemBanner, {
    color: "#d9edf7",
    get children() {
      return [createComponent(Icon, {
        name: "warning"
      }), (() => {
        const _el$9 = _tmpl$155.cloneNode(true);
        insert(_el$9, () => _4("You are offline, some features may be disabled."));
        return _el$9;
      })(), (() => {
        const _el$10 = _tmpl$434.cloneNode(true), _el$11 = _el$10.firstChild;
        insert(_el$10, () => _4("Learn more"), _el$11);
        insert(_el$10, createComponent(Icon, {
          name: "bi-box-arrow-up-right",
          "class": "right"
        }), null);
        return _el$10;
      })()];
    }
  });
}
function App() {
  let ngAppElement, connectivityBanner;
  onMount(() => {
    ngApp.bootstrap(ngAppElement);
    if (serverConfig.impersonating_from) {
      showBanner(ImpersonateBanner);
    }
    if (isIE()) {
      showBanner(DeprecatedBrowserBanner);
    }
  });
  createEffect(() => {
    if (connectivityBanner) {
      connectivityBanner.close();
      connectivityBanner = null;
    }
    if (isOnline() && !isConnected() && isAuthenticated()) {
      connectivityBanner = showBanner(RealTimeIssueBanner);
    } else if (!isOnline() && isAuthenticated()) {
      connectivityBanner = showBanner(OfflineBanner);
    }
  });
  createEffect(on(() => currentUser2.app_params.release_notes_version_read, () => {
    checkUnreadReleaseAnnouncements();
  }, {
    defer: true
  }));
  createEffect(() => {
    showNextUnreadReleaseAnnouncement();
  });
  return createComponent(ThemeContext, {
    get children() {
      return [createComponent(SystemBannerContainer, {}), (() => {
        const _el$12 = _tmpl$529.cloneNode(true), _el$13 = _el$12.firstChild, _el$14 = _el$13.firstChild;
        insert(_el$12, createComponent(NgComponent, {
          directive: "nav-sidebar-system"
        }), _el$13);
        const _ref$ = ngAppElement;
        typeof _ref$ === "function" ? use(_ref$, _el$13) : ngAppElement = _el$13;
        insert(_el$14, createComponent(Router2, {}));
        return _el$12;
      })(), createComponent(ToastNotificationsContainer, {})];
    }
  });
}
delegateEvents(["click"]);

// public/app/actions/group.ts
function respHandler(group2) {
  group2 = cardGroupStore.upsert(group2);
  cardStateStore.createOrUpdateAliasFromGroup(group2);
  return group2;
}
function ensureCardAndGroupId(group2, data2) {
  return { ...data2 || {}, group_id: group2.id, card_id: data2?.card_id || group2.parent_id };
}
function formatData4(group2) {
  return {
    title: group2.title,
    description: group2.description,
    color: group2.color,
    icon: group2.icon,
    show_flow_indicator: group2.show_flow_indicator,
    always_show_description: group2.always_show_description,
    card_state: group2.card_state,
    default_card_model_id: group2.default_card_model_id,
    auto_assign_user: group2.auto_assign_user,
    max_cards_limit: group2.max_cards_limit,
    is_creation_hidden: group2.is_creation_hidden,
    start_date: group2.start_date ? moment_default(group2.start_date).format("YYYY-MM-DD") : null,
    end_date: group2.end_date ? moment_default(group2.end_date).format("YYYY-MM-DD") : null,
    validation_rule: group2.validation_rule || null
  };
}
function saveGroup(group2, parent) {
  if (group2.id) {
    return updateGroup(group2, { card_id: parent.id, ...formatData4(group2) });
  }
  return createGroupFromObject(group2, parent);
}
async function createGroup(groupType, parent, title) {
  const group2 = await api_default.card_groups.create_group.post({ card_id: parent.id, type_id: groupType.id, title });
  return respHandler(group2);
}
async function createGroupFromObject(group2, parent) {
  const g3 = await api_default.card_groups.create_group.post(Object.assign({
    card_id: parent?.id || group2.parent_id,
    type_id: group2.type_id
  }, formatData4(group2)));
  return respHandler(Object.assign(group2, g3));
}
async function updateGroup(group2, data2) {
  group2 = await api_default.card_groups.update.put(ensureCardAndGroupId(group2, data2));
  return respHandler(group2);
}
async function moveGroup(group2, parent, position) {
  const g3 = await api_default.card_groups.relocate.post(ensureCardAndGroupId(group2, { card_id: parent.id, position }));
  return cardGroupStore.transaction(() => {
    cardGroupStore.relocate(group2, position);
    return cardGroupStore.update(g3);
  });
}
async function relocateGroup(group2, parent, newParent, relocateCards) {
  parent = parent || { ...cardStore.get(group2.parent_id) };
  const g3 = await api_default.card_groups.relocate.post(ensureCardAndGroupId(group2, {
    card_id: parent.id,
    parent_id: newParent.id,
    relocate_cards: relocateCards || false
  }));
  return cardGroupStore.transaction(() => {
    cardGroupStore.reorder(group2, null, group2.position);
    group2 = cardGroupStore.update(g3);
    cardGroupStore.reorder(group2, group2.position, null);
    if (relocateCards) {
      cardStore.relocateAllInGroupToParent(group2, newParent);
    }
    return group2;
  });
}
async function copyGroup(group2, parent, newParent, keepCards, copyCards) {
  parent = parent || { ...cardStore.get(group2.parent_id) };
  let newGroup = await api_default.card_groups.copy.post(ensureCardAndGroupId(group2, {
    card_id: parent.id,
    parent_id: newParent.id,
    keep_cards: keepCards,
    copy_cards: copyCards
  }));
  if (parent.project_id === newParent.project_id) {
    newGroup = cardGroupStore.insert(newGroup);
    if (copyCards) {
      const nbParentChildren = cardStore.query({ parent_id: parent.id }).length;
      const nbGroupChildren = cardStore.query({ parent_id: parent.id, groups: matchGroup(group2.id) }).length;
      return new Promise((resolve2, reject2) => {
        const loadChildren = () => {
          loadChildCardsOf(parent).then((objs) => {
            if (nbGroupChildren > 0 && objs.length === nbParentChildren) {
              setTimeout(loadChildren, 100);
            } else {
              resolve2(newGroup);
            }
          });
        };
        setTimeout(loadChildren, 100);
      });
    }
  }
  return newGroup;
}
async function toggleGroupSubscribed(group2, parent) {
  if (cardGroupSubscriptionStore.isSubscribed(group2)) {
    await api_default.card_groups.unsubscribe.delete(ensureCardAndGroupId(group2, { card_id: parent.id }));
    cardGroupSubscriptionStore.unsubscribeFrom(group2);
  } else {
    await api_default.card_groups.subscribe.post(ensureCardAndGroupId(group2, { card_id: parent.id }));
    cardGroupSubscriptionStore.subscribeTo(group2);
  }
}
async function toggleCardNotifications(group2, parent) {
  const s3 = cardGroupSubscriptionStore.getForGroup(group2);
  await api_default.card_groups.subscribe.post(ensureCardAndGroupId(group2, {
    card_id: parent.id,
    notify_card_changes: !s3.notify_card_changes
  }));
  cardGroupSubscriptionStore.toggleCardNotifications(group2);
}
async function archiveGroup(group2, parent, archiveChildren) {
  const oldPosition = group2.position;
  group2 = await api_default.card_groups.archive.post(ensureCardAndGroupId(group2, {
    card_id: parent.id,
    archive_children: archiveChildren || false
  }));
  group2 = respHandler(group2);
  cardStore.broadcast("changed");
  cardGroupStore.reorder(group2, null, oldPosition);
  if (archiveChildren) {
    cardStore.archiveAllFromGroup(group2);
  }
  return group2;
}
async function restoreGroup(group2, parent) {
  group2 = await api_default.card_groups.restore.delete(ensureCardAndGroupId(group2, { card_id: parent.id }));
  return respHandler(group2);
}
async function deleteGroup(group2, parent) {
  await api_default.card_groups.delete.delete(ensureCardAndGroupId(group2, { card_id: parent.id }));
  cardGroupStore.transaction(() => {
    cardGroupStore.reorder(group2, null, group2.position);
    cardGroupStore.remove(group2);
  });
  cardStore.clearGroupsAfterDeletion(group2);
}
function setCardsStateFromGroup(group2, parent, state) {
  cardStore.setCardsStateFromGroup(group2, state);
  return api_default.card_groups.set_cards_state.post(ensureCardAndGroupId(group2, { card_id: parent.id, state }));
}

// public/app/apps/cards/common/component-mixins/attr-visibility.ts
var CardsAppAttrVisibilityMixin = {
  $inject: ["$scope"],
  specialFields: [],
  initAttrVisibilityMixin() {
    this.visibleAttributes = [];
    this.availableAttributes = /* @__PURE__ */ new Map();
    this.refreshAvailableAttributes();
    this.refreshVisibleAttributes();
    this.watchAttributes();
    this.$scope.$watch("$ctrl.availableAttributes", (newAvailableAttributes, oldAvailableAttributes) => {
      if (newAvailableAttributes === oldAvailableAttributes) return;
      const attrNameUpdates = {};
      for (const [newName, newAttrGroup] of newAvailableAttributes) {
        for (const [oldName, oldAttrGroup] of oldAvailableAttributes) {
          if (equals(newAttrGroup, oldAttrGroup) && newName !== oldName) {
            attrNameUpdates[oldName] = newName;
            break;
          }
        }
      }
      let newVisibleAttrNames = this.options?.visible_attributes;
      if (newVisibleAttrNames !== void 0) {
        if (Object.keys(attrNameUpdates).length !== 0) {
          newVisibleAttrNames = newVisibleAttrNames.map((name2) => attrNameUpdates[name2] || name2);
        }
      }
      newVisibleAttrNames = getVisibleAttrNames(
        newVisibleAttrNames,
        this.options?.all_attrs_visible,
        this.availableAttributes
      );
      const newAllAttrsVisible = getAllAttrsVisible(newVisibleAttrNames, this.availableAttributes);
      this.updateVisibleAttributes(newVisibleAttrNames, newAllAttrsVisible);
    });
  },
  changeAttrVisibilityMixin(changes) {
    const storeChanged = changes.store && !changes.store.isFirstChange();
    const boardChanged = changes.board && !changes.board.isFirstChange();
    const projectChanged = boardChanged && projectStore.tryGetForCard(this.board)?.id !== this.project?.id;
    const optionsChanged = changes.options && !changes.options.isFirstChange();
    const optionChanged = (optionLabel) => optionsChanged && !equals(this.options?.[optionLabel], changes.options.previousValue?.[optionLabel]);
    if (optionChanged("visible_attributes") || optionChanged("all_attrs_visible")) {
      this.refreshVisibleAttributes();
    }
    if (projectChanged || !this.project && storeChanged) {
      this.refreshAvailableAttributes();
      this.refreshVisibleAttributes();
      this.watchAttributes();
    }
  },
  refreshAvailableAttributes() {
    const availableAttrs = getAvailableAttrs(this.project, this.store, { specialFields: this.specialFields });
    if (availablesEquals(this.availableAttributes, availableAttrs)) return;
    this.availableAttributes = availableAttrs;
  },
  refreshVisibleAttributes() {
    const visibleAttrNames = getVisibleAttrNames(
      this.options?.visible_attributes,
      this.options?.all_attrs_visible,
      this.availableAttributes
    );
    if (!equals(visibleAttrNames, this.visibleAttrNames)) {
      const visibleAttributes = /* @__PURE__ */ new Map();
      for (const attrName of visibleAttrNames) {
        if (this.availableAttributes.has(attrName)) {
          visibleAttributes.set(attrName, this.availableAttributes.get(attrName));
        }
      }
      this.visibleAttrNames = visibleAttrNames;
      this.visibleAttributes = Array.from(visibleAttributes.values());
    }
  },
  watchAttributes() {
    if (this.watchAttributesOff) this.watchAttributesOff();
    const modelStore = getScopedModelStore(this.project, this.store);
    const groupTypeStore = getScopedGroupTypeStore(this.project, this.store);
    const watcher = () => {
      this.refreshAvailableAttributes();
      this.refreshVisibleAttributes();
    };
    this.watchAttributesOff = offMany([
      modelStore.$watchAll(this.$scope, watcher, false),
      groupTypeStore.$watchAll(this.$scope, watcher, false)
    ]);
  },
  updateVisibleAttributes(attrsNames, allAttrsVisible) {
    if (!equals(this.options?.visible_attributes, attrsNames) || this.options?.all_attrs_visible !== allAttrsVisible) {
      this.onChange?.({ $changes: { options: {
        ...this.options,
        visible_attributes: attrsNames,
        all_attrs_visible: allAttrsVisible
      } } });
    }
  },
  toggleAttrVisibility(attrName) {
    toggleAttrVisibility(
      attrName,
      this.visibleAttrNames,
      this.availableAttributes,
      (visibleAttrNames, allAttrsVisible) => this.updateVisibleAttributes(visibleAttrNames, allAttrsVisible)
    );
  },
  destroyAttrVisibilityMixin() {
    if (this.watchAttributesOff) this.watchAttributesOff();
  }
};

// public/app/apps/cards/common/component-mixins/card-creator.js
var CardsAppCardCreatorMixin = {
  $inject: [
    "$scope",
    "$compile",
    "$timeout",
    "$element",
    "addCardLinkModal",
    "cardModal",
    "$q"
  ],
  initCardCreatorMixin() {
    this.customTemplate = this.cardCreatorTemplate || "";
    this.cardCreatorHtml = `<cards-app-card-creator
      custom-template="${this.customTemplate}"
      filtered="$ctrl.filtered"
      options="$ctrl.cardCreatorOptions"
      on-card-create="$ctrl.createCard($title, $openModal)"
      on-close="$ctrl.closeCreator($event)"
      on-link-create="$ctrl.openCreateLinkModal()"
      on-load="$ctrl.updateCreator()"
      on-edit="$ctrl.updateCreator()"
    ></cards-app-card-creator>`;
    this.isCreatingCard = false;
    if (this.withCardSelector) {
      this.refreshSelectorWatchers();
    }
    this.$scope.$on("closeCardCreator", () => {
      this.closeCreator();
    });
  },
  changeCardCreatorMixin(changes) {
    const selectorChanged = changes.selector && !changes.selector.isFirstChange();
    if (this.withCardSelector && selectorChanged) {
      this.refreshSelectorWatchers();
    }
  },
  get canCreateCard() {
    const groups = this.groups || [this.group];
    if (!this.project || this.project.is_archived || this.project.is_portfolio) {
      return false;
    }
    return groups.some((group2) => !group2 || !group2.is_creation_hidden) && groups.every((group2) => canAddCard(this.project, group2 ? group2.id : null));
  },
  openCreator() {
    if (this.isCreatingCard) return;
    if (!this.canCreateCard) return;
    const cardContainerElement = jquery_default(this.$element).find(".ui-sortable-cards-items-container");
    this.isOpeningCreator = true;
    this.isCreatingCard = true;
    this.lastCardCreated = null;
    if (this.withCardSelector) {
      this.selector.selectPage(this.selectorPage, "bottom");
    }
    this.creatorScope = this.$scope.$new();
    this.creatorElement = jquery_default(this.$compile(this.cardCreatorHtml)(this.creatorScope));
    cardContainerElement.append(this.creatorElement);
    this.isOpeningCreator = false;
    if (this.openCreatorScrollTimeout) {
      this.$timeout.cancel(this.openCreatorScrollTimeout);
    }
    this.openCreatorScrollTimeout = this.$timeout(() => {
      cardContainerElement.scrollTop(cardContainerElement[0].scrollHeight);
    }, 0, false);
  },
  reframeCreator() {
    const cardContainerElement = jquery_default(this.$element).find(".ui-sortable-cards-items-container");
    let needScroll;
    const currentScrollTop = cardContainerElement[0].scrollTop;
    const spanHeight = cardContainerElement[0].clientHeight;
    const spanLimit = {
      top: currentScrollTop,
      bottom: currentScrollTop + spanHeight
    };
    const creatorOffset = {
      top: this.creatorElement[0].offsetTop,
      bottom: this.creatorElement[0].offsetTop + this.creatorElement[0].offsetHeight
    };
    if (spanLimit.top > creatorOffset.top) {
      needScroll = creatorOffset.top;
    }
    if (spanLimit.bottom < creatorOffset.bottom) {
      needScroll = creatorOffset.bottom;
    }
    if (needScroll) {
      cardContainerElement.scrollTop(needScroll);
    }
  },
  updateCreator() {
    if (this.onEditingCard) {
      this.onEditingCard();
    }
  },
  closeCreator(event2) {
    if (this.withCardSelector) {
      if (event2 && event2.keyCode === 9) {
        this.selector.nextPage();
      }
      this.refreshSelector();
    }
    if (this.isCreatingCard) {
      this.removeCreator();
    }
  },
  removeCreator() {
    this.isCreatingCard = false;
    if (this.creatorScope) {
      this.creatorScope.$destroy();
    }
    if (this.creatorElement) {
      this.creatorElement.remove();
      this.creatorElement = null;
    }
    if (this.removeCreatorTimeout) {
      this.$timeout.cancel(this.removeCreatorTimeout);
    }
    if (this.onEditingCard) {
      this.removeCreatorTimeout = this.$timeout(() => {
        this.onEditingCard();
      });
    }
  },
  createCard(title, openModal2) {
    const staticGroups = [];
    const dynamicGroups = [];
    const groups = this.groups || [this.group];
    groups.forEach((group2) => {
      if (group2) {
        if (!group2.is_dynamic) {
          staticGroups.push(group2);
        } else {
          dynamicGroups.push(group2);
        }
      }
    });
    const [tmpCards, onCardsCreatedPromise] = createManyCards(this.board, title, staticGroups, null);
    this.$q.when(onCardsCreatedPromise, (cards) => {
      cards.forEach((card) => {
        dynamicGroups.forEach((group2) => this.$q.digest(group2.handleCardEnter(card, false)));
      });
      if (openModal2) {
        this.$cardModal.open(cards[0], { parentSelector: null, showArchived: this.options?.include_archived });
        this.afterCardCreation(cards[0]);
      }
    });
    if (openModal2) {
      this.closeCreator();
    } else {
      this.afterCardCreation(tmpCards[tmpCards.length - 1]);
    }
  },
  afterCardCreation(card) {
    this.lastCardCreated = card;
    if (this.afterCreationScrollTimeout) {
      this.$timeout.cancel(this.afterCreationScrollTimeout);
    }
    this.afterCreationScrollTimeout = this.$timeout(() => {
      const cardContainerElement = jquery_default(this.$element).find(".ui-sortable-cards-items-container");
      cardContainerElement.scrollTop(cardContainerElement[0].scrollHeight);
    }, 500, false);
  },
  openCreateLinkModal() {
    const staticGroups = [];
    const dynamicGroups = [];
    const groups = this.groups || [this.group];
    groups.forEach((group2) => {
      if (group2) {
        if (!group2.is_dynamic) {
          staticGroups.push(group2);
        } else {
          dynamicGroups.push(group2);
        }
      }
    });
    this.$addCardLinkModal.open(this.board, staticGroups, dynamicGroups);
  },
  refreshSelector() {
    if (!this.selector.selected) return;
    if (this.lastCardCreated) {
      this.selector.select(this.lastCardCreated);
    } else {
      this.selector.selectLastOfPage(this.selectorPage);
    }
  },
  refreshSelectorWatchers() {
    if (this.deregisterSelectorWatchers) {
      this.deregisterSelectorWatchers();
    }
    this.deregisterSelectorWatchers = offMany([
      this.selector.on(null, this.selectorPage, () => {
        if (this.selector.selectedPageSection === "bottom") {
          if (!this.isCreatingCard) {
            this.openCreator();
          }
        }
      }),
      this.selector.off(null, this.selectorPage, () => {
        if (this.selector.selectedPageSection === "bottom" && this.isCreatingCard && !this.isOpeningCreator) {
          this.removeCreator();
        }
      })
    ]);
  },
  destroyCardCreatorMixin() {
    if (this.removeCreatorTimeout) {
      this.$timeout.cancel(this.removeCreatorTimeout);
      this.removeCreatorTimeout = null;
    }
    if (this.afterCreationScrollTimeout) {
      this.$timeout.cancel(this.afterCreationScrollTimeout);
      this.afterCreationScrollTimeout = null;
    }
    if (this.openCreatorScrollTimeout) {
      this.$timeout.cancel(this.openCreatorScrollTimeout);
      this.openCreatorScrollTimeout = null;
    }
    if (this.deregisterSelectorWatchers) {
      this.deregisterSelectorWatchers();
    }
  }
};

// public/app/apps/cards/common/component-mixins/date.ts
var CardsAppDateMixin = {
  $inject: ["$scope"],
  initDateMixin() {
    this.availableAttributes = /* @__PURE__ */ new Map();
    this.activeDateAttribute = /* @__PURE__ */ new Map();
    this.activeDateAttributeNames = [];
    this.refreshAttributesWatcher();
    this.$scope.$on("connectivityChanged", () => this.refreshDatesEditable());
    this.$scope.$on("screensize:changed", () => this.refreshDatesEditable());
  },
  changeDateMixin(changes) {
    const storeChanged = changes.store && !changes.store.isFirstChange();
    const boardChanged = changes.board && !changes.board.isFirstChange();
    const projectChanged = boardChanged && (projectStore.tryGetForCard(this.board) || {}).id !== (this.project || {}).id;
    if (projectChanged || !this.project && storeChanged || this.haveActiveDateAttrsChanged(changes)) {
      this.refreshAttributesWatcher();
    }
  },
  haveActiveDateAttrsChanged(changes, onInit = false) {
    return changes.options && (!changes.options.isFirstChange() || onInit) && useFieldKeys.some(
      (prop2) => this.options?.[prop2] !== changes.options.previousValue?.[prop2]
    );
  },
  refreshAttributesWatcher() {
    if (this.deregisterAttributesWatcher) this.deregisterAttributesWatcher();
    const modelStore = getScopedModelStore(this.project, this.store);
    this.showEmptyNotice = true;
    if (modelStore) {
      this.deregisterAttributesWatcher = modelStore.subscribe(() => {
        this.refreshAvailableDateAttributes();
        this.refreshActiveDateAttributes();
        this.refreshDatesEditable();
        this.$scope.$applyAsync();
      }, true);
    } else if (!this.project) {
      this.showEmptyNotice = false;
    }
  },
  refreshAvailableDateAttributes() {
    const availableDateAttributes = getAvailableAttrsOfType(
      this.project,
      this.store,
      "date"
    );
    if (availablesEquals(this.availableDateAttributes, availableDateAttributes))
      return;
    this.availableDateAttributes = availableDateAttributes;
  },
  refreshActiveDateAttributes() {
    let activeDateAttribute = getSelectedAttributes(
      this.availableDateAttributes,
      this.options,
      !this.multipleActiveDates
    );
    if (availablesEquals(this.activeDateAttribute, activeDateAttribute)) return;
    this.activeDateAttribute = activeDateAttribute;
    this.activeDateAttributeNames = Array.from(this.activeDateAttribute.keys());
  },
  refreshDatesEditable() {
    if (!this.project || isScreensizeXS() || !isConnected() || this.activeDateAttribute.size === 0) {
      this.datesEditable = false;
      return;
    }
    for (const [attrName, attrGroup] of this.activeDateAttribute) {
      for (const attr of attrGroup) {
        if (canEditSomeAttributes(this.project, attr) && !attr.is_computed) {
          this.datesEditable = true;
          return;
        }
      }
    }
    this.datesEditable = false;
  },
  destroyDateMixin() {
    if (this.deregisterAttributesWatcher) this.deregisterAttributesWatcher();
  }
};

// public/app/apps/cards/common/group-utils.ts
function setGroupSortBy(options2, group2, value2, reverse = false) {
  const newModeOptions = Object.assign({}, unwrap(options2));
  if (newModeOptions[`groups_${group2.title}_order`]) {
    newModeOptions[`groups_${group2.title}_order`] = null;
  }
  if (newModeOptions[`table_${group2.title}_order`]) {
    newModeOptions[`table_${group2.title}_order`] = null;
  }
  const title = group2.title.toLowerCase();
  let overrides2 = Object.assign({}, newModeOptions["sort_by_overrides"] || {});
  if (value2) {
    overrides2[title] = { value: value2, reverse };
  } else if (overrides2[title]) {
    delete overrides2[title];
  }
  newModeOptions["sort_by_overrides"] = overrides2;
  return newModeOptions;
}
function getGroupSortBy(options2, group2, forced) {
  let value2 = getSortBy(options2, forced);
  if (group2) {
    const title = group2.title.toLowerCase();
    if (options2["sort_by_overrides"] && options2["sort_by_overrides"][title]) {
      value2 = options2["sort_by_overrides"][title];
    } else if (options2[`groups_${group2.title}_order`]) {
      value2 = options2[`groups_${group2.title}_order`];
    } else if (options2[`table_${group2.title}_order`]) {
      value2 = options2[`table_${group2.title}_order`];
    }
  }
  return value2;
}
function handleCardDroppedInGroup(groupBy2, groups, params) {
  const { card, position, append: append2, fromCtrl } = params;
  const groupsToAdd = [];
  const groupsToRelocate = [];
  const groupTypesToRemove = [];
  let ungroupedToSort = false;
  for (const [idx, group2] of groups.entries()) {
    if (!groupBy2[idx].getGroupType()) {
      if (groupBy2[idx].getAttribute()) {
        if (group2) {
          if (!cardHasAttrValue(card, group2.attribute_value, group2.attribute_id)) {
            group2.handleCardEnter(card, append2);
          }
        } else {
          if (fromCtrl && fromCtrl.groups) {
            const group3 = (Array.isArray(fromCtrl.groups) ? fromCtrl.groups : [fromCtrl.groups])[idx];
            if (group3) {
              group3.handleCardLeave(card);
            }
          }
        }
        continue;
      }
    }
    if (group2) {
      if (!groupBy2[idx].oneGroupPerCard && append2) {
        groupsToAdd.push(group2);
      } else {
        groupsToRelocate.push(group2);
      }
    } else {
      if (groupBy2[idx].getGroupType()) {
        if (cardHasGroupFromGroupType(card, groupBy2[idx].getGroupType())) {
          groupTypesToRemove.push(groupBy2[idx].getGroupType());
        } else {
          ungroupedToSort = true;
        }
      } else {
        ungroupedToSort = true;
      }
    }
  }
  return Promise.all([
    groupsToAdd.length ? addCardToGroup(card, groupsToAdd, position) : null,
    groupsToRelocate.length ? relocateCard(card, groupsToRelocate, position) : null,
    ungroupedToSort ? moveCardInUngrouped(card, position) : null,
    ...groupTypesToRemove.map(
      (groupType) => removeCardFromGroupType(card, groupType, position)
    )
  ]);
}

// public/app/apps/cards/common/component-mixins/group.js
var CardsAppGroupMixin = {
  $inject: ["$scope", "stylesheetManager", "$timeout", "projectPage", "$q"],
  initGroupMixin() {
    this.modeOptionsKeyPrefix = this.modeOptionsKeyPrefix || "group_";
    this.firstDisplay = true;
    this.shouldRenderFilteredCards = !this.filtered;
    this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
    this.title = this.customTitle || (this.group ? this.group.title : "");
    this.totalCardsCount = 0;
    this.showProjectOnCards = !this.board && (this.groupBy || []).every((groupByDim) => !groupByDim.isProjects());
    this.canSortGroupBy = this.groupBy ? canSortGroupBy(this.project, this.groupBy[0]) : null;
    this.debouncedRefreshCards = debounce2(() => {
      this.refreshCards();
    }, 50);
    this.refreshSortBy();
    this.refreshCardsWatcher();
    this.refreshGroupWatcher();
    this.toggleCollapse();
    if (this.withStats) {
      this.showStats = (this.options || {})[this.modeOptionsKey + "_stats"] || false;
    }
    if (this.withProgressBar) {
      this.showProgress = (this.options || {})["showProgress"] || this.showStats;
    }
    if (this.options?.hideEmptyGroups) {
      this.$element.toggleClass("hidden", this.isGroupFilteredOut());
    }
    if (this.withCardSelector) {
      this.refreshSelectorPage();
      this.$scope.$on("cardSelectorRefreshPageItems", () => this.refreshSelectorPageItems());
    }
    if (this.withCardsAttributeAggregation) {
      this.aggregations = [];
    }
    this.$scope.$on("connectivityChanged", () => {
      this.refreshSortBy();
    });
    this.$scope.$on("shouldRenderFilteredCards", (event2, newVal) => {
      this.shouldRenderFilteredCards = newVal;
      this.refreshCardsWatcher();
    });
    this.$scope.$on("shouldOpenCardCreatorOnInit", () => {
      if (this.openCreator && this.openCreatorOnInit) {
        this.openCreator();
      }
    });
    this.$scope.$on("selectAllCards", (e3, cardIds) => {
      if (!this.collapsed) {
        this.$projectPage.selectedCards.push(...this.cards.filter((c3) => (!cardIds || cardIds.includes(c3.id)) && this.isCardFiltered(c3)).map((c3) => c3.id));
      }
    });
    if (!this.selectAllCardsDisabled) {
      this.$scope.$on("selectAllCardsInGroup", (e3, groupId) => {
        if (!this.collapsed && groupId === this.group?.id) {
          this.cards.filter((c3) => this.isCardFiltered(c3)).forEach((c3) => this.$projectPage.selectCard(c3));
        }
      });
    }
  },
  changeGroupMixin(changes) {
    const groupChanged = changes.group && !changes.group.isFirstChange();
    const storeChanged = changes.store && !changes.store.isFirstChange();
    const customTitleChanged = changes.customTitle && !changes.customTitle.isFirstChange();
    const boardChanged = changes.board && !changes.board.isFirstChange();
    const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
    const firstGroupByChanged = groupByChanged && !equals2((this.groupBy || [])[0], (changes.groupBy.previousValue || [])[0]);
    const matchingCardIdsChanged = changes.matchingCardIds && !changes.matchingCardIds.isFirstChange() && !equals(this.matchingCardIds, changes.matchingCardIds.previousValue);
    const optionsChanged = changes.options && !changes.options.isFirstChange();
    const optionChanged = (optionLabel) => optionsChanged && !equals(this.options?.[optionLabel], changes.options.previousValue?.[optionLabel]);
    const selectorChanged = changes.selector && !changes.selector.isFirstChange();
    if (firstGroupByChanged && !storeChanged && !optionChanged("include_archived") && !!this.group) {
      this.destroyGroupMixin();
      return;
    }
    if (boardChanged) {
      this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
    }
    if (groupChanged || customTitleChanged) {
      this.title = this.customTitle || (this.group ? this.group.title : "");
    }
    if (firstGroupByChanged || boardChanged) {
      this.showProjectOnCards = !this.board && (this.groupBy || []).every((groupByDim) => !groupByDim.isProjects());
      this.canSortGroupBy = this.groupBy ? canSortGroupBy(this.project, this.groupBy[0]) : null;
    }
    let sortByChanged = false;
    if (optionsChanged) {
      sortByChanged = this.refreshSortBy();
    }
    if (groupChanged || storeChanged || optionChanged("include_archived") || optionChanged("include_descendants")) {
      this.refreshCardsWatcher();
    } else if (sortByChanged) {
      this.refreshCards();
    } else if (matchingCardIdsChanged) {
      this.$element.toggleClass("hidden", this.isGroupFilteredOut());
      if (!this.shouldRenderFilteredCards) {
        this.refreshCardsWatcher();
      } else {
        const oldMatchingCardsCount = this.matchingCardsCount;
        const oldAggregations = this.aggregations;
        this.matchingCards = this._matchingCards;
        this.refreshMatchingCardsCount();
        if (this.withCardsAttributeAggregation) {
          this.aggregations = getCardsAttributeAggregations(this.matchingCards, this.project);
        }
        if (oldMatchingCardsCount !== this.matchingCardsCount || !equals(this.aggregations, oldAggregations)) {
          this.$scope.$applyAsync();
        }
      }
    } else if (optionChanged("hideEmptyGroups")) {
      this.$element.toggleClass("hidden", this.isGroupFilteredOut());
    }
    if (groupChanged || optionsChanged) {
      this.refreshGroupWatcher();
    }
    if (optionChanged(this.modeOptionsKey + "_collapsed")) {
      this.toggleCollapse();
    }
    if (optionChanged(this.modeOptionsKey + "_stats")) {
      if (this.withStats) {
        this.showStats = (this.options || {})[this.modeOptionsKey + "_stats"] || false;
      }
      if (this.withProgressBar) {
        this.showProgress = (this.options || {})[this.modeOptionsKey + "_stats"] || this.showStats;
      }
    } else if (this.withProgressBar && optionChanged("showProgress")) {
      this.showProgress = (this.options || {})["showProgress"] || this.showStats;
    }
    if (this.withCardSelector && (groupChanged || selectorChanged)) {
      this.refreshSelectorPage();
    }
    if (this.withCardSelector && selectorChanged) {
      this.refreshSelectorPageItems();
    }
  },
  get showMisc() {
    return !!this.group && (this.totalCardsCount === 0 || !!this.group.always_show_description) && (!!this.group.description || !!this.group.icon);
  },
  get canEditTitle() {
    return !!this.project && !this.project.is_archived && !!this.group && !this.group.is_dynamic && isConnected() && canEditGroup(this.project, this.group.id);
  },
  get canSortCards() {
    return !!this.project && !this.project.is_archived && this.canSortGroupBy;
  },
  get canFreeSort() {
    return !this.freeSortDisabled && !this.group?.is_dynamic && canFreeSort(this.project, this.groupBy, this.options);
  },
  get modeOptionsKey() {
    return this.modeOptionsKeyPrefix + this.title;
  },
  get filtered() {
    return !!this.filter;
  },
  onOptionsChange(name2, value2) {
    const newModeOptions = { ...this.options || {} };
    newModeOptions[this.modeOptionsKey + "_" + name2] = value2;
    return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
  },
  isGroupFilteredOut() {
    if (!(this.options || {}).hideEmptyGroups) return false;
    return !(this.cards || []).some((card) => this.isCardFiltered(card));
  },
  refreshCardsWatcher(immediate = true) {
    if (this.cardStoreWatcherOff) this.cardStoreWatcherOff();
    this.debouncedRefreshCards.clear();
    this.cardStore = this.formatStore(this.shouldRenderFilteredCards);
    if (!this.cardStore) return;
    this.cardStoreWatcherOff = this.cardStore.subscribe(
      () => this.debouncedRefreshCards(),
      immediate
    );
  },
  queryCards() {
    return sortCardQuery(this.cardStore.query(), this.sortBy, !this.group, {
      modelStore: getScopedModelStore(this.project, this.cardStore),
      groupTypeStore: getScopedGroupTypeStore(this.project, this.cardStore)
    });
  },
  refreshCards() {
    const oldCards = this.cards;
    const cards = this.queryCards();
    this.deregisterAddCardsTimer();
    if (this.firstDisplay && this.handleCards) {
      this.cards = [];
      this.firstDisplay = false;
      this.addCards(cards);
    } else {
      this.cards = cards;
      this.refreshAfterCardsUpdate(oldCards);
    }
  },
  addCards(cards) {
    this.cards = this.cards.concat(cards.splice(0, Math.min(cards.length, 100)));
    if (cards.length > 0) {
      this.addCardsTimeout = this.$timeout(() => {
        this.addCardsTimeout = null;
        this.addCards(cards);
      }, 50);
    } else {
      this.refreshAfterCardsUpdate();
    }
  },
  deregisterAddCardsTimer() {
    if (this.addCardsTimeout) {
      this.$timeout.cancel(this.addCardsTimeout);
      this.addCardsTimeout = null;
    }
  },
  get _allCards() {
    return this.shouldRenderFilteredCards ? this.cards || [] : this.formatStore(true).query();
  },
  get _matchingCards() {
    return this.shouldRenderFilteredCards && this.filtered && Array.isArray(this.matchingCardIds) ? (this.cards || []).filter((c3) => this.matchingCardIds.includes(c3.id)) : this.cards || [];
  },
  refreshAfterCardsUpdate(oldCards) {
    let needDigest = false;
    if ((oldCards || []).length !== (this.cards || []).length || (oldCards || []).some((c3, idx) => this.cards[idx].id !== c3.id)) {
      needDigest = true;
    }
    if (this.withCardSelector) this.refreshSelectorPageItems();
    const old = {
      totalCardsCount: this.totalCardsCount,
      matchingCardsCount: this.matchingCardsCount,
      aggregations: this.aggregations
    };
    this.totalCardsCount = this._allCards.length;
    this.matchingCards = this._matchingCards;
    this.refreshMatchingCardsCount();
    if (this.withCardsAttributeAggregation) {
      this.aggregations = getCardsAttributeAggregations(this.matchingCards, this.project);
    }
    if (Object.keys(old).some((key2) => !equals(old[key2], this[key2]))) {
      needDigest = true;
    }
    if (this.options?.hideEmptyGroups) {
      this.$element.toggleClass("hidden", this.isGroupFilteredOut());
    }
    if (needDigest) {
      this.$scope.$applyAsync();
    }
  },
  refreshSelectorPageItems() {
    this.selector.replacePageItems(this.selectorPage, this.cards);
  },
  refreshMatchingCardsCount() {
    if ((this.cards || []).length > 0 && this.filtered && Array.isArray(this.matchingCardIds)) {
      this.matchingCardsCount = this.matchingCards.length;
    } else {
      this.matchingCardsCount = null;
    }
  },
  formatStore(shouldRenderFilteredCards = true) {
    let scope = {};
    let store2 = this.store;
    if (this.group) {
      if (this.group.is_dynamic) {
        scope = {};
        store2 = this.group.getCardStore((this.options || {}).include_archived, (this.options || {}).include_descendants);
      } else {
        scope["groups"] = matchGroup(this.group.id);
      }
    }
    if (!shouldRenderFilteredCards && this.filtered) {
      scope["id"] = query_exports.any(this.matchingCardIds || []);
    }
    return store2 ? Object.keys(scope).length > 0 ? store2.scoped(scope) : store2 : null;
  },
  refreshSelectorPage() {
    if (this.selectorWatchersOffs) {
      this.selectorWatchersOffs.map((off) => off());
    }
    if (!this.selector) {
      this.selectorPage = null;
      return;
    }
    if (this.group) {
      this.selectorPage = { group: this.group };
    } else if (this.store) {
      this.selectorPage = { ungrouped: true };
    }
    this.selectorWatchersOffs = [this.selectorPage].reduce((accu, selectorPage) => {
      const listeners = [
        this.selector.on(null, selectorPage, () => {
          if (this.selector.selectedPageSection === "header") {
            if (!this.group) {
              this.selector.nextPage();
            } else if (!this.canEditTitle) {
              this.selector.unselectPage();
            } else {
              this.editingTitle = true;
            }
          }
        }),
        this.selector.off(null, selectorPage, () => {
          if (this.selector.selectedPageSection === "header" && this.editingTitle) {
            this.editingTitle = false;
          }
        })
      ];
      return accu.concat(listeners);
    }, []);
  },
  refreshSortBy() {
    const newSortBy = getGroupSortBy(this.options, this.group || { title: this.title }, !this.canFreeSort);
    if (!equals(this.sortBy, newSortBy)) {
      this.sortBy = newSortBy;
      return true;
    }
  },
  toggleStats(value2) {
    const newVal = value2 !== void 0 ? value2 : !this.showStats;
    this.onOptionsChange("stats", newVal);
  },
  toggleCollapse() {
    this.collapsed = this.groupBy && !this.groupBy[0].isNothing() && (this.options || {})[this.modeOptionsKey + "_collapsed"] || false;
    this.expandedOnce = this.expandedOnce || (this.collapsed ? void 0 : true);
    this.$element.toggleClass("is-collapsed", this.collapsed);
    this.$scope.$broadcast("refreshCardHighlight");
  },
  hasAggregation(attr) {
    for (let aggregate of this.aggregations) {
      if (aggregate.name === attr.name) {
        return true;
      }
    }
    return false;
  },
  getAggregatedValue(attr) {
    for (let aggregate of this.aggregations) {
      if (aggregate.name === attr.name) {
        return aggregate.value;
      }
    }
  },
  setColorWatcher() {
    return this.groupBy[0].getGroupStore().watch(this.group, "updated", (gr) => {
      const classNamePrefix = this.modeOptionsKeyPrefix.replace(/_/g, "-");
      if (this.color && this.color !== gr.color) {
        jquery_default(this.$element).removeClassRegex(classNamePrefix);
      }
      if (!gr || !gr.color) {
        return;
      }
      const name2 = classNamePrefix + gr.color.substr(1);
      this.$stylesheetManager.createTheme(name2, gr.color, this.groupColorTheme);
      this.$element.addClass(name2);
      this.color = gr.color;
    }), this.groupBy[1].getGroupStore().watch(this.group, "updated", (gr) => {
      const classNamePrefix = this.modeOptionsKeyPrefix.replace(/_/g, "-");
      if (this.color && this.color !== gr.color) {
        jquery_default(this.$element).removeClassRegex(classNamePrefix);
      }
      if (!gr || !gr.color) {
        return;
      }
      const name2 = classNamePrefix + gr.color.substr(1);
      this.$stylesheetManager.createTheme(name2, gr.color, this.groupColorTheme);
      this.$element.addClass(name2);
      this.color = gr.color;
    });
  },
  refreshGroupWatcher() {
    if (this.groupWatchersOff) {
      this.groupWatchersOff();
    }
    if (!this.group) return;
    this.groupWatchersOff = offMany([
      this.setColorWatcher(),
      this.groupBy[0].getGroupStore().watch(this.group, "updated", (group2) => {
        if (this.title !== group2.title) {
          this.$scope.$evalAsync(() => {
            this.title = group2.title;
          });
        }
      }, false)
    ]);
  },
  // drop actions don't wait for API response to update the cardStore so that we can update the UI right away.
  // We don't want to wait to cardStore.watcher because it debounce the update of the UI
  // and the card is briefly back to its previous position.
  // So we deregister the watcher, refresh the cards then register the watcher back,
  // in both fromCtrl and targetCtrl
  // TODO: we might want to have a better implementation of this mecanism
  beforeCardDropped(params) {
    this.cardStoreWatcherOff();
    this.cardStoreWatcherOff = null;
  },
  handleCardDropped(params) {
    const promise = handleCardDroppedInGroup(this.groupBy, [this.group], params);
    this.$q.digest(promise);
    return promise;
  },
  afterCardDropped(params) {
    this.refreshCards();
    this.refreshCardsWatcher(false);
  },
  isCardFiltered(card) {
    if (!isConnected()) return true;
    if (!Array.isArray(this.matchingCardIds)) return true;
    return this.matchingCardIds.indexOf(card.id) !== -1;
  },
  destroyGroupMixin() {
    if (this.cardStoreWatcherOff) this.cardStoreWatcherOff();
    if (this.groupWatchersOff) this.groupWatchersOff();
    if (this.debouncedUpdateCardsTimerId) {
      this.$timeout.cancel(this.debouncedUpdateCardsTimerId);
    }
    if (this.selectorWatchersOffs) {
      this.selectorWatchersOffs.map((off) => off());
    }
    this.deregisterAddCardsTimer();
    this.debouncedRefreshCards.clear();
  }
};

// public/app/apps/cards/common/component-mixins/groupable.ts
var CardsAppGroupableMixin = {
  $inject: ["$scope", "cardsSelector", "cardModal", "$q"],
  initGroupableMixin() {
    this.groups = [];
    this.ungroupedCardsStore = null;
    this.ungroupedCardsVisible = false;
    if (this.withCardSelector) {
      this.selector = this.$cardsSelector.push(this.$scope);
      this.selector.canSelectPages = true;
      this.selector.cycleThroughPagesWhenSelected = true;
      this.addGroupHotkey = "i";
      this.$cardsSelector.hotkeys(this.$scope, [
        {
          combo: "c",
          needsCard: false,
          description: _4("Add a card"),
          callback: (card, selector) => {
            selector.selectPage(selector.getCurrentPage() || 0, "bottom");
          }
        },
        {
          combo: "shift+i",
          description: _4("Edit group title"),
          callback: (card, selector) => {
            const currentPage = selector.getCurrentPage();
            if (!currentPage.ungrouped) {
              selector.selectPage(currentPage, "header", false);
            }
          }
        }
      ], () => !this.$cardModal.current);
    }
    this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
    this.onGroupByChanged();
    this.refreshUngroupedLabel();
    this.watchSortChoices(true);
    this.isFilteredOnFirstGroupBy = isProjectFilteredOnGroupBy((this.groupBy || [])[0], this.project, this.filter);
    this.$scope.$on("minimizeAllGroups", () => {
      this.toggleAllCollapsed(true);
    });
    this.$scope.$on("maximizeAllGroups", () => {
      this.toggleAllCollapsed(false);
    });
    this.$scope.$on("startSortingCards", () => {
      this.$scope.$broadcast("closeCardCreator");
    });
  },
  changeGroupableMixin(changes) {
    const storeChanged = changes.store && !changes.store.isFirstChange();
    const boardChanged = changes.board && !changes.board.isFirstChange();
    const projectChanged = boardChanged && (projectStore.tryGetForCard(this.board) || {}).id !== (this.project || {}).id;
    const optionsChanged = changes.options && !changes.options.isFirstChange();
    const filterChanged = changes.filter && !changes.filter.isFirstChange();
    const showUngroupedCardsChanged = optionsChanged && (this.options || {}).showUngroupedCards !== (changes.options.previousValue || {}).showUngroupedCards;
    const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
    const firstGroupByChanged = groupByChanged && !equals2((this.groupBy || [])[0], (changes.groupBy.previousValue || [])[0]);
    if (boardChanged) {
      this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
    }
    if (firstGroupByChanged || storeChanged) {
      this.onGroupByChanged();
      this.refreshUngroupedLabel();
    } else if (showUngroupedCardsChanged) {
      this.refreshUngroupedVisibility();
      if (this.withCardSelector) this.refreshSelectorPages();
    }
    if (projectChanged || !this.project && storeChanged) {
      this.watchSortChoices(true);
    }
    if (firstGroupByChanged || projectChanged || filterChanged) {
      this.isFilteredOnFirstGroupBy = isProjectFilteredOnGroupBy((this.groupBy || [])[0], this.project, this.filter);
    }
  },
  refreshUngroupedLabel() {
    if (!this.groupBy || this.groupBy[0].isNothing()) {
      this.ungroupedLabel = _4("(ungrouped)");
    } else {
      this.ungroupedLabel = _4("(no {group_type})", { group_type: this.groupBy[0].getLabel().toLowerCase() });
    }
  },
  get canAddGroup() {
    if (!this.project || this.project.status || !this.groupBy || !this.groupBy[0]) return false;
    return this.groupBy[0].canAddGroup() && !this.project.is_archived && isConnected() && canAddGroup(this.project);
  },
  // WATCHING GROUP BY
  onGroupByChanged() {
    if (this.deregisterStoreWatchers) {
      this.deregisterStoreWatchers();
    }
    this.deregisterStoreWatchers = offMany([
      this.setupUngroupedCardsWatcher(),
      this.setupGroupsWatcher()
    ]);
    if (this.withCardSelector) this.refreshSelectorPages();
  },
  setupGroupsWatcher() {
    this.groups = [];
    if (!this.groupBy || !this.groupBy[0]) return;
    const groupStore = this.groupBy[0].getGroupStore();
    return groupStore.subscribe(() => {
      const oldGroupsCount = (this.groups || []).length;
      this.groups = groupStore.query({}, { sortBy: "position" });
      if (this.withCardSelector) this.refreshSelectorPages();
      if (oldGroupsCount !== this.groups.length) {
        this.$scope.$applyAsync();
      }
    }, true);
  },
  setupUngroupedCardsWatcher() {
    this.refreshUngroupedVisibility();
    if (!this.groupBy || !this.groupBy[0]) return;
    this.ungroupedCardsStore = this.groupBy[0].getUngroupedCardsStore();
    return this.ungroupedCardsStore.subscribe(() => {
      const oldUngroupedCardsVisible = this.ungroupedCardsVisible;
      this.refreshUngroupedVisibility();
      if (this.withCardSelector) this.refreshSelectorPages();
      if (oldUngroupedCardsVisible !== this.ungroupedCardsVisible) {
        this.$scope.$applyAsync();
      }
    });
  },
  // UNGROUPED VISIBILITY
  refreshUngroupedVisibility() {
    this.ungroupedCardsVisible = isUngroupedVisible((this.groupBy || [])[0], (this.options || {}).showUngroupedCards);
  },
  watchSortChoices(immediate) {
    if (this.watchSortChoicesOff) this.watchSortChoicesOff();
    const modelStore = getScopedModelStore(this.project, this.store);
    const groupTypeStore = getScopedGroupTypeStore(this.project, this.store);
    const watcher = () => {
      this.sortChoices = getSortableAttributes(this.project, this.store, true);
    };
    this.watchSortChoicesOff = offMany([
      modelStore.$watchAll(this.$scope, watcher, false),
      groupTypeStore.$watchAll(this.$scope, watcher, false)
    ]);
    if (immediate) {
      watcher();
    }
  },
  matchGroup(group2) {
    const query2 = this.filter;
    if (!query2) {
      return true;
    }
    const re2 = "#((({[^}]+})|([a-z\xC0-\u017F0-9_]+))(:(({[^}]+})|([a-z\xC0-\u017F0-9_]+)))?)";
    const matches3 = query2.match(new RegExp(re2, "gi"));
    if (!matches3 || !matches3.length) {
      return true;
    }
    if (query2.match(/(^|\s)not\s/gi)) {
      return true;
    }
    let typeIds = [];
    for (let i3 = 0; i3 < matches3.length; i3++) {
      const m3 = matches3[i3].match(new RegExp(re2, "i"));
      let search = unescapeKqlName(m3[2]);
      let type = null;
      if (m3[6] && m3[6] !== "{*}") {
        const typeName2 = unescapeKqlName(m3[2]);
        type = cardGroupTypeStore.queryByName(this.project, typeName2, true)?.[0];
        if (!type) {
          return true;
        }
        search = unescapeKqlName(m3[6]);
        if (kqlNameMatch(group2.title, search)) {
          return true;
        }
      }
      if (!type && kqlNameMatch(group2.title, search)) {
        return true;
      }
      if (type) {
        typeIds = typeIds.concat(type.id);
      } else {
        typeIds = typeIds.concat(pluck(cardGroupStore.query({
          parent_id: query_exports.any([void 0, this.board.id, this.project.top_level_card.id]),
          owner: query_exports.objMatch({ id: this.project.owner.id, type: this.project.owner.type }),
          title: (v3) => kqlNameMatch(v3, search)
        }), "type_id"));
      }
    }
    const seen = {};
    typeIds = typeIds.filter((typeId) => seen.hasOwnProperty(typeId) ? false : seen[typeId] = true);
    return !this.groupBy || !typeIds.length || typeIds.indexOf(group2.type_id) === -1 || typeIds.some((typeId) => {
      return this.groupBy.reduce((accu, gBy) => {
        if (!gBy) return accu;
        const groupType = gBy.getGroupType();
        if (!groupType) return accu;
        return accu.concat(groupType.id);
      }, []).indexOf(typeId) === -1;
    });
  },
  // SELECTORS
  refreshSelectorPages() {
    this.selector.resetPages();
    if (this.ungroupedCardsVisible) {
      this.selector.addPage([], { ungrouped: true });
    }
    this.groups.forEach((g3) => {
      this.selector.addPage([], { group: g3 });
    });
    this.$scope.$broadcast("cardSelectorRefreshPageItems");
  },
  toggleAllCollapsed(value2) {
    const newModeOptions = { ...this.options || {} };
    newModeOptions[(this.modeOptionsKeyPrefix || "groups") + "_" + this.ungroupedLabel + "_collapsed"] = value2;
    this.groups.forEach((group2) => {
      newModeOptions[(this.modeOptionsKeyPrefix || "groups") + "_" + group2.title + "_collapsed"] = value2;
    });
    return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
  },
  destroyGroupableMixin() {
    if (this.deregisterStoreWatchers) this.deregisterStoreWatchers();
    if (this.watchSortChoicesOff) this.watchSortChoicesOff();
  }
};

// public/app/apps/cards/calendar/ng-components/calendar.js
angular_default.module("kantree").directive("cardsAppCalendar", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/calendar/ng-components/templates/calendar.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppDateMixin) {
        static get $inject() {
          return (super.$inject || []).concat([
            "$element",
            "$scope",
            "$timeout",
            "cardsSelector",
            "$q",
            "cardModal",
            "cardGroupTypeGroupsModal",
            "cardICalendarModal",
            "iCalendarModal",
            "menuDropdown",
            "addCardLinkModal"
          ]);
        }
        constructor() {
          super(...arguments);
          this.onEventSourceUpdate = debounce2((scheduled3, unscheduled) => {
            this.$scope.$evalAsync(() => this._onEventSourceUpdate(scheduled3, unscheduled));
          }, 60);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.selector = this.$cardsSelector.push(this.$scope);
          this.unscheduled = [];
          this.unscheduledCollapsed = true;
          this.autoCollapseUnscheduled = true;
          this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          this.canCreateCard = this.project && !this.project.is_archived && !this.project.is_portfolio && canAddCard(this.project, null);
          this.cardsEditable = this.project && !this.project.is_archived && canEditCard(this.project);
          this.groupsEditable = this.project && !this.project.is_archived;
          this.multipleActiveDates = true;
          this.initDateMixin();
          this.refreshCardStoreWatcher();
          if (this.project || this.store) {
            this.groupTypeStore = getScopedGroupTypeStore(this.project, this.store, true);
            this.refreshAvailableDateAttributes();
            this.refreshDraggable();
          }
          if (this.board) {
            this.groupStore = getScopedGroupStore(this.board, this.store, null, this.options?.include_archived);
            this.refreshGroupStoreWatcher();
          }
          this.$scope.$on("connectivityChanged", () => this.refreshDraggable());
          this.$scope.$on("screensize:changed", () => this.refreshDraggable());
        }
        $onChanges(changes) {
          const storeChanged = changes.store && !changes.store.isFirstChange();
          const boardChanged = changes.board && !changes.board.isFirstChange();
          const projectChanged = boardChanged && (projectStore.tryGetForCard(this.board) || {}).id !== (this.project || {}).id;
          const optionsChanged = changes.options && !changes.options.isFirstChange();
          const includeArchivedChanged = optionsChanged && (this.options || {}).include_archived !== (changes.options.previousValue || {}).include_archived;
          const includeDescendantsChanged = optionsChanged && (this.options || {}).include_descendants !== (changes.options.previousValue || {}).include_descendants;
          const matchingCardIdsChanged = changes.matchingCardIds && !changes.matchingCardIds.isFirstChange();
          if (boardChanged) {
            this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          }
          this.changeDateMixin(changes);
          if (storeChanged || boardChanged || includeArchivedChanged || includeDescendantsChanged) {
            this.refreshCardStoreWatcher();
          } else if (matchingCardIdsChanged || this.haveActiveDateAttrsChanged(changes)) {
            this.refreshCards();
          }
          if (storeChanged || projectChanged) {
            this.groupTypeStore = getScopedGroupTypeStore(this.project, this.store, true);
            this.refreshDraggable();
          }
          if (this.haveActiveDateAttrsChanged(changes)) {
            this.refreshDraggable();
          }
          if (storeChanged || boardChanged || includeArchivedChanged) {
            if (this.board) {
              this.groupStore = getScopedGroupStore(this.board, this.store, null, this.options?.include_archived);
            } else {
              this.groupStore = null;
            }
            this.refreshGroupStoreWatcher();
          }
        }
        $postLink() {
          this.$scope.$on("projectSidePanelToggled", () => this.$scope.$broadcast("calendarComputeAspectRatio"));
          this.$scope.$on("gridstackChange", (event2) => this.$scope.$broadcast("calendarComputeAspectRatio"));
        }
        _onEventSourceUpdate(scheduled3, unscheduled) {
          this.unscheduled = unscheduled;
          this.$cardsSelector.addPage(unscheduled.map((u3) => u3.card));
          this.$cardsSelector.addPage(scheduled3.map((u3) => u3.card));
          if (this.autoCollapseUnscheduled && this.unscheduled.length) {
            this.unscheduledCollapsed = false;
          }
          this.autoCollapseUnscheduled = false;
          this.$timeout(() => {
            if (this.datesEditable) {
              this.$element.find(".unscheduled-cards .card-tile:not(.archived)").draggable({
                revert: true,
                distance: 6,
                revertDuration: 0,
                zIndex: 1e3,
                appendTo: "body",
                helper: function() {
                  const self2 = jquery_default(this);
                  const clone3 = self2.clone();
                  clone3.width(self2.outerWidth(true));
                  clone3.height(self2.outerHeight(true));
                  return clone3;
                }
              });
            }
          }, 0, false);
        }
        refreshCardStoreWatcher() {
          if (this.deregisterCardStoreWatcher) this.deregisterCardStoreWatcher();
          if (this.store) {
            this.deregisterCardStoreWatcher = this.store.subscribe(() => this.refreshCards(), true);
          }
        }
        refreshCards() {
          if (!!this.board) {
            this.cards = this.store.query().filter((card) => areAttributesAvailableForCard(card, this.activeDateAttribute) && cardMatchesFilterResult(card, this.matchingCardIds));
          } else {
            this.cards = this.store.query();
          }
          this.$scope.$broadcast("calendarUpdateEvents");
        }
        refreshGroupStoreWatcher() {
          if (this._groupStoreWatcherOff) this._groupStoreWatcherOff();
          if (this.groupStore) {
            this._groupStoreWatcherOff = this.groupStore.subscribe(() => this.refreshGroups(), true);
          }
        }
        refreshGroups() {
          this.groups = this.groupStore.scoped({ end_date: query_exports.notNull() }).query();
          this.$scope.$broadcast("calendarUpdateEvents");
        }
        refreshDraggable() {
          const draggableElements = this.$element.find(".unscheduled-cards .card-tile:not(.archived)");
          draggableElements.each((idx, element2) => {
            if (jquery_default(element2).draggable("instance")) {
              jquery_default(element2).draggable(this.datesEditable ? "enable" : "disable");
            }
          });
        }
        onCalendarChange(startDate, endDate, event2) {
          if (startDate && event2.allDay && endDate.clone().utc().format("HH:mm") === "00:00") {
            endDate = endDate.clone().subtract(1, "day");
          }
          if (event2.cardId) {
            const card = this.store.tryGet(event2.cardId);
            if (card) {
              let attr = event2.attr;
              if (!attr && this.activeDateAttribute.size) {
                attr = getCardAvailableAttributes(card, this.activeDateAttribute).find((attr2) => !attr2.is_computed);
              }
              if (attr) {
                this.$q.digest(setCardAttribute(
                  this.store.get(event2.cardId),
                  attr.id,
                  formatServerDateRange(attr, startDate, endDate)
                ));
              }
            }
          } else if (event2.groupId) {
            if (cardGroupStore.exists(event2.groupId)) {
              this.$q.digest(updateGroup(cardGroupStore.get(event2.groupId), {
                card_id: this.board.id,
                start_date: startDate.format("YYYY-MM-DD"),
                end_date: endDate.format("YYYY-MM-DD")
              }));
            }
          }
        }
        onEventSelect(event2) {
          if (event2.cardId) {
            if (this.store.exists(event2.cardId)) {
              this.$cardModal.open(this.store.get(event2.cardId), { parentSelector: this.selector, showArchived: (this.options || {}).include_archived });
            }
          } else if (event2.groupId && this.board) {
            if (this.groupTypeStore.exists(event2.groupId)) {
              this.$cardGroupTypeGroupsModal.open(this.groupTypeStore.get(event2.groupTypeId), this.board);
            }
          }
        }
        onDateSelected(start, stop, event2) {
          if (!event2) return;
          const attributes = {}, attr = findEditableAttribute(this.activeDateAttribute, this.project);
          if (!attr) return;
          attributes[attr.id] = formatServerDateRange(attr, start, stop.subtract(1, "days"));
          this.$menuDropdown.open(event2.target, {
            config: [{
              component: "cards-app-card-creator-menu-component",
              params: {
                filtered: false,
                onCardCreate: (title, openModal2) => {
                  const [tmpCards, onCardsCreatedPromise] = createManyCards(this.board, title, [], attributes);
                  if (openModal2) {
                    this.$q.when(onCardsCreatedPromise, (cards) => this.$cardModal.open(cards[0]));
                  }
                },
                onLinkCreate: () => {
                  this.$addCardLinkModal.open(this.board, [], [], attributes);
                }
              }
            }]
          }, this.$scope, { classes: "drop-theme-menu drop-theme-arrow drop-theme-card-creator" });
        }
        showIcalendarFeed() {
          if (this.board) {
            this.$cardICalendarModal.open(this.board);
          } else {
            this.$iCalendarModal.open(this.$q.digest(api_default.search.get_calendar_url.get({ q: this.filter })));
          }
        }
        toggleUnscheduledCollapse() {
          this.unscheduledCollapsed = !this.unscheduledCollapsed;
          this.$scope.$broadcast("calendarComputeAspectRatio");
        }
        onUnscheduledHeaderClick(event2) {
          event2.stopPropagation();
          this.toggleUnscheduledCollapse();
        }
        $onDestroy() {
          this.destroyDateMixin();
          if (this.deregisterCardStoreWatcher) this.deregisterCardStoreWatcher();
          if (this._groupStoreWatcherOff) this._groupStoreWatcherOff();
        }
      }
    };
  }
]);

// public/app/utils/selector.js
function SelectorError() {
}
function Selector(pages) {
  this.reset(pages);
}
Selector.prototype.reset = function(pages) {
  this.total = 0;
  this.position = null;
  this.previousPosition = null;
  this.selected = null;
  this.selectedPage = null;
  this.onListeners = [];
  this.offListeners = [];
  this.resetPages(pages || []);
  this.canSelectPages = false;
  this.cycleThroughPagesWhenSelected = false;
  this.blockItemSelectionWhilePageSelected = true;
  return this;
};
Selector.prototype.hasItems = function() {
  return this.total;
};
Selector.prototype.resetPages = function(pages) {
  this.pages = [];
  this.total = 0;
  if (pages) {
    pages.forEach(function(page) {
      this.addPage(page.items, page);
    }, this);
  }
  return this;
};
Selector.prototype._computePageBounds = function() {
  var cumul = 0;
  for (var i3 = 0; i3 < this.pages.length; i3++) {
    Object.assign(this.pages[i3], {
      index: i3,
      start: cumul,
      end: cumul + this.pages[i3].items.length
    });
    cumul += this.pages[i3].items.length;
  }
};
Selector.prototype.addPage = function(items, data2) {
  var start = 0;
  if (this.pages.length > 0) {
    start = this.pages[this.pages.length - 1].end;
  }
  this.pages.push(Object.assign({
    index: this.pages.length,
    items,
    start,
    end: start + items.length
  }, data2 || {}));
  this.total += items.length;
  return this;
};
Selector.prototype.matchPage = function(a3, b3) {
  return a3 && b3 && (a3 === b3 || query_exports.matchObject(a3, b3));
};
Selector.prototype.findPage = function(props2) {
  if (typeof props2 === "number") {
    return this.pages[props2];
  }
  var match2 = false;
  for (var i3 = 0; i3 < this.pages.length; i3++) {
    if (this.matchPage(this.pages[i3], props2)) {
      return this.pages[i3];
    }
  }
};
Selector.prototype.replacePageItems = function(page, items = []) {
  page = this.findPage(page);
  if (page) {
    this.total = this.total - page.items.length + items.length;
    page.items = items;
    this._computePageBounds();
    if (this.selected) {
      this._select(this.selected);
    }
  }
};
Selector.prototype.removePage = function(page) {
  page = this.findPage(page);
  if (page) {
    this.pages.splice(page.index, 1);
    this.total -= page.items.length;
    this._computePageBounds();
    if (this.selected) {
      this._select(this.selected);
    }
  }
};
Selector.prototype.getPageFromPosition = function(position) {
  for (var i3 = 0; i3 < this.pages.length; i3++) {
    if (position >= this.pages[i3].start && position < this.pages[i3].end) {
      return this.pages[i3];
    }
  }
  return null;
};
Selector.prototype.getCurrentPage = function() {
  if (this.selectedPage) {
    return this.selectedPage;
  }
  return this.getPageFromPosition(this.position);
};
Selector.prototype._move = function(delta) {
  var pos = this.position;
  if (pos === null) {
    pos = this.previousPosition || 0;
  }
  if (pos === 0 && delta < 0) {
    pos = this.total - 1;
  } else if (pos === this.total - 1 && delta > 0) {
    pos = 0;
  } else {
    pos += delta;
    if (pos < 0) {
      pos = 0;
    } else if (pos >= this.total) {
      pos = this.total - 1;
    }
  }
  return this.selectByPosition(pos);
};
Selector.prototype.prev = function(delta) {
  if (!this.selectedPage && this.position === null && this.previousPosition === null) {
    return this.selectByPosition(this.total - 1);
  }
  return this._move(-(delta || 1));
};
Selector.prototype.next = function(delta) {
  if (!this.selectedPage && this.position === null && this.previousPosition === null) {
    return this.selectByPosition(0);
  }
  return this._move(delta || 1);
};
Selector.prototype._movePage = function(delta) {
  var pos = this.position;
  if (pos === null) {
    pos = this.previousPosition || 0;
  }
  var page = this.getCurrentPage();
  var delta1 = delta / Math.abs(delta);
  if (!this.selectedPage && (this.pages.length === 1 || !page)) {
    return this._move(delta1);
  }
  var pageIndex = page.index + delta;
  var pagesCount = this.pages.length;
  if (pageIndex < 0) {
    pageIndex = pagesCount - (pagesCount + -pageIndex) % pagesCount;
  } else if (pageIndex >= pagesCount) {
    pageIndex = (pageIndex + 1) % pagesCount - 1;
  }
  if (this.cycleThroughPagesWhenSelected && this.selectedPage) {
    return this.selectPage(this.pages[pageIndex], this.selectedPageSection);
  }
  var i3 = pageIndex;
  while (this.pages[i3].items.length === 0) {
    i3 += delta1;
    if (i3 >= this.pages.length) {
      i3 = 0;
    }
    if (i3 < 0) {
      i3 = this.pages.length - 1;
    }
    if (i3 === pageIndex) {
      break;
    }
  }
  var newPage = this.pages[i3];
  var deltaStartPage = Math.max(pos - page.start, 0);
  pos = newPage.start + deltaStartPage;
  if (pos >= newPage.end) {
    pos = newPage.end - 1;
  }
  return this.selectByPosition(pos);
};
Selector.prototype.prevPage = function(delta) {
  if (!this.selectedPage && this.position === null && this.previousPosition === null) {
    return this.selectByPosition(0);
  }
  return this._movePage(-(delta || 1));
};
Selector.prototype.nextPage = function(delta) {
  if (!this.selectedPage && this.position === null && this.previousPosition === null) {
    return this.selectByPosition(0);
  }
  return this._movePage(delta || 1);
};
Selector.prototype.selectPage = function(page, section, takeOverPage) {
  page = this.findPage(page);
  takeOverPage = typeof takeOverPage === "undefined" || takeOverPage;
  if (this.canSelectPages) {
    if (this.selectedPage === page) {
      return;
    }
    this.unselect();
    this.selectedPage = page;
    this.selectedPageSection = section;
    this._dispatch(this.onListeners, null, page);
  } else {
    this.selectFirstOfPage(page.index, takeOverPage);
  }
};
Selector.prototype.unselectPage = function() {
  if (!this.selectedPage) return;
  this.unselect();
  if (this.previousPosition !== null) {
    this.selectByPosition(this.previousPosition);
  }
};
Selector.prototype.selectFirstOfPage = function(page, takeOverPage) {
  page = this.findPage(page);
  if (!page) {
    throw new SelectorError("Unknown page");
  }
  if (page.end === page.start && !takeOverPage) {
    return;
  }
  return this.selectByPosition(page.start, takeOverPage);
};
Selector.prototype.selectLastOfPage = function(page, takeOverPage) {
  page = this.findPage(page);
  if (!page) {
    throw new SelectorError("Unknown page");
  }
  if (page.end === page.start && !takeOverPage) {
    return;
  }
  return this.selectByPosition(Math.max(page.end - 1, page.start), takeOverPage);
};
Selector.prototype.select = function(item, takeOverPage, selectIfNotFound) {
  if (!takeOverPage && this.selectedPage && this.blockItemSelectionWhilePageSelected || this.selected === item) {
    return;
  }
  return this._select(item, takeOverPage, selectIfNotFound);
};
Selector.prototype._select = function(item, takeOverPage, selectIfNotFound) {
  var pos = 0;
  for (var i3 = 0; i3 < this.pages.length; i3++) {
    for (var j = 0; j < this.pages[i3].items.length; j++) {
      if (this.pages[i3].items[j] === item) {
        this.unselect();
        return this.selectByPosition(pos, takeOverPage);
      }
      pos++;
    }
  }
  if (selectIfNotFound) {
    this.unselect();
    this.selected = item;
    this._dispatch(this.onListeners, this.selected);
    return item;
  }
};
Selector.prototype.selectByPosition = function(pos, takeOverPage) {
  if (this.position === pos) {
    return;
  }
  if (this.selectedPage) {
    if (this.blockItemSelectionWhilePageSelected && !takeOverPage) {
      return;
    }
    this._dispatch(this.offListeners, null, this.selectedPage);
    this.selectedPage = null;
  } else if (this.selected) {
    this.unselect();
  }
  this.position = pos;
  var page = this.getPageFromPosition(pos);
  this.selected = page.items[pos - page.start];
  this._dispatch(this.onListeners, this.selected);
  return this.selected;
};
Selector.prototype.unselect = function() {
  if (this.selected) {
    this.position = null;
    this._dispatch(this.offListeners, this.selected);
  } else if (this.selectedPage) {
    this._dispatch(this.offListeners, null, this.selectedPage);
  }
  this.selected = null;
  this.selectedPage = null;
  this.selectedPageSection = null;
};
Selector.prototype._dispatch = function(listeners, item, page) {
  listeners.forEach(function(cb2) {
    cb2.call(this, item, page);
  }, this);
};
Selector.prototype._addListener = function(listeners, item, page, callback) {
  var cb2;
  if (typeof item === "function") {
    cb2 = item;
  } else {
    if (typeof page === "function") {
      callback = page;
      page = null;
    }
    var self2 = this;
    cb2 = function(obj, p4) {
      if (item === obj && (!page || self2.matchPage(p4, page))) {
        callback(obj, p4);
      }
    };
  }
  listeners.push(cb2);
  return function() {
    listeners.splice(listeners.indexOf(cb2), 1);
  };
};
Selector.prototype.on = function(item, page, callback) {
  return this._addListener(this.onListeners, item, page, callback);
};
Selector.prototype.$on = function(scope, item, page, callback) {
  scope.$on("$destroy", this.on(item, page, function(item2) {
    callback(item2);
  }));
};
Selector.prototype.off = function(item, page, callback) {
  return this._addListener(this.offListeners, item, page, callback);
};
Selector.prototype.$off = function(scope, item, page, callback) {
  scope.$on("$destroy", this.off(item, page, function(item2) {
    callback(item2);
  }));
};
var selector_default = Selector;

// public/app/apps/cards/checklist/ng-components/checklist-group.js
angular_default.module("kantree").directive("cardsAppChecklistGroup", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<?",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        sortChoices: "<?",
        selector: "<?",
        visibleAttrNames: "<?",
        openCreatorOnInit: "<?",
        showUngroupedTooltip: "<?",
        hideHeader: "<?",
        onChange: "&?"
      },
      templateUrl: "/static/app/apps/cards/checklist/ng-components/templates/checklist-group.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin, CardsAppCardCreatorMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element"]);
        }
        constructor(...args) {
          super(...args);
          this.cardCreatorTemplate = "/static/app/apps/cards/checklist/ng-components/templates/card-creator.html";
          this.cardCreatorOptions = {
            cancelBtn: false,
            rows: 1,
            placeholder: _4("Add card"),
            saveBtnLabel: _4("Add"),
            autosizeOpts: {
              append: null
            }
          };
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.modeOptionsKeyPrefix = "lists_";
          this.withCardSelector = true;
          this.handleCards = true;
          this.groupColorTheme = "/static/app/apps/cards/checklist/ng-components/templates/checklist-group-color.css.html";
          this.sortableOptions = {
            duplication: () => !(this.groupBy || [])[0].oneGroupPerCard,
            _scrollHelperOptions: {
              disabled: true
            },
            _containersScrollHelperOptions: {
              scrollable: jquery_default(this.$element).parents(".ui-sortable-groups"),
              threshold: {
                default: { top: 60, bottom: 60 },
                xs: { top: 30, bottom: 30 }
              }
            },
            beforeStart: () => {
              this.$scope.$emit("startSortingCards");
            }
          };
          this.initGroupMixin();
          this.initCardCreatorMixin();
          this.settingsDropConfig = {
            tetherOptions: {
              constraints: [{
                to: "window",
                attachment: "together",
                pin: true
              }]
            }
          };
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
          this.changeCardCreatorMixin(changes);
        }
        onTitleEditStart() {
          this.editingTitle = true;
          if (this.selector && this.selectorPage) {
            const selectedPage = this.selector.getCurrentPage();
            if (!selector_default.prototype.matchPage(selectedPage, this.selectorPage)) {
              this.selector.selectPage(this.selectorPage, "header");
            }
          }
        }
        onTitleEditEnd(event2) {
          if (this.selector) {
            if (event2.keyCode === 9) {
              this.selector.nextPage();
            } else {
              const currentPage = this.selector.getCurrentPage();
              this.selector.unselectPage();
              if (currentPage) {
                this.selector.selectFirstOfPage(currentPage);
              }
            }
          }
          this.editingTitle = false;
        }
        $onDestroy() {
          this.destroyGroupMixin();
          this.destroyCardCreatorMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/checklist/ng-components/checklist.js
angular_default.module("kantree").directive("cardsAppChecklist", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/checklist/ng-components/templates/checklist.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupableMixin, CardsAppAttrVisibilityMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$element"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.specialFields = ["__ref__", "__comments__", "__children__", "__cover__"];
          this.modeOptionsKeyPrefix = "lists";
          this.withCardSelector = true;
          this.initGroupableMixin();
          this.initAttrVisibilityMixin();
          this.$scope.$on("maximizeAllCards", () => {
            this.$scope.$broadcast("showAllChildren");
          });
          this.$scope.$on("minimizeAllCards", () => {
            this.$scope.$broadcast("hideAllChildren");
          });
        }
        $onChanges(changes) {
          this.changeGroupableMixin(changes);
          this.changeAttrVisibilityMixin(changes);
        }
        $postLink() {
          const $viewportInner = this.$element.find(".ui-sortable-groups");
          activateViewScroll(
            this.$element,
            ".ui-sortable-groups",
            ".ui-sortable-groups, .cards-app-checklist-sortable-groups",
            true
          );
          this.scrollToBottom = debounce2((event2) => {
            $viewportInner.scrollTop($viewportInner[0].scrollHeight);
            if (event2 && event2.keyCode === 13) {
              this.selector.selectPage(this.selector.pages.length - 1, "bottom");
              this.$scope.$applyAsync();
            }
          }, 10);
        }
        $onDestroy() {
          this.destroyGroupableMixin();
          this.destroyAttrVisibilityMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/common/ui/group-header/ng-components/header.js
angular_default.module("kantree").component("cardsAppGroupHeader", {
  templateUrl: "/static/app/apps/cards/common/ui/group-header/ng-components/templates/header.html",
  bindings: {
    group: "<?",
    customTitle: "<?",
    board: "<?",
    filter: "<?",
    filterScopes: "<?",
    options: "<?",
    modeOptionsKeyPrefix: "<?",
    menuCustomDropConfig: "<?",
    editingTitle: "<?",
    onTitleEditStart: "&?",
    onTitleEditEnd: "&?",
    onCounterToggled: "&?",
    totalCount: "<?",
    matchingCount: "<?",
    sortBy: "<?",
    sortChoices: "<?",
    canFreeSort: "<?",
    showDesc: "<?",
    showIcon: "<?",
    hideCollapseBtn: "<?",
    showUngroupedTooltip: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = [
      "$scope",
      "$element",
      "$q",
      "$sanitize",
      "menuDropdown",
      "cardGroupsActionsMenu",
      "cardGroupsSortByMenu",
      "$injector"
    ];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.formatDate = formatDate;
      this.titleEditorOptions = {
        saveChange: (event2, newTitle, callback) => {
          if (newTitle && newTitle.length && newTitle !== this.title) {
            this.$q.digest(updateGroup(this.group, { card_id: this.board.id, title: newTitle }));
          }
          this.onTitleEditEnd && this.onTitleEditEnd({ $event: event2 });
          callback();
        },
        cancelChange: (event2, callback) => {
          this.onTitleEditEnd && this.onTitleEditEnd({ $event: event2 });
          callback();
        },
        saveOn: {
          tab: true,
          clickOutside: true
        },
        cancelOn: { clickOutside: false },
        hideOn: { save: true },
        resetOn: { save: false },
        saveBtn: false,
        cancelBtn: false,
        inputType: "input",
        enabled: false
      };
      this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
      this.refreshCanEditTitle();
      this.refreshGroupMenu();
      this.$scope.$watch("$ctrl.titleEditorOptions.enabled", (newVal, oldVal) => {
        if (newVal === oldVal) return;
        this.$element.toggleClass("editing-title", !!newVal);
      });
      this.$scope.$on("connectivityChanged", () => {
        this.refreshCanEditTitle();
        this.refreshGroupMenu();
      });
    }
    $onChanges(changes) {
      const groupChanged = changes.group && !changes.group.isFirstChange();
      const boardChanged = changes.board && !changes.board.isFirstChange();
      const projectChanged = boardChanged && (projectStore.tryGetForCard(this.board) || {}).id !== (this.project || {}).id;
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const optionChanged = (optionLabel) => optionsChanged && !equals((this.options || {})[optionLabel], (changes.options.previousValue || {})[optionLabel]);
      const editingTitleChanged = changes.editingTitle && !changes.editingTitle.isFirstChange();
      const filterChanged = changes.filter && !changes.filter.isFirstChange();
      const sortByChanged = changes.sortBy && !changes.sortBy.isFirstChange();
      const sortChoicesChanged = changes.sortChoices && !changes.sortChoices.isFirstChange();
      if (boardChanged) {
        this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
      }
      if (sortByChanged || sortChoicesChanged || optionChanged("include_descendants") || optionChanged("include_archived") || groupChanged || boardChanged || filterChanged) {
        this.refreshGroupMenu();
      }
      if (groupChanged) {
        this.$element.toggleClass("editable", this.canOpenSettings);
      }
      if (groupChanged || projectChanged) {
        this.refreshCanEditTitle();
      }
      if (editingTitleChanged) {
        if (this.titleEditorOptions.enabled && !this.editingTitle) {
          this.titleEditorOptions.enabled = false;
        } else if (!this.titleEditorOptions.enabled && this.editingTitle) {
          this.canEditTitle && this.startEditTitle();
        }
      }
    }
    $postLink() {
      this.$element.toggleClass("editable", this.canOpenSettings);
    }
    get title() {
      return this.customTitle || (this.group ? this.group.title : "");
    }
    get icon() {
      if (!this.showIcon || !this.group) return null;
      return this.group.icon;
    }
    static DESC_MAX_SIZE = 500;
    get desc() {
      if (this.showUngroupedTooltip) return _4("Contains cards which are not categorized");
      if (!this.showDesc || !this.group) return null;
      let desc = (this.group.description || "").trim();
      if (desc.length === 0) return null;
      if (desc.length > this.constructor.DESC_MAX_SIZE) {
        desc = desc.slice(0, this.constructor.DESC_MAX_SIZE + 1) + "...";
      }
      return this.$sanitize(desc);
    }
    get modeOptionsKey() {
      return this.modeOptionsKeyPrefix + this.title;
    }
    get canOpenSettings() {
      return !!this.group && !this.group.is_dynamic && !!this.onChange;
    }
    get collapsed() {
      return (this.options || {})[this.modeOptionsKey + "_collapsed"] || false;
    }
    set collapsed(newVal) {
      const newModeOptions = { ...this.options || {} };
      newModeOptions[this.modeOptionsKey + "_collapsed"] = newVal;
      this.onChange && this.onChange({ $changes: { options: newModeOptions } });
    }
    get groupMenuDropConfig() {
      return Object.assign({
        classes: "drop-theme-menu drop-theme-arrow drop-theme-group-menu"
      }, this.menuCustomDropConfig || {});
    }
    get cardCounterLimitReached() {
      return this.group && !!this.group.max_cards_limit && (this.matchingCount !== void 0 && this.matchingCount !== null ? this.matchingCount : this.totalCount) > this.group.max_cards_limit;
    }
    get cardCounterLabel() {
      if (this.matchingCount !== void 0 && this.matchingCount !== null) {
        return this.matchingCount + (!!this.group && !!this.group.max_cards_limit ? "/" + this.group.max_cards_limit : "") + " (" + this.totalCount + ")";
      } else {
        return this.totalCount + (!!this.group && !!this.group.max_cards_limit ? "/" + this.group.max_cards_limit : "");
      }
    }
    get cardCounterTooltip() {
      if (this.matchingCount !== void 0 && this.matchingCount !== null) {
        return _4("Number of cards matching filter") + (!!this.group && !!this.group.max_cards_limit ? " / " + _4("Soft limit") : "") + " (" + _4("Total number of cards in the group") + ")";
      } else {
        return _4("Total number of cards in the group") + (!!this.group && !!this.group.max_cards_limit ? "/" + _4("Soft limit") : "");
      }
    }
    setSortBy(value2, reverse) {
      const newModeOptions = setGroupSortBy(this.options, this.group || { title: this.title }, value2, reverse);
      return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
    }
    refreshCanEditTitle() {
      this.canEditTitle = !!this.project && !this.project.is_archived && !!this.group && !this.group.is_dynamic && isConnected() && canEditGroup(this.project, this.group.id);
    }
    buildPathFromPage(page) {
      if (page === "calendar") {
        return [[1, 0], [4, 0]];
      }
      if (page === "rules") {
        return [[1, 0], [3, 0]];
      }
      if (page === "sort by") {
        return [[1, 0], [2, 0]];
      } else {
        return void 0;
      }
    }
    refreshGroupMenu() {
      let sortByMenuParams;
      if (this.sortChoices) {
        sortByMenuParams = [this.sortBy, {
          choices: this.sortChoices,
          canFreeSort: this.canFreeSort,
          sortByChanged: (value2, reverse) => this.setSortBy(value2, reverse)
        }];
      }
      const actionsMenuOptions = {
        includeDescendants: (this.options || {}).include_descendants,
        includeArchived: (this.options || {}).include_archived,
        filter: this.filter,
        withBatch: true
      };
      if (sortByMenuParams) {
        actionsMenuOptions.sortByMenuParams = sortByMenuParams;
      }
      if (this.canOpenSettings) {
        this.menu = this.$cardGroupsActionsMenu.get(this.group, this.board, actionsMenuOptions);
      } else if (sortByMenuParams) {
        this.menu = this.$cardGroupsSortByMenu.get(...sortByMenuParams);
      } else {
        this.menu = null;
      }
    }
    openGroupActionsMenu(page, event2) {
      let toggleEl = jquery_default(this.$element).find(".js-group-action-menu").get(0);
      let newMenu;
      if (!this.menu) {
        return;
      }
      if (this.canOpenSettings) {
        newMenu = Object.assign({}, this.menu, {
          defaultPath: this.buildPathFromPage(page)
        });
        if (page && this.lastPage !== page) {
          this.lastPage = page;
          if (this.drop && this.drop.drop) {
            this.$menuDropdown.close(this.drop, event2);
          }
          this.drop = this.$menuDropdown.open(toggleEl, newMenu, this.$scope, this.groupMenuDropConfig);
        } else {
          this.drop = this.$menuDropdown.toggle(this.drop, toggleEl, newMenu, this.$scope, this.groupMenuDropConfig, event2);
        }
      } else {
        this.drop = this.$menuDropdown.toggle(this.drop, toggleEl, this.menu, this.$scope, this.groupMenuDropConfig, event2);
      }
    }
    startEditTitle() {
      if (this.titleEditorOptions.enabled) return;
      if (this.collapsed) {
        this.collapsed = false;
      }
      this.titleEditorOptions.enabled = true;
      this.onTitleEditStart && this.onTitleEditStart();
    }
    onTitleClick() {
      if (!this.canEditTitle && this.group.onTitleClick) {
        this.$injector.invoke(this.group.onTitleClick);
      }
    }
    $onDestroy() {
      if (this.derefisterStoreWatcher) this.derefisterStoreWatcher();
    }
  }
});

// public/app/apps/cards/common/ui/group-header/ng-components/misc.js
angular_default.module("kantree").component("cardsAppGroupMisc", {
  template: `
    <div class="group-icon" ng-show="$ctrl.icon"><i ng-class="$ctrl.icon|iconClass"></i></div>
    <div class="group-desc" ng-show="$ctrl.desc">{{$ctrl.desc}}</div>
  `,
  bindings: {
    group: "<"
  },
  controller: class extends AngularClass {
    get icon() {
      if (!this.group) return null;
      return this.group.icon;
    }
    static DESC_MAX_SIZE = 500;
    get desc() {
      if (!this.group) return null;
      let desc = (this.group.description || "").trim();
      if (desc.length === 0) return null;
      if (desc.length > this.constructor.DESC_MAX_SIZE) {
        desc = desc.slice(0, this.constructor.DESC_MAX_SIZE + 1) + "...";
      }
      return desc;
    }
  }
});

// public/app/apps/cards/common/ui/group-header/ng-components/progress.js
angular_default.module("kantree").component("cardsAppGroupProgress", {
  template: `
    <div class="progress-wrapper">
      <div class="progress">
        <div class="progress-bar progress-bar-success" ng-style="{width: ($ctrl.progress || 0) + '%',}"></div>
      </div>
      <span class="pct">{{$ctrl.progress}}%</span>
    </div>
  `,
  bindings: {
    cards: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $onInit() {
      this.refreshProgress();
    }
    $onChanges(changes) {
      if (changes.cards && !changes.cards.isFirstChange()) {
        this.refreshProgress();
      }
    }
    get total() {
      return this.cards ? this.cards.length : 0;
    }
    get finished() {
      return this.cards.reduce((accu, card) => {
        if (card.is_archived || ["dropped", "closed"].indexOf(card.state) !== -1) {
          return accu;
        }
        if (card.finished) {
          return accu + 1;
        }
        return accu;
      }, 0);
    }
    refreshProgress() {
      const progress2 = this.total ? Math.round(this.finished * 100 / this.total) : 0;
      if (progress2 !== this.progress) {
        this.progress = progress2;
        this.$element.toggleClass("hidden", !this.progress && this.progress !== 0);
      }
    }
  }
});

// public/app/apps/cards/common/ui/group-header/ng-components/stats.js
angular_default.module("kantree").component("cardsAppGroupStats", {
  template: `
    <div class="stats">
      <div ng-repeat="stat in $ctrl.stats" class="aggreg">
        <span class="title">{{stat.name}}</span><span class="value">{{stat.value}}</span>
      </div>
    </div>
  `,
  bindings: {
    cards: "<",
    project: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $onInit() {
      this.refreshStats();
    }
    $onChanges(changes) {
      if (changes.cards && !changes.cards.isFirstChange() || changes.project && !changes.project.isFirstChange()) {
        this.refreshStats();
      }
    }
    refreshStats() {
      const stats = getCardsAttributeAggregations(this.cards, this.project);
      if (!equals(stats, this.stats)) {
        this.stats = stats;
        this.$element.toggleClass("hidden", !this.stats || this.stats.length === 0);
      }
    }
  }
});

// public/app/apps/cards/common/group-by/GroupBy.js
var GroupBy = class {
  constructor(spec, cardStore2, board, includeArchived) {
    this.spec = spec;
    this.project = null;
    if (board) {
      this.project = projectStore.tryGetForCard(board) || null;
    }
    this.opts = {};
    this.ungroupedScopeFilters = {};
    this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
    this.groupStore = new CardGroupStore({ autoLoad: false });
    this.oneGroupPerCard = true;
  }
  getGroupStore() {
    return this.groupStore;
  }
  getUngroupedCardsStore() {
    return this.ungroupedCardsStore;
  }
  equals(groupBy2) {
    return equals(this, groupBy2);
  }
  removeWatchers() {
    if (this.opts.watchersOff) {
      this.opts.watchersOff();
    }
  }
  isGroupType() {
    return this.spec && this.spec.type === "group_type";
  }
  isAttribute() {
    return this.spec && this.spec.type === "attribute";
  }
  isName() {
    return this.spec && this.spec.type === "name";
  }
  isProjects() {
    return this.spec && this.spec.type === "projects";
  }
  isOrgs() {
    return this.spec && this.spec.type === "orgs";
  }
  isTeams() {
    return this.spec && this.spec.type === "teams";
  }
  isNothing() {
    return !this.spec || !this.spec.type || this.spec.type === "nothing";
  }
  canAddGroup() {
    return false;
  }
  isSortable() {
    return false;
  }
  getGroupType() {
    return null;
  }
  getAttribute() {
    return null;
  }
};

// public/app/apps/cards/common/group-by/AttributeGroupBy.js
groupByRegistry.register("attribute", class extends GroupBy {
  static formatSpecLabel(spec) {
    return (cardModelStore.getAttribute(spec.id) || {}).name;
  }
  constructor(spec, cardStore2, board, includeArchived) {
    super(...arguments);
    const project = projectStore.tryGetForCard(board);
    this.attribute = cardModelStore.getAttribute(spec.id);
    const attrType = attributeTypeRegistry.get(this.attribute.type);
    this.opts.inModels = cardModelStore.getModelsWithAttributes({ id: this.attribute.id }, project);
    this.ungroupedScopeFilters.model_id = (model_id) => {
      return this.attribute.model_is_base || this.opts.inModels.some((model) => model.id === model_id);
    };
    if (this.attribute.type === "group_type") {
      this.groupType = cardGroupTypeStore.tryGet(this.attribute.group_type_id);
      this.oneGroupPerCard = this.groupType.one_group_per_card;
      this.groupStore = cardGroupStore.scopedByType(this.groupType, board).scoped({
        is_archived: (v3) => includeArchived ? true : !v3
      });
      this.ungroupedScopeFilters.groups = query_exports.not(query_exports.arrayOfObjMatch((group2) => {
        group2 = cardGroupStore.tryGet(group2.id);
        if (!group2 || !includeArchived && group2.is_archived) {
          return false;
        }
        if (this.groupType.id !== group2.type_id) {
          return false;
        }
        if (this.groupType.scope === "org") {
          return group2.owner.id === this.groupType.owner.id && group2.owner.type === this.groupType.owner.type;
        } else if (this.groupType.scope === "project" && project) {
          return group2.parent_id === project.top_level_card.id;
        } else {
          return group2.parent_id === board.id;
        }
      }));
    } else {
      this.opts.watchersOff = attrType.fillCardGroupByStore(board, cardModelStore.getAttributeOwner(this.attribute), this.attribute, this.groupStore);
    }
    if (attrType.getUngroupedCardStoreFilters) {
      this.ungroupedScopeFilters = attrType.getUngroupedCardStoreFilters(board, cardModelStore.getAttributeOwner(this.attribute), this.attribute, this.groupStore);
    } else {
      this.ungroupedScopeFilters.attributes = query_exports.not(query_exports.arrayMatch((attribute2) => {
        if (this.attribute.id === attribute2.id) {
          return true;
        }
        return false;
      }));
      if (attrType.defaultValueIsUngrouped) {
        this.ungroupedScopeFilters.id = () => false;
      }
    }
    this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
  }
  getAttribute() {
    return this.attribute;
  }
  getGroupType() {
    return this.groupType;
  }
  getLabel() {
    return (this.attribute || {}).name;
  }
  canAddGroup() {
    return !!this.groupType;
  }
  isSortable() {
    return !!this.groupType;
  }
});

// public/app/apps/cards/common/group-by/GroupTypeGroupBy.js
groupByRegistry.register("group_type", class extends GroupBy {
  static formatSpecLabel(spec) {
    return (cardGroupTypeStore.tryGet(spec.id) || {}).name;
  }
  constructor(spec, cardStore2, board, includeArchived) {
    super(...arguments);
    const project = projectStore.tryGetForCard(board);
    this.groupType = getScopedGroupTypeStore(project, cardStore2, true).tryGet(spec.id);
    this.oneGroupPerCard = this.groupType.one_group_per_card;
    this.groupStore = getScopedGroupStore(board, cardStore2, this.groupType, includeArchived);
    this.ungroupedScopeFilters = {
      groups: query_exports.not(query_exports.arrayMatch((group2) => {
        group2 = this.groupStore.tryGet(group2.id);
        if (!group2 || !includeArchived && group2.is_archived) {
          return false;
        }
        if (this.groupType.id !== group2.type_id) {
          return false;
        }
        if (this.groupType.scope === "org") {
          return group2.owner.id === this.groupType.owner.id && group2.owner.type === this.groupType.owner.type;
        } else if (this.groupType.scope === "project" && project) {
          return group2.parent_id === project.top_level_card.id;
        } else {
          return group2.parent_id === board.id;
        }
      }))
    };
    if (this.groupType.attribute_id) {
      var attribute2 = getScopedModelStore(project, cardStore2).getAttribute(this.groupType.attribute_id);
      this.opts.inModels = getScopedModelStore(project, cardStore2).getModelsWithAttributes({ id: attribute2.id }, project);
      this.ungroupedScopeFilters.model_id = (model_id) => {
        return this.attribute.model_is_base || this.ops.inModels.some((model) => model.id === model_id);
      };
    }
    this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
  }
  getGroupType() {
    return this.groupType;
  }
  getLabel() {
    return (this.groupType || {}).name;
  }
  canAddGroup() {
    return true;
  }
  isSortable() {
    return true;
  }
});

// public/app/apps/cards/common/group-by/NameGroupBy.js
var caseInsensitive = true;
groupByRegistry.register("name", class extends GroupBy {
  static formatSpecLabel(spec) {
    return spec.id;
  }
  constructor(spec, cardStore2, board, includeArchived, groups) {
    super(...arguments);
    (groups || []).forEach((group2) => {
      this.groupStore.createDynamicGroup(null, {
        title: group2.title,
        getCardStore: () => {
          return cardStore2.scopedByAttributeValueOrGroup(this.spec.id, group2.title, caseInsensitive);
        }
      });
    });
    this.ungroupedScopeFilters.attributes = (attributes) => {
      if (!groups) {
        return true;
      }
      return attributes.every((attribute2) => {
        if (attribute2.name.localeCompare(this.getLabel(), { sensitivity: caseInsensitive ? "accent" : "variant" }) !== 0) return true;
        var attrType = attributeTypeRegistry.get(attribute2.type);
        if (attrType && angular.isFunction(attrType.equals)) {
          return groups.every((group2) => !attrType.equals(attribute2, group2.title));
        }
        if (Array.isArray(attribute2.value)) {
          return attribute2.value.every((attrVal) => {
            if (!angular.isString(attrVal)) return false;
            return groups.every((group2) => group2.title.localeCompare(attrVal, void 0, { sensitivity: caseInsensitive ? "accent" : "variant" }) !== 0);
          });
        }
        if (!angular.isString(attribute2.value)) return false;
        return groups.every((group2) => group2.title.localeCompare(attribute2.value, void 0, { sensitivity: caseInsensitive ? "accent" : "variant" }) !== 0);
      });
    };
    this.ungroupedScopeFilters.groups = (storedGroups) => {
      if (!groups) {
        return true;
      }
      return storedGroups.every((storedGroup) => {
        return groups.every((group2) => group2.title.localeCompare(storedGroup.title, void 0, { sensitivity: caseInsensitive ? "accent" : "variant" }) !== 0);
      });
    };
    if (groups) {
      this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
    } else {
      this.ungroupedCardsStore = cardStore2;
    }
  }
  getLabel() {
    return this.spec.id;
  }
});

// public/app/apps/cards/common/group-by/NothingGroupBy.js
groupByRegistry.register("nothing", class extends GroupBy {
  static default = true;
  static isAvailable() {
    return true;
  }
  static get displayName() {
    return _4("Ungrouped");
  }
  static formatSpecLabel(spec) {
    return _4("Ungrouped");
  }
  getLabel() {
    return _4("Nothing");
  }
});

// public/app/apps/cards/common/group-by/OrgGroupBy.js
groupByRegistry.register("orgs", class extends GroupBy {
  static isAvailable(board) {
    return !board;
  }
  static get displayName() {
    return _4("Organizations");
  }
  static formatSpecLabel(spec) {
    return _4("Organizations");
  }
  constructor(spec, cardStore2, board, includeArchived, orgs) {
    super(...arguments);
    this.orgs = orgs;
    (orgs || []).map((org2) => {
      let title;
      if (org2.type === "org") {
        title = org2.name;
      } else if (org2.type === "user") {
        title = _4("Personal workspace");
      } else if (org2.type === "shared") {
        title = _4("Shared workspaces");
      } else {
        title = _4("Other workspaces");
      }
      return { ...org2, title };
    }).sort((a3, b3) => a3.title.localeCompare(b3.title)).forEach((org2) => {
      this.groupStore.createDynamicGroup(null, {
        org_id: org2.id,
        title: org2.title,
        getCardStore: (withArchived, includeDescendants) => {
          return cardStore2.scoped({
            project_id: (project_id) => {
              const project = projectStore.tryGet(project_id);
              if (!project || !project.owner) {
                return false;
              }
              return this.isCardOrgEquals(project.owner, org2);
            },
            is_archived: (v3) => withArchived ? true : !v3
          });
        }
      });
    });
    this.ungroupedScopeFilters.project_id = (project_id) => {
      if (!orgs) return true;
      return orgs.every((org2) => {
        const project = projectStore.tryGet(project_id);
        if (!project || !project.owner) {
          return true;
        }
        return !this.isCardOrgEquals(project.owner, org2);
      });
    };
    if (orgs) {
      this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
    } else {
      this.ungroupedCardsStore = cardStore2;
    }
  }
  getLabel() {
    return _4("Organizations");
  }
  getOrgForCard(card) {
    const project = projectStore.tryGet(card.project_id);
    if (!project || !project.owner) {
      return null;
    }
    return this.orgs.find((org2) => this.isCardOrgEquals(project.owner, org2));
  }
  isCardOrgEquals(cardOrg, org2) {
    if (!org2 && !cardOrg) return true;
    if (org2 && !cardOrg || !org2 && cardOrg) return false;
    const storedCardOrg = orgStore.tryGet(cardOrg.id);
    if (org2.type === "user") {
      return cardOrg.type === "user" && currentUser2.username === cardOrg.name;
    }
    if (org2.type === "org") {
      return cardOrg.type === "org" && storedCardOrg && Number.isInteger(storedCardOrg.permission) && storedCardOrg.id === org2.id;
    }
    if (org2.type === "shared") {
      return cardOrg.type === "shared" || cardOrg.type === "user" && currentUser2.username !== cardOrg.name || (cardOrg.type === "org" && !storedCardOrg || !Number.isInteger(storedCardOrg.permission));
    }
  }
});

// public/app/apps/cards/common/group-by/ProjectGroupBy.js
groupByRegistry.register("projects", class extends GroupBy {
  static isAvailable(board) {
    return !board;
  }
  static get displayName() {
    return _4("Workspaces");
  }
  static formatSpecLabel(spec) {
    return _4("Workspaces");
  }
  constructor(spec, cardStore2, board, includeArchived, projects) {
    super(...arguments);
    this.projects = projects;
    (projects || []).sort((a3, b3) => a3.title.localeCompare(b3.title)).forEach((project) => {
      this.groupStore.createDynamicGroup(null, {
        project_id: project.id,
        title: project.title,
        color: project.color,
        getCardStore: (withArchived, includeDescendants) => {
          return cardStore2.scopedByProject(project).scoped({
            is_archived: (v3) => withArchived ? true : !v3
          });
        }
      });
    });
    this.ungroupedScopeFilters.project_id = (project_id) => {
      if (!projects) return true;
      return projects.every((project) => project.id !== project_id);
    };
    if (projects) {
      this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
    } else {
      this.ungroupedCardsStore = cardStore2;
    }
  }
  getLabel() {
    return _4("Workspaces");
  }
});

// public/app/apps/cards/common/group-by/TeamGroupBy.js
groupByRegistry.register("teams", class extends GroupBy {
  static isAvailable(board) {
    return !board;
  }
  static get displayName() {
    return _4("Teams");
  }
  static formatSpecLabel(spec) {
    return _4("Teams");
  }
  constructor(spec, cardStore2, isArchived, project, teams) {
    super(...arguments);
    this.teams = teams;
    (teams || []).sort((a3, b3) => a3.name.localeCompare(b3.name)).forEach((team) => {
      this.groupStore.createDynamicGroup(null, {
        team_id: team.id,
        title: team.name,
        getCardStore: (withArchived, includeDescendants) => {
          return cardStore2.scoped({
            project_id: (project_id) => {
              const project2 = projectStore.tryGet(project_id);
              if (!project2 || !project2.team) {
                return false;
              }
              return project2.team.id === team.id;
            },
            is_archived: (v3) => withArchived ? true : !v3
          });
        }
      });
    });
    this.ungroupedScopeFilters.project_id = (project_id) => {
      if (!teams) return true;
      return teams.every((team) => {
        const project2 = projectStore.tryGet(project_id);
        if (!project2 || !project2.team) {
          return true;
        }
        return project2.team.id !== team.id;
      });
    };
    if (teams) {
      this.ungroupedCardsStore = cardStore2.scoped(this.ungroupedScopeFilters);
    } else {
      this.ungroupedCardsStore = cardStore2;
    }
  }
  getLabel() {
    return _4("Teams");
  }
  getTeamForCard(card) {
    const project = projectStore.tryGet(card.project_id);
    if (!project || !project.team) {
      return null;
    }
    return project.team.id;
  }
});

// public/app/apps/cards/common/ui/nav/menus/group-by.js
angular_default.module("kantree").service("cardsAppGroupByMenu", class extends AngularClass {
  static $inject = ["$q", "cardGroupTypeGroupsModal", "$timeout"];
  getMenuItems(board, selectedGroupBy, disabledGroupBy, choices, notifyChange) {
    const items = [];
    const project = board ? projectStore.tryGetForCard(board) : null;
    groupByRegistry.forEach((cls, clsName) => {
      if (cls.isAvailable && cls.isAvailable(board, choices)) {
        items.push({
          label: cls.displayName,
          action: () => notifyChange({ type: clsName }),
          filterable: true,
          selected: () => selectedGroupBy instanceof cls,
          disabled: () => clsName !== "nothing" && disabledGroupBy instanceof cls
        });
      }
    });
    let _items = [];
    let groupTypeChoices = [];
    if (!project || !project.is_portfolio) {
      groupTypeChoices = choices.filter((item) => item.type === "group_type");
      if (groupTypeChoices.length) {
        _items.push(...groupTypeChoices.map((itemSpec) => {
          const gt = itemSpec.obj || cardGroupTypeStore.tryGet(itemSpec.id);
          const item = {
            label: gt.name,
            action: () => notifyChange({ type: "group_type", id: gt.id }),
            filterable: true,
            selected: () => selectedGroupBy instanceof groupByRegistry.get("group_type") && gt.id === selectedGroupBy.getGroupType().id,
            disabled: () => disabledGroupBy instanceof groupByRegistry.get("group_type") && gt.id === disabledGroupBy.getGroupType().id
          };
          if (board) {
            item.buttons = [{
              icon: "bi-three-dots",
              action: () => this.$cardGroupTypeGroupsModal.open(gt, cardStore.get(board.id)),
              offline: false
            }];
          }
          return item;
        }));
      }
      if (project && !project.is_archived && isAllowedInProject(project, "card_group_type", "CREATE")) {
        _items.push({
          label: _4("Add new context"),
          action: () => {
            inputDialog(_4("Context name:")).then((value2) => {
              if (!value2) return;
              this.$q.when(
                createGroupType({ name: value2, scope: "project" }, null, project),
                (gt) => notifyChange({ type: "group_type", id: gt.id })
              );
            });
          },
          classes: "add-new-context-btn"
        });
      }
      if (_items.length) {
        items.push(
          { label: "--" },
          { subheader: _4("Contexts") },
          ..._items
        );
      }
    }
    const attributeChoices = choices.filter((item) => item.type === "attribute");
    if (attributeChoices.length) {
      items.push(
        { label: "--" },
        { subheader: _4("Fields") }
      );
      items.push(...attributeChoices.map((itemSpec) => {
        const attr = itemSpec.obj || cardModelStore.getAttribute(itemSpec.id);
        return {
          label: attr.name,
          small: !attr.model_is_base ? "(" + attr.model_name + ")" : null,
          action: () => notifyChange({ type: "attribute", id: attr.id }),
          filterable: true,
          selected: () => selectedGroupBy instanceof groupByRegistry.get("attribute") && attr.id === selectedGroupBy.getAttribute().id,
          disabled: () => disabledGroupBy instanceof groupByRegistry.get("attribute") && attr.id === disabledGroupBy.getAttribute().id
        };
      }));
    }
    const nameChoices = choices.filter((item) => item.type === "name");
    if (nameChoices.length) {
      if (groupTypeChoices.length || attributeChoices.length) {
        items.push(
          { label: "--" },
          { subheader: _4("Other") }
        );
      }
      items.push(...nameChoices.sort((a3, b3) => {
        return a3.id.localeCompare(b3.id, currentUser2.locale, { sensitivity: "base", ignorePunctuation: true, numeric: true });
      }).map((itemSpec) => {
        const label = itemSpec.id;
        const types2 = itemSpec.types.filter((val, idx, arr) => arr.indexOf(val) === idx);
        let small, tooltip, icon;
        if (itemSpec.types.length >= 1) {
          small = "(" + _n("{count} workspace", "{count} workspaces", itemSpec.types.length) + ")";
        }
        if (types2.length > 1) {
          tooltip = types2.map((type) => attributeTypeRegistry.get(type)).filter(Boolean).map((attrType) => {
            const count = itemSpec.types.filter((t3) => t3 === attrType.name).length;
            return attrType.title + " (" + count + ")";
          }).join(", ");
          icon = "plus-square-o";
        }
        if (types2.length === 1) {
          const attrType = attributeTypeRegistry.get(types2[0]);
          if (attrType) icon = attrType.icon;
          if (types2[0] === "context") {
            tooltip = _4("Context");
            icon = "cubes";
          }
        }
        return {
          label,
          icon,
          tooltip,
          small,
          action: () => notifyChange({ type: "name", id: itemSpec.id }),
          selected: () => selectedGroupBy instanceof groupByRegistry.get("name") && itemSpec.id === selectedGroupBy.spec.id,
          disabled: () => disabledGroupBy instanceof groupByRegistry.get("name") && itemSpec.id === disabledGroupBy.spec.id,
          filterable: true
        };
      }));
    }
    return items;
  }
  getMenu(board, selectedGroupBy, disabledGroupBy, choices, notifyChange) {
    return {
      config: () => this.getMenuItems(board, selectedGroupBy, disabledGroupBy, choices, notifyChange)
    };
  }
});

// public/app/apps/cards/common/ui/nav/menus/modes.js
angular_default.module("kantree").service("cardsAppModesMenu", class extends AngularClass {
  getMenuItems(selectedMode, cardsApps, org2, notifyChange) {
    return cardsApps.map((mode) => {
      const item = {
        label: mode.title,
        icon: mode.icon,
        selected: () => selectedMode === mode.name,
        action: () => notifyChange(mode)
      };
      if (mode.requireFeatureFlag && org2) {
        item["featureFlag"] = [org2, mode.requireFeatureFlag];
      }
      return item;
    });
  }
  getMenu(selectedMode, cardsApps, org2, notifyChange) {
    return {
      config: () => this.getMenuItems(selectedMode, cardsApps, org2, notifyChange),
      options: {
        title: _4("View cards as"),
        icon: "bi-display"
      }
    };
  }
});

// public/app/apps/cards/common/ui/nav/ng-components/batch-btn.js
angular_default.module("kantree").component("cardsAppBatchBtn", {
  template: `
    <button class="btn btn-topbar" ng-show="!$ctrl.readonly"
      drop-menu="$ctrl.dropMenu" uib-tooltip="{{::$ctrl.tooltipLabel}}" tooltip-placement="bottom">
      <i class="fa fa-magic"></i> {{::$ctrl.btnLabel}}
      <span class="bi-caret-down-fill"></span>
    </button>
  `,
  bindings: {
    board: "<?",
    options: "<?",
    filter: "<?",
    readonly: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["projectExportModal", "cardBatchEditMenuFactory", "$scope"];
    $onInit() {
      this.tooltipLabel = _4("Batch actions");
      this.btnLabel = _4("Batch");
      this.dropMenu = { config: () => () => {
        let items = [];
        const project = this.board ? projectStore.tryGetForCard(this.board) : null;
        if (project && this.board) {
          const batchItems = this.$cardBatchEditMenuFactory.getItems({
            project,
            parent: this.board,
            includeArchived: !!(this.options || {}).include_archived,
            batchParams: {
              filter: this.filter,
              parent_id: (this.options || {}).include_descendants ? null : this.board.id
            }
          });
          if (batchItems.length) {
            items = items.concat(batchItems, [{ label: "--" }]);
          }
        }
        if (canExportData(project)) {
          items.push({
            label: _4("Export"),
            icon: "download",
            action: () => {
              this.$projectExportModal.open(project, this.filter, null, null, (this.options || {}).include_descendants);
            }
          });
        }
        if (items[items.length - 1].label === "--") {
          items.pop();
        }
        return items;
      }, options: {
        title: _4("Actions on matching cards")
      } };
    }
  }
});

// public/app/apps/cards/common/ui/nav/ng-components/field-btn.js
angular_default.module("kantree").directive("cardsAppFieldBtn", [
  function() {
    return {
      template: `
        <button class="btn btn-topbar" ng-disabled="$ctrl.readonly">
          <i ng-class="$ctrl.icon|iconClass"></i> {{$ctrl.label}}
          <span class="bi-caret-down-fill" ng-hide="$ctrl.readonly"></span>
        </button>
      `,
      restrict: "E",
      replace: true,
      scope: {
        project: "<",
        store: "<",
        attrType: "<",
        multiple: "<?",
        options: "<",
        readonly: "<?",
        onChange: "&"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$scope", "$element", "menuDropdown", "$q"];
        $onInit() {
          if (this.project || this.store) {
            this.refresh();
          }
        }
        $onChanges(changes) {
          if (changes.attrType && !changes.attrType.isFirstChange() || changes.options && !changes.options.isFirstChange() || changes.project && !changes.project.isFirstChange() || changes.store && !changes.store.isFirstChange()) {
            this.refresh();
          }
        }
        $postLink() {
          this.$element.on("click touchstart", () => {
            this.$menuDropdown.open(this.$element[0], this.menu, this.$scope, {
              classes: "drop-theme-menu drop-theme-arrow drop-theme-app-field-selector"
            });
          });
        }
        refresh() {
          const availableAttrs = getAvailableAttrsOfType(this.project, this.store, this.attrType);
          const attrType = attributeTypeRegistry.get(this.attrType);
          this.selectedAttrs = getSelectedAttributes(availableAttrs, this.options, !this.multiple);
          this.selectedAttrsNames = Array.from(this.selectedAttrs.keys());
          if (!attrType) {
            this.icon = null;
            this.label = _4("Select field");
          } else {
            this.icon = attrType.icon;
            if (this.selectedAttrs.size === 0) {
              this.label = _4("Select {type} field", { type: attrType.title.toLowerCase() });
            } else {
              const field2 = this.selectedAttrsNames.join(", ");
              this.label = this.selectedAttrs.size > 1 ? _4("Using fields {field}", { field: field2 }) : _4("Using field {field}", { field: field2 });
            }
          }
          let forceMenuRefresh;
          this.menu = {
            config: () => () => {
              const availableAttrs2 = getAvailableAttrsOfType(this.project, this.store, this.attrType);
              const items = [];
              forceMenuRefresh = false;
              items.push({
                subheader: _4("Use the following {type} field", { type: attrType.title.toLowerCase() })
              });
              for (const [attrName, attrGroup] of availableAttrs2) {
                items.push({
                  checkbox: true,
                  icon: attrGroup.icon,
                  color: attrGroup.fromDifferentTypes ? "orange" : void 0,
                  label: attrGroup.label,
                  help: attrGroup.length > 1 ? _4("{nb} fields under this name", { nb: attrGroup.length }).concat(
                    attrGroup.fromDifferentTypes ? ` (${_4("with different types")})` : ""
                  ) : void 0,
                  filterable: true,
                  filterPredicate: (filter4) => attrGroup.label.toLowerCase().indexOf(filter4.toLowerCase()) >= 0,
                  value: () => this.selectedAttrs.size === 0 || this.selectedAttrsNames.some((attrName2) => attrGroup.name === attrName2),
                  closeAfterToggle: false,
                  toggle: () => {
                    forceMenuRefresh = false;
                    let newSelectedAttrsNames = this.selectedAttrsNames;
                    if (this.selectedAttrsNames.some((attrName2) => attrGroup.name === attrName2)) {
                      if (this.selectedAttrs.size === 1) {
                        forceMenuRefresh = true;
                      } else {
                        newSelectedAttrsNames = newSelectedAttrsNames.filter((name2) => name2 !== attrGroup.name);
                      }
                    } else if (this.multiple) {
                      newSelectedAttrsNames.push(attrGroup.name);
                    } else {
                      newSelectedAttrsNames = [attrGroup.name];
                    }
                    this.onChange({ $changes: { use_field: newSelectedAttrsNames } });
                  }
                });
              }
              if (this.project && canManageAttributes(this.project)) {
                items.push({
                  offline: false,
                  input: true,
                  placeholder: _4("Add a {type} field", { type: attrType.title.toLowerCase() }),
                  submit: (name2) => {
                    const model = cardModelStore.getProjectModel(this.project);
                    this.$q.when(createAttribute(this.project, model, {
                      type: this.attrType,
                      name: name2,
                      description: null,
                      default_value: null,
                      container: null,
                      options: {},
                      is_pii: false
                    }, null), (attr) => {
                      this.onChange({ $changes: { use_field: this.selectedAttrsNames.concat([attr.name]) } });
                    });
                  }
                });
              }
              return items;
            },
            options: {
              watch: (cb2, scope) => {
                return offMany([
                  getScopedModelStore(this.project, this.store).$watchAll(scope, cb2),
                  scope.$watchCollection(() => this.selectedAttrsNames, cb2),
                  scope.$watch(() => forceMenuRefresh, cb2)
                ]);
              }
            }
          };
        }
      }
    };
  }
]);

// public/app/apps/cards/common/ui/nav/ng-components/filter-btn.js
angular_default.module("kantree").component("cardsAppFilterBtn", {
  templateUrl: "/static/app/apps/cards/common/ui/nav/ng-components/templates/filter-btn.html",
  bindings: {
    board: "<?",
    cardStore: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    shrinked: "<?",
    onChange: "&?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "dropdown", "$element", "$document"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.refreshStores();
    }
    $onChanges(changes) {
      if (changes.board) {
        this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
      }
      if ((changes.filter || changes.filterRepr || changes.shrinked) && !this.useInput) {
        this.refreshLabel();
      }
      if (changes.filterScopes && !changes.filterScopes.isFirstChange() || changes.board && !changes.board.isFirstChange() || changes.cardStore && !changes.cardStore.isFirstChange()) {
        this.refreshStores();
      }
    }
    notifyChange(filter4) {
      this.onChange({ $changes: { filter: filter4 } });
    }
    refreshStores() {
      const filterScopesStores = getStoresForFilterScopes(this.filterScopes);
      const org2 = orgStore.tryGetForProject(this.project);
      this.stores = Object.assign({
        "cardModel": getScopedModelStore(this.project, this.cardStore),
        "groupType": getScopedGroupTypeStore(this.project, this.cardStore),
        "projectMember": this.project ? projectMemberStore.scopedByProject(this.project) : void 0,
        "role": org2 ? roleStore.scopedByOrg(org2) : void 0,
        "group": (groupType) => {
          return getScopedGroupStore(this.board, this.cardStore, groupType);
        }
      }, this.filterScopes ? filterScopesStores : {});
    }
    refreshLabel() {
      if (!this.filter || this.shrinked) {
        this.label = null;
        return;
      }
      if (!this.filterRepr) {
        this.label = _4("some fields");
        return;
      }
      this.label = this.filterRepr;
    }
    $postLink() {
      if (!this.useInput) {
        this.$element.on("click", () => this.openDrop());
      }
    }
    openDrop() {
      const dropHtml = `
        <filter-editor stores="$ctrl.stores" source="$ctrl.filter" filter-scopes="$ctrl.filterScopes"
          on-change="$ctrl.notifyChange($source)" project="$ctrl.project"></filter-editor>
      `;
      this.drop = this.$dropdown.openCompile(this.$element[0], dropHtml, this.$scope, {
        classes: "cards-app-filter-btn-drop drop-theme-menu drop-theme-arrow",
        _useChildScope: true,
        tetherOptions: {
          constraints: [{
            to: "window",
            pin: true,
            attachment: "together none"
          }]
        }
      });
    }
  }
});

// public/app/apps/cards/common/ui/nav/ng-components/group-by-btn.js
angular_default.module("kantree").directive("cardsAppGroupbyBtn", [
  function() {
    return {
      template: `
        <button class="btn btn-topbar cards-app-group-by-btn" ng-class="{'active': $ctrl.hasGroupBy}" ng-disabled="$ctrl.readonly">
          <i class="bi-collection"></i> {{$ctrl.label}}
          <span class="bi-caret-down-fill" ng-hide="$ctrl.readonly"></span>
        </button>
      `,
      restrict: "E",
      replace: true,
      scope: {
        board: "<",
        groupBy: "<",
        choices: "<?",
        groupableTwice: "<?",
        readonly: "<?",
        shrinked: "<?",
        onChange: "&?"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$scope", "dropdown", "$element"];
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
        }
        $onChanges(changes) {
          if (changes.groupBy || changes.groupableTwice || changes.shrinked) {
            this.refreshLabel();
          }
        }
        get hasGroupBy() {
          return this.groupBy && this.groupBy.some((gby) => !gby.isNothing());
        }
        notifyChange(spec) {
          this.onChange({ $spec: spec });
        }
        refreshLabel() {
          this.label = _p("group-by-btn", "Group");
          if (!this.hasGroupBy || this.shrinked) {
            return;
          }
          let groupBySpecs = this.groupBy.map((groupBy2) => groupBy2.spec);
          if (!this.groupableTwice || this.groupBy && this.groupBy[1].isNothing()) {
            groupBySpecs = groupBySpecs.slice(0, 1);
          }
          this.label = _4("Grouped by {groupby}", { groupby: formatSpecLabel(groupBySpecs) });
        }
        $postLink() {
          this.$element.on("click", () => this.openDrop());
        }
        openDrop() {
          const dropHtml = `
            <groupby-editor board="$ctrl.board" group-by="$ctrl.groupBy" groupable-twice="$ctrl.groupableTwice"
              choices="$ctrl.choices" on-change="$ctrl.notifyChange($spec)" on-drop-closed="!$afterSet ? $ctrl.$dropdown.close($ctrl.drop) : null"></groupby-editor>
          `;
          this.drop = this.$dropdown.openCompile(this.$element[0], dropHtml, this.$scope, {
            classes: "cards-app-groupby-btn-drop drop-theme-menu drop-theme-arrow",
            tetherOptions: {
              constraints: [{
                to: "window",
                pin: true,
                attachment: "together none"
              }]
            }
          });
        }
      }
    };
  }
]);
angular_default.module("kantree").component("groupbyEditor", {
  templateUrl: "/static/app/apps/cards/common/ui/nav/ng-components/templates/group-by-editor.html",
  bindings: {
    board: "<",
    groupBy: "<",
    groupableTwice: "<?",
    choices: "<?",
    onChange: "&",
    onDropClosed: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "cardsAppGroupByMenu"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.firstGroupBy = this.groupBy[0].spec;
      this.secondGroupBy = this.groupBy[1].spec;
      this.refreshMenuBuilder();
      this.menuLabelFormatter = (value2) => value2 && formatSpecLabel(value2);
      this.dropConfig = { classes: "groupby-editor-pretty-select-drop drop-theme-menu" };
    }
    $onChanges(changes) {
      const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
      if (groupByChanged) {
        this.refreshMenuBuilder();
      }
    }
    refreshMenuBuilder() {
      this.columnMenuBuilder = (notifyChange) => this.$cardsAppGroupByMenu.getMenu(this.board, this.groupBy[0], this.groupBy[1], this.choices, notifyChange);
      this.laneMenuBuilder = (notifyChange) => this.$cardsAppGroupByMenu.getMenu(this.board, this.groupBy[1], this.groupBy[0], this.choices, notifyChange);
    }
    notifyChange(pos, spec) {
      const cleanSpecs = this.groupBy.map((gBy) => ({ ...gBy.spec }));
      cleanSpecs[pos] = spec;
      this.onChange({ $spec: cleanSpecs });
    }
  }
});
angular_default.module("kantree").component("groupByEditorMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&?"
  },
  template: `
    <groupby-editor board="$ctrl.params.board" group-by="$ctrl.params.groupBy"
      groupable-twice="$ctrl.params.groupableTwice"
      choices="$ctrl.params.choices" on-change="$ctrl.params.onChange($spec)"
      on-drop-closed="!$afterSet ? $ctrl.onClose({$forceClose: true}) : null"
    ></groupby-editor>
  `
});

// public/app/apps/cards/common/ui/nav/ng-components/modes-btn.js
angular_default.module("kantree").directive("cardsAppModesBtn", [
  function() {
    return {
      template: `
        <button class="btn btn-topbar cards-app-mode-btn" ng-disabled="$ctrl.readonly">
          <i ng-class="$ctrl.icon|iconClass"></i> {{$ctrl.title}}
          <span class="bi-caret-down-fill" ng-hide="$ctrl.readonly"></span>
        </button>
      `,
      restrict: "E",
      replace: true,
      scope: {
        mode: "<",
        board: "<?",
        filterScopes: "<?",
        readonly: "<?",
        onChange: "&"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$scope", "$element", "cardsAppModesMenu", "menuDropdown"];
        $onInit() {
          this.refreshMode();
          const project = this.board ? projectStore.tryGetForCard(this.board) : null;
          this.cardsApps = getAvailableCardsApps(project, this.filterScopes);
        }
        $onChanges(changes) {
          if (changes.mode && !changes.mode.isFirstChange()) {
            this.refreshMode();
            if (this.mode !== changes.mode.previousValue) {
              if (this.$menuDropdown.isOpened(this.drop)) {
                this.$menuDropdown.refreshMenu(this.drop, this.menu);
              }
            }
          }
        }
        $postLink() {
          this.$element.on("click touchstart", () => {
            this.$menuDropdown.open(this.$element[0], this.menu, this.$scope, {
              classes: "drop-theme-menu drop-theme-arrow drop-theme-app-mode-selector"
            });
          });
        }
        refreshMode() {
          const mode = cardsAppRegistry.get(this.mode) || {};
          this.icon = mode.icon;
          this.title = mode.title;
        }
        get menu() {
          const project = this.board ? projectStore.tryGetForCard(this.board) : null;
          const org2 = orgStore.tryGetForProject(project);
          return this.$cardsAppModesMenu.getMenu(this.mode, this.cardsApps, org2, (mode) => this.onChange({ $mode: mode }));
        }
      }
    };
  }
]);

// public/app/apps/cards/common/ui/nav/ng-components/options-btn.js
angular_default.module("kantree").component("cardsAppOptionsBtn", {
  templateUrl: "/static/app/apps/cards/common/ui/nav/ng-components/templates/options-btn.html",
  bindings: {
    mode: "<",
    store: "<",
    board: "<",
    groupBy: "<",
    options: "<",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.refreshTitle();
      this.refreshMenu();
      this._initModelStoreChanges();
    }
    _initModelStoreChanges() {
      if (this.unsubscribeModelStore) {
        this.unsubscribeModelStore();
      }
      const modelStore = getScopedModelStore(this.board, this.store);
      if (!modelStore) return;
      this.unsubscribeModelStore = modelStore.subscribe("changed", () => {
        this.refreshMenu();
      });
    }
    $onDestroy() {
      if (this.unsubscribeModelStore) {
        this.unsubscribeModelStore();
      }
    }
    $onChanges(changes) {
      if (["mode", "store", "board", "groupBy", "options"].some((propName) => changes[propName] && !changes[propName].isFirstChange())) {
        this.refreshTitle();
        this.refreshMenu();
      }
      if (changes.board && !changes.board.isFirstChange() || changes.store && !changes.store.isFirstChange()) {
        this._initModelStoreChanges();
      }
    }
    refreshTitle() {
      this.title = cardsAppRegistry.get(this.mode)?.title;
    }
    refreshMenu() {
      if (cardsAppRegistry.get(this.mode)?.menu && !!this.board) {
        this.modeOptionsMenu = cardsAppRegistry.get(this.mode).menu(
          this.store,
          this.board,
          this.groupBy,
          this.options,
          (changes) => this.onChange({ $changes: changes })
        );
      } else {
        this.modeOptionsMenu = null;
      }
    }
  }
});

// public/app/apps/cards/common/ui/nav/ng-components/sort-btn.js
angular_default.module("kantree").component("cardsAppSortBtn", {
  template: `
    <button class="btn btn-topbar" ng-class="{'active': $ctrl.hasSortBy}" ng-show="!$ctrl.readonly" drop-menu="$ctrl.dropMenu">
      <i class="bi-sort-down"></i>
      <span>{{$ctrl.btnLabel}}</span>
      <span class="bi-caret-down-fill"></span>
    </button>
  `,
  bindings: {
    mode: "<?",
    project: "<?",
    store: "<?",
    options: "<?",
    groupBy: "<?",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "cardGroupsSortByMenu"];
    $onInit() {
      ensureConnectivity(() => this.$scope.$applyAsync(() => {
        this.watch(true);
      }));
    }
    $onChanges(changes) {
      if (["options", "mode", "groupBy", "shrinked"].some((propName) => changes[propName] && !changes[propName].isFirstChange())) {
        this.watch(true);
      }
    }
    watch(immediate) {
      if (this.watchOff) this.watchOff();
      const modelStore = getScopedModelStore(this.project, this.store);
      const groupTypeStore = getScopedGroupTypeStore(this.project, this.store);
      const watcher = () => this.refresh();
      this.watchOff = offMany([
        modelStore.$watchAll(this.$scope, watcher, false),
        groupTypeStore.$watchAll(this.$scope, watcher, false)
      ]);
      if (immediate) {
        watcher();
      }
    }
    refresh() {
      const sortChoices = getSortableAttributes(this.project, this.store, true);
      const freeSort = !!cardsAppRegistry.get(this.mode)?.freeSort && canFreeSort(this.project, this.groupBy, this.options);
      const sortBy3 = getSortBy(this.options, !freeSort);
      this.hasSortBy = !!sortBy3;
      if (sortBy3 && !this.shrinked) {
        let value2 = sortBy3.value;
        const builtin = cardGroupStaticSortBy.find((item) => item.value === value2);
        if (builtin) {
          value2 = builtin.label.toLowerCase();
        } else if (typeof value2 === "number") {
          value2 = sortChoices.find((item) => item.id === value2);
          if (value2) {
            value2 = value2.label.toLowerCase();
          } else {
            value2 = "?";
          }
        }
        this.btnLabel = _4("Sorted by {value}", { value: value2 });
      } else {
        this.btnLabel = _4("Sort");
      }
      this.dropMenu = this.$cardGroupsSortByMenu.get(sortBy3, {
        choices: sortChoices,
        canFreeSort: freeSort,
        sortByChanged: (value2, reverse) => {
          const options2 = setSortBy(this.options, value2, reverse);
          this.onChange({ $changes: options2 });
        }
      });
    }
    $onDestroy() {
      if (this.watchOff) this.watchOff();
    }
  }
});

// public/app/loaders/automation.js
async function loadAutomationRulesForProject(project) {
  try {
    const rules = await loadMany(
      automationRuleStore,
      api_default.project_automations.list_automation_rules,
      { project_id: project.id }
    );
    automationRuleStore.scopedByProject(project).removeAllNotMatching(rules);
    return rules;
  } catch (r3) {
    automationRuleStore.scopedByProject(project).removeAll();
    throw r3;
  }
}
var eventsCache;
var actionsCache;
var queriesCache;
async function loadAvailableAutomationEvents() {
  if (eventsCache) {
    return eventsCache;
  }
  eventsCache = api_default.automation_types.list_automation_events.get();
  const events2 = await eventsCache;
  eventsCache = events2;
  return events2;
}
async function loadAvailableAutomationActions() {
  if (actionsCache) {
    return actionsCache;
  }
  const actions2 = await api_default.automation_types.list_automation_actions.get();
  actionsCache = actions2;
  return actions2;
}
async function loadAvailableAutomationQueries() {
  if (queriesCache) {
    return queriesCache;
  }
  const queries = await api_default.automation_types.list_automation_queries.get();
  queriesCache = queries;
  return queries;
}

// public/app/apps/cards/common/ui/nav/ng-components/actions-btn.js
angular_default.module("kantree").component("cardsAppActionsBtn", {
  template: `
    <button class="btn btn-topbar" drop-menu="$ctrl.dropMenu" force-open="$ctrl.forceOpen"
      uib-tooltip="{{::$ctrl.tooltipLabel}}" tooltip-placement="bottom">
      <i class="fa fa-bolt"></i> {{::$ctrl.btnLabel}}
      <span class="bi-caret-down-fill"></span>
    </button>
  `,
  bindings: {
    options: "<?",
    project: "<?",
    onChange: "&?"
  },
  controller: class extends AngularClass {
    static get $inject() {
      return (super.$inject || []).concat(["$timeout", "$q", "$scope", "$element", "actionsAppearanceEditorMenuFactory", "projectPage"]);
    }
    $onInit() {
      this.selectedRules = /* @__PURE__ */ new Set();
      this.$q.when(loadAutomationRulesForProject(this.project), () => {
        this.loadRules();
      });
      this.tooltipLabel = _4("List of actions");
      this.btnLabel = _4("Actions");
      this.$scope.$on("openActionsMenu", () => {
        this.forceOpen = true;
        this.$timeout(() => {
          this.forceOpen = false;
        }, 0);
      });
    }
    loadRules() {
      this.rules = automationRuleStore.scopedByProject(this.project).query({ trigger_event: "manual" });
      this.options.automations_rules?.forEach((ruleId) => {
        const rule = this.rules.find((rule2) => rule2.id === ruleId);
        if (rule) this.selectedRules.add(rule);
      });
      const rulesList = this.rules.map((rule) => {
        return {
          checkbox: true,
          label: rule.name,
          offline: true,
          mobile: true,
          value: () => this.selectedRules.has(rule),
          toggle: () => this.toggleRule(rule)
        };
      });
      if (rulesList.length === 0) {
        rulesList.push({ desc: _4("No manual automation rules have been created yet in this workspace") });
      }
      this.dropMenu = {
        config: () => () => [
          ...this.runnableRules(),
          {
            label: "--"
          },
          {
            label: _4("Select actions"),
            submenu: [
              ...rulesList,
              { label: "--", enabled: () => canManageAutomations(this.project) },
              {
                label: "Create action",
                icon: "plus",
                action: () => {
                  this.$projectPage.gotoApp("automations");
                  this.$timeout(() => this.$projectPage.trigger("addRule", "manual"), 200);
                },
                enabled: () => canManageAutomations(this.project)
              }
            ]
          },
          {
            label: _4("Hide actions"),
            icon: "eye-slash",
            action: () => {
              this.onChange({ $changes: { ...this.options, showActions: !this.options.showActions } });
            }
          },
          { label: "--" },
          {
            desc: _4("Lock this view to show selected actions as a toolbar.")
          }
        ],
        options: {
          classes: "actions-topbar-menu"
        }
      };
    }
    toggleRule(rule) {
      if (this.selectedRules.has(rule)) {
        this.selectedRules.delete(rule);
      } else {
        this.selectedRules.add(rule);
      }
      this.onChange({ $changes: { ...this.options, automations_rules: Array.from(this.selectedRules).map((rule2) => rule2.id) } });
    }
    runnableRules() {
      if (this.selectedRules.size > 0) {
        return Array.from(this.selectedRules).map((rule) => {
          const actionsAppearanceEditorMenu = this.$actionsAppearanceEditorMenuFactory.get(rule, this.project);
          return {
            submenu: actionsAppearanceEditorMenu.config,
            options: actionsAppearanceEditorMenu.options,
            buttons: [
              {
                icon: rule?.icon || "play-circle",
                label: rule?.name,
                color: rule?.background_color ? rule.background_color : null,
                classes: "btn-default btn-text actions-topbar-menu-actions-btn",
                action: () => {
                  this.runRule(rule);
                }
              },
              {
                icon: "pencil",
                action: "openSubmenu",
                classes: "btn-icon btn-default btn-text",
                enabled: () => canManageViews(this.project)
              }
            ]
          };
        });
      } else {
        return [
          { subheader: _4("No actions selected.") },
          { desc: _4("Selected actions will show up here once toggled on.") }
        ];
      }
    }
    runRule(rule) {
      this.running = true;
      this.$q.when(runAutomationRule(this.project, rule), () => {
        this.$timeout(() => {
          this.running = false;
          toastNotify(_4("Triggered automation"), "success");
        }, 500);
      });
    }
  }
});

// public/app/apps/cards/common/ui/nav/app-nav.js
angular_default.module("kantree").component("cardsAppNav", {
  template: `
    <dynamic-directive directive="{{$ctrl.cardsAppNavComponentName}}" mode="$ctrl.mode" board="$ctrl.board"
      store="$ctrl.store" filter="$ctrl.filter" filter-scopes="$ctrl.filterScopes" group-by="$ctrl.groupBy"
      options="$ctrl.options" matching-card-ids="$ctrl.matchingCardIds" group-by-groups="$ctrl.groupByGroups"
      group-by-choices="$ctrl.groupByChoices" readonly="$ctrl.readonly" filter-repr="$ctrl.filterRepr"
      shrinked="$ctrl.shrinked" on-change="$ctrl.onChange({$changes: $changes})"></dynamic-directive>
  `,
  bindings: {
    mode: "<?",
    board: "<?",
    store: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    groupByChoices: "<",
    groupByGroups: "<?",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    $onInit() {
      this.cardsAppNavComponentName = this.navComponentName;
    }
    $onChanges(changes) {
      const modeChanged = changes.mode && !changes.mode.isFirstChange();
      if (modeChanged) {
        this.cardsAppNavComponentName = this.navComponentName;
      }
    }
    get navComponentName() {
      if (!this.mode) return null;
      const project = this.board ? projectStore.tryGetForCard(this.board) : null;
      const app = cardsAppRegistry.get(this.mode);
      if (!isAppAvailable(app, project)) {
        return null;
      }
      return app?.navComponent || "cards-app-nav-default";
    }
  }
});
angular_default.module("kantree").component("cardsAppNavDefault", {
  template: `
    <cards-app-modes-btn mode="$ctrl.mode" board="$ctrl.board" filter-scopes="$ctrl.filterScopes"
      readonly="$ctrl.readonly" on-change="$ctrl.setMode($mode)"></cards-app-modes-btn>

    <cards-app-field-btn ng-if="$ctrl.app.needsField && !$ctrl.missingFeatureFlag" project="$ctrl.project" store="$ctrl.store" attr-type="$ctrl.app.needsField" readonly="$ctrl.readonly"
      options="$ctrl.options" on-change="$ctrl.setOptions($changes)" multiple="$ctrl.app.needsFieldMultiple"></cards-app-field-btn>

    <cards-app-groupby-btn ng-if="$ctrl.app.groupable && !$ctrl.missingFeatureFlag" board="$ctrl.board" group-by="$ctrl.groupBy"
      choices="$ctrl.groupByChoices" groupable-twice="$ctrl.app.groupableTwice" readonly="$ctrl.readonly"
      shrinked="$ctrl.shrinked" on-change="$ctrl.setGroupBy($spec)"></cards-app-groupby-btn>

    <cards-app-filter-btn ng-if="$ctrl.app.filterable && !$ctrl.missingFeatureFlag" board="$ctrl.board" card-store="$ctrl.store" filter="$ctrl.filter" filter-scopes="$ctrl.filterScopes" filter-repr="$ctrl.filterRepr"
      options="$ctrl.options" readonly="$ctrl.readonly" shrinked="$ctrl.shrinked" on-change="$ctrl.search($changes)"></cards-app-filter-btn>

    <cards-app-sort-btn ng-if="$ctrl.app.sortable && $ctrl.project && !$ctrl.missingFeatureFlag" mode="$ctrl.mode" project="$ctrl.project" store="$ctrl.store" group-by="$ctrl.groupBy"
      options="$ctrl.options" readonly="$ctrl.readonly" shrinked="$ctrl.shrinked" on-change="$ctrl.setOptions($changes)"></cards-app-sort-btn>

    <cards-app-actions-btn ng-if="$ctrl.project && !$ctrl.missingFeatureFlag && $ctrl.canRunAutomations" ng-show="$ctrl.options.showActions" mode="$ctrl.mode" project="$ctrl.project" store="$ctrl.store" group-by="$ctrl.groupBy"
      options="$ctrl.options" readonly="$ctrl.readonly" shrinked="$ctrl.shrinked" on-change="$ctrl.setOptions($changes)"></cards-app-actions-btn>

    <cards-app-options-btn ng-if="!$ctrl.missingFeatureFlag" mode="$ctrl.mode" board="$ctrl.board" store="$ctrl.store"  group-by="$ctrl.groupBy" options="$ctrl.options"
      on-change="$ctrl.setOptions($changes)"></cards-app-options-btn>
  `,
  bindings: {
    mode: "<?",
    board: "<?",
    store: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    groupByChoices: "<",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    $onChanges(changes) {
      if (changes.mode) {
        this.app = cardsAppRegistry.get(this.mode) || {};
        this.refreshMissingFeatureFlag();
      }
      if (changes.board) {
        this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
        this.canRunAutomations = this.project ? canRunAutomations(this.project) : false;
        this.refreshMissingFeatureFlag();
      }
    }
    refreshMissingFeatureFlag() {
      const org2 = orgStore.tryGetForProject(this.project);
      this.missingFeatureFlag = this.app.requireFeatureFlag && !hasFeatureFlag(org2, this.app.requireFeatureFlag);
    }
    setGroupBy(group_by) {
      this.onChange({ $changes: { options: { ...this.options || {}, group_by } } });
    }
    setMode(mode) {
      this.onChange({ $changes: { options: { ...this.options || {}, mode: mode.name } } });
    }
    setOptions(options2) {
      this.onChange({ $changes: { options: { ...this.options || {}, ...options2 } } });
    }
    search(options2) {
      this.onChange({ $changes: { options: { ...this.options || {}, ...options2 } } });
    }
  }
});

// public/app/apps/cards/common/ui/ng-components/add-group.js
angular_default.module("kantree").component("addCardGroup", {
  templateUrl: "/static/app/apps/cards/common/ui/ng-components/templates/add-group.html",
  bindings: {
    groupBy: "<",
    groupsCount: "<",
    board: "<",
    closeEditorOnEnter: "<?",
    enableEditorAutoOpeningOnInit: "<?",
    openEditorHotkey: "<?",
    enableOpenEditorHotkey: "<?",
    enableTourWatchers: "<?",
    onGroupAdded: "&?",
    onEditorOpened: "&?",
    showLabel: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "cardsSelector", "cardModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.capitalize = capitalize;
      this.watchGroups();
      this.setupCreator();
      if (this.onEditorOpened) {
        this.$scope.$watch("$ctrl.creatorOptions.enabled", (newVal, oldVal) => {
          if (newVal === oldVal) return;
          if (newVal) {
            this.onEditorOpened();
          }
        });
      }
      if (this.openEditorHotkey) {
        const hotkey = {
          combo: this.openEditorHotkey,
          needsCard: false,
          description: _4("Add a group"),
          callback: () => {
            if (this.groupBy.isGroupType(void 0, true) && this.enableOpenEditorHotkey) {
              this.creatorOptions.enabled = true;
            }
          }
        };
        this.$cardsSelector.hotkeys(this.$scope, [hotkey], () => !this.$cardModal.current);
      }
      if (this.enableTourWatchers) {
        this.$scope.$on("tourCompleted", this.onTourHidden);
        this.$scope.$on("tourCanceled", this.onTourHidden);
        this.$scope.$on("tourHidden", this.onTourHidden);
      }
    }
    $onChanges(changes) {
      if (changes.groupBy && !changes.groupBy.isFirstChange() && !this.groupBy.equals(changes.groupBy.previousValue)) {
        this.watchGroups();
        this.setupCreator();
      }
    }
    setupCreator() {
      this.creatorOptions = {
        enabled: false,
        saveChange: (e3, inputTitle, cb2) => {
          if (!inputTitle || !inputTitle.length) return;
          const newVal = capitalize(this.groupBy.getLabel()) + " " + (this.groupsCount + 2);
          this.$q.when(createGroup(this.groupBy.getGroupType(true), this.board, inputTitle), (group2) => {
            if (e3.keyCode === 13 && this.closeEditorOnEnter) {
              this.creatorOptions.enabled = false;
            }
            if (this.onGroupAdded) {
              this.onGroupAdded({ $event: e3 });
            }
            cb2(false, newVal);
          });
        },
        saveOn: {
          enter: true,
          tab: true
        },
        resetOn: {
          save: false
        },
        watchingInitValue: true,
        inputType: "input",
        saveBtnLabel: _4("Add"),
        placeholder: _4(
          "Add a {groupType}",
          { groupType: this.groupBy.getLabel() }
        )
      };
      if (this.groupsCount === 0 && this.enableEditorAutoOpeningOnInit) {
        this.creatorOptions.enabled = true;
      }
    }
    onTourHidden() {
      if (this.groupsCount === 0) {
        this.$scope.$evalAsync(() => {
          this.creatorOptions.enabled = true;
        });
      }
    }
    watchGroups() {
      if (this.groupsWatcherOff) this.groupsWatcherOff();
      this.groupsWatcherOff = this.groupBy.getGroupStore().subscribe(() => {
        const oldCount = this.groupsCount;
        this.groupsCount = this.groupBy.getGroupStore().count();
        if (oldCount !== this.groupsCount) {
          this.$scope.$applyAsync();
        }
      }, true);
    }
    $onDestroy() {
      if (this.groupsWatcherOff) this.groupsWatcherOff();
    }
  }
});

// public/app/apps/cards/common/ui/ng-components/board-progress.js
angular_default.module("kantree").component("cardsAppBoardProgress", {
  template: `
    <div class="progress">
      <div class="progress-bar"
        ng-repeat="bar in $ctrl.progressBars"
        ng-style="{width: bar.progress + '%'}"
        ng-class="bar.css_class"
        uib-tooltip="{{bar.title}}"
      >{{bar.progress}}%</div>
    </div>`,
  bindings: {
    store: "<",
    groupBy: "<?",
    options: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.refreshProgressBar();
    }
    $onChanges(changes) {
      const storeChanged = changes.store && !changes.store.isFirstChange();
      const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const showUngroupedCardsCanged = optionsChanged && (this.options || {}).showUngroupedCards !== (changes.options.previousValue || {}).showUngroupedCards;
      if (storeChanged) {
        this.refreshProgressBar();
      } else if (showUngroupedCardsCanged || groupByChanged) {
        this.refreshProgressBar();
      }
    }
    refreshProgressBar() {
      if (this.deregisterStoreWatcher) this.deregisterStoreWatcher();
      this.deregisterStoreWatcher = this.store.subscribe(() => {
        let q = {};
        if (!(this.options || {}).showUngroupedCards && this.groupBy && this.groupBy[0]) {
          q = (obj) => !query_exports.matchObject(obj, this.groupBy[0].ungroupedScopeFilters);
        }
        const r3 = this.store.query(q);
        let total = 0, inProgress = 0, completed = 0;
        for (const [state, c3] of Object.entries(countBy_default(r3, "state"))) {
          if (["in_progress", "waiting"].indexOf(state) !== -1) {
            inProgress += c3;
            total += c3;
          } else if (state === "completed") {
            completed += c3;
            total += c3;
          } else if (["undecided", "accepted"].indexOf(state) !== -1) {
            total += c3;
          }
        }
        const progressBars = [];
        if (completed > 0) {
          progressBars.push({
            name: "completed",
            title: _4("Completed"),
            progress: Math.round(completed * 100 / total),
            css_class: "progress-bar-success"
          });
        }
        if (inProgress > 0) {
          progressBars.push({
            name: "inProgress",
            title: _4("In Progress"),
            progress: Math.round(inProgress * 100 / total),
            css_class: "progress-bar-warning"
          });
        }
        this.progressBars = progressBars;
        if ((this.options || {}).showUngroupedCards) {
          this.$scope.$applyAsync();
        }
      }, true);
    }
    $onDestroy() {
      if (this.deregisterStoreWatcher) this.deregisterStoreWatcher();
    }
  }
});

// public/app/apps/cards/common/ui/ng-components/card-creator.js
angular_default.module("kantree").component("cardsAppCardCreator", {
  templateUrl: ["$attrs", function($attrs) {
    return $attrs.customTemplate && $attrs.customTemplate.length > 0 ? $attrs.customTemplate : "/static/app/apps/cards/common/ui/ng-components/templates/card-creator.html";
  }],
  bindings: {
    filtered: "<?",
    options: "<?",
    onLoad: "&",
    onEdit: "&",
    onClose: "&",
    onCardCreate: "&",
    onLinkCreate: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$timeout", "$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.setupCreator();
    }
    $postLink() {
      if (this.onLoad) {
        this.firstTimer = this.$timeout(() => {
          this.secondTimer = this.$timeout(() => {
            this.onLoad();
          }, 0, false);
        }, 0, false);
      }
    }
    setupCreator() {
      this.creatorOptions = {
        saveChange: (event2, title, cb2) => {
          if (!title || !title.length) {
            return;
          }
          var mustOpenModal = event2.ctrlKey && event2.keyCode === 13;
          this.$scope.$applyAsync(() => {
            this.onCardCreate({
              $event: event2,
              $title: title,
              $openModal: mustOpenModal
            });
          });
          cb2(mustOpenModal);
        },
        cancelChange: (event2, cb2) => {
          this.$scope.$applyAsync(() => this.onClose({ $event: event2 }));
          cb2();
        },
        selectOnFocus: false,
        cancelOn: { tab: true },
        enabled: true,
        placeholder: _4("Name your new card..."),
        ...this.options
      };
      if (this.onEdit) {
        this.creatorOptions.onEdit = (event2, title) => {
          this.onEdit({ $title: title });
        };
      }
    }
    handleLinkCreateClick() {
      this.onLinkCreate();
    }
    $onDestroy() {
      if (this.firstTimer) {
        this.$timeout.cancel(this.firstTimer);
        this.firstTimer = null;
      }
      if (this.secondTimer) {
        this.$timeout.cancel(this.secondTimer);
        this.secondTimer = null;
      }
    }
  }
});
angular_default.module("kantree").component("cardsAppCardCreatorMenuComponent", {
  bindings: {
    params: "<",
    onClose: "&"
  },
  template: `
    <cards-app-card-creator filtered="$ctrl.params.filtered" on-close="$ctrl.onClose()"
      on-card-create="$ctrl.onCardCreate($title, $openModal, $event)" on-link-create="$ctrl.onLinkCreate()"></cards-app-card-creator>
  `,
  controller: class extends AngularClass {
    onCardCreate(title, openModal2, event2) {
      this.params.onCardCreate(title, openModal2, event2);
      this.onClose();
    }
    onLinkCreate() {
      this.onClose();
      this.params.onLinkCreate();
    }
  }
});

// public/app/apps/cards/common/ui/ng-components/cards-app.js
angular_default.module("kantree").component("cardsApp", {
  template: `
    <div ng-if="$ctrl.cardsAppComponentName">
      <dynamic-directive directive="{{$ctrl.cardsAppComponentName}}" store="$ctrl._store" board="$ctrl._board" filter="$ctrl._filter"
        filter-scopes="$ctrl._filterScopes" group-by="$ctrl._groupBy" options="$ctrl._options" matching-card-ids="$ctrl._matchingCardIds"
        readonly="$ctrl._readonly" on-change="$ctrl.onChange({$changes: $changes})"></dynamic-directive>
    </div>
    <div ng-if="!$ctrl.cardsAppComponentName">
      <div class="cards-app-empty-notice" ng-if="$ctrl.appRequiresFlag">
        <div>{{$ctrl.featureFlagDescription}}</div>
        <button type="button" class="btn btn-cta mt-3" ng-if="$ctrl.showUpgradeBtn" ng-click="$ctrl.openOrgSettings()"><i class="bi-stars"></i>{{_("Try Kantree Business")}}</button>
      </div>
      <div class="cards-app-empty-notice" ng-if="!$ctrl.appRequiresFlag">
        <div>{{_("This type of view does not exist or is not available anymore")}}</div>
      </div>
    </div>
  `,
  bindings: {
    mode: "<?",
    store: "<",
    board: "<?",
    filter: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    readonly: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "orgSettingsModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      if (changes.mode) {
        if (!this.mode) {
          this.cardsAppComponentName = null;
          this.appRequiresFlag = false;
          this.featureFlagDescription = null;
        } else {
          const project = this.board ? projectStore.tryGetForCard(this.board) : null;
          const org2 = orgStore.tryGetForProject(project);
          const app = cardsAppRegistry.get(this.mode);
          this.appTitle = app.title;
          if (app.requireFeatureFlag && !hasFeatureFlag(org2, app.requireFeatureFlag)) {
            this.cardsAppComponentName = null;
            this.appRequiresFlag = true;
            this.showUpgradeBtn = true;
            this.featureFlagDescription = app.featureFlagDescription;
          } else {
            this.cardsAppComponentName = !isAppAvailable(app, project) ? null : app?.component;
            this.appRequiresFlag = false;
            this.featureFlagDescription = null;
            this.refresh();
          }
        }
      } else {
        this.refresh();
      }
    }
    refresh() {
      this._store = this.store;
      this._board = this.board;
      this._filter = this.filter;
      this._filterScopes = this.filterScopes;
      this._groupBy = this.groupBy;
      this._options = this.options;
      this._matchingCardIds = this.matchingCardIds;
      this._readonly = this.readonly;
    }
    openOrgSettings() {
      const project = this.board ? projectStore.tryGetForCard(this.board) : null;
      const org2 = orgStore.tryGetForProject(project);
      if (org2) {
        this.$orgSettingsModal.open(org2, "billing");
      }
    }
  }
});

// public/app/ui/utils/drag-scroll.js
var DragScrollHelper = class {
  constructor(options2) {
    this.SCROLL_SPEED_MIN = 5;
    this.SCROLL_SPEED_MAX = 40;
    this.options = Object.assign({}, {
      scrollable: "body",
      tolerance: "cursor"
    }, options2);
    this.update("scrollable");
    this.reset();
    if (this.options.draggable) {
      this.update("draggable", this.options.draggable);
    }
  }
  get canScrollHorizontally() {
    return typeof this.options.threshold.default.left !== "undefined" || typeof this.options.threshold.default.right !== "undefined";
  }
  get canScrollVertically() {
    return typeof this.options.threshold.default.top !== "undefined" || typeof this.options.threshold.default.bottom !== "undefined";
  }
  update(objName, newObj) {
    if (typeof newObj !== "undefined") {
      return Object.assign(this[objName], newObj);
    }
    if (objName === "scrollable") {
      const $scrollableEl = jquery_default(this.options.scrollable);
      this.scrollable = {
        width: $scrollableEl.outerWidth(),
        height: $scrollableEl.outerHeight(),
        offset: $scrollableEl.offset()
      };
    }
  }
  resetCache() {
    this.cache = {
      position: {
        x: 0,
        y: 0
      },
      delta: {
        x: 0,
        y: 0
      },
      mouseSpeed: {
        x: 0,
        y: 0
      },
      timestamp: Date.now()
    };
    this.resetCacheSpeed();
  }
  resetCacheSpeed() {
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
      this.scrollTimer = null;
    }
    this.cache.scrollSpeed = {
      x: 0,
      y: 0
    };
    this.cache.minSpeed = {
      x: 0,
      y: 0
    };
  }
  resetDraggable() {
    this.draggable = {
      width: 0,
      height: 0,
      mousePosition: {
        x: 0,
        y: 0
      }
    };
  }
  reset() {
    this.resetDraggable();
    this.resetCache();
  }
  calculateMouseSpeed(delta) {
    const timestamp2 = Date.now();
    const elapsed = timestamp2 - this.cache.timestamp;
    return {
      x: 1e3 * delta.x / elapsed,
      y: 1e3 * delta.y / elapsed
    };
  }
  smoothMouseSpeed(mouseSpeed) {
    return {
      x: 0.7 * mouseSpeed.x + 0.3 * this.cache.mouseSpeed.x,
      y: 0.7 * mouseSpeed.y + 0.3 * this.cache.mouseSpeed.y
    };
  }
  updatePositionCache(x3, y3) {
    this.cache.delta = {
      x: x3 - this.cache.position.x,
      y: y3 - this.cache.position.y
    };
    this.cache.position.x = x3;
    this.cache.position.y = y3;
    this.cache.mouseSpeed = this.smoothMouseSpeed(this.calculateMouseSpeed(this.cache.delta));
  }
  updateScroll(x3, y3, thresholdSize) {
    this.updatePositionCache(x3, y3);
    const scrollSpeed = {};
    let draggableCoord = {};
    const s3 = this.scrollable;
    const t3 = this.options.threshold[thresholdSize] || this.options.threshold["default"];
    if (this.options.tolerance === "border") {
      draggableCoord = {
        left: x3 - this.draggable.mousePosition.x,
        right: x3 + this.draggable.width - this.draggable.mousePosition.x,
        top: y3 - this.draggable.mousePosition.y,
        bottom: y3 + this.draggable.height - this.draggable.mousePosition.y
      };
    } else {
      draggableCoord = {
        left: x3,
        right: x3,
        top: y3,
        bottom: y3
      };
    }
    if (typeof t3.top !== "undefined" && draggableCoord.top < s3.offset.top + t3.top) {
      scrollSpeed.y = -this.computeScrollSpeed(
        "y",
        this.cache.mouseSpeed,
        s3.offset.top + t3.top - draggableCoord.top,
        t3.top
      );
    }
    if (typeof t3.bottom !== "undefined" && draggableCoord.bottom > s3.offset.top + s3.height - t3.bottom) {
      scrollSpeed.y = this.computeScrollSpeed(
        "y",
        this.cache.mouseSpeed,
        draggableCoord.bottom - (s3.offset.top + s3.height - t3.bottom),
        t3.bottom
      );
    }
    if (typeof t3.left !== "undefined" && draggableCoord.left < s3.offset.left + t3.left) {
      scrollSpeed.x = -this.computeScrollSpeed(
        "x",
        this.cache.mouseSpeed,
        s3.offset.left + t3.left - draggableCoord.left,
        t3.left
      );
    }
    if (typeof t3.right !== "undefined" && draggableCoord.right > s3.offset.left + s3.width - t3.right) {
      scrollSpeed.x = this.computeScrollSpeed(
        "x",
        this.cache.mouseSpeed,
        draggableCoord.right - (s3.offset.left + s3.width - t3.right),
        t3.right
      );
    }
    if (scrollSpeed.x || scrollSpeed.y) {
      this.scroll(scrollSpeed);
      return true;
    } else {
      this.resetCacheSpeed();
      return false;
    }
  }
  calculateMinimumScrollSpeed(value2) {
    return Math.min(Math.max(value2, this.SCROLL_SPEED_MIN), this.SCROLL_SPEED_MAX);
  }
  computeScrollSpeed(direction, mouseSpeed, distance, threshold) {
    let a3, b3;
    if (distance < 0) {
      return 0;
    }
    if (!this.cache.minSpeed[direction]) {
      this.cache.minSpeed[direction] = this.calculateMinimumScrollSpeed(mouseSpeed[direction]);
    }
    b3 = this.cache.minSpeed[direction];
    if (threshold) {
      a3 = (this.SCROLL_SPEED_MAX - b3) / threshold;
    } else {
      a3 = 2;
    }
    if (threshold && distance >= threshold) {
      return this.SCROLL_SPEED_MAX;
    } else {
      return a3 * distance + b3;
    }
  }
  scroll(speed) {
    const isScrolling = this.cache.scrollSpeed.x || this.cache.scrollSpeed.y;
    const doScroll = () => {
      if (!this.cache.scrollSpeed.x && !this.cache.scrollSpeed.y) {
        if (this.scrollTimer) {
          cancelAnimationFrame(this.scrollTimer);
          this.scrollTimer = null;
        }
        return;
      }
      let scrollTop, scrollLeft;
      let maxScrollTop, maxScrollLeft;
      const $scrollableEl = jquery_default(this.options.scrollable);
      if (typeof this.options.scroll !== "undefined") {
        this.options.scroll.call(this, this.cache.scrollSpeed);
      } else {
        if (this.cache.scrollSpeed.y) {
          scrollTop = $scrollableEl.scrollTop();
          maxScrollTop = $scrollableEl[0].scrollHeight - $scrollableEl[0].clientHeight;
          if (this.cache.scrollSpeed.y > 0 && scrollTop >= maxScrollTop || this.cache.scrollSpeed.y < 0 && scrollTop <= 0) {
            this.resetCacheSpeed();
            return;
          }
          $scrollableEl.scrollTop(scrollTop + this.cache.scrollSpeed.y);
        }
        if (this.cache.scrollSpeed.x) {
          scrollLeft = $scrollableEl.scrollLeft();
          maxScrollLeft = $scrollableEl[0].scrollWidth - $scrollableEl[0].clientWidth;
          if (this.cache.scrollSpeed.x > 0 && scrollLeft >= maxScrollLeft || this.cache.scrollSpeed.x < 0 && scrollLeft <= 0) {
            this.resetCacheSpeed();
            return;
          }
          $scrollableEl.scrollLeft(scrollLeft + this.cache.scrollSpeed.x);
        }
      }
      this.scrollTimer = requestAnimationFrame(doScroll);
    };
    this.cache.scrollSpeed = speed;
    if (!isScrolling) {
      doScroll();
    }
  }
};

// public/app/apps/cards/common/ui/ng-components/sortable-cards-container.js
angular_default.module("kantree").component("sortableCardsContainer", {
  template: `<div class="ui-sortable-cards" ui-sortable="$ctrl._options" ng-model="$ctrl.cards" data-delay="200" ng-transclude></div>`,
  bindings: {
    cards: "<",
    onDrop: "&",
    beforeDrop: "&",
    afterDrop: "&",
    options: "<",
    sortBy: "<",
    groups: "<",
    board: "<",
    collapsed: "<",
    editable: "<",
    isFiltered: "<",
    isCardFiltered: "&"
  },
  transclude: true,
  controller: class extends AngularClass {
    static $inject = ["$element", "$timeout", "$q", "$interval", "$scope", "projectPage"];
    $onInit() {
      this.refreshOptions();
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.refreshOptions();
        this.toggleHiddenPlaceholderClasses();
      }
      if (changes.cards && !changes.cards.isFirstChange()) {
        this.toggleHiddenPlaceholderClasses();
      }
      if (changes.groups && !changes.groups.isFirstChange()) {
        this.sortableElement.then((sortableElement) => {
          sortableElement.groups = this.groups || [];
        });
      }
      if (changes.board && !changes.board.isFirstChange() || changes.editable && !changes.editable.isFirstChange()) {
        this.sortableElement.then((sortableElement) => {
          sortableElement.board = this.board;
          jquery_default(sortableElement).sortable("option", "disabled", !!this.disabled);
        });
      }
      if (changes.collapsed && !changes.collapsed.isFirstChange()) {
        this.sortableElement.then((sortableElement) => {
          this.refreshAfterCollapseChange();
        });
      }
    }
    $postLink() {
      this.initSortableElement();
      this.toggleHiddenPlaceholderClasses();
      this.sortableElement.then((sortableElement) => {
        jquery_default(sortableElement).sortable("option", "disabled", !!this.disabled);
        this.$scope.$on("connectivityChanged", (e3, connected) => {
          jquery_default(sortableElement).sortable("option", "disabled", !!this.disabled);
        });
      });
      this.$element.on("delayed", function(event2) {
        jquery_default(this).find(".touched").removeClass("touched").addClass("pressed");
      });
    }
    async initSortableElement() {
      const sortableElement = await this.sortableElement;
      sortableElement.board = this.board;
      sortableElement.groups = this.groups || [];
      const items = (jquery_default(sortableElement).sortable("instance").items || []).filter((item) => item.instance === jquery_default(sortableElement).sortable("instance"));
      if ((this.cards || []).length !== items.length || items.length === 0) {
        jquery_default(sortableElement).sortable("refresh");
      }
    }
    get sortableElement() {
      if (this._sortableElement) {
        return this.$q.resolve(this._sortableElement);
      } else return this.fetchSortableElement().promise;
    }
    // wait (2s max) for sortable to be instanciated
    fetchSortableElement() {
      if (!this._sortableElementDeferred) {
        const deferred = this.$q.defer();
        this._sortableElementDeferred = deferred;
        deferred.promise.catch((r3) => console.warn(r3)).finally(() => {
          this._sortableElementDeferred = null;
        });
        this._sortableElementIntervalPromise = this.$interval(() => {
          const sortableElement = this.$element.find(".ui-sortable-cards")[0];
          if (sortableElement && jquery_default(sortableElement).sortable("instance")) {
            this._sortableElement = sortableElement;
            this.$interval.cancel(this._sortableElementIntervalPromise);
            deferred.resolve(this._sortableElement);
          }
        }, 100, 20, false);
        this._sortableElementIntervalPromise.then(() => {
          deferred.reject("sortable-cards not found");
        }).catch((r3) => null).finally(() => {
          this._sortableElementIntervalPromise = null;
        });
      }
      return this._sortableElementDeferred;
    }
    toggleHiddenPlaceholderClasses(inContainerSource = false) {
      this.$element.find(".ui-sortable-cards").toggleClass(
        "with-hidden-placeholder",
        (!this.canDropInSameContainer || !this.customPositionEnabled) && !!this.cards && (this.cards.length > 1 || this.cards.length === 1 && !inContainerSource)
      );
    }
    setScrollHelper(event2, ui) {
      const rect = ui.placeholder[0].getBoundingClientRect();
      this.scrollHelper = new DragScrollHelper(Object.assign({}, this._options._scrollHelperOptions || {}, {
        scrollable: this.scrollableElement,
        draggable: {
          width: ui.helperProportions.width,
          height: ui.helperProportions.height,
          mousePosition: {
            x: event2.clientX - rect.left,
            y: event2.clientY - rect.top
          }
        }
      }));
    }
    get isScrollable() {
      if (!this.scrollHelper || this._options._scrollHelperOptions.disabled) return false;
      const scrollableElement = this.scrollableElement;
      return this.scrollHelper.canScrollHorizontally && scrollableElement.scrollWidth > scrollableElement.clientWidth || this.scrollHelper.canScrollVertically && scrollableElement.scrollHeight > scrollableElement.clientHeight;
    }
    get scrollableElement() {
      if (this._options._scrollHelperOptions.scrollable === ".ui-sortable-cards") {
        return this._sortableElement;
      }
      return this.$element.find(this._options._scrollHelperOptions.scrollable)[0];
    }
    get disabled() {
      return !this.board || !this.editable || !isConnected();
    }
    refreshAfterCollapseChange() {
      if (!this.expandedOnce) {
        jquery_default(this._sortableElement).sortable("refresh");
      }
      this.expandedOnce = this.expandedOnce || this.collapsed;
    }
    refreshOptions() {
      this._options = Object.assign({}, {
        appendTo: "body",
        helper: "clone",
        items: ".card-tile:not(.archived):not(form):not(.locked):not(.sortable-disabled):not(.hidden)",
        itemsContainer: ".ui-sortable-cards-items-container",
        connectWith: ".ui-sortable-cards",
        placeholder: "ui-sortable-cards-placeholder",
        distance: 6,
        scroll: false,
        zIndex: 0,
        duplication: true,
        _dragoverSelector: () => {
        },
        _canDropInSameContainer: true,
        _customPositionEnabled: true,
        _scrollHelperOptions: {
          scrollable: ".ui-sortable-cards",
          threshold: {
            default: { top: 50, bottom: 50 },
            xs: { top: 30, bottom: 30 }
          }
        },
        _containersScrollHelperOptions: {
          scrollable: null,
          threshold: {
            default: { top: 40, right: 60, bottom: 40, left: 60 },
            xs: { top: 25, right: 30, bottom: 25, left: 30 }
          },
          tolerance: "border"
        },
        start: (event2, ui) => {
          if (this.$projectPage.isActive && this.$projectPage.selectedCards?.length) {
            this.$scope.$applyAsync(() => {
              this.$projectPage.clearSelectedCards();
            });
          }
          ui.item.sortable.targetCtrl = this;
          ui.item.toggleClass("dragged");
          ui.item.sortable.sourceCtrl = this;
          ui.placeholder.height(ui.helperProportions.height - 1);
          this.toggleHiddenPlaceholderClasses(true);
          if (!this._options._scrollHelperOptions.disabled) {
            this.setScrollHelper(event2, ui);
          }
          if (!this._options._containersScrollHelperOptions.disabled) {
            const scrollableElement = jquery_default(this._options._containersScrollHelperOptions.scrollable)[0];
            ui.item.sortable.containersScrollHelper = new DragScrollHelper(this._options._containersScrollHelperOptions);
            ui.item.sortable.isContainersScrollable = ui.item.sortable.containersScrollHelper.canScrollHorizontally && scrollableElement.scrollWidth > scrollableElement.clientWidth || ui.item.sortable.containersScrollHelper.canScrollVertically && scrollableElement.scrollHeight > scrollableElement.clientHeight;
            const rect = ui.placeholder[0].getBoundingClientRect();
            ui.item.sortable.containersScrollHelper.update("draggable", {
              width: ui.helperProportions.width,
              height: ui.helperProportions.height,
              mousePosition: {
                x: event2.clientX - rect.left,
                y: event2.clientY - rect.top
              }
            });
          }
        },
        disabledContainers: (ui, callback) => {
          const cardScope = ui.item[0].scope();
          const draggedCard = cardScope.$ctrl ? cardScope.$ctrl.card : cardScope.card;
          const apply3 = (valids) => {
            const disabled = ui.containers.reduce((accu, container) => {
              const containerElement = container.element[0];
              const containerGroups = Array.isArray(containerElement.groups) ? containerElement.groups : [containerElement.groups];
              const disabledGroups = this.getDisabledGroups(containerGroups, draggedCard, containerElement.board, valids);
              if (!disabledGroups) return accu;
              const key2 = Object.keys(this.sortableCardsDisableMessages).sort((a3, b3) => a3.priority - b3.priority).find((key3) => disabledGroups[key3] && disabledGroups[key3].length);
              if (key2) {
                const message = this.sortableCardsDisableMessages[key2].message(disabledGroups[key2].map((group2) => group2.title).join(" and "));
                accu.push({ container, content: this.createDisableDropContent(message) });
              }
              return accu;
            }, []);
            callback(disabled);
          };
          apply3();
        },
        over: (event2, ui) => {
          ui.item.sortable.targetCtrl = this;
          this.setScrollHelper(event2, ui);
          const dragoverSel = this._options._dragoverSelector();
          if (dragoverSel) {
            jquery_default(dragoverSel).removeClass("drag-hover");
            ui.placeholder.parents(dragoverSel).addClass("drag-hover");
          }
        },
        sort: (event2, ui) => {
          const { targetCtrl, containersScrollHelper, isContainersScrollable } = ui.item.sortable;
          if (targetCtrl.isScrollable) {
            const isContainerScrolled = targetCtrl.scrollHelper.updateScroll(event2.pageX, event2.pageY, getScreensize());
            if (isContainerScrolled && containersScrollHelper) {
              containersScrollHelper.resetCacheSpeed();
              return;
            }
          }
          if (containersScrollHelper && isContainersScrollable) {
            const isContainersScrolled = containersScrollHelper.updateScroll(event2.pageX, event2.pageY, getScreensize());
            if (isContainersScrolled && targetCtrl.isScrollable) {
              targetCtrl.scrollHelper.resetCacheSpeed();
            }
          }
        },
        out: (event2, ui) => {
          if (this.scrollHelper) {
            this.scrollHelper.reset();
            this.scrollHelper = null;
          }
        },
        update: (event2, ui) => {
          const { sourceCtrl, targetCtrl, cancel, droptarget, index: index2, dropindex } = ui.item.sortable;
          if (sourceCtrl !== this) return;
          if (event2.originalEvent.target === null) {
            cancel();
          }
          if (!droptarget || !droptarget.length) {
            cancel();
          }
          if (targetCtrl === this) {
            if (!this.canDropInSameContainer) {
              cancel();
            } else if (index2 === dropindex) {
              cancel();
            }
          }
        },
        beforeStop: (event2, ui) => {
          ui.item.removeClass("pressed");
        },
        receive: (event2, ui) => {
          if (this.scrollHelper) {
            this.scrollHelper.reset();
            this.scrollHelper = null;
          }
        },
        stop: (event2, ui) => {
          const {
            containersScrollHelper,
            targetCtrl = this,
            isCanceled,
            // the dragged card has already been added by ng-sortable.js in the droptargetModel
            // See : L246 for connected lists sort and L260 for normal sort
            droptargetModel: droptargetCards,
            model: card,
            dropindex,
            index: index2
          } = ui.item.sortable;
          const droppedInSameList = targetCtrl === this;
          if (containersScrollHelper) {
            containersScrollHelper.reset();
          }
          if (this.scrollHelper) {
            this.scrollHelper.reset();
            this.scrollHelper = null;
          }
          const dragoverSel = this._options._dragoverSelector();
          if (dragoverSel) {
            jquery_default(dragoverSel).removeClass("drag-hover");
          }
          ui.item.toggleClass("dragged");
          ui.item.removeAttr("style");
          if (isCanceled()) return;
          if (!droptargetCards) return;
          let position = null;
          if (this.customPositionEnabled) {
            let getNewPosition = function(dropIndex, replacing) {
              let relativeToCard, shift2 = 0, position2 = null;
              let predicate = (c3) => (!targetGroup || !c3.is_archived) && c3.id !== card.id;
              if (self2.isFiltered) {
                predicate = (c3) => (!targetGroup || !c3.is_archived) && c3.id !== card.id && self2.isCardFiltered({ $card: c3 });
              }
              if (replacing === "upper") {
                relativeToCard = droptargetCards.slice(dropIndex + 1).find((c3) => predicate(c3));
                if (!relativeToCard) {
                  shift2 = 1;
                  relativeToCard = droptargetCards.slice(0, dropIndex).reverse().find((c3) => predicate(c3));
                }
              } else if (replacing === "lower") {
                relativeToCard = droptargetCards.slice(0, dropIndex).reverse().find((c3) => predicate(c3));
                if (!relativeToCard) {
                  shift2 = -1;
                  relativeToCard = droptargetCards.slice(dropIndex + 1).find((c3) => predicate(c3));
                }
              }
              if (relativeToCard) {
                if (!targetGroup) {
                  if (!droppedInSameList) {
                    if (card.position > relativeToCard.position) {
                      if (shift2 === 1) {
                        position2 = relativeToCard.position + 1;
                      } else {
                        position2 = relativeToCard.position;
                      }
                    } else {
                      if (shift2 === 1) {
                        position2 = relativeToCard.position;
                      } else {
                        position2 = relativeToCard.position - 1;
                      }
                    }
                    if (ui.item.sortable.dropindex >= droptargetCards.length - 1) {
                      const highestPositionInProject = Math.max(1, ...pluck(cardStore.query({ parent_id: relativeToCard.parent_id }), "position"));
                      position2 = Math.min(position2, highestPositionInProject);
                    }
                  } else {
                    if (shift2 === 0) {
                      if (card.position > relativeToCard.position && replacing === "lower") {
                        shift2 = 1;
                      } else if (card.position < relativeToCard.position && replacing === "upper") {
                        shift2 = -1;
                      }
                    }
                    position2 = relativeToCard.position + shift2;
                  }
                  if (position2 < 1) {
                    position2 = 1;
                  }
                } else {
                  let relCgc = relativeToCard.groups.find((g3) => targetGroup && g3.id === targetGroup.id);
                  if (droppedInSameList) {
                    let cgc = card.groups.find((g3) => targetGroup && g3.id === targetGroup.id);
                    if (shift2 === 0) {
                      if (relCgc && cgc && cgc.position > relCgc.position && replacing === "lower") {
                        shift2 = 1;
                      } else if (relCgc && cgc && cgc.position < relCgc.position && replacing === "upper") {
                        shift2 = -1;
                      }
                    }
                  }
                  position2 = relCgc ? relCgc.position + shift2 : null;
                  if (position2 < 0) {
                    position2 = 0;
                  }
                }
              } else {
                if (!targetGroup) {
                  position2 = card.position;
                } else {
                  position2 = 0;
                }
              }
              return position2;
            };
            const targetGroup = (targetCtrl.groups ? Array.isArray(targetCtrl.groups) ? targetCtrl.groups : [targetCtrl.groups] : [])[0];
            const self2 = this;
            if (droptargetCards.length <= 1) {
              position = null;
            } else if (droppedInSameList) {
              if (index2 < dropindex) {
                position = getNewPosition(dropindex, "lower");
              } else if (index2 > dropindex) {
                position = getNewPosition(dropindex, "upper");
              }
            } else {
              position = getNewPosition(dropindex, "upper");
            }
          }
          jquery_default(".ui-sortable-cards").sortable("disable");
          const $onDropParams = { card, position, append: ui.isDuplication, fromCtrl: this };
          targetCtrl.beforeDrop({ $onDropParams });
          if (!droppedInSameList) {
            this.beforeDrop({ $onDropParams });
          }
          targetCtrl.onDrop({ $onDropParams }).catch((r3) => console.warn(r3)).finally(() => jquery_default(".ui-sortable-cards").sortable("enable"));
          targetCtrl.afterDrop({ $onDropParams });
          if (!droppedInSameList) {
            this.afterDrop({ $onDropParams });
          }
        }
      }, Object.assign({}, this.options || {}, { disabled: !this.board }));
    }
    getDisabledGroups(groups, draggedCard, board, valids) {
      const sourceGroups = this.groups ? Array.isArray(this.groups) ? this.groups : [this.groups] : [];
      return groups.reduce((accu, group2, idx) => {
        const sourceGroup = sourceGroups[idx];
        if (!group2) return accu;
        if (group2.is_dynamic && group2.getCardStore().exists(draggedCard.id)) {
          if (sourceGroup && sourceGroup.id !== group2.id) {
            if (accu.alreadyMember) {
              accu.alreadyMember.push(group2);
            } else accu.alreadyMember = [group2];
            return accu;
          } else return accu;
        }
        if (sourceGroup && sourceGroup.id === group2.id) return accu;
        if (board) {
          if (group2.scope === "card" && board.id !== draggedCard.parent_id) {
            if (accu.boardScopedGroups) {
              accu.boardScopedGroups.push(group2);
            } else accu.boardScopedGroups = [group2];
            return accu;
          }
          const project = projectStore.tryGetForCard(board);
          if (project && !isAllowedInProject(project, "card_group", "MOVE_CARDS", group2.id)) {
            if (accu.notAllowed) {
              accu.notAllowed.push(group2);
            } else accu.notAllowed = [group2];
            return accu;
          }
        }
        if (group2.is_archived) {
          if (accu.archived) accu.archived.push(group2);
          else accu.archived = [group2];
          return accu;
        }
        if (draggedCard.groups.map((g3) => g3.id).indexOf(group2.id) !== -1) {
          if (accu.alreadyThere) {
            accu.alreadyThere.push(group2);
          } else accu.alreadyThere = [group2];
          return accu;
        }
        if (valids && typeof valids[group2.id] !== "undefined" && !valids[group2.id]) {
          if (accu.requirementsMissed) {
            accu.requirementsMissed.push(group2);
          } else accu.requirementsMissed = [group2];
          return accu;
        }
        return accu;
      }, {});
    }
    createDisableDropContent(message) {
      const disableContent = document.createElement("div");
      const disableContentIcon = document.createElement("i");
      const disableContentMessage = document.createElement("p");
      disableContentIcon.className = "fa fa-ban";
      disableContentMessage.innerText = message;
      disableContent.appendChild(disableContentIcon);
      disableContent.appendChild(disableContentMessage);
      return disableContent;
    }
    get canDropInSameContainer() {
      return this._options._canDropInSameContainer && !this.sortBy;
    }
    get customPositionEnabled() {
      return this._options._customPositionEnabled && !this.sortBy;
    }
    get sortableCardsDisableMessages() {
      return {
        "archived": {
          priority: 1,
          message: (groups) => _4("{groups} archived.", { groups })
        },
        "alreadyThere": {
          priority: 2,
          message: (groups) => _4("This card is already in {groups}.", { groups })
        },
        "boardScopedGroups": {
          priority: 3,
          message: (groups) => _4("You can't move cards that don't belong to this board inside {groups}.", { groups })
        },
        "notAllowed": {
          priority: 4,
          message: (groups) => _4("You don't have permissions to move cards inside {groups}.", { groups })
        },
        "alreadyMember": {
          priority: 5,
          message: (groups) => _4("{groups} already assigned to this card.", { groups })
        },
        "requirementsMissed": {
          priority: 6,
          message: (groups) => _4("This card does not meet the validation rule for {groups}", { groups })
        }
      };
    }
    $onDestroy() {
      if (this.scrollHelper) {
        this.scrollHelper.reset();
      }
      if (this._sortableElementIntervalPromise) {
        this.$interval.cancel(this._sortableElementIntervalPromise);
        this._sortableElementIntervalPromise = null;
      }
      if (this._sortableElementDeferred) {
        this._sortableElementDeferred.reject("sortable-cards-container has been destroyed before sortableElement has been initialized");
        this._sortableElementDeferred = null;
      }
    }
  }
});

// public/app/apps/cards/common/ui/ng-components/sortable-groups-container.js
angular_default.module("kantree").component("sortableGroupsContainer", {
  template: `<div class="ui-sortable-groups" ui-sortable="$ctrl._options" ng-model="$ctrl.groups" data-delay="200" ng-transclude></div>`,
  bindings: {
    groups: "<",
    options: "<",
    project: "<"
  },
  transclude: true,
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope", "$interval", "$q"];
    $onInit() {
      this.refreshOptions();
      this.$scope.$on("connectivityChanged", () => {
        this.sortableElement.then((sortableElement) => {
          jquery_default(sortableElement).sortable("option", "disabled", !this.project || !this.editable);
        });
      });
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.refreshOptions();
      }
      if (changes.groups && !changes.groups.isFirstChange()) {
        this.sortableElement.then((sortableElement) => {
          sortableElement.groups = this.groups || [];
        });
      }
      if (changes.project && !changes.project.isFirstChange()) {
        this.sortableElement.then((sortableElement) => {
          sortableElement.project = this.project;
          jquery_default(sortableElement).sortable("option", "disabled", !this.project || !this.editable);
        });
      }
    }
    $postLink() {
      this.initSortableElement();
      this.$element.on("delayed", function(event2) {
        jquery_default(this).find(".touched").removeClass("touched").addClass("pressed");
      });
    }
    get editable() {
      return !this.project.is_archived && canEditGroup(this.project) && isConnected();
    }
    async initSortableElement() {
      const sortableElement = await this.sortableElement;
      sortableElement.project = this.project;
      sortableElement.groups = this.groups || [];
      if (this.project) {
        this.$scope.$watch(() => this.project.is_archived, (newVal, oldVal) => {
          if (newVal === oldVal) return;
          jquery_default(sortableElement).sortable("option", "disabled", !this.editable);
        });
        this.$scope.$on("connectivityChanged", () => {
          jquery_default(sortableElement).sortable("option", "disabled", !this.editable);
        });
        const items = (jquery_default(sortableElement).sortable("instance").items || []).filter((item) => item.instance === jquery_default(sortableElement).sortable("instance"));
        if ((this.groups || []).length !== items.length) {
          jquery_default(sortableElement).sortable("refresh");
        }
      }
    }
    get sortableElement() {
      if (this._sortableElement) {
        return this.$q.resolve(this._sortableElement);
      } else return this.fetchSortableElement().promise;
    }
    // wait (2s max) for sortable to be instanciated
    fetchSortableElement() {
      if (!this._sortableElementDeferred) {
        const deferred = this.$q.defer();
        this._sortableElementDeferred = deferred;
        deferred.promise.catch((r3) => console.warn(r3)).finally(() => {
          this._sortableElementDeferred = null;
        });
        this._sortableElementIntervalPromise = this.$interval(() => {
          const sortableElement = this.$element.find(".ui-sortable-groups")[0];
          if (sortableElement && jquery_default(sortableElement).sortable("instance")) {
            this._sortableElement = sortableElement;
            this.$interval.cancel(this._sortableElementIntervalPromise);
            deferred.resolve(this._sortableElement);
          }
        }, 100, 20, false);
        this._sortableElementIntervalPromise.then(() => {
          deferred.reject("sortable-groups not found");
        }).catch((r3) => null).finally(() => {
          this._sortableElementIntervalPromise = null;
        });
      }
      return this._sortableElementDeferred;
    }
    get isScrollable() {
      if (!this.scrollHelper) return false;
      const scrollableElement = this.scrollableElement;
      return this.scrollHelper.canScrollHorizontally && scrollableElement.scrollWidth > scrollableElement.clientWidth || this.scrollHelper.canScrollVertically && scrollableElement.scrollHeight > scrollableElement.clientHeight;
    }
    get scrollableElement() {
      if (this._options._scrollHelperOptions.scrollable === ".ui-sortable-groups") {
        return this._sortableElement;
      }
      return jquery_default(this._options._scrollHelperOptions.scrollable)[0];
    }
    updateScrollHelper(event2, ui) {
      if (this.scrollHelperUpdateTaskId) {
        cancelAnimationFrame(this.scrollHelperUpdateTaskId);
        this.scrollHelperUpdateTaskId = null;
      }
      this.scrollHelperUpdateTaskId = requestAnimationFrame(() => {
        const rect = ui.placeholder[0].getBoundingClientRect();
        this.scrollHelper.update("draggable", {
          width: ui.helperProportions.width,
          height: ui.helperProportions.height,
          mousePosition: {
            x: event2.clientX - rect.left,
            y: event2.clientY - rect.top
          }
        });
      });
    }
    on(action, event2, ui) {
      if (!this.options) return;
      if (!this.options.on) return;
      if (this.options.on[action]) {
        this.options.on[action](event2, ui);
      }
    }
    refreshOptions() {
      this._options = Object.assign({}, {
        appendTo: "body",
        helper: "clone",
        items: ".ui-sortable-groups-item",
        itemsContainer: ".ui-sortable-groups-items-container",
        placeholder: "ui-sortable-groups-placeholder",
        scroll: false,
        // we use the dragScrollHelperInstance
        distance: 6,
        axis: false,
        zIndex: 0,
        handle: false,
        intersectTolerance: 0.3,
        _scrollHelperOptions: {
          scrollable: ".ui-sortable-groups",
          threshold: {
            default: { top: 60, bottom: 60 },
            xs: { top: 30, bottom: 30 }
          },
          tolerance: "cursor"
        },
        start: (event2, ui) => {
          ui.placeholder.width(ui.helper.outerWidth());
          ui.placeholder.height(ui.helper.outerHeight());
          this.scrollHelper = new DragScrollHelper(this._options._scrollHelperOptions);
          ui.item.sortable.isScrollable = this.isScrollable;
          if (ui.item.sortable.isScrollable) {
            this.updateScrollHelper(event2, ui);
          }
          this.on("start", event2, ui);
        },
        sort: (event2, ui) => {
          if (ui.item.sortable.isScrollable) {
            this.updateScrollHelper(event2, ui);
            this.scrollHelper.updateScroll(event2.pageX, event2.pageY, getScreensize());
          }
        },
        beforeStop: (event2, ui) => {
          ui.item.sortable.newPosition = this.groups[ui.item.index()].position;
        },
        stop: (event2, ui) => {
          const { droptarget, model: group2, newPosition } = ui.item.sortable;
          if (this.scrollHelperUpdateTaskId) {
            cancelAnimationFrame(this.scrollHelperUpdateTaskId);
            this.scrollHelperUpdateTaskId = null;
          }
          this.scrollHelper.reset();
          if (!droptarget) return;
          this.$q.digest(moveGroup(group2, { id: this.project.top_level_card_id }, newPosition));
        }
      }, Object.assign({}, this.options || {}, { disabled: !this.project || !this.editable }));
    }
    $onDestroy() {
      if (this._sortableElementIntervalPromise) {
        this.$interval.cancel(this._sortableElementIntervalPromise);
        this._sortableElementIntervalPromise = null;
      }
      if (this._sortableElementDeferred) {
        this._sortableElementDeferred.reject("sortable-groups-container destroyed before a sortable DOM element has been initialized");
        this._sortableElementDeferred = null;
      }
    }
  }
});

// public/app/apps/cards/common/timeline/components/CommonCardTimelineWrapper.tsx
function CommonCardTimelineWrapper(props2) {
  const _props = mergeProps({
    frontend: {
      onPeriodClick: (item) => {
        props2.cardModal?.open(item.card);
      }
    },
    backend: {
      createPeriod: (payload) => {
        if (payload.isMilestone) {
          payload.start = payload.end;
        }
        const itemStore = payload.parent;
        updateDateAttribute(itemStore.card, cardModelStore.getAttribute(payload.id), payload.start, payload.end).catch(autoCatchAsRequestErrorDialog([400]));
      },
      movePeriods: (payloads) => {
        updateDateAttributes(payloads).catch(autoCatchAsRequestErrorDialog([400]));
      },
      resizePeriod: (start, end, payload) => {
        const itemStore = payload.item;
        updateDateAttribute(itemStore.card, cardModelStore.getAttribute(payload.period.id), start, end).catch(autoCatchAsRequestErrorDialog([400]));
      },
      deletePeriod: (period, card) => {
        updateDateAttribute(card, cardModelStore.getAttribute(period.id), void 0, void 0).catch(autoCatchAsRequestErrorDialog([400]));
      }
    }
  }, props2);
  return createComponent(EventProvider, {
    get children() {
      return createComponent(TimelineViewProvider, {
        get cardModal() {
          return _props.cardModal;
        },
        get matchingCardIds() {
          return _props.matchingCardIdsSignal[0];
        },
        onChange: (changes) => _props.onChange({
          $changes: changes
        }),
        get timelineItemCreateFn() {
          return _props.timelineItemCreateFn;
        },
        get frontend() {
          return _props.frontend;
        },
        get backend() {
          return _props.backend;
        },
        get children() {
          return createComponent(CardCompareFunctionProvider, {
            get children() {
              return createComponent(ManageGroups, {
                get groupBy() {
                  return _props.groupBySignal[0]()[0];
                },
                get children() {
                  return _props.children;
                }
              });
            }
          });
        }
      });
    }
  });
}

// public/app/apps/cards/common/timeline/stores/gantt-timeline-item.ts
var GanttTimelineItemStore = class extends CardTimelineItemStore {
  constructor() {
    super(...arguments);
    this._ganttConfig = useGanttConfig();
    this.defaultModel = useDefaultModel();
  }
  getGanttConfig() {
    if (!this.card) return null;
    return getGanttConfigForModel(this._ganttConfig, this.card.model_id);
  }
  get hasActiveDateField() {
    const config3 = this.getGanttConfig();
    if (!this.card) return true;
    const projectModel = this.defaultModel();
    const models = config3.models[config3.date.name] ?? [];
    const modelIds = models.map((m3) => m3.id);
    return modelIds.includes(projectModel.id) || modelIds.includes(this.card.model_id);
  }
  get hasChildWithActiveDateField() {
    return this.children.some(
      (child) => child.hasActiveDateField || child.hasChildWithActiveDateField
    );
  }
  onInit() {
    super.onInit();
    const availableDateAttrs = useAvailableAttributesOfType("date");
    if (this.card && !this.isRoot) {
      this.dependencyConfig = createMemo(() => {
        const config3 = this.getGanttConfig();
        if (!config3?.relationship?.name) return [];
        const out = [];
        const configs = [
          { name: config3.relationship.name, color: config3.relationship.color }
        ];
        for (const c3 of configs) {
          if (!c3.name) continue;
          const attr = getCardAttribute(this.card, c3.name);
          if (!attr) continue;
          if (!attr.value || attr.value.length === 0) continue;
          for (const dependency of attr.value) {
            out.push({ attr, dependency, color: c3.color });
          }
        }
        return out;
      });
      this.fields = createMemo(() => {
        const config3 = this.getGanttConfig();
        const dateAttrGroupMap = availableDateAttrs();
        return [{ ...config3.date }, ...config3.secondary_dates].map((c3) => {
          if (!dateAttrGroupMap.has(c3.name)) return null;
          const attrGroup = dateAttrGroupMap.get(c3.name);
          const attr = attrGroup.getFirstAvailableAttributes(this.card);
          if (!attr) return null;
          const color = c3.color !== null ? c3.color : cardModelStore.tryGet(this.card.model_id)?.card_color ?? "#fafafa";
          return {
            id: attr.id,
            name: c3.name,
            color,
            attr,
            isMilestone: c3.type === "milestone" /* Milestone */
          };
        }).filter(Boolean);
      });
      setupGanttItemPeriod(this);
    }
  }
};

// public/app/ui/timeline/timeline-utils/timeline-selectables.ts
function setupTimelineSelectable(timelineStore, periodSelectable, relationSelectable) {
  const keyboardState2 = useKeyboard();
  const spaceBarPressed = useSpacebar({ preventDefault: false });
  createEventListener(
    () => (
      // Remove listener if something moving/resizing.
      !timelineStore.itemsMoving && !timelineStore.itemsResizing && !spaceBarPressed() ? timelineStore.viewport : void 0
    ),
    "click",
    () => {
      if (!keyboardState2.Control && !keyboardState2.Shift) {
        if (periodSelectable && periodSelectable.selection.length > 0) {
          periodSelectable.unselectAll();
        }
        if (relationSelectable && relationSelectable.selection.length > 0) {
          relationSelectable.unselectAll();
        }
      }
    }
  );
}

// public/app/apps/cards/common/timeline/components/SidebarItem.tsx
var _tmpl$156 = /* @__PURE__ */ template(`<span class="gantt-sidebar_group-count"><span></span></span>`, 4);
var _tmpl$273 = /* @__PURE__ */ template(`<button class="btn btn-icon gantt-sidebar-go-to-period"><span class="sr-only"></span></button>`, 4);
var _tmpl$350 = /* @__PURE__ */ template(`<div class="timeline-sticky-sidebar"><div class="gantt-sidebar_group-header"><div class="title title-indented"><button class="title-text"><span></span></button></div></div></div>`, 10);
var _tmpl$435 = /* @__PURE__ */ template(`<div class="spacer"></div>`, 2);
function SidebarItem() {
  const timeline = useTimelineStore();
  const itemStore = useTimelineItem();
  const timelineView = useTimelineViewContext();
  const options2 = useAppOptions();
  const toggleIcon = useTimelineHeaderToggleIcon();
  const fontWeight = useTimelineItemFontWeight();
  const children2 = useTimelineItemChildren();
  const indentation = useTimelineItemIndentation();
  const colors = useTimelineItemColor();
  const toggleChildrenVisibility = useTimelineItemToggleChildrenVisibility();
  const openCardModal = (e3) => {
    timelineView.cardModal?.open(itemStore.card);
  };
  const [nextPeriodRef, setNextPeriodRef] = createSignal(null);
  let timeout = null;
  const goToNextPeriod = (event2) => {
    event2.stopPropagation();
    const ref = nextPeriodRef();
    const periods = (itemStore?.periods ?? []).filter((p4) => !!p4.start || !!p4.end);
    const currentRefIndex = periods.findIndex((p4) => p4.elt === ref);
    const nextIndex = (currentRefIndex + 1) % periods.length;
    const nextPeriod = periods[nextIndex];
    if (!nextPeriod) return;
    if (!nextPeriod.elt) return;
    if (nextPeriod.start.getTime() < timeline.period.start.getTime() || nextPeriod.end.getTime() > timeline.period.end.getTime()) {
      const start = nextPeriod.start.getTime() < timeline.period.start.getTime() ? nextPeriod.start : timeline.period.start;
      const end = nextPeriod.end.getTime() > timeline.period.end.getTime() ? nextPeriod.end : timeline.period.end;
      timeline.setState("period", {
        start,
        end
      });
    }
    const newRef = nextPeriod.elt;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      const target = newRef.querySelector(".timeline-period-content") || newRef;
      target?.scrollIntoView({
        behavior: "smooth",
        block: "nearest",
        inline: "center"
      });
      setNextPeriodRef(newRef);
    });
  };
  return (() => {
    const _el$ = _tmpl$350.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.firstChild;
    _el$2.addEventListener("mouseleave", () => itemStore.unhoverise());
    _el$2.addEventListener("mouseenter", () => itemStore.hoverise());
    insert(_el$3, createComponent(Show, {
      get when() {
        return children2().length > 0 && itemStore.hasChildrenMatchingFilter;
      },
      get children() {
        return createComponent(IconButton, {
          "class": "toggle-button",
          get icon() {
            return toggleIcon();
          },
          onClick: toggleChildrenVisibility
        });
      }
    }), _el$4);
    _el$4.$$click = openCardModal;
    insert(_el$5, () => itemStore.card?.title);
    insert(_el$3, createComponent(Show, {
      get when() {
        return children2()?.length > 0;
      },
      get children() {
        const _el$6 = _tmpl$156.cloneNode(true), _el$7 = _el$6.firstChild;
        insert(_el$6, createComponent(Icon, {
          name: "bi-list-check"
        }), _el$7);
        insert(_el$7, createComponent(Show, {
          get when() {
            return timelineView.matchingCardIds()?.length > 0;
          },
          get fallback() {
            return children2()?.length;
          },
          get children() {
            return [createMemo(() => itemStore.matchingFilterChildrenCount), "/", createMemo(() => children2()?.length)];
          }
        }));
        return _el$6;
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      get when() {
        return itemStore.periods?.length > 0;
      },
      get fallback() {
        return _tmpl$435.cloneNode(true);
      },
      get children() {
        const _el$8 = _tmpl$273.cloneNode(true), _el$9 = _el$8.firstChild;
        _el$8.$$click = goToNextPeriod;
        insert(_el$9, () => _4("Go to the next period"));
        insert(_el$8, createComponent(Icon, {
          name: "bi-chevron-right"
        }), null);
        return _el$8;
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = itemStore.stackedRowCount, _v$2 = !!itemStore.hasPeriodSelected, _v$3 = !!itemStore.isHovered, _v$4 = !!(itemStore.card?.finished || itemStore.card?.is_archived), _v$5 = !!(itemStore.card?.finished && (options2.strikeDoneCards || options2.strikeDoneCards === void 0)), _v$6 = fontWeight(), _v$7 = colors.bg(), _v$8 = !!colors.bg() ? colors.text() : "inherit", _v$9 = `${indentation()}px`;
      _v$ !== _p$._v$ && _el$.style.setProperty("--stack-count", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$2.classList.toggle("selected", _p$._v$2 = _v$2);
      _v$3 !== _p$._v$3 && _el$2.classList.toggle("hovered", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$2.classList.toggle("finished", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$2.classList.toggle("struck-title", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$2.style.setProperty("font-weight", _p$._v$6 = _v$6);
      _v$7 !== _p$._v$7 && _el$2.style.setProperty("background-color", _p$._v$7 = _v$7);
      _v$8 !== _p$._v$8 && _el$2.style.setProperty("color", _p$._v$8 = _v$8);
      _v$9 !== _p$._v$9 && _el$3.style.setProperty("--indentation", _p$._v$9 = _v$9);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0,
      _v$6: void 0,
      _v$7: void 0,
      _v$8: void 0,
      _v$9: void 0
    });
    return _el$;
  })();
}
delegateEvents(["click"]);

// public/app/apps/cards/gantt/GanttArrow.tsx
function GanttArrow(props2) {
  const startConfig = getGanttConfig(() => props2.relation.start.card.model_id);
  const endConfig = getGanttConfig(() => props2.relation.end.card.model_id);
  const startElt = () => {
    const mainField = startConfig().date.name;
    return props2.relation.start.periods.find((p4) => p4.name === mainField);
  };
  const endElt = () => {
    const mainField = endConfig().date.name;
    return props2.relation.end.periods.find((p4) => p4.name === mainField);
  };
  return createComponent(Arrow, mergeProps(props2, {
    start: startElt,
    end: endElt
  }));
}

// public/app/apps/cards/gantt/gantt-view.tsx
var _tmpl$157 = /* @__PURE__ */ template(`<div class="timeline-sticky-sidebar-bg-panel"><div></div></div>`, 4);
var _tmpl$274 = /* @__PURE__ */ template(`<header></header>`, 2);
var _tmpl$351 = /* @__PURE__ */ template(`<div class="timeline-view"></div>`, 2);
var _tmpl$436 = /* @__PURE__ */ template(`<button class="menu-item-main-action-button"><span class="menu-item-label"></span></button>`, 4);
var _tmpl$530 = /* @__PURE__ */ template(`<div class="timeline-tools"></div>`, 2);
var _tmpl$624 = /* @__PURE__ */ template(`<div class="board-notice board-notice-warning"></div>`, 2);
var GanttView = () => {
  const groups = useTimelineGroups();
  const timelineStore = useTimelineStore();
  const periodSelectable = usePeriodSelectable();
  const relationSelectable = useRelationSelectable();
  const {
    store: relationContextMenu,
    ContextMenuProvider
  } = createContextMenu();
  const ganttConfig = useGanttConfig();
  const relationShipApi = useRelationshipApi();
  const options2 = useAppOptions();
  setupTimelineSelectable(timelineStore, periodSelectable, relationSelectable);
  const onRemoveRelations = (relations) => {
    relations.forEach((relation) => relationShipApi.remove(relation, buildGanttConfig(ganttConfig, relation.start.card.model_id)));
    relationSelectable.unselect(...relations);
  };
  const [relationMenu, setRelationMenu] = createStore({
    items: []
  });
  createEventListener(() => relationContextMenu.isOpen ? timelineStore.viewport : void 0, "scroll", (e3) => {
    relationContextMenu.isOpen = false;
  });
  const onRelationContextMenu = (e3, relation) => {
    e3.preventDefault();
    if (!ganttConfig.configurations[0].relationship.editable) return;
    relationSelectable?.select(relation);
    relationContextMenu.x = e3.clientX;
    relationContextMenu.y = e3.clientY;
    relationContextMenu.isOpen = true;
    setRelationMenu(produce((m3) => {
      m3.items = [{
        name: _4("Delete"),
        // TODO: improve label with multiple selected relations
        action: () => {
          onRemoveRelations(relationSelectable.selection);
          relationContextMenu.isOpen = false;
        }
      }];
    }));
  };
  return (() => {
    const _el$ = _tmpl$351.cloneNode(true);
    insert(_el$, createComponent(InvalidGanttConfig, {}), null);
    insert(_el$, createComponent(Timeline, {
      get displayDensity() {
        return options2?.displayDensity;
      },
      get children() {
        return createComponent(FreeLineProvider, {
          get children() {
            return [createComponent(CriticalPathProvider, {
              get children() {
                return [createComponent(SidebarHeader, {}), _tmpl$157.cloneNode(true), createComponent(For, {
                  get each() {
                    return groups();
                  },
                  children: (root3) => createComponent(NodeItemProvider, {
                    store: root3,
                    get children() {
                      return createComponent(RootNodeTimelineItem, {
                        rowOffset: 1,
                        children: (rowOffset) => createComponent(NodeTimelineItem, {
                          rowOffset
                        })
                      });
                    }
                  })
                }), createComponent(Show, {
                  get when() {
                    return relationContextMenu.isOpen;
                  },
                  get children() {
                    return createComponent(ContextMenuProvider, {
                      get children() {
                        return createComponent(ContextMenu, {
                          onClickOutside: () => relationContextMenu.isOpen = false,
                          get children() {
                            return [(() => {
                              const _el$3 = _tmpl$274.cloneNode(true);
                              insert(_el$3, () => _4("Relationship actions"));
                              return _el$3;
                            })(), createComponent(Menu, {
                              get each() {
                                return relationMenu.items;
                              },
                              "class": "timeline-context-menu",
                              children: (item) => (() => {
                                const _el$4 = _tmpl$436.cloneNode(true), _el$5 = _el$4.firstChild;
                                _el$4.$$click = () => item.action();
                                insert(_el$5, () => item.name);
                                return _el$4;
                              })()
                            })];
                          }
                        });
                      }
                    });
                  }
                }), createComponent(TimelineTools, {})];
              }
            }), createComponent(RelationShipLayerWrapper, {
              onRemoveRelations,
              onRelationContextMenu,
              relationComponent: GanttArrow
            })];
          }
        });
      }
    }), null);
    return _el$;
  })();
};
function TimelineTools() {
  const periodSelectable = usePeriodSelectable();
  return (() => {
    const _el$6 = _tmpl$530.cloneNode(true);
    insert(_el$6, createComponent(Presence, {
      get children() {
        return createComponent(Show, {
          get when() {
            return periodSelectable.selection.length > 0;
          },
          get children() {
            return createComponent(Motion.p, {
              animate: {
                opacity: [0, 1],
                y: [10, 0]
              },
              exit: {
                opacity: [1, 0],
                y: [0, 10]
              },
              transition: {
                duration: 0.2
              },
              "class": "selected-period-count",
              get children() {
                return _4("{count} period(s) selected", {
                  count: periodSelectable.selection.length
                });
              }
            });
          }
        });
      }
    }));
    return _el$6;
  })();
}
function NodeTimelineItem(props2) {
  let ref;
  const virtualContainerApi = useVirtualContainer();
  const timelineStore = useTimelineStore();
  const viewContext = useTimelineViewContext();
  const itemStore = useTimelineItem();
  const options2 = useAppOptions();
  if (!!itemStore.card) {
    setupTimelineItemCardRelation();
  }
  const nbChildren = createMemo(() => itemStore.children.length);
  createEffect(() => {
    const periods = itemStore.periods;
    periods.forEach((p4) => {
      p4.start;
      p4.end;
    });
    itemStore.computeStackLevels();
  });
  const stackedRowCount = createMemo(() => itemStore.stackedRowCount);
  const onNewItem = (e3) => {
    const clickedDate = getNewItemDate(e3, timelineStore);
    console.log(moment_default(clickedDate).format("DD/MM/YYYY"));
  };
  const onPeriodCreated = (payload) => {
    viewContext.backend.createPeriod(payload);
  };
  onMount(() => {
    const obs = new ResizeObserver((entries2) => {
      if (itemStore.parent.isRoot && entries2[0]) {
        const height = entries2[0].contentRect.height;
        virtualContainerApi?.itemHeightSetter?.(height);
      }
    });
    if (itemStore.parent.isRoot) {
      obs.observe(ref);
    }
    onCleanup(() => obs.disconnect());
  });
  onCleanup(() => {
    itemStore.unhoverise();
  });
  const visibleChildren = createMemo(() => itemStore.children.filter((child) => child.matchingFilter || child.hasChildrenMatchingFilter), [], {
    equals: (prev, next2) => {
      if (prev.length !== next2.length) return false;
      for (let i3 = 0; i3 < prev.length; i3++) {
        if (prev[i3].id !== next2[i3].id) return false;
      }
      return true;
    }
  });
  return createComponent(TimelineRow, {
    ref: (elt) => ref = elt,
    "class": "group",
    get ["data-title"]() {
      return itemStore.title ?? itemStore.card?.title ?? itemStore.id;
    },
    get classList() {
      return {
        hovered: itemStore.isHovered
      };
    },
    get rowOffset() {
      return props2.rowOffset ?? 0;
    },
    get displayAllItems() {
      return options2.displayAllItems;
    },
    get children() {
      return [createComponent(SidebarItem, {}), createComponent(TimelineRow, {
        row: 0,
        "class": "timeline-card-row",
        get classList() {
          return {
            moving: itemStore.moving,
            resizing: itemStore.resizing,
            group: nbChildren() > 0
          };
        },
        get style() {
          return {
            "--stack-count": stackedRowCount()
          };
        },
        onMouseEnter: () => itemStore.hoverise(),
        onMouseLeave: () => itemStore.unhoverise(),
        onDblClick: onNewItem,
        get displayAllItems() {
          return options2.displayAllItems;
        },
        get children() {
          return [createComponent(CardPeriodCreator, {
            onPeriodCreated
          }), createComponent(Show, {
            get when() {
              return nbChildren() === 0;
            },
            get fallback() {
              return createComponent(NodeTimelinePeriods, {
                get periods() {
                  return itemStore.periods;
                }
              });
            },
            get children() {
              return createComponent(For, {
                get each() {
                  return itemStore.periods;
                },
                children: (period) => createComponent(NodePeriodProvider, {
                  store: period,
                  get children() {
                    return createComponent(NodeTimelinePeriod, {});
                  }
                })
              });
            }
          })];
        }
      }), createComponent(Show, {
        get when() {
          return itemStore.visibleChild && itemStore.hasChildrenMatchingFilter;
        },
        get children() {
          return createComponent(For, {
            get each() {
              return visibleChildren();
            },
            children: (childStore, index2) => createComponent(NodeItemProvider, {
              store: childStore,
              get children() {
                return createComponent(NodeTimelineItem, {
                  get rowOffset() {
                    return index2() + 1;
                  }
                });
              }
            })
          });
        }
      })];
    }
  });
}
function InvalidGanttConfig() {
  const availableDateFields = useAvailableAttributesOfType("date");
  const availableRelationFields = useAvailableAttributesOfType("relationships");
  const config3 = useGanttConfig();
  const isConfigValid = createMemo(() => {
    if (!config3 || !config3.configurations.length) return false;
    const dateNames = [...availableDateFields().keys()];
    const relationNames = [...availableRelationFields().keys()];
    return config3.configurations.every((c3) => {
      if (!dateNames.includes(c3.date.name)) return false;
      if (c3.relationship && !relationNames.includes(c3.relationship.name)) return false;
      for (const sd of c3.secondary_dates) {
        if (!dateNames.includes(sd.name)) return false;
      }
      return true;
    });
  });
  return createComponent(Show, {
    get when() {
      return !isConfigValid();
    },
    get children() {
      const _el$7 = _tmpl$624.cloneNode(true);
      insert(_el$7, () => _4("The Gantt configuration contains invalid field names and might not work properly. Please update it or ask an administrator to do so."));
      return _el$7;
    }
  });
}
delegateEvents(["click"]);

// public/app/apps/cards/gantt/GanttViewWrapper.tsx
var _tmpl$158 = /* @__PURE__ */ template(`<div class="gantt-wizard-wrapper"></div>`, 2);
var _tmpl$275 = /* @__PURE__ */ template(`<p></p>`, 2);
var _tmpl$352 = /* @__PURE__ */ template(`<p><b></b></p>`, 4);
var _tmpl$437 = /* @__PURE__ */ template(`<div class="gantt-migration-modal-wrapper"></div>`, 2);
var _tmpl$531 = /* @__PURE__ */ template(`<video autoplay loop muted><source type="video/mp4"><source type="video/webm"></video>`, 4);
function GanttViewWrapper(props2) {
  const project = useProject();
  const cardStore2 = useCardStore();
  const options2 = useAppOptions();
  const Wizard = () => (() => {
    const _el$ = _tmpl$158.cloneNode(true);
    insert(_el$, createComponent(Show, {
      get when() {
        return !props2.useOldAppearanceOptions;
      },
      get children() {
        return createComponent(GanttVideoTutorial, {});
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return canManageSettings(project());
      },
      get fallback() {
        return createComponent(Unconfigured, {});
      },
      get children() {
        return createComponent(Button, {
          get label() {
            return _4("Configure Gantt");
          },
          size: "lg",
          onClick: () => openGanttWizardModal(project, () => cardStore2)
        });
      }
    }), null);
    return _el$;
  })();
  const showWizard = () => {
    const prjt = project();
    return !prjt.gantt_config || !prjt.gantt_config?.configurations;
  };
  onMount(() => {
    props2.useOldAppearanceOptions && showWizard() && openModal(() => createComponent(ProjectProvider, {
      get project() {
        return project();
      },
      get children() {
        return createComponent(CardStoreProvider, {
          store: cardStore2,
          get children() {
            return createComponent(AppOptionsProvider, {
              store: options2,
              get children() {
                return createComponent(MigrationToGanttConfigModal, {});
              }
            });
          }
        });
      }
    }), {
      windowClass: "gantt-migration-modal"
    });
  });
  return createComponent(Show, {
    get when() {
      return !showWizard();
    },
    get fallback() {
      return createComponent(Wizard, {});
    },
    get children() {
      return createComponent(GanttConfigProvider, {
        get children() {
          return createComponent(RelationShipProvider, {
            get children() {
              return createComponent(CommonCardTimelineWrapper, mergeProps(props2, {
                get timelineItemCreateFn() {
                  return GanttTimelineItemStore.create.bind(GanttTimelineItemStore);
                },
                get children() {
                  return createComponent(GanttView, {});
                }
              }));
            }
          });
        }
      });
    }
  });
}
function Unconfigured() {
  return (() => {
    const _el$2 = _tmpl$275.cloneNode(true);
    insert(_el$2, () => _4("You are currently not allowed to configure the Gantt view. This action can only be performed by an administrator."));
    return _el$2;
  })();
}
function MigrationToGanttConfigModal() {
  const project = useProject();
  const cardStore2 = useCardStore();
  const modal = useModal();
  return (() => {
    const _el$3 = _tmpl$437.cloneNode(true);
    insert(_el$3, createComponent(ModalHeader, {
      get title() {
        return _4("Changes to the Gantt configuration");
      }
    }), null);
    insert(_el$3, createComponent(ModalBody, {
      get children() {
        return [(() => {
          const _el$4 = _tmpl$352.cloneNode(true), _el$5 = _el$4.firstChild;
          insert(_el$5, () => _4(`Over the last few months, based on your feedback, we have been working
          on a new version of our Gantt view. Today, we are releasing our work,
          introducing a new way to configure your view.`));
          return _el$4;
        })(), (() => {
          const _el$6 = _tmpl$275.cloneNode(true);
          insert(_el$6, () => _4(`In a simple scenario, you can just select one date field and one
          relationship field, and you're good to go. In more complex
          scenarios, you can choose additional date fields to display per card,
          or override this configuration for specific card types.`));
          return _el$6;
        })(), (() => {
          const _el$7 = _tmpl$275.cloneNode(true);
          insert(_el$7, () => _4(`We will assist you in transferring your current Gantt views. Let's dive into it!`));
          return _el$7;
        })(), createComponent(GanttVideoTutorial, {})];
      }
    }), null);
    insert(_el$3, createComponent(ModalFooter, {
      get children() {
        return createComponent(Button, {
          get label() {
            return _4("Configure Gantt");
          },
          onClick: () => {
            modal.close();
            openGanttWizardModal(project, () => cardStore2);
          }
        });
      }
    }), null);
    return _el$3;
  })();
}
function GanttVideoTutorial() {
  return (() => {
    const _el$8 = _tmpl$531.cloneNode(true), _el$9 = _el$8.firstChild, _el$10 = _el$9.nextSibling;
    createRenderEffect((_p$) => {
      const _v$ = prependBaseUrl("/static/assets/tour/videos/presentation-gantt.mp4"), _v$2 = prependBaseUrl("/static/assets/tour/videos/presentation-gantt.webm");
      _v$ !== _p$._v$ && setAttribute(_el$9, "src", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && setAttribute(_el$10, "src", _p$._v$2 = _v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$8;
  })();
}

// public/app/apps/cards/gantt/ng-components/gantt.jsx
angular_default.module("kantree").directive("cardsAppGantt", [function() {
  return {
    //---act as component
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    //---
    bindToController: {
      store: "<",
      board: "<?",
      filter: "<?",
      filterScopes: "<?",
      groupBy: "<?",
      options: "<?",
      matchingCardIds: "<?",
      onChange: "&"
    },
    templateUrl: "/static/app/apps/cards/gantt/ng-components/templates/gantt.html",
    controller: class extends angularClassMixin(AngularClass, CardsAppDateMixin) {
      static get $inject() {
        return (super.$inject || []).concat(["$scope", "$element", "$q", "$timeout", "cardModal"]);
      }
      $onInit() {
        injectI18nHelpersIntoScope(this.$scope);
        const useOldAppearanceOptions = !!this.options?.dateFields?.length;
        this.optionStore = TimelineAppOptions.create(this.options ?? {});
        this.groupBySignal = createSignal(this.groupBy);
        this.matchingCardIdsSignal = createSignal(this.matchingCardIds);
        const _self$ = this;
        this.GanttView = () => createComponent(KeyboardProvider, {
          get children() {
            return createComponent(BoardProvider, {
              get board() {
                return _self$.board;
              },
              get children() {
                return createComponent(ProjectProvider, {
                  get board() {
                    return _self$.board;
                  },
                  get children() {
                    return createComponent(CardStoreProvider, {
                      get store() {
                        return _self$.store;
                      },
                      get children() {
                        return createComponent(ScopedModelStoreProvider, {
                          get children() {
                            return createComponent(ScopedGroupTypeStoreProvider, {
                              get children() {
                                return createComponent(AppOptionsProvider, {
                                  get store() {
                                    return _self$.optionStore;
                                  },
                                  get children() {
                                    return createComponent(AvailableAttributesProvider, {
                                      get children() {
                                        return createComponent(GanttViewWrapper, {
                                          get cardModal() {
                                            return _self$.$cardModal;
                                          },
                                          get onChange() {
                                            return _self$.onChange;
                                          },
                                          get groupBySignal() {
                                            return _self$.groupBySignal;
                                          },
                                          get matchingCardIdsSignal() {
                                            return _self$.matchingCardIdsSignal;
                                          },
                                          useOldAppearanceOptions
                                        });
                                      }
                                    });
                                  }
                                });
                              }
                            });
                          }
                        });
                      }
                    });
                  }
                });
              }
            });
          }
        });
        this.$scope.$on("displayAllGanttItems", function() {
          this.optionStore.toggleDisplayAllItems(true);
        });
        this.$scope.$on("hideAllGanttItems", function() {
          this.optionStore.toggleDisplayAllItems(false);
        });
        this.$scope.$on("maximizeAllCards", function() {
          const event2 = new CustomEvent("maximizeAllCards");
          window.dispatchEvent(event2);
        });
        this.$scope.$on("minimizeAllCards", function() {
          const event2 = new CustomEvent("minimizeAllCards");
          window.dispatchEvent(event2);
        });
      }
      $onChanges(changes) {
        if (changes.options && !changes.options.isFirstChange()) {
          this.optionStore.updateOptions(changes.options.currentValue);
        }
        if (changes.groupBy && !changes.groupBy.isFirstChange()) {
          this.groupBySignal[1](changes.groupBy.currentValue);
        }
        if (changes.matchingCardIds && !changes.matchingCardIds.isFirstChange()) {
          this.matchingCardIdsSignal[1](changes.matchingCardIds.currentValue);
        }
      }
    }
  };
}]);

// public/app/apps/cards/gantt/ng-components/nav.js
angular_default.module("kantree").component("cardsAppNavGantt", {
  templateUrl: "/static/app/apps/cards/gantt/ng-components/templates/nav.html",
  bindings: {
    mode: "<?",
    board: "<?",
    store: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    groupByChoices: "<",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&"
  }
});

// public/app/apps/cards/kanban/ng-components/kanban-column.js
angular_default.module("kantree").directive("cardsAppKanbanColumn", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        sortChoices: "<?",
        visibleAttrNames: "<?",
        onChange: "&?",
        selector: "<?",
        openCreatorOnInit: "<?",
        showUngroupedTooltip: "<?"
      },
      templateUrl: "/static/app/apps/cards/kanban/ng-components/templates/kanban-column.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin, CardsAppCardCreatorMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.modeOptionsKeyPrefix = "groups_";
          this.withStats = true;
          this.withProgressBar = true;
          this.withCardSelector = true;
          this.groupColorTheme = "/static/app/apps/cards/kanban/ng-components/templates/kanban-group-color.css.html";
          this.handleCards = true;
          this.sortableOptions = {
            duplication: () => this.groupBy && !this.groupBy[0].oneGroupPerCard,
            _scrollHelperOptions: {
              scrollable: ".ui-sortable-cards-items-container",
              threshold: {
                default: { top: 50, bottom: 50 },
                xs: { top: 30, bottom: 30 }
              }
            },
            _containersScrollHelperOptions: {
              scrollable: jquery_default(this.$element).parents(".ui-sortable-groups"),
              threshold: {
                default: { right: 60, left: 60 },
                xs: { right: 30, left: 30 }
              }
            },
            beforeStart: () => {
              this.$scope.$emit("startSortingCards");
            }
          };
          this.initGroupMixin();
          this.initCardCreatorMixin();
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
          this.changeCardCreatorMixin(changes);
        }
        onTitleEditStart() {
          this.editingTitle = true;
          if (this.selector && this.selectorPage) {
            const selectedPage = this.selector.getCurrentPage();
            if (!selector_default.prototype.matchPage(selectedPage, this.selectorPage)) {
              this.selector.selectPage(this.selectorPage, "header");
            }
          }
        }
        onTitleEditEnd(event2) {
          if (this.selector) {
            if (event2.keyCode === 9) {
              this.selector.nextPage();
            } else {
              const currentPage = this.selector.getCurrentPage();
              this.selector.unselectPage();
              if (currentPage) {
                this.selector.selectFirstOfPage(currentPage);
              }
            }
          }
          this.editingTitle = false;
        }
        $onDestroy() {
          this.destroyGroupMixin();
          this.destroyCardCreatorMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/kanban/ng-components/kanban-simple.js
angular_default.module("kantree").directive("cardsAppKanbanSimple", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/kanban/ng-components/templates/kanban-simple.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupableMixin, CardsAppAttrVisibilityMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$element"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.specialFields = ["__ref__", "__comments__", "__children__", "__cover__"];
          this.withCardSelector = true;
          this.sortableOptions = {
            helper: function(event2, currentItem) {
              var h3 = currentItem.clone();
              var classes = "cards-app-kanban-column-sortable-helper ";
              h3.addClass(classes);
              return h3;
            },
            handle: ".group-title",
            axis: "x",
            _scrollHelperOptions: {
              scrollable: ".ui-sortable-groups",
              threshold: {
                default: { right: 60, left: 60 },
                xs: { right: 30, left: 30 }
              },
              tolerance: "cursor"
            },
            on: {
              start: (event2, ui) => {
                ui.placeholder.width(ui.helper.find(".inner").outerWidth());
              }
            }
          };
          this.initGroupableMixin();
          this.initAttrVisibilityMixin();
          this.$scope.$on("maximizeAllCards", () => this.$scope.$broadcast("showAllChildren"));
          this.$scope.$on("minimizeAllCards", () => this.$scope.$broadcast("hideAllChildren"));
        }
        $onChanges(changes) {
          this.changeGroupableMixin(changes);
          this.changeAttrVisibilityMixin(changes);
        }
        $postLink() {
          const $viewportInner = this.$element.find("> sortable-groups-container > .ui-sortable-groups");
          this.scrollToRight = debounce2((event2) => {
            $viewportInner.scrollLeft($viewportInner[0].scrollWidth);
            if (event2 && event2.keyCode === 13) {
              this.selector.selectPage(this.selector.pages.length - 1, "bottom");
              this.$scope.$applyAsync();
            }
          }, 10);
          activateViewScroll(
            this.$element,
            "> sortable-groups-container > .ui-sortable-groups",
            `.kanban-sortable-columns,
            cards-app-kanban-column > sortable-cards-container > .ui-sortable-cards
            `,
            () => this.groupBy && !this.groupBy[1].isNothing()
          );
        }
        isColumnStretchable(group2) {
          if (!group2 || !group2.title) {
            return true;
          }
          return !(this.options || {})["groups_" + group2.title + "_collapsed"];
        }
        $onDestroy() {
          this.destroyGroupableMixin();
          this.destroyAttrVisibilityMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/kanban/matrix-utils.js
function buildMatrix(columnGroups, laneGroups, cardStore2, groupBy2, includeArchived, columnSortBys, cardCmpOptions) {
  var matrix = createMatrix(laneGroups.length + 1, columnGroups.length + 1);
  var lanesIndex = createIndex(groupBy2[1], laneGroups);
  var columnsIndex = createIndex(groupBy2[0], columnGroups);
  var cardQueryFilter = {};
  if (groupBy2.some((gby) => gby.isAttribute())) {
    cardQueryFilter = {
      model_id: function(model_id) {
        return groupBy2.every(function(groupBy3) {
          if (!groupBy3.isAttribute()) {
            return true;
          } else {
            if (groupBy3.getAttribute().model_is_base) {
              return true;
            } else {
              for (var i3 = 0; i3 < groupBy3.opts.inModels.length; i3++) {
                if (groupBy3.opts.inModels[i3].id === model_id) {
                  return true;
                }
              }
              return false;
            }
          }
        });
      }
    };
  }
  var cards = cardStore2.query(cardQueryFilter);
  cards.forEach(function(card) {
    var cardLaneIndexes = getCardIndex(card, groupBy2[1], lanesIndex, includeArchived);
    var cardColumnIndexes = getCardIndex(card, groupBy2[0], columnsIndex, includeArchived);
    cardLaneIndexes.forEach(function(cardLaneIndex) {
      cardColumnIndexes.forEach(function(cardColumnIndex) {
        try {
          insertCard(card, matrix[cardLaneIndex][cardColumnIndex], columnSortBys[cardColumnIndex], cardCmpOptions);
        } catch (e3) {
          console.log(e3);
        }
      });
    });
  });
  return matrix;
}
function createMatrix(n4, m3) {
  var matrix = [];
  for (var i3 = 0; i3 < n4; i3++) {
    matrix[i3] = [];
    for (var j = 0; j < m3; j++) {
      matrix[i3][j] = [];
    }
  }
  return matrix;
}
function createIndex(groupBy2, groups) {
  const index2 = {
    "ungrouped": 0
  };
  let toLowerCase = false;
  let indexPropName = "id";
  if (groupBy2.isAttribute() && groupBy2.getAttribute().type !== "group_type") {
    indexPropName = "attribute_value";
  }
  if (groupBy2.isName()) {
    indexPropName = "title";
    toLowerCase = true;
  }
  if (groupBy2.isProjects()) {
    indexPropName = "project_id";
  }
  if (groupBy2.isOrgs()) {
    indexPropName = "org_id";
  }
  if (groupBy2.isTeams()) {
    indexPropName = "team_id";
  }
  groups.forEach((group2, idx) => {
    index2[toLowerCase ? group2[indexPropName].toLowerCase() : group2[indexPropName]] = idx + 1;
  });
  return index2;
}
function getCardIndex(card, groupBy2, index2, includeArchived) {
  if (groupBy2.isNothing()) return [0];
  let indexes = [];
  if (groupBy2.isProjects()) {
    if (index2[card.project_id] !== void 0) {
      return [index2[card.project_id]];
    }
    return [0];
  }
  if (groupBy2.isOrgs()) {
    const org2 = groupBy2.getOrgForCard(card);
    if (org2 && index2[org2.id] !== void 0) {
      return [index2[org2.id]];
    }
    return [0];
  }
  if (groupBy2.isTeams()) {
    const team = groupBy2.getTeamForCard(card);
    if (team && index2[team.id] !== void 0) {
      return [index2[team.id]];
    }
    return [0];
  }
  let indexableGroups = [];
  if (groupBy2.isGroupType() || groupBy2.isAttribute() && groupBy2.getAttribute().type === "group_type") {
    indexableGroups = (card.groups || []).reduce((accu, cardGroup) => {
      const group2 = groupBy2.getGroupStore().tryGet(cardGroup.id);
      if (!group2) return accu;
      if (group2.is_archived && !includeArchived) return accu;
      return accu.concat([group2]);
    }, []);
    const gt = groupBy2.getGroupType(true);
    if (gt) {
      indexableGroups = indexableGroups.filter((group2) => group2.type_id === gt.id);
    } else {
      indexableGroups = [];
    }
  } else if (groupBy2.isName()) {
    indexableGroups = card.groups || [];
  }
  indexes.push.apply(indexes, (groupBy2.isName() ? indexableGroups.map((group2) => index2[group2.title.toLowerCase()]) : indexableGroups.map((group2) => index2[group2.id])).filter((value2, index3, self2) => self2.indexOf(value2) === index3));
  let indexableAttributes = card.attributes || [];
  if (groupBy2.isGroupType() || groupBy2.isAttribute() && groupBy2.getAttribute().type === "group_type") {
    indexableAttributes = [];
  } else if (groupBy2.isAttribute()) {
    indexableAttributes = indexableAttributes.filter((attribute2) => attribute2.id === groupBy2.getAttribute().id);
  } else if (groupBy2.isName()) {
    indexableAttributes = indexableAttributes.filter((attribute2) => attribute2.name.localeCompare(groupBy2.getLabel(), { sensitivity: "accent" }) === 0);
  }
  let attributeIndexes = indexableAttributes.reduce(function(accu, attribute2) {
    if (Array.isArray(attribute2.value)) {
      attribute2.value.forEach(function(val) {
        if (groupBy2.isName() && attribute2.type === "members") {
          accu = accu.concat(index2[(val.display_name || val.username).toLowerCase()]);
        } else if (Array.isArray(val)) {
          accu = accu.concat(index2[val[0]]);
        } else if (val.id) {
          accu = accu.concat(index2[val.id]);
        } else {
          accu = accu.concat(index2[val]);
        }
      });
      return accu;
    } else {
      if (groupBy2.isName() && attribute2.type === "bool") {
        if (attribute2.value === true) {
          return accu.concat(index2[_4("Yes").toLowerCase()]);
        } else {
          return accu.concat(index2[_4("No").toLowerCase()]);
        }
      }
      if (groupBy2.isName()) {
        return accu.concat(index2[(attribute2.value || "").toLowerCase()]);
      }
      return accu.concat(index2[attribute2.value]);
    }
  }, []);
  if (groupBy2.isAttribute() && groupBy2.getAttribute().type !== "group_type" && !attributeIndexes.length) {
    const matchUngroupedAttr = groupBy2.getGroupStore().query({ match_ungrouped: true })?.[0];
    if (matchUngroupedAttr) {
      attributeIndexes = [index2[matchUngroupedAttr.attribute_value]];
    }
  }
  indexes = indexes.concat(attributeIndexes).filter((value2, index3, self2) => self2.indexOf(value2) === index3).filter((value2) => typeof value2 !== "undefined");
  return indexes.length ? indexes : [0];
}
function getCardPosition(array, searchElement, cmp4) {
  if (!array.length) {
    return 0;
  }
  var minIndex = 0;
  var maxIndex = array.length - 1;
  var currentIndex;
  var currentElement;
  var cmpSign;
  while (minIndex <= maxIndex) {
    currentIndex = (minIndex + maxIndex) / 2 | 0;
    currentElement = array[currentIndex];
    cmpSign = cmp4(currentElement, searchElement);
    if (cmpSign < 0) {
      minIndex = currentIndex + 1;
    } else if (cmpSign > 0) {
      maxIndex = currentIndex - 1;
    } else {
      return currentIndex + 1;
    }
  }
  return cmpSign < 0 ? currentIndex + 1 : currentIndex;
}
function insertCard(card, cardlist, sortBy3, options2) {
  var cmp4 = getCardCompareFunc(sortBy3, options2);
  var idx = getCardPosition(cardlist, card, cmp4);
  cardlist.splice(idx, 0, card);
}

// public/app/apps/cards/kanban/ng-components/kanban-swimlanes.js
angular_default.module("kantree").directive("cardsAppKanbanSwimlanes", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/kanban/ng-components/templates/kanban-swimlanes.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppAttrVisibilityMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$timeout", "$element", "$q"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.specialFields = ["__ref__", "__comments__", "__children__", "__cover__"];
          this.firstLaneDisplay = false;
          this.columnGroups = [];
          this.laneGroups = [];
          this.lanesVisibility = {};
          this.columnsVisibility = {};
          this.shouldRenderFilteredCards = !this.filtered;
          this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          this.initAttrVisibilityMixin();
          this.refreshCardMatrixDebounced = debounce2(() => {
            this.$scope.$applyAsync(() => {
              this.refreshCardMatrix();
            });
          }, 64);
          this.sortableLanesOptions = {
            handle: ".group-title",
            axis: "y",
            _scrollHelperOptions: {
              scrollable: this.$element[0],
              threshold: {
                default: { top: 60, bottom: 60 },
                xs: { top: 30, bottom: 30 }
              },
              tolerance: "cursor"
            },
            on: {
              start: (event2, ui) => {
                ui.helper.css("left", ui.originalPosition.left);
              }
            }
          };
          this.sortableColumnsOptions = {
            handle: ".group-title",
            axis: "x",
            _scrollHelperOptions: {
              scrollable: this.$element[0],
              threshold: {
                default: { right: 60, left: 60 },
                xs: { right: 30, left: 30 }
              },
              tolerance: "cursor"
            },
            on: {
              start: (event2, ui) => {
                ui.helper.css("top", ui.originalPosition.top);
              }
            }
          };
          this.isFilteredOnFirstGroupBy = isProjectFilteredOnGroupBy((this.groupBy || [])[0], this.project, this.filter);
          this.isFilteredOnSecondGroupBy = isProjectFilteredOnGroupBy((this.groupBy || [])[1], this.project, this.filter);
          this.onGroupByChanged();
          this.refreshUngroupedVisibility("column");
          this.refreshUngroupedVisibility("lane");
          this.$scope.$on("connectivityChanged", () => {
            this.updateBoardSortable();
            this.refreshLanesAndColumnsVisibility();
            this.refreshCardMatrixDebounced();
          });
          this.$scope.$on("startSortingCards", () => {
            this.$scope.$broadcast("closeCardCreator");
          });
          this.$scope.$on("shouldRenderFilteredCards", (event2, newVal) => {
            this.shouldRenderFilteredCards = newVal;
            this.refreshStoreListener();
          });
        }
        $onChanges(changes) {
          this.changeAttrVisibilityMixin(changes);
          const boardChanged = changes.board && !changes.board.isFirstChange();
          const projectChanged = boardChanged && projectStore.tryGetForCard(this.board)?.id !== this.project?.id;
          const storeChanged = changes.store && !changes.store.isFirstChange();
          const filterChanged = changes.filter && !changes.filter.isFirstChange();
          const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
          const firstGroupByChanged = groupByChanged && !equals2((this.groupBy || [])[0], (changes.groupBy.previousValue || [])[0]);
          const secondGroupByChanged = groupByChanged && !equals2((this.groupBy || [])[1], (changes.groupBy.previousValue || [])[1]);
          const optionsChanged = changes.options && !changes.options.isFirstChange();
          const optionChanged = (optionLabel) => optionsChanged && !equals((this.options || {})[optionLabel], (changes.options.previousValue || {})[optionLabel]);
          const matchingCardIdsChanged = changes.matchingCardIds && !changes.matchingCardIds.isFirstChange();
          if (boardChanged) {
            this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          }
          ;
          if (firstGroupByChanged || secondGroupByChanged || storeChanged) {
            this.onGroupByChanged();
          } else {
            if (storeChanged) {
              this.refreshStoreListener();
            }
            if (optionChanged("showUngroupedCards")) {
              this.refreshUngroupedVisibility("column");
              this.refreshUngroupedVisibility("lane");
            }
          }
          if (optionsChanged) {
            const sortByChanged = [null].concat(this.columnGroups).some((group2) => {
              const newVal = getGroupSortBy(this.options, group2 || { title: this.columnUngroupedLabel }, true);
              const oldVal = getGroupSortBy(changes.options.previousValue, group2 || { title: this.columnUngroupedLabel }, true);
              return newVal.value !== oldVal.value || newVal.reverse !== oldVal.reverse;
            });
            if (sortByChanged) {
              this.refreshCardMatrixDebounced();
            }
          }
          if (optionChanged("hideEmptyGroups")) {
            this.refreshLanesAndColumnsVisibility();
          }
          if (matchingCardIdsChanged) {
            if (!this.shouldRenderFilteredCards) {
              this.refreshStoreListener();
            }
            this.refreshLanesAndColumnsVisibility();
          }
          if (firstGroupByChanged || projectChanged || filterChanged) {
            this.isFilteredOnFirstGroupBy = isProjectFilteredOnGroupBy((this.groupBy || [])[0], this.project, this.filter);
          }
          if (secondGroupByChanged || projectChanged || filterChanged) {
            this.isFilteredOnSecondGroupBy = isProjectFilteredOnGroupBy((this.groupBy || [])[1], this.project, this.filter);
          }
        }
        isLocked() {
          return isScreensizeXS() || !isConnected();
        }
        isColumnStretchable(group2) {
          if (!group2 || !group2.title) {
            return true;
          }
          return !(this.options || {})["groups_" + group2.title + "_collapsed"];
        }
        onGroupByChanged() {
          if (this.deregisterGroupByListeners) this.deregisterGroupByListeners();
          this.updateBoardSortable();
          this.deregisterGroupByListeners = offMany([
            this.setupColumnUngroupedStore(),
            this.setupColumnGroups(),
            this.setupLaneGroups(),
            this.setupLaneUngroupedStore()
          ]);
          this.refreshStoreListener();
        }
        setupColumnGroups() {
          this.columnGroups = [];
          if (!this.groupBy || !this.groupBy[0]) return;
          const store2 = this.groupBy[0].getGroupStore();
          this.columnGroups = store2.query({}, { sortBy: "position" });
          this.refreshCardMatrixDebounced();
          return store2.subscribe(() => {
            this.columnGroups = store2.query({}, { sortBy: "position" });
            this.refreshCardMatrixDebounced();
          });
        }
        setupColumnUngroupedStore() {
          const groupBy2 = this.groupBy[0];
          if (!this.groupBy || !this.groupBy[0]) return;
          this.columnUngroupedStore = groupBy2.ungroupedCardsStore;
          this.columnUngroupedLabel = groupBy2.isNothing() ? _4("(ungrouped)") : _4("(no {group_by})", { group_by: groupBy2.getLabel().toLowerCase() });
          this.refreshUngroupedVisibility("column");
          return this.columnUngroupedStore.subscribe(() => {
            const oldColumnUngroupedVisible = this.columnUngroupedVisible;
            this.refreshUngroupedVisibility("column");
            if (oldColumnUngroupedVisible !== this.columnUngroupedVisible) {
              this.$scope.$applyAsync();
            }
          });
        }
        setupLaneGroups() {
          this.laneGroups = [];
          if (!this.groupBy || !this.groupBy[1]) return;
          this.firstLaneDisplay = true;
          this.updateLaneGroups();
          return this.groupBy[1].groupStore.subscribe(() => {
            this.updateLaneGroups();
            this.refreshCardMatrixDebounced();
          });
        }
        updateLaneGroups() {
          const qResults = this.groupBy[1].groupStore.query({}, { sortBy: "position" });
          const laneGroups = Array.from(qResults);
          this.allLaneGroups = qResults;
          if (this.addingLaneGroupTimer) {
            this.$timeout.cancel(this.addingLaneGroupTimer);
            this.addingLaneGroupTimer = null;
          }
          if (this.firstLaneDisplay) {
            this.laneGroups = [];
            this.addLaneGroups(laneGroups);
          } else {
            this.laneGroups = laneGroups;
            this.refreshAfterLaneGroupsUpdate();
          }
        }
        addLaneGroups(laneGroups) {
          this.laneGroups = this.laneGroups.concat(laneGroups.splice(0, Math.min(laneGroups.length, 7)));
          if (laneGroups.length > 0) {
            this.addingLaneGroupTimer = this.$timeout(() => {
              this.addLaneGroups(laneGroups);
            }, 50);
          } else {
            this.refreshAfterLaneGroupsUpdate();
          }
        }
        refreshAfterLaneGroupsUpdate() {
          if (this.firstLaneDisplay) {
            this.firstLaneDisplay = false;
          }
          if (this.updateLaneHeaderScrollTimer) {
            this.$timeout.cancel(this.updateLaneHeaderScrollTimer);
          }
          this.updateLaneHeaderScrollTimer = this.$timeout(() => this.updateLanesHeaderPosition, 0, false);
        }
        setupLaneUngroupedStore() {
          const groupBy2 = this.groupBy[1];
          if (!this.groupBy || !this.groupBy[1]) return;
          this.laneUngroupedStore = groupBy2.ungroupedCardsStore;
          this.laneUngroupedLabel = groupBy2.isNothing() ? _4("(ungrouped)") : _4("(no {group_by})", { group_by: groupBy2.getLabel().toLowerCase() });
          this.refreshUngroupedVisibility("lane");
          if (!groupBy2.isNothing()) {
            return this.laneUngroupedStore.subscribe(() => {
              const oldLaneUngroupedVisible = this.laneUngroupedVisible;
              this.refreshUngroupedVisibility("lane");
              if (oldLaneUngroupedVisible !== this.laneUngroupedVisible) {
                this.$scope.$applyAsync();
              }
            });
          } else {
            return angular_default.noop;
          }
        }
        refreshStoreListener() {
          if (this.deregisterStoreListener) this.deregisterStoreListener();
          if (this.store) {
            const scope = {};
            if (!this.shouldRenderFilteredCards && this.filtered) {
              scope["id"] = query_exports.any(this.matchingCardIds || []);
            }
            this.cardStore = this.store.scoped(scope);
            this.deregisterStoreListener = this.cardStore.subscribe(() => this.refreshCardMatrixDebounced(), true);
          }
        }
        refreshCardMatrix() {
          const columnSortBys = [null].concat(this.columnGroups).map((group2) => {
            return getGroupSortBy(this.options, group2 || { title: this.columnUngroupedLabel }, true);
          });
          this.cards = buildMatrix(
            this.columnGroups,
            this.allLaneGroups,
            this.cardStore,
            this.groupBy,
            (this.options || {}).include_archived,
            columnSortBys,
            {
              modelStore: getScopedModelStore(this.project, this.cardStore),
              groupTypeStore: getScopedGroupTypeStore(this.project, this.cardStore)
            }
          );
          this.refreshLanesAndColumnsVisibility();
        }
        refreshUngroupedVisibility(type) {
          const groupBy2 = this.groupBy[type === "lane" ? 1 : 0];
          const labelProp = type + "UngroupedVisible";
          const oldVisibility = this[labelProp];
          this[labelProp] = isUngroupedVisible(groupBy2, (this.options || {}).showUngroupedCards) || // if no group in lane show ungrouped instead
          type === "lane" && !this.laneGroups.length;
          if (oldVisibility !== this[labelProp]) {
            this.refreshLanesAndColumnsVisibility();
          }
        }
        refreshLanesAndColumnsVisibility() {
          this.lanesVisibility = {};
          this.columnsVisibility = {};
          if (!this.options?.hideEmptyGroups) return;
          (this.cards || []).forEach((lane, laneIdx) => {
            lane.forEach((cards, columIdx) => {
              if (this.lanesVisibility[laneIdx] && this.columnsVisibility[columIdx]) return;
              if (cards.some((card) => this.isCardFiltered(card))) {
                this.columnsVisibility[columIdx] = (columIdx !== 0 || this.columnUngroupedVisible) && (laneIdx !== 0 || this.laneUngroupedVisible);
                this.lanesVisibility[laneIdx] = (columIdx !== 0 || this.columnUngroupedVisible) && (laneIdx !== 0 || this.laneUngroupedVisible);
              }
            });
          });
        }
        isColumnVisible(idx) {
          if (!this.options?.hideEmptyGroups) return idx !== 0 || this.columnUngroupedVisible;
          return !!this.columnsVisibility[idx];
          ;
        }
        isLaneVisible(idx) {
          if (!this.options?.hideEmptyGroups) return idx !== 0 || this.laneUngroupedVisible;
          return !!this.lanesVisibility[idx];
          ;
        }
        isCardFiltered(card) {
          if (!isConnected()) return true;
          if (!Array.isArray(this.matchingCardIds)) return true;
          return this.matchingCardIds.indexOf(card.id) !== -1;
        }
        get filtered() {
          return !!this.filter;
        }
        updateBoardSortable() {
          const lanesSortable = this.$element.find(".swimlanes-lanes .ui-sortable-groups");
          const conlumnsSortable = this.$element.find(".swimlanes-columns-headers .ui-sortable-groups");
          const editable2 = isAuthenticated() && isConnected() && this.project && canEditGroup(this.project);
          if (lanesSortable.sortable("instance")) {
            if (editable2 && this.groupBy && this.groupBy[1].isSortable()) {
              lanesSortable.sortable("enable");
            } else {
              lanesSortable.sortable("disable");
            }
          }
          if (conlumnsSortable.sortable("instance")) {
            if (editable2 && this.groupBy && this.groupBy[0].isSortable()) {
              conlumnsSortable.sortable("enable");
            } else {
              conlumnsSortable.sortable("disable");
            }
          }
        }
        $postLink() {
          this.viewportInnerElement = this.$element;
          this.columnsHeadersElement = this.$element.find(".swimlanes-columns-headers");
          this.columnsHeadersFirstCellElement = this.$element.find(".swimlanes-columns-headers-first-cell");
          this.scrollTop = 0;
          this.scrollLeft = 0;
          this.scrollEventListener = () => this.scrollHandler();
          this.viewportInnerElement.scroll(this.scrollEventListener);
          activateViewScroll(
            this.$element,
            null,
            `cards-app-swimlanes-cardlist > sortable-cards-container > .ui-sortable-cards,
            .swimlanes-sortable-columns-headers,
            .swimlanes-cardlists,
            .swimlanes-columns-headers-first-cell,
            > sortable-groups-container`,
            () => this.groupBy && !this.groupBy[1].isNothing()
          );
        }
        updateLanesHeaderPosition() {
          const lanesHeaderElements = this.$element.find("cards-app-swimlanes-lane-header");
          const addLaneButtonElement = this.$element.find(".swimlanes-lanes add-card-group");
          const scrollLeft = this.viewportInnerElement.get(0).scrollLeft;
          if (this.scrollLeft !== scrollLeft) {
            this.scrollLeft = scrollLeft;
            lanesHeaderElements.toggleClass("is-scrolled", !!scrollLeft);
            addLaneButtonElement.toggleClass("is-scrolled", !!scrollLeft);
            this.columnsHeadersFirstCellElement.toggleClass("is-scrolled-left", !!scrollLeft);
            lanesHeaderElements.css("left", scrollLeft);
            addLaneButtonElement.css("margin-left", scrollLeft);
            this.columnsHeadersFirstCellElement.css("left", scrollLeft);
          }
        }
        scrollHandler() {
          this.updateLanesHeaderPosition();
          const scrollTop = this.viewportInnerElement.get(0).scrollTop;
          if (this.scrollTop !== scrollTop) {
            this.scrollTop = scrollTop;
            this.columnsHeadersElement.toggleClass("is-scrolled", !!scrollTop);
            this.columnsHeadersElement.css("top", scrollTop);
          }
        }
        scrollToRight(event2) {
          this.viewportInnerElement.scrollLeft(this.viewportInnerElement[0].scrollWidth);
        }
        scrollToBottom(event2) {
          this.viewportInnerElement.scrollTop(this.viewportInnerElement[0].scrollHeight);
        }
        canAddGroup(groupBy2) {
          if (!this.project || this.project.status || !groupBy2) return false;
          return groupBy2.canAddGroup() && !this.project.is_archived && isConnected() && canAddGroup(this.project);
        }
        $onDestroy() {
          this.viewportInnerElement.off("scroll", this.scrollEventListener);
          if (this.updateLaneHeaderScrollTimer) {
            this.$timeout.cancel(this.updateLaneHeaderScrollTimer);
            this.updateLaneHeaderScrollTimer = null;
          }
          if (this.deregisterGroupByListeners) this.deregisterGroupByListeners();
          if (this.deregisterStoreListener) this.deregisterStoreListener();
          this.destroyAttrVisibilityMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/kanban/ng-components/kanban.js
angular_default.module("kantree").component("cardsAppKanban", {
  template: `
    <dynamic-directive directive="{{$ctrl.kanbanComponentName}}" class="board-viewport-inner"
      store="$ctrl.store" board="$ctrl.board" filter="$ctrl.filter" filter-scopes="$ctrl.filterScopes"
      group-by="$ctrl.groupBy" options="$ctrl.options" matching-card-ids="$ctrl.matchingCardIds"
      on-change="$ctrl.onChange({$changes: $changes})"
    ></dynamic-directive>
    <cards-app-board-progress ng-if="!!$ctrl.options.showProgress" store="$ctrl.store"
      group-by="$ctrl.groupBy" options="$ctrl.options"></cards-app-board-progress>
  `,
  bindings: {
    store: "<",
    board: "<?",
    filter: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $onChanges() {
      this.kanbanComponentName = this.groupBy && !this.groupBy[1].isNothing() ? "cards-app-kanban-swimlanes" : "cards-app-kanban-simple";
      this.$element.toggleClass("board-density-compact", this.options?.displayDensity === "compact");
      this.$element.toggleClass("board-density-large", this.options?.displayDensity === "large");
      this.$element.toggleClass("stretched", !!this.options?.stretched);
    }
  }
});

// public/app/apps/cards/kanban/ng-components/swimlanes-cardlist.js
angular_default.module("kantree").directive("cardsAppSwimlanesCardlist", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        laneGroup: "<?",
        laneTitle: "<?",
        columnGroup: "<?",
        columnTitle: "<?",
        cards: "<?",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        visibleAttrNames: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/kanban/ng-components/templates/swimlanes-cardlist.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppCardCreatorMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element", "$q", "stylesheetManager"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.groups = [this.columnGroup, this.laneGroup];
          this.cards = this.cards || [];
          this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          this.canSortGroupBy = this.groupBy ? this.groupBy.some((groupBy2) => canSortGroupBy(this.project, groupBy2)) : null;
          this.colorTheme = "/static/app/apps/cards/kanban/ng-components/templates/kanban-group-color.css.html";
          this.refreshColorWatcher();
          this.showProjectOnCards = !this.board && (this.groupBy || []).every((groupByDim) => !groupByDim.isProjects());
          this.refreshSortBy();
          this.refreshDisplayedCards();
          this.$element.toggleClass("is-lane-collapsed", !!this.laneCollapsed);
          this.$element.toggleClass("is-column-collapsed", !!this.columnCollapsed);
          this.afterCollapsedChange();
          this.$scope.$on("maximizeAllCards", () => {
            this.$scope.$broadcast("showAllChildren");
          });
          this.$scope.$on("minimizeAllCards", () => {
            this.$scope.$broadcast("hideAllChildren");
          });
          this.$scope.$on("connectivityChanged", () => {
            this.refreshSortBy();
          });
          this.sortableOptions = {
            _canDropInSameContainer: false,
            _customPositionEnabled: false,
            _dragoverSelector: () => "cards-app-swimlanes-cardlist",
            _scrollHelperOptions: {
              disabled: true
            },
            _containersScrollHelperOptions: {
              scrollable: jquery_default("cards-app-kanban-swimlanes"),
              threshold: {
                default: { top: 40, right: 60, bottom: 40, left: 60 },
                xs: { top: 25, right: 30, bottom: 25, left: 30 }
              }
            },
            beforeStart: () => {
              this.$scope.$emit("startSortingCards");
            }
          };
          this.initCardCreatorMixin();
        }
        $onChanges(changes) {
          const columnGroupChanged = changes.columnGroup && !changes.columnGroup.isFirstChange();
          const laneGroupChanged = changes.laneGroup && !changes.laneGroup.isFirstChange();
          const cardsChanged = changes.cards && !changes.cards.isFirstChange();
          const boardChanged = changes.board && !changes.board.isFirstChange();
          const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
          const optionsChanged = changes.options && !changes.options.isFirstChange();
          const optionChanged = (optionLabel) => optionsChanged && !equals((this.options || {})[optionLabel], (changes.options.previousValue || {})[optionLabel]);
          if (optionsChanged) {
            this.refreshSortBy();
          }
          if (optionChanged(this.laneModeOptionsKey + "_collapsed")) {
            this.$element.toggleClass("is-lane-collapsed", !!this.laneCollapsed);
            this.afterCollapsedChange();
          }
          if (optionChanged(this.columnModeOptionsKey + "_collapsed")) {
            this.$element.toggleClass("is-column-collapsed", !!this.columnCollapsed);
            this.afterCollapsedChange();
          }
          if (groupByChanged || boardChanged) {
            this.showProjectOnCards = !this.board && this.groupBy.every((groupByDim) => !groupByDim.isProjects());
          }
          if (groupByChanged) {
            this.canSortGroupBy = this.groupBy ? this.groupBy.some((groupBy2) => canSortGroupBy(this.project, groupBy2)) : null;
          }
          if (columnGroupChanged || laneGroupChanged) {
            this.groups = [this.columnGroup, this.laneGroup];
          }
          if (columnGroupChanged || optionChanged("color_rows")) {
            this.refreshColorWatcher();
          }
          if (cardsChanged) {
            this.refreshDisplayedCards();
          }
          this.changeCardCreatorMixin(changes);
        }
        $postLink() {
          jquery_default(this.$element).on("click", (event2) => {
            if (this.laneCollapsed || this.columnCollapsed) {
              this.expandCardlist();
            }
          });
        }
        get filtered() {
          return !!this.filter;
        }
        get canSortCards() {
          return !!this.project && !this.project.is_archived && this.canSortGroupBy;
        }
        isCardFiltered(card) {
          if (!isConnected()) return true;
          if (!Array.isArray(this.matchingCardIds)) return true;
          return this.matchingCardIds.indexOf(card.id) !== -1;
        }
        get columnModeOptionsKey() {
          if (this.columnGroup) {
            return "groups_" + this.columnGroup.title;
          } else {
            return "groups_" + this.columnTitle;
          }
        }
        get laneModeOptionsKey() {
          if (this.laneGroup) {
            return "lane_" + this.laneGroup.title;
          } else {
            return "lane_" + this.laneTitle;
          }
        }
        afterCollapsedChange() {
          this.expandedOnce = this.expandedOnce || (this.laneCollapsed || this.columnCollapsed ? void 0 : true);
        }
        get laneCollapsed() {
          return (this.options || {})[this.laneModeOptionsKey + "_collapsed"] || false;
        }
        get columnCollapsed() {
          return (this.options || {})[this.columnModeOptionsKey + "_collapsed"] || false;
        }
        get archived() {
          return this.laneGroup && this.laneGroup.is_archived || this.columnGroup && this.columnGroup.is_archived;
        }
        expandCardlist() {
          const newModeOptions = Object.assign({}, this.options || {});
          if (this.columnModeOptionsKey) {
            newModeOptions[this.columnModeOptionsKey + "_collapsed"] = false;
          }
          if (this.laneModeOptionsKey) {
            newModeOptions[this.laneModeOptionsKey + "_collapsed"] = false;
          }
          return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
        }
        // Same method than in mixins/group
        beforeCardDropped(params) {
        }
        handleCardDropped(params) {
          const promise = handleCardDroppedInGroup(this.groupBy, this.groups, params);
          this.$q.digest(promise);
          return promise;
        }
        afterCardDropped(params) {
        }
        refreshSortBy() {
          const newSortBy = getGroupSortBy(this.options, this.columnGroup, true);
          if (!equals(this.sortBy, newSortBy)) {
            this.sortBy = newSortBy;
            return true;
          }
        }
        refreshDisplayedCards() {
          this.displayedCards = this.cards;
        }
        setColorWatcher() {
          const coloredPosition = this.options.color_rows ? 1 : 0;
          return this.groupBy[0].getGroupStore().watch(this.columnGroup, "updated", (gr) => {
            const classNamePrefix = "group-";
            if (!gr || !gr.color) {
              return;
            }
            const name2 = classNamePrefix + gr.id;
            if (coloredPosition === 0) {
              this.$stylesheetManager.createTheme(name2, gr.color, this.colorTheme);
              this.$element.addClass(name2);
              this.color = gr.color;
            } else {
              this.$element.removeClass(name2);
            }
          }), this.groupBy[1].getGroupStore().watch(this.laneGroup, "updated", (gr) => {
            const classNamePrefix = "group-";
            if (!gr || !gr.color) {
              return;
            }
            const name2 = classNamePrefix + gr.id;
            if (coloredPosition === 1) {
              this.$stylesheetManager.createTheme(name2, gr.color, this.colorTheme);
              this.$element.addClass(name2);
              this.color = gr.color;
            } else {
              this.$element.removeClass(name2);
            }
          });
        }
        refreshColorWatcher() {
          if (this.colorWatcherOff) {
            this.colorWatcherOff();
          }
          this.colorWatcherOff = this.setColorWatcher();
        }
        $onDestroy() {
          if (this.colorWatcherOff) {
            this.colorWatcherOff();
          }
          this.destroyCardCreatorMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/kanban/ng-components/swimlanes-column-header.js
angular_default.module("kantree").directive("cardsAppSwimlanesColumnHeader", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        showUngroupedTooltip: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/kanban/ng-components/templates/swimlanes-column-header.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.withStats = true;
          this.withProgressBar = true;
          this.modeOptionsKeyPrefix = "groups_";
          this.groupColorTheme = "/static/app/apps/cards/kanban/ng-components/templates/kanban-group-color.css.html";
          this.initGroupMixin();
          this.watchSortChoices(true);
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
          const storeChanged = changes.store && !changes.store.isFirstChange();
          const boardChanged = changes.board && !changes.board.isFirstChange();
          if (boardChanged || storeChanged) {
            this.watchSortChoices(true);
          }
        }
        watchSortChoices(immediate) {
          if (this.watchSortChoicesOff) this.watchSortChoicesOff();
          const modelStore = getScopedModelStore(this.project, this.store);
          const groupTypeStore = getScopedGroupTypeStore(this.project, this.store);
          const watcher = () => {
            this.sortChoices = getSortableAttributes(this.project, this.store, true);
          };
          this.watchSortChoicesOff = offMany([
            modelStore.$watchAll(this.$scope, watcher, false),
            groupTypeStore.$watchAll(this.$scope, watcher, false)
          ]);
          if (immediate) {
            watcher();
          }
        }
        onTitleEditStart() {
          this.editingTitle = true;
        }
        onTitleEditEnd(event2) {
          this.editingTitle = false;
        }
        $onDestroy() {
          this.destroyGroupMixin();
          if (this.watchSortChoicesOff) this.watchSortChoicesOff();
        }
      }
    };
  }
]);
angular_default.module("kantree").directive("cardsAppSwimlanesColumnSubHeader", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        sortChoices: "<?",
        onChange: "&"
      },
      template: `
        <div class="inner">
          <cards-app-group-progress cards="$ctrl.matchingCards" ng-if="$ctrl.showProgress"></cards-app-group-progress>
          <cards-app-group-stats cards="$ctrl.matchingCards" project="$ctrl.project"
            ng-if="$ctrl.showStats"></cards-app-group-stats>
          <cards-app-group-misc group="$ctrl.group" ng-if="$ctrl.showMisc"></cards-app-group-misc>
        </div>
      `,
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$element", "$scope"]);
        }
        $onInit() {
          this.modeOptionsKeyPrefix = "groups_";
          this.withStats = true;
          this.withProgressBar = true;
          this.selectAllCardsDisabled = true;
          this.groupColorTheme = "/static/app/apps/cards/kanban/ng-components/templates/kanban-group-color.css.html";
          this.initGroupMixin();
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
        }
        $onDestroy() {
          this.destroyGroupMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/kanban/ng-components/swimlanes-lane-header.js
angular_default.module("kantree").directive("cardsAppSwimlanesLaneHeader", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        showUngroupedTooltip: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/kanban/ng-components/templates/swimlanes-lane-header.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.menuDropConfig = {
            tetherOptions: {
              targetAttachment: "middle right",
              attachment: "top left",
              offset: "19px 0",
              constraints: [
                {
                  to: "window",
                  pin: true,
                  attachment: "none"
                }
              ]
            }
          };
          this.modeOptionsKeyPrefix = "lane_";
          this.groupColorTheme = "/static/app/apps/cards/kanban/ng-components/templates/kanban-group-color.css.html";
          this.initGroupMixin();
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
        }
        onTitleEditStart() {
          this.editingTitle = true;
        }
        onTitleEditEnd(event2) {
          this.editingTitle = false;
        }
        $onDestroy() {
          this.destroyGroupMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/map/map-view.tsx
var import_leaflet = __toESM(require_leaflet_src());
var import_dompurify2 = __toESM(require_purify());
var _tmpl$159 = /* @__PURE__ */ template(`<div class="map-empty-state"><i class="bi-geo-alt"></i><p></p><p class="map-empty-hint"></p></div>`, 8);
var _tmpl$276 = /* @__PURE__ */ template(`<div class="map-view"><div class="map-container"></div></div>`, 4);
var DefaultIcon = import_leaflet.default.icon({
  iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
  iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
  shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});
import_leaflet.default.Marker.prototype.options.icon = DefaultIcon;
function MapView(props2) {
  let mapContainer;
  let map5;
  let markersLayer;
  const cardStore2 = useCardStore();
  const appOptions = useAppOptions();
  const availableLocationAttrs = useAvailableAttributesOfType("location");
  const allCards = cardStore2.react({});
  const selectedFieldNames = createMemo(() => {
    const available = availableLocationAttrs();
    const options2 = appOptions?.getState() || {};
    const selected = getSelectedAttributes(available, options2, true);
    return Array.from(selected.keys());
  });
  const cardsWithLocations = createMemo(() => {
    const cards = [];
    const matchingIds = props2.matchingCardIds?.();
    const selectedFields = selectedFieldNames();
    for (const card of allCards()) {
      if (Array.isArray(matchingIds) && !matchingIds.includes(card.id)) {
        continue;
      }
      if (card.attributes) {
        for (const attr of card.attributes) {
          if (attr.type === "location" && attr.value && selectedFields.includes(attr.name)) {
            const location2 = typeof attr.value === "string" ? {
              address: attr.value
            } : attr.value;
            if (location2 && location2.address) {
              cards.push({
                card,
                location: location2,
                attrName: attr.name,
                hasCoords: location2.lat != null && location2.lng != null
              });
            }
          }
        }
      }
    }
    return cards;
  });
  const mappableCards = createMemo(() => {
    return cardsWithLocations().filter((item) => item.hasCoords);
  });
  const unmappableCards = createMemo(() => {
    return cardsWithLocations().filter((item) => !item.hasCoords);
  });
  onMount(() => {
    if (!mapContainer) return;
    map5 = import_leaflet.default.map(mapContainer).setView([48.8566, 2.3522], 4);
    import_leaflet.default.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      maxZoom: 19
    }).addTo(map5);
    markersLayer = import_leaflet.default.layerGroup().addTo(map5);
    const resizeObserver = new ResizeObserver(() => {
      map5?.invalidateSize();
    });
    resizeObserver.observe(mapContainer);
    onCleanup(() => {
      resizeObserver.disconnect();
      if (map5) {
        map5.remove();
        map5 = null;
      }
    });
  });
  createEffect(() => {
    if (!map5 || !markersLayer) return;
    markersLayer.clearLayers();
    const items = mappableCards();
    if (items.length === 0) return;
    const bounds = [];
    for (const item of items) {
      const {
        card,
        location: location2
      } = item;
      const lat = location2.lat;
      const lng = location2.lng;
      const marker = import_leaflet.default.marker([lat, lng]).bindTooltip(`
          <div class="map-card-popup">
            <strong>${import_dompurify2.default.sanitize(card.title)}</strong>
            <div class="map-card-popup-address">${import_dompurify2.default.sanitize(location2.address || "")}</div>
          </div>
        `).on("click", () => {
        props2.onCardClick?.(card);
      });
      markersLayer.addLayer(marker);
      bounds.push([lat, lng]);
    }
    if (bounds.length > 0) {
      if (bounds.length === 1) {
        map5.setView(bounds[0], 14);
      } else {
        map5.fitBounds(bounds, {
          padding: [50, 50],
          maxZoom: 16
        });
      }
    }
  });
  const hasNoCards = createMemo(() => {
    return cardsWithLocations().length === 0;
  });
  const hasNoMappableCards = createMemo(() => {
    return mappableCards().length === 0 && unmappableCards().length > 0;
  });
  return (() => {
    const _el$ = _tmpl$276.cloneNode(true), _el$2 = _el$.firstChild;
    const _ref$ = mapContainer;
    typeof _ref$ === "function" ? use(_ref$, _el$2) : mapContainer = _el$2;
    insert(_el$, createComponent(Show, {
      get when() {
        return hasNoCards();
      },
      get children() {
        const _el$3 = _tmpl$159.cloneNode(true), _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling, _el$6 = _el$5.nextSibling;
        insert(_el$5, () => _4("No cards with location attributes found"));
        insert(_el$6, () => _4("Add a location attribute to your cards to see them on the map"));
        return _el$3;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return hasNoMappableCards();
      },
      get children() {
        const _el$7 = _tmpl$159.cloneNode(true), _el$8 = _el$7.firstChild, _el$9 = _el$8.nextSibling, _el$10 = _el$9.nextSibling;
        insert(_el$9, () => _4("No cards with coordinates found"));
        insert(_el$10, () => _4("Coordinates are being calculated. This may take a moment."));
        return _el$7;
      }
    }), null);
    return _el$;
  })();
}

// public/app/apps/cards/map/map-app-options.ts
var MapAppOptions = class extends AppOptions {
  constructor() {
    super(...arguments);
    this.use_field = prop([]);
  }
};

// public/app/apps/cards/map/ng-components/map.jsx
angular_default.module("kantree").directive("cardsAppMap", [function() {
  return {
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    bindToController: {
      store: "<",
      board: "<?",
      filter: "<?",
      filterScopes: "<?",
      groupBy: "<?",
      options: "<?",
      matchingCardIds: "<?",
      onChange: "&"
    },
    templateUrl: "/static/app/apps/cards/map/ng-components/templates/map.html",
    controller: class extends AngularClass {
      static get $inject() {
        return (super.$inject || []).concat(["$scope", "$element", "cardModal"]);
      }
      $onInit() {
        injectI18nHelpersIntoScope(this.$scope);
        this.matchingCardIdsSignal = createSignal(this.matchingCardIds);
        this.optionStore = MapAppOptions.create(this.options ?? {});
        const _self$ = this;
        this.MapView = () => createComponent(KeyboardProvider, {
          get children() {
            return createComponent(BoardProvider, {
              get board() {
                return _self$.board;
              },
              get children() {
                return createComponent(ProjectProvider, {
                  get board() {
                    return _self$.board;
                  },
                  get children() {
                    return createComponent(CardStoreProvider, {
                      get store() {
                        return _self$.store;
                      },
                      get children() {
                        return createComponent(ScopedModelStoreProvider, {
                          get children() {
                            return createComponent(ScopedGroupTypeStoreProvider, {
                              get children() {
                                return createComponent(AppOptionsProvider, {
                                  get store() {
                                    return _self$.optionStore;
                                  },
                                  get children() {
                                    return createComponent(AvailableAttributesProvider, {
                                      get children() {
                                        return createComponent(MapView, {
                                          get matchingCardIds() {
                                            return _self$.matchingCardIdsSignal[0];
                                          },
                                          onCardClick: (card) => _self$.$cardModal.open(card)
                                        });
                                      }
                                    });
                                  }
                                });
                              }
                            });
                          }
                        });
                      }
                    });
                  }
                });
              }
            });
          }
        });
      }
      $onChanges(changes) {
        if (changes.matchingCardIds && !changes.matchingCardIds.isFirstChange()) {
          this.matchingCardIdsSignal[1](changes.matchingCardIds.currentValue);
        }
        if (changes.options && !changes.options.isFirstChange()) {
          this.optionStore.updateOptions(changes.options.currentValue || {});
        }
      }
    }
  };
}]);

// public/app/apps/cards/table/ng-components/table-column-header.js
function isColumnEditable(namedAttrGroup, project) {
  if (!project) return false;
  if (namedAttrGroup.length >= 2) return false;
  const attr = namedAttrGroup[0];
  return attr.id >= 0 && canManageAttributes(project) || attr.id < 0 && isAllowedInProject(project, "card_group_type", "EDIT", attr.group_type_id);
}
angular_default.module("kantree").component("cardsAppTableColumnHeader", {
  templateUrl: "/static/app/apps/cards/table/ng-components/templates/table-column-header.html",
  bindings: {
    attrs: "<",
    board: "<?",
    sortBy: "<?",
    onSortChange: "&?",
    onToggleVisibility: "&?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "cardGroupTypeGroupsModal", "attributeOptionsModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
      this.refresh();
      this.$scope.$on("connectivityChanged", () => this.refresh());
      this.$scope.$on("screensize:changed", () => this.refresh());
    }
    $onChanges(changes) {
      if (changes.attrs && !changes.attrs.isFirstChange() || changes.board && !changes.board.isFirstChange()) {
        this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
        this.refresh();
      }
    }
    get isLocked() {
      return isScreensizeXS() || !isConnected();
    }
    refresh() {
      if (!this.attrs) {
        this.headerSettingsMenu = null;
      } else {
        this.headerSettingsMenu = {
          config: this.getHeaderSettingsMenuItems()
        };
      }
      if (this.renaming && (!isColumnEditable(this.attrs, this.project) || this.isLocked)) {
        this.renaming = false;
      }
    }
    startRename() {
      if (this.isLocked || !isColumnEditable(this.attrs, this.project)) return;
      this.renaming = true;
      this.title = this.attrs.label;
    }
    rename() {
      this.renaming = false;
      if (this.isLocked || !isColumnEditable(this.attrs, this.project)) return;
      const attr = this.attrs[0];
      if (attr.id < 0) {
        const groupType = cardGroupTypeStore.tryGet(attr.group_type_id);
        const newGroupType = Object.assign({}, groupType, {
          name: this.title,
          singular_name: this.title,
          plural_name: this.title
        });
        this.$q.digest(saveGroupType(newGroupType));
        return;
      } else if (attr.id >= 0) {
        const newAttr = Object.assign({}, attr, {
          name: this.title
        });
        const model = cardModelStore.getAttributeOwner(attr);
        this.$q.digest(new ModelAttributeGroup(
          this.project,
          model,
          cardModelStore.getExtendedModelAttributes(model, this.project)
        ).update(newAttr));
      }
    }
    cancelRename() {
      this.renaming = false;
    }
    getHeaderSettingsMenuItems() {
      if (!this.attrs) return [];
      let items = [];
      let attr = this.attrs[0];
      const attrType = attributeTypeRegistry.get(attr.type);
      if (attrType.sortable === true) {
        items.push(
          {
            label: _4("Sort ascending"),
            icon: "sort-amount-asc",
            action: () => this.onSortChange({ $reverse: false })
          },
          {
            label: _4("Sort descending"),
            icon: "sort-amount-desc",
            action: () => this.onSortChange({ $reverse: true })
          },
          { label: "--" }
        );
      }
      if (isColumnEditable(this.attrs, this.project) && !this.isLocked) {
        items.push({
          label: _4("Rename"),
          action: () => {
            this.startRename();
          }
        });
        if (attr.id < 0) {
          items.push({
            label: _4("Context settings"),
            action: () => {
              this.$cardGroupTypeGroupsModal.open(cardGroupTypeStore.get(attr.group_type_id), this.board);
            },
            enabled: () => !!this.board
          });
        } else if (attr.id >= 0) {
          items.push({
            label: _4("Field options"),
            action: () => {
              const model = cardModelStore.getAttributeOwner(attr);
              const attrGroup = new ModelAttributeGroup(this.project, model, cardModelStore.getExtendedModelAttributes(model, this.project));
              this.$attributeOptionsModal.open(this.project, attrGroup, attr);
            }
          });
        }
        items.push({ label: "--" });
      }
      items.push({
        label: _4("Hide column"),
        action: () => {
          this.onToggleVisibility();
        }
      });
      return items;
    }
  }
});

// public/app/apps/cards/table/ng-components/table-group.js
angular_default.module("kantree").directive("cardsAppTableGroup", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<?",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        sortChoices: "<?",
        visibleAttributes: "<?",
        hideHeader: "<?",
        selector: "<?",
        selectorPage: "<?",
        openCreatorOnInit: "<?",
        showUngroupedTooltip: "<?",
        onChange: "&?"
      },
      templateUrl: "/static/app/apps/cards/table/ng-components/templates/table-group.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin, CardsAppCardCreatorMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element", "$timeout"]);
        }
        constructor(...args) {
          super(...args);
          this.cardCreatorTemplate = "/static/app/apps/cards/table/ng-components/templates/card-creator.html";
          this.cardCreatorOptions = {
            cancelBtn: false,
            rows: 1,
            placeholder: _4("Add card"),
            saveBtnLabel: _4("Add"),
            autosizeOpts: {
              append: null
            }
          };
          this.menuCustomDropConfig = {
            tetherOptions: {
              attachment: "top left",
              offset: "0 22px"
            }
          };
          this.sortableOptions = {
            items: ".ui-sortable-cards-item:not(.archived):not(.locked)",
            duplication: () => !(this.groupBy || [])[0].oneGroupPerCard,
            _scrollHelperOptions: {
              disabled: true
            },
            _containersScrollHelperOptions: {
              scrollable: ".cards-app-table-inner",
              threshold: {
                default: { top: 60, bottom: 60 },
                xs: { top: 30, bottom: 30 }
              }
            },
            beforeStart: () => {
              this.$scope.$emit("startSortingCards");
            }
          };
          this.columnWidths = {};
          this.withCardsAttributeAggregation = true;
          this.isScreensizeXS = isScreensizeXS;
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.modeOptionsKeyPrefix = "table_";
          this.withCardSelector = true;
          this.groupColorTheme = "/static/app/apps/cards/table/ng-components/templates/table-group-color.css.html";
          this.handleCards = true;
          this.initGroupMixin();
          this.initCardCreatorMixin();
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
          this.changeCardCreatorMixin(changes);
          const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
          if (groupByChanged && !!this.group) {
            return;
          }
          if (changes.options && !changes.options.isFirstChange() && (this.options || {})["column_widths"] !== (changes.options.previousValue || {})["column_widths"] || changes.visibleAttributes && !changes.visibleAttributes.isFirstChange()) {
            this.updateColumnWidths();
          }
        }
        $postLink() {
          requestAnimationFrame(() => {
            this.updateColumnWidths(true);
          });
        }
        updateColumnWidths(forced = false) {
          const newColumnWidths = { ...this.options?.column_widths };
          if (toInt(this.columnWidths.__title__) !== toInt(newColumnWidths.__title__) || forced) {
            this.$element.find(".cards-app-table-cell.cards-app-table-cell-header").outerWidth(Math.max(toInt(newColumnWidths.__title__), 100) + 50);
          }
          if (this.visibleAttributes && this.visibleAttributes.length > 0) {
            this.$element.find(".header .cards-app-table-cell").toArray().slice(1).map((el2, idx) => {
              const namedAttrGroupName = this.visibleAttributes[idx].name;
              if (toInt(this.columnWidths[namedAttrGroupName]) !== toInt(newColumnWidths[namedAttrGroupName]) || forced) {
                jquery_default(el2).outerWidth(Math.max(toInt(newColumnWidths[namedAttrGroupName]), 100));
              }
            });
          }
          this.columnWidths = newColumnWidths;
        }
        onTitleEditStart() {
          this.editingTitle = true;
          if (this.selector && this.selectorPage) {
            const selectedPage = this.selector.getCurrentPage();
            if (!selector_default.prototype.matchPage(selectedPage, this.selectorPage)) {
              this.selector.selectPage(this.selectorPage, "header");
            }
          }
        }
        onTitleEditEnd(event2) {
          if (this.selector) {
            if (event2.keyCode === 9) {
              this.selector.nextPage();
            } else {
              const currentPage = this.selector.getCurrentPage();
              this.selector.unselectPage();
              if (currentPage) {
                this.selector.selectFirstOfPage(currentPage);
              }
            }
          }
          this.editingTitle = false;
        }
        $onDestroy() {
          this.destroyGroupMixin();
          this.destroyCardCreatorMixin();
        }
      }
    };
  }
]);

// public/app/apps/cards/table/ng-components/table-row-template.js
var { iconClass: iconClass3 } = (init_icons(), __toCommonJS(icons_exports));
(function() {
  var template3 = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
  templates["tableRow"] = template3({ "1": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return "#" + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "ref") : stack1, depth0));
  }, "3": function(container, depth0, helpers2, partials, data2) {
    return '<i class="bi-box-arrow-up-right"></i>';
  }, "5": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return 'style="width:' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "titleWidth") || (depth0 != null ? lookupProperty(depth0, "titleWidth") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "titleWidth", "hash": {}, "data": data2, "loc": { "start": { "line": 13, "column": 105 }, "end": { "line": 13, "column": 119 } } }) : helper)) + 'px;"';
  }, "7": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="model-indicator ' + iconClass3(container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "indicator") : stack1, depth0))) + '"></i>';
  }, "9": function(container, depth0, helpers2, partials, data2) {
    return '<i class="request-indicator fa fa-inbox"></i>';
  }, "11": function(container, depth0, helpers2, partials, data2) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="state-indicator ' + iconClass3(alias2(alias1((stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "icon") : stack1, depth0))) + '" title="' + alias2(alias1((stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "label") : stack1, depth0)) + '"></i>';
  }, "13": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <span class="link" ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(14, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 19, "column": 21 }, "end": { "line": 19, "column": 68 } } })) != null ? stack1 : "") + ' title="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "linkTooltip") || (depth0 != null ? lookupProperty(depth0, "linkTooltip") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(alias1, { "name": "linkTooltip", "hash": {}, "data": data2, "loc": { "start": { "line": 19, "column": 76 }, "end": { "line": 19, "column": 91 } } }) : helper)) + '">\n    ' + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "unless", "hash": {}, "fn": container.program(16, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 20, "column": 4 }, "end": { "line": 20, "column": 70 } } })) != null ? stack1 : "") + "\n    " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(18, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 21, "column": 4 }, "end": { "line": 21, "column": 69 } } })) != null ? stack1 : "") + "\n  </span>\n";
  }, "14": function(container, depth0, helpers2, partials, data2) {
    return 'class="fa-stack"';
  }, "16": function(container, depth0, helpers2, partials, data2) {
    return '<i class="fa fa-chain"></i>';
  }, "18": function(container, depth0, helpers2, partials, data2) {
    return '<i class="fa fa-chain-broken"></i>';
  }, "20": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<span class="comments"><i class="fa fa-comments-o"></i> ' + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "nb_comments") : stack1, depth0)) + "</span>";
  }, "22": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <span title="' + alias2((helper = (helper = lookupProperty(helpers2, "childrenTooltip") || (depth0 != null ? lookupProperty(depth0, "childrenTooltip") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(alias1, { "name": "childrenTooltip", "hash": {}, "data": data2, "loc": { "start": { "line": 26, "column": 15 }, "end": { "line": 26, "column": 34 } } }) : helper)) + '">\n    <i class="' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "board_created") : stack1, { "name": "if", "hash": {}, "fn": container.program(23, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 27, "column": 14 }, "end": { "line": 27, "column": 60 } } })) != null ? stack1 : "") + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "board_created") : stack1, { "name": "unless", "hash": {}, "fn": container.program(25, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 27, "column": 60 }, "end": { "line": 27, "column": 114 } } })) != null ? stack1 : "") + '"></i>\n    ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "nb_finished_children") : stack1, { "name": "if", "hash": {}, "fn": container.program(27, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 28, "column": 4 }, "end": { "line": 28, "column": 74 } } })) != null ? stack1 : "") + "\n    " + alias2(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "nb_children") : stack1, depth0)) + "\n  </span>\n";
  }, "23": function(container, depth0, helpers2, partials, data2) {
    return "fa fa-columns";
  }, "25": function(container, depth0, helpers2, partials, data2) {
    return "bi-list-check";
  }, "27": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "nb_finished_children") : stack1, depth0)) + "/";
  }, "29": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, alias3 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="cards-app-table-cell attribute is-' + alias2(alias1((stack1 = (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "attribute") : stack1) != null ? lookupProperty(stack1, "type") : stack1, depth0)) + " " + ((stack1 = lookupProperty(helpers2, "unless").call(alias3, (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "available") : stack1, { "name": "unless", "hash": {}, "fn": container.program(30, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 34, "column": 69 }, "end": { "line": 34, "column": 118 } } })) != null ? stack1 : "") + " " + ((stack1 = lookupProperty(helpers2, "unless").call(alias3, (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "editable") : stack1, { "name": "unless", "hash": {}, "fn": container.program(32, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 34, "column": 119 }, "end": { "line": 34, "column": 166 } } })) != null ? stack1 : "") + '" data-column-name="' + alias2(alias1((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "dataColumnName") : stack1, depth0)) + '" ' + ((stack1 = lookupProperty(helpers2, "if").call(alias3, (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "attrSourceLabel") : stack1, { "name": "if", "hash": {}, "fn": container.program(34, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 34, "column": 210 }, "end": { "line": 34, "column": 275 } } })) != null ? stack1 : "") + " " + ((stack1 = lookupProperty(helpers2, "if").call(alias3, (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "width") : stack1, { "name": "if", "hash": {}, "fn": container.program(36, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 34, "column": 276 }, "end": { "line": 34, "column": 330 } } })) != null ? stack1 : "") + ">\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias3, (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "available") : stack1, { "name": "if", "hash": {}, "fn": container.program(38, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 35, "column": 0 }, "end": { "line": 39, "column": 7 } } })) != null ? stack1 : "") + ((stack1 = lookupProperty(helpers2, "if").call(alias3, (stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "hasMultipleAttrs") : stack1, { "name": "if", "hash": {}, "fn": container.program(41, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 40, "column": 0 }, "end": { "line": 40, "column": 103 } } })) != null ? stack1 : "") + "\n</div>\n";
  }, "30": function(container, depth0, helpers2, partials, data2) {
    return "not-available";
  }, "32": function(container, depth0, helpers2, partials, data2) {
    return "not-editable";
  }, "34": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return 'title="' + container.escapeExpression(container.lambda((stack1 = blockParams[1][0]) != null ? lookupProperty(stack1, "attrSourceLabel") : stack1, depth0)) + '"';
  }, "36": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return 'style="width:' + container.escapeExpression(container.lambda((stack1 = blockParams[1][0]) != null ? lookupProperty(stack1, "width") : stack1, depth0)) + 'px;"';
  }, "38": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return (stack1 = lookupProperty(helpers2, "each").call(depth0 != null ? depth0 : container.nullContext || {}, (stack1 = blockParams[1][0]) != null ? lookupProperty(stack1, "widgets") : stack1, { "name": "each", "hash": {}, "fn": container.program(39, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 36, "column": 2 }, "end": { "line": 38, "column": 11 } } })) != null ? stack1 : "";
  }, "39": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return (stack1 = container.invokePartial((((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "partial") : stack1) || container.hooks.helperMissing).call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "widget.partial", "hash": {}, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 37, "column": 8 }, "end": { "line": 37, "column": 24 } } }), depth0, { "data": data2, "blockParams": blockParams, "indent": "    ", "helpers": helpers2, "partials": partials, "decorators": container.decorators })) != null ? stack1 : "";
  }, "41": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="fa fa-circle" title="' + container.escapeExpression(container.lambda((stack1 = blockParams[1][0]) != null ? lookupProperty(stack1, "hasMultipleAttrsTooltip") : stack1, depth0)) + '"></i>';
  }, "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = depth0 != null ? depth0 : container.nullContext || {}, alias2 = container.lambda, alias3 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="cards-app-table-row-append">\n  <i class="bi-plus"></i>\n</div>\n<div class="cards-app-table-row-append-disabled">\n  <i class="bi-dash-circle-fill"></i>\n</div>\n<div class="cards-app-table-cell ref js-open-modal" data-col-id="ref">\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showRef") : depth0, { "name": "if", "hash": {}, "fn": container.program(1, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 8, "column": 2 }, "end": { "line": 8, "column": 37 } } })) != null ? stack1 : "") + "\n  " + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, depth0 != null ? lookupProperty(depth0, "showRef") : depth0, { "name": "unless", "hash": {}, "fn": container.program(3, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 9, "column": 2 }, "end": { "line": 9, "column": 69 } } })) != null ? stack1 : "") + '\n</div>\n<div class="cards-app-table-cell ref loader js-open-modal"><i class="fa fa-spin fa-spinner"></i></div>\n<div class="cards-app-table-cell ref offline js-open-modal"><i class="fa fa-refresh"></i></div>\n<div class="cards-app-table-cell title js-open-modal" data-col-id="title" ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "titleWidth") : depth0, { "name": "if", "hash": {}, "fn": container.program(5, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 13, "column": 74 }, "end": { "line": 13, "column": 130 } } })) != null ? stack1 : "") + '>\n  <span class="title" title="' + alias3(alias2((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "title") : stack1, depth0)) + '"><span>' + alias3(alias2((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "title") : stack1, depth0)) + "</span></span>\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "indicator") : stack1, { "name": "if", "hash": {}, "fn": container.program(7, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 15, "column": 2 }, "end": { "line": 15, "column": 89 } } })) != null ? stack1 : "") + "\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "from_request") : stack1, { "name": "if", "hash": {}, "fn": container.program(9, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 16, "column": 2 }, "end": { "line": 16, "column": 79 } } })) != null ? stack1 : "") + "\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "icon") : stack1, { "name": "if", "hash": {}, "fn": container.program(11, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 17, "column": 2 }, "end": { "line": 17, "column": 103 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "is_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(13, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 18, "column": 2 }, "end": { "line": 23, "column": 9 } } })) != null ? stack1 : "") + "  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "nb_comments") : stack1, { "name": "if", "hash": {}, "fn": container.program(20, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 24, "column": 2 }, "end": { "line": 24, "column": 116 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "nb_children") : stack1, { "name": "if", "hash": {}, "fn": container.program(22, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 25, "column": 2 }, "end": { "line": 31, "column": 9 } } })) != null ? stack1 : "") + "</div>\n" + ((stack1 = lookupProperty(helpers2, "each").call(alias1, depth0 != null ? lookupProperty(depth0, "cols") : depth0, { "name": "each", "hash": {}, "fn": container.program(29, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 33, "column": 0 }, "end": { "line": 42, "column": 9 } } })) != null ? stack1 : "");
  }, "usePartial": true, "useData": true, "useBlockParams": true });
})();

// public/app/apps/cards/table/ng-components/table-row.js
angular_default.module("kantree").component("cardsAppTableRow", {
  bindings: {
    card: "<",
    columnWidths: "<",
    visibleAttributes: "<",
    showArchived: "<?",
    strikeTitleWhenDone: "<?",
    selector: "<?"
  },
  controller: [
    "$scope",
    "$element",
    "attributeRepr",
    "cardModal",
    "$sanitize",
    "$timeout",
    "cardActionsMenuFactory",
    "menuDropdown",
    "$q",
    "$state",
    "$compile",
    "projectPage",
    function($scope2, $element2, attributeRepr, cardModal, $sanitize, $timeout2, cardActionsMenuFactory, menuDropdown, $q, $state, $compile, projectPage) {
      let $ctrl = this;
      let cardWatcherOff;
      let hasModelTheme = false;
      let content2;
      function _canEditAttribute(attr) {
        const attrType = attributeTypeRegistry.get(attr.type);
        return !$ctrl.card._temp && !$ctrl.card.is_archived && !$ctrl.card.is_parent_archived && isAuthenticated() && isConnected() && (!attrType.requireValidOptions || attr.valid_options) && (canEditAttribute($ctrl.project, attr) && !attrType.widgetOptions?.valueIsOption || canManageAttributes($ctrl.project) && attrType.widgetOptions?.valueIsOption) && (!attr.auto_group_type_attribute || canMoveCardsInThisGroupType($ctrl.project, attr.group_type_id));
      }
      function canEditTitle() {
        return !$ctrl.card.is_link && !$ctrl.card.is_archived && !$ctrl.card.is_parent_archived && isAuthenticated() && isConnected() && isAllowedInProject($ctrl.project, "card", "EDIT", $ctrl.card.id);
      }
      let columnWidths = {};
      function updateColumnWidths() {
        const newColumnWidths = { ...$ctrl.columnWidths };
        const $titleElement = jquery_default(jquery_default($element2).find(".cards-app-table-cell").get(3));
        const $attributeElements = jquery_default($element2).find(".cards-app-table-cell").toArray().slice(4);
        if (toInt(columnWidths.__title__) !== toInt(newColumnWidths.__title__)) {
          $titleElement.outerWidth(Math.max(toInt(newColumnWidths.__title__), 100));
        }
        $attributeElements.map((el2, idx) => {
          const namedAttrGroupName = $ctrl.visibleAttributes[idx].name;
          if (toInt(columnWidths[namedAttrGroupName]) !== toInt(newColumnWidths[namedAttrGroupName])) {
            jquery_default(el2).outerWidth(Math.max(toInt(newColumnWidths[namedAttrGroupName]), 100));
          }
        });
        columnWidths = newColumnWidths;
      }
      const cardEditorOptions = {
        saveChange: (event2, title, cb2) => {
          $q.when(updateCard($ctrl.card, { title }), cb2);
          stopTitleEditor();
        },
        cancelChange: () => {
          stopTitleEditor();
        },
        inputType: "input",
        saveBtn: false,
        cancelBtn: false,
        saveOn: { tab: true },
        hideOn: { save: true },
        resetOn: { save: false }
      };
      let editorScope, editorElement;
      function startTitleEditor() {
        const tpl = '<div class="text-composer" text-composer="cardEditorOptions" init-value="$ctrl.card.title"></div>';
        editorScope = $scope2.$new();
        editorScope.cardEditorOptions = cardEditorOptions;
        editorElement = $compile(tpl)(editorScope);
        jquery_default($element2).find(".cards-app-table-cell.title").addClass("editing").html(editorElement);
        $timeout2(function() {
          editorElement.find("input").focus();
        });
      }
      function stopTitleEditor() {
        editorScope.$destroy();
        editorElement.remove();
        editorScope = null;
        editorElement = null;
        content2 = null;
        render3();
      }
      function buildWidgets(attr, card) {
        return attributeRepr.getAttributeWidgets(attr, card, { expanded: true, expandable: true });
      }
      function buildRenderParams() {
        const card = $ctrl.card;
        const params = { card, model: $ctrl.model };
        if (card.nb_children) {
          params.childrenTooltip = _4("Number of sub-cards") + (card.nb_completed_pct > 0 ? _4(" ({pct}% completed)", { pct: card.nb_completed_pct }) : "");
        }
        const cardVisibleAttrs = getCardAvailableAttributesAsMap(card, new Map($ctrl.visibleAttributes.map((namedAttrGroup) => [namedAttrGroup.name, namedAttrGroup])));
        params.cols = $ctrl.visibleAttributes.map((namedAttrGroup) => {
          if (cardVisibleAttrs.has(namedAttrGroup.name)) {
            const cardAttrs = cardVisibleAttrs.get(namedAttrGroup.name);
            const attr = cardAttrs[0];
            const attrType = attributeTypeRegistry.get(attr.type);
            if (attrType.statelessAsync) {
              new ModelAttributeGroup($ctrl.project, $ctrl.model.model, [attr]).getObjAttributeValue(card, attr)[1].then((value2) => renderAsyncRepr(value2, attr, card));
            }
            const col = {
              widgets: buildWidgets(attr, card),
              available: true,
              editable: _canEditAttribute(attr, attrType),
              attribute: attr,
              dataColumnName: namedAttrGroup.sanitizedName,
              // Handlebars doesn't escape special character exactly like angular
              obj: card
            };
            if (Object.keys($ctrl.columnWidths || {}).includes(namedAttrGroup.name)) {
              col.width = Math.max(toInt($ctrl.columnWidths[namedAttrGroup.name]), 100);
            }
            if (cardAttrs.length >= 2) {
              col.hasMultipleAttrs = true;
              col.hasMultipleAttrsTooltip = _4("This card has {nb} available fields with this name", { nb: cardAttrs.length });
              var attrSource = namedAttrGroup.getAttrSource(attr);
              col.attrSourceLabel = ["group_type", "model", "project", "owner"].filter((key2) => attrSource[key2] !== void 0).map((key2) => attrSource[key2]).join(" - ");
            }
            return col;
          } else {
            const col = {
              widgets: [],
              available: false,
              editable: false,
              attribute: namedAttrGroup[0]
            };
            if (Object.keys($ctrl.columnWidths || {}).includes(namedAttrGroup.name)) {
              col.width = Math.max(toInt($ctrl.columnWidths[namedAttrGroup.name]), 100);
            }
            return col;
          }
        });
        if (Object.keys($ctrl.columnWidths || {}).includes("__title__")) {
          params.titleWidth = Math.max(toInt($ctrl.columnWidths["__title__"]), 100);
        }
        params.showRef = card.ref > 0;
        params.state = cardStateStore.getForCard(card);
        params.linkTooltip = card.broken_link ? _4("Broken link") : card.link_has_own_attributes ? _4("This card points to another card") : _4("This card is a mirrored card");
        return params;
      }
      function renderAsyncRepr(value2, attr, card) {
        const cardAttr = { id: attr.id, value: value2 };
        const widgets = buildWidgets(attr, { ...card, attributes: [...card.attributes || [], cardAttr] });
        const newRepr = widgets.map((widget) => handlebars_default.partials[widget.component]({ widget })).join("");
        $element2.find(`[data-column-name="${$sanitize(attr.name)}"]`).html(newRepr);
      }
      let disposeReprListeners;
      function render3() {
        $element2[0].scope = () => $scope2;
        const params = buildRenderParams();
        const newContent = handlebars_default.templates.tableRow(params);
        if (content2 !== newContent) {
          $element2.html(newContent);
          content2 = newContent;
        }
        $element2.data("card-id", params.card.id);
        $element2.toggleClass("locked", !params.card.ref && params.card.ref !== 0 && !params.card.offline && cardStore.isLocked(params.card));
        $element2.toggleClass("offline", !!params.card.offline);
        $element2.toggleClass("archived", params.card.is_archived);
        $element2.toggleClass("finished", params.card.finished);
        $element2.toggleClass("struck-title", params.card.finished && (!!$ctrl.strikeTitleWhenDone || $ctrl.strikeTitleWhenDone === void 0));
        if (hasModelTheme) {
          jquery_default($element2).removeClassRegex("card-model-theme-");
          hasModelTheme = false;
        }
        if ($ctrl.model.model && $ctrl.model.model.style_class_name) {
          $element2.addClass($ctrl.model.model.style_class_name);
          hasModelTheme = true;
        } else if (!$ctrl.card.parent_id && $ctrl.project.card_model_theme) {
          $element2.addClass($ctrl.project.card_model_theme);
          hasModelTheme = true;
        }
        if (disposeReprListeners) {
          disposeReprListeners();
        }
        disposeReprListeners = offMany(params.cols.map((col) => {
          const reprElement = jquery_default($element2).find(`.cards-app-table-cell.attribute[data-column-name="${col.dataColumnName}"]`);
          const attributeGroup = new ModelAttributeGroup($ctrl.project, $ctrl.model.model, [col.attribute]);
          return attributeRepr.setReprEventListeners(reprElement, $scope2, attributeGroup, col.attribute, $ctrl.card, col.widgets, col.editable);
        }));
      }
      let modelWatcherOff;
      function modelChanged() {
        if (modelWatcherOff) modelWatcherOff();
        $ctrl.model = getCardCompositeModel($ctrl.card);
        const watchers = [];
        if ($ctrl.model.model) {
          watchers.push(cardModelStore.watch($ctrl.model.model, "updated", modelChanged, false));
        }
        if ($ctrl.card.model_id && !cardModelStore.exists($ctrl.card.model_id)) {
          watchers.push(cardModelStore.watch($ctrl.card.model_id, "inserted", modelChanged, false));
        }
        if (watchers.length) {
          modelWatcherOff = offMany(watchers);
        }
        render3();
      }
      let lockOff;
      $ctrl.$onInit = function() {
        $ctrl.project = projectStore.getForCard($ctrl.card);
        if (!$ctrl.project) return;
        cardWatcherOff = cardStore.watch($ctrl.card, "updated", modelChanged);
        lockOff = cardStore.watch($ctrl.card, ["locked", "unlocked"], () => {
          $element2.toggleClass("locked", !$ctrl.card.ref && $ctrl.card.ref !== 0 && !$ctrl.card.offline && cardStore.isLocked($ctrl.card));
        });
        $scope2.$on("connectivityChanged", () => render3());
        $ctrl.selected = false;
        $ctrl.highlighted = false;
        function selectCard() {
          $ctrl.selected = true;
          $element2.toggleClass("selected", true);
          $element2.removeClass("highlighted");
        }
        function unselectCard() {
          $ctrl.selected = false;
          $element2.toggleClass("selected", false);
          if ($ctrl.highlighted) {
            $element2.addClass("highlighted");
          }
        }
        $scope2.$on("refreshCardSelection", (e3, cardIds) => {
          if (cardIds.includes($ctrl.card.id)) {
            selectCard();
          }
        });
        $scope2.$on("selectCards", (e3, cardIds) => {
          if (cardIds.includes($ctrl.card.id)) {
            selectCard();
          }
        });
        $scope2.$on("unselectCard", (e3, cardId) => {
          if (cardId === $ctrl.card.id) {
            unselectCard();
          }
        });
        $scope2.$on("selectAllCards", (e3, cardIds) => {
          if (!cardIds || cardIds.includes($ctrl.card.id)) {
            selectCard();
          }
        });
        $scope2.$on("clearSelectedCards", () => unselectCard());
        function highlightCard(cardIds) {
          $ctrl.highlighted = cardIds.includes($ctrl.card.id);
          if (!$ctrl.selected) {
            $element2.toggleClass("highlighted", $ctrl.highlighted);
          }
        }
        $scope2.$on("highlightCards", (e3, cardIds) => highlightCard(cardIds));
        $scope2.$on("refreshCardHighlight", () => projectPage.isActive && highlightCard(projectPage.highlightedCardIds));
        $scope2.$on("scrollToCard", (e3, cardId) => {
          if ($ctrl.card.id === cardId) {
            $element2.parents(".cards-app-table-inner").scrollTo($element2, 100, { offset: { top: -50 } });
          }
        });
        if ($ctrl.selector) {
          jquery_default($element2).hover((event2) => {
            if (event2.button) {
              return;
            }
            $ctrl.selector.select($ctrl.card);
          }, (event2) => {
            if (event2.button) {
              return;
            }
            if ($ctrl.selector.selected) {
              $ctrl.selector.unselect();
            }
          });
          $ctrl.selector.$on($scope2, $ctrl.card, () => {
            $element2.addClass("hover");
          });
          $ctrl.selector.$off($scope2, () => {
            $element2.removeClass("hover");
          });
        }
        let cancelOpen = false;
        let touchedTimer;
        let touchedAction = false;
        $element2.on("touchstart", () => {
          touchedAction = true;
          cancelOpen = false;
          touchedTimer = setTimeout(() => {
            cancelOpen = true;
          }, 200);
          $element2.addClass("touched");
        });
        $element2.on("touchend", () => {
          touchedAction = false;
          if (touchedTimer) {
            clearTimeout(touchedTimer);
            $element2.removeClass("touched");
            $element2.removeClass("pressed");
          }
        });
        jquery_default($element2).on("click", ".js-open-modal", (e3) => {
          if (e3.ctrlKey && projectPage.isProjectActive($ctrl.project)) {
            if (projectPage.isCardSelected($ctrl.card)) {
              projectPage.unselectCard($ctrl.card);
            } else {
              projectPage.selectCard($ctrl.card);
            }
            $scope2.$applyAsync();
            return;
          }
          if (touchedTimer) {
            clearTimeout(touchedTimer);
            $element2.removeClass("touched");
            $element2.removeClass("pressed");
          }
          if (cancelOpen) {
            return;
          }
          if (jquery_default(e3.target).parents(".cards-app-table-cell.title.editing").length) {
            return;
          }
          if ($ctrl.selector) {
            $ctrl.selector.select($ctrl.card, true);
          }
          cardModal.open($ctrl.card, { parentSelector: $ctrl.selector, showArchived: $ctrl.showArchived });
        });
        jquery_default($element2).on("click", ".cards-app-table-cell.title:not(.editing) > .title > span", (e3) => {
          e3.stopPropagation();
          if (canEditTitle()) {
            startTitleEditor();
          } else {
            if ($ctrl.selector) {
              $ctrl.selector.select($ctrl.card, true);
            }
            cardModal.open($ctrl.card, { parentSelector: $ctrl.selector, showArchived: $ctrl.showArchived });
          }
        });
        $element2.on("contextmenu", (e3) => {
          e3.preventDefault();
          e3.stopPropagation();
          if (cancelOpen) return;
          const elementOffset = jquery_default($element2).offset();
          const contextMenuDropConfig = {
            classes: "card-actions-menu",
            tetherOptions: {
              targetOffset: e3.clientY - elementOffset.top + "px " + (e3.clientX - elementOffset.left) + "px"
            }
          };
          const menu = cardActionsMenuFactory.get($ctrl.card, {
            editable: true,
            hideShareableLink: true,
            hideMakeReccuring: true,
            hideRequest: true,
            dataPrefetched: !$ctrl.card.is_link,
            showSelect: true
          });
          menuDropdown.openContextMenu($element2[0], menu, $scope2, contextMenuDropConfig);
        });
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.columnWidths && !changes.columnWidths.isFirstChange()) {
          updateColumnWidths();
        }
        if (changes.visibleAttributes && !changes.visibleAttributes.isFirstChange()) {
          $timeout2(() => modelChanged());
        }
        if (changes.strikeTitleWhenDone && !changes.strikeTitleWhenDone.isFirstChange()) {
          if ($ctrl.card.finished) {
            $timeout2(() => modelChanged());
          }
        }
      };
      $ctrl.$onDestroy = function() {
        if (cardWatcherOff) cardWatcherOff();
        if (lockOff) lockOff();
        if (modelWatcherOff) modelWatcherOff();
        if (editorScope) stopTitleEditor();
        if (disposeReprListeners) disposeReprListeners();
      };
    }
  ]
});

// public/app/apps/cards/table/ng-components/table.js
angular_default.module("kantree").directive("cardsAppTable", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/table/ng-components/templates/table.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupableMixin, CardsAppAttrVisibilityMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$element", "addAttributeMenuFactory", "$q", "$sanitize"]);
        }
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.withCardSelector = true;
          this.modeOptionsKeyPrefix = "table";
          this.specialFields = !this.board ? ["__project__", "__state__"] : [];
          this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          this.columnSortableOptions = {
            items: ".cards-app-table-cell",
            axis: "x",
            forcePlaceholderSize: true,
            start: (e3, ui) => {
              ui.placeholder.width(ui.helperProportions.width - 1);
            },
            stop: (e3, ui) => {
              this.updateVisibleAttributes(this.visibleAttributes.map(({ name: name2 }) => name2));
            }
          };
          this.sortableTableGroupsOptions = {
            handle: ".group-title",
            distance: 6,
            zIndex: 0,
            axis: "y",
            delay: 100,
            _scrollHelperOptions: {
              scrollable: ".cards-app-table-inner",
              threshold: {
                default: { top: 60, bottom: 60 },
                xs: { top: 30, bottom: 30 }
              },
              tolerance: "cursor"
            },
            on: {
              start: (event2, ui) => {
                ui.helper.css("left", ui.originalPosition.left);
              }
            }
          };
          this.addColumnDropWatchers = (cb2) => {
            return this.$scope.$watch("$ctrl.visibleAttributes", (newVal, oldVal) => {
              if (newVal === oldVal) return;
              cb2();
            });
          };
          this.addColumnDropConfig = {
            _preUpdate: (drop) => {
              const viewportInner = jquery_default(this.$element).find(".cards-app-table-inner");
              if (viewportInner) {
                viewportInner.scrollLeft(viewportInner[0].scrollWidth);
              }
            }
          };
          const attrVisibilityMenuOptions = { specialFields: this.specialFields };
          this.addColumnMenu = {
            config: () => () => {
              const items = getAttrsVisibilityMenuItems(
                this.project,
                this.store,
                this.options,
                attrVisibilityMenuOptions,
                (visibleAttrNames, allAttrsVisible) => this.updateVisibleAttributes(visibleAttrNames, allAttrsVisible)
              );
              if (!this.isLocked() && this.project && canManageAttributes(this.project)) {
                const addAttrMenu = this.$addAttributeMenuFactory.get(null, (attrType) => {
                  this.$q.when(new ModelAttributeGroup(this.project, null, cardModelStore.getExtendedModelAttributes(null, this.project)).create(null, attrType.name, null, null), (attr) => {
                    this.refreshAvailableAttributes();
                    this.toggleAttrVisibility(attr.name);
                  });
                });
                items.push({ label: "--" }, {
                  label: _4("Add field"),
                  icon: "bi-plus-lg",
                  submenu: addAttrMenu.config,
                  options: addAttrMenu.options
                });
              }
              return items;
            },
            options: { watch: getAttrsVisibilityMenuWatcher(this.project, this.store, () => this.options) }
          };
          this.initGroupableMixin();
          this.initAttrVisibilityMixin();
          this.refreshSortBy();
          this.$scope.$on("maximizeAllCards", () => this.$scope.$broadcast("showAllChildren"));
          this.$scope.$on("minimizeAllCards", () => this.$scope.$broadcast("hideAllChildren"));
          const updateColumnWidthOnRename = (newName, oldName) => {
            this.$scope.$applyAsync(() => {
              const widths = { ...this.options?.column_widths };
              if (widths[oldName] || widths[oldName] === 0) {
                widths[newName] = widths[oldName];
                widths[oldName] = null;
                delete widths[oldName];
                this.onChange && this.onChange({ $changes: { options: { ...this.options, column_widths: widths } } });
              }
            });
          };
          onAttributeRenamed.subscribe(updateColumnWidthOnRename);
          onGroupTypeRenamed.subscribe(updateColumnWidthOnRename);
          this.$scope.$on("connectivityChanged", () => {
            this.refreshSortBy();
          });
        }
        $onChanges(changes) {
          const boardChanged = changes.board && !changes.board.isFirstChange();
          const projectChanged = boardChanged && projectStore.tryGetForCard(this.board)?.id !== this.project?.id;
          const groupByChanged = changes.groupBy && !changes.groupBy.isFirstChange();
          const firstGroupByChanged = groupByChanged && !equals2((this.groupBy || [])[0], (changes.groupBy.previousValue || [])[0]);
          const optionsChanged = changes.options && !changes.options.isFirstChange();
          const optionChanged = (optionLabel) => optionsChanged && !equals(this.options?.[optionLabel], changes.options.previousValue?.[optionLabel]);
          if (projectChanged) {
            this.project = this.board ? projectStore.tryGetForCard(this.board) : null;
          }
          if (optionChanged("sort_by") || optionChanged("order_by")) {
            this.refreshSortBy();
          }
          const options2 = ["hideVerticalBorders", "hideHorizontalBorders", "stripedRows"];
          const innerElement = jquery_default(this.$element).find(".cards-app-table-inner");
          for (const opt of options2) {
            if (optionChanged(opt)) {
              innerElement.toggleClass(opt);
            }
          }
          if (optionChanged("rowHeight")) {
            if (changes.options.previousValue?.rowHeight) {
              innerElement.removeClass(changes.options.previousValue.rowHeight);
            }
            if (changes.options.currentValue?.rowHeight) {
              innerElement.toggleClass(changes.options.currentValue.rowHeight);
            }
          }
          if (firstGroupByChanged) {
            this.$element.toggleClass("boxed-groups", this.hasBoxedGroups);
          }
          this.changeGroupableMixin(changes);
          this.changeAttrVisibilityMixin(changes);
        }
        $postLink() {
          const options2 = ["hideVerticalBorders", "hideHorizontalBorders", "rowHeight", "stripedRows"];
          const innerElement = jquery_default(this.$element).find(".cards-app-table-inner");
          for (const opt of options2) {
            if (this.options[opt]) {
              innerElement.addClass(opt === "rowHeight" ? this.options[opt] : opt);
            }
          }
          this.$element.toggleClass("boxed-groups", this.hasBoxedGroups);
          if (this.selector) {
            this.selector.on((item, page) => {
              if (item) {
                this.$element.addClass("has-selection");
              }
            });
            this.selector.off((item, page) => {
              this.$element.removeClass("has-selection");
            });
          }
          const header = jquery_default(this.$element).find(".cards-app-table-header");
          jquery_default(this.$element).find(".cards-app-table-inner").scroll(function() {
            header.css("top", this.scrollTop);
          });
          activateViewScroll(
            this.$element,
            "> .cards-app-table-inner",
            `> .cards-app-table-inner,
            .cards-app-table-body .ui-sortable-groups-items-container,
            .cards-app-table-row.header .cards-app-table-cell:not(.cards-app-table-cell-header)
            `,
            true
          );
        }
        get hasBoxedGroups() {
          return this.groupBy && !this.groupBy[0].isNothing();
        }
        isLocked() {
          return isScreensizeXS() || !isConnected();
        }
        refreshSortBy() {
          const forcedSortBy = !canFreeSort(this.project, this.groupBy, this.options);
          this.sortBy = getSortBy(this.options, forcedSortBy);
        }
        setSortBy(value2, reverse) {
          const newModeOptions = setSortBy(this.options, value2, reverse);
          return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
        }
        startResizingColumn(event2, idx) {
          const cell = jquery_default(event2.target).parents(".cards-app-table-cell");
          const width = cell.outerWidth();
          const columnName = idx === 0 ? "__title__" : this.visibleAttributes[idx - 1].name;
          const screenX = event2.screenX;
          const resize = (event3) => {
            let widths = { ...this.options?.column_widths };
            if (!widths) {
              widths = {};
            }
            const newWidth = Math.max(Math.floor(width + (event3.screenX - screenX)), 100);
            if (widths[columnName] !== newWidth) {
              widths[columnName] = newWidth;
              this.onChange && this.onChange({ $changes: { options: { ...this.options, column_widths: widths } } });
              this.$scope.$applyAsync();
            }
          };
          const endResize = () => {
            jquery_default(document).off("mousemove", resize);
            jquery_default(document).off("mouseup", endResize);
          };
          jquery_default(document).on("mousemove", resize);
          jquery_default(document).on("mouseup", endResize);
        }
        getTableWidth() {
          const columnWidths = this.options?.column_widths || {};
          const refCellWidth = 50;
          const titleCellWidth = Object.keys(columnWidths).includes("__title__") ? Math.max(toInt(columnWidths["__title__"]), 100) : 350;
          let attributeCellWidths = 0;
          for (const attrGroup of this.visibleAttributes) {
            if (Object.keys(columnWidths).includes(attrGroup.name)) {
              attributeCellWidths += Math.max(toInt(columnWidths[attrGroup.name]), 100);
            } else {
              attributeCellWidths += 150;
            }
          }
          return refCellWidth + titleCellWidth + attributeCellWidths + (this.hasBoxedGroups ? 21 : 0);
        }
        getColumWidth(columnName) {
          return Object.keys(this.options?.column_widths || {}).includes(columnName) ? Math.max(toInt(this.options.column_widths[columnName]), 100) : null;
        }
        $onDestroy() {
          this.destroyGroupableMixin();
          this.destroyAttrVisibilityMixin();
        }
      }
    };
  }
]);

// public/app/ui/utils/optimized-window-resize.js
var OptimizedWindowResize = class {
  constructor() {
    this.resizeHandlers = [];
    this.running = false;
    this.windowWidth = window.innerWidth;
    this.windowHeight = window.innerHeight;
    window.addEventListener("resize", () => {
      if (!this.running) {
        this.running = true;
        if (window.requestAnimationFrame) {
          window.requestAnimationFrame(() => this.resizeHandler());
        } else {
          setTimeout(() => this.resizeHandler(), 66);
        }
      }
    });
  }
  resizeHandler() {
    this.windowWidth = window.innerWidth;
    this.windowHeight = window.innerHeight;
    for (let handler of this.resizeHandlers) {
      handler(this.windowWidth, this.windowHeight);
    }
    this.running = false;
  }
  addHandler(handler) {
    if (handler) {
      this.resizeHandlers.push(handler);
    }
  }
  removeHandler(handler) {
    const i3 = this.resizeHandlers.indexOf(handler);
    if (i3 !== -1) {
      this.resizeHandlers.splice(i3, 1);
    }
  }
};
var optimizedWindowResize = new OptimizedWindowResize();

// public/app/apps/cards/timeline/ng-components/base-timeline.js
angular_default.module("kantree").component("timeline", {
  templateUrl: "/static/app/apps/cards/timeline/ng-components/templates/base-timeline.html",
  bindings: {
    dateRange: "<?",
    compactMode: "<?",
    onUpdateObject: "&?",
    onUpdateDateRange: "&?",
    editable: "<?"
  },
  transclude: true,
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$timeout", "$document"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this._DISPLAY_MARGIN = 0;
      this.compactMode = this.compactMode || false;
      this.spanUnit = "days";
      this.dateRange = this.dateRange || {
        start: moment_default().subtract(15, this.spanUnit),
        end: moment_default().add(10, this.spanUnit)
      };
      this.groups = [];
      this.cachedMousePosition = {};
      this.maxScrollPos = {};
      this.infiniteScrollingFatigue = false;
      this.debounceUpdateDateRange = debounce2((range2) => {
        this.$scope.$evalAsync(() => {
          this.lastScrolledRange = range2;
          this.onUpdateDateRange({ $scrolledRange: range2 });
        });
      }, 200);
      this.debounceRefreshUI = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshUI();
        });
      }, 60);
    }
    $onChanges(changes) {
      if (changes.dateRange && !changes.dateRange.isFirstChange()) {
        if (this.dateRange.start.isSame(this.lastScrolledRange.start, "day") && this.dateRange.end.isSame(this.lastScrolledRange.end, "day")) {
          return;
        }
        this.lastScrolledRange = this.dateRange;
        if (this.dateRange.start.isSame(changes.dateRange.previousValue.start, "day") && this.dateRange.end.isSame(changes.dateRange.previousValue.end, "day")) {
          return;
        }
        let needsUIrefresh = false;
        this.dateRangePeriod = this.computeDateRangePeriod(this.dateRange, this.spanUnit);
        const oldDateRangePeriod = changes.dateRange.previousValue.end.diff(changes.dateRange.previousValue.start, this.spanUnit, this.spanUnit !== "days");
        if (this.dateRangePeriod !== oldDateRangePeriod) {
          needsUIrefresh = true;
          this.setSpanUnitWidth();
        }
        if (this.dateRange.start.isSameOrBefore(this.totalDateRange.start)) {
          needsUIrefresh = true;
          this.totalDateRange = Object.assign({}, this.totalDateRange, {
            start: this.dateRange.start.clone().subtract(this.dateRangePeriod, this.spanUnit).startOf("months").startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit)
          });
        }
        if (this.dateRange.end.isSameOrAfter(this.totalDateRange.end)) {
          needsUIrefresh = true;
          this.totalDateRange = Object.assign({}, this.totalDateRange, {
            end: this.dateRange.end.clone().add(this.dateRangePeriod, this.spanUnit).startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit)
          });
        }
        if (needsUIrefresh) {
          this.refreshUI();
        }
        this.$timeout(() => this.scrollToDateRange(), 0, false);
      }
      if (changes.compactMode && !changes.compactMode.isFirstChange()) {
        this.$timeout(() => {
          this.setContainerWidth();
          this.setSpanUnitWidth();
          this.debounceRefreshUI();
          this.scrollToDateRange();
        }, 0, false);
      }
    }
    $postLink() {
      this.$element.addClass("timeline");
      this.setContainerWidth();
      this.setSpanUnitWidth();
      this.dateRangePeriod = this.computeDateRangePeriod(this.dateRange, this.spanUnit);
      this.totalDateRange = {
        start: this.dateRange.start.clone().subtract(this.dateRangePeriod, this.spanUnit).startOf("months").startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit),
        end: this.dateRange.end.clone().add(this.dateRangePeriod, this.spanUnit).startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit)
      };
      this.refreshUI();
      this.$timeout(() => this.updateBackgroundHeight(), 1e3, false);
      this.$timeout(() => this.scrollToDateRange(), 0, false);
      this._onScroll = (event2) => this.onScroll(event2);
      this._onWheel = (event2) => this.onWheel(event2);
      this._onResize = (event2) => this.onResize(event2);
      this.containerElement.on("scroll", this._onScroll);
      this.containerElement.on("wheel", this._onWheel);
      optimizedWindowResize.addHandler(this._onResize);
    }
    $onDestroy() {
      this.containerElement.off("scroll", this._onScroll);
      this.containerElement.off("wheel", this._onWheel);
      optimizedWindowResize.removeHandler(this._onResize);
    }
    applyObjectChange(newObject, oldObject) {
      this.onUpdateObject({
        $data: { newObject, oldObject }
      });
    }
    get containerElement() {
      if (!this._containerElement) {
        this._containerElement = jquery_default(this.$element).find(".timeline-container");
      }
      return this._containerElement;
    }
    get backgroundElement() {
      if (!this._backgroundElement) {
        this._backgroundElement = jquery_default(this.$element).find(".timeline-background");
      }
      return this._backgroundElement;
    }
    get datesElement() {
      if (!this._datesElement) {
        this._datesElement = jquery_default(this.$element).find(".timeline-dates");
      }
      return this._datesElement;
    }
    get viewportElement() {
      if (!this._viewportElement) {
        this._viewportElement = jquery_default(this.$element).find(".timeline-viewport");
      }
      return this._viewportElement;
    }
    get maxScrollLeft() {
      return this.containerElement.get(0).scrollWidth - this.containerElement.get(0).clientWidth;
    }
    getObjectPosition(object2) {
      return this.getDateRangePosition(object2.dateRange);
    }
    getDateRangePosition(dateRange) {
      let period = this.computeDateRangePeriod(dateRange, this.spanUnit);
      if (this.spanUnit === "days") {
        period += 1;
      }
      const leftPos = dateRange.start.diff(this.totalDateRange.start.clone().startOf("day"), this.spanUnit, this.spanUnit !== "days");
      return {
        left: leftPos * this.minSpanWidth,
        width: period * this.minSpanWidth
      };
    }
    computeDateRangePeriod(dateRange, spanUnit) {
      return dateRange.end.diff(dateRange.start, spanUnit, spanUnit !== "days");
    }
    setContainerWidth() {
      this.containerWidth = this.containerElement.width();
    }
    setSpanUnitWidth() {
      const dayWidth = (this.containerWidth - this._DISPLAY_MARGIN * 2) / (this.computeDateRangePeriod(this.dateRange, "days") + 1);
      const previousSpanUnit = this.spanUnit;
      if (dayWidth < 6) {
        this.spanUnit = "months";
        this.currentSpanLabel = _4("This month");
        this.minSpanWidth = Math.floor((this.containerWidth - this._DISPLAY_MARGIN * 2) / this.computeDateRangePeriod(this.dateRange, "months"));
      } else if (dayWidth < 9) {
        this.spanUnit = "weeks";
        this.currentSpanLabel = _4("This week");
        this.minSpanWidth = Math.floor((this.containerWidth - this._DISPLAY_MARGIN * 2) / this.computeDateRangePeriod(this.dateRange, "weeks"));
      } else {
        this.spanUnit = "days";
        this.currentSpanLabel = _4("Today");
        this.minSpanWidth = Math.floor(dayWidth);
      }
      if (previousSpanUnit !== this.spanUnit) {
        this.dateRangePeriod = this.computeDateRangePeriod(this.dateRange, this.spanUnit);
        this.totalDateRange = {
          start: this.dateRange.start.clone().subtract(this.dateRangePeriod, this.spanUnit).startOf("months").startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit),
          end: this.dateRange.end.clone().add(this.dateRangePeriod, this.spanUnit).startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit)
        };
      }
    }
    // UI
    refreshUI(withBackgroundHeight) {
      this.updateBackground(this.totalDateRange);
      this.updateDates(this.totalDateRange);
      this.updateViewportWidth();
      if (withBackgroundHeight) {
        this.updateBackgroundHeight();
      }
    }
    updateBackground(dateRange) {
      const start = dateRange.start.clone();
      const end = dateRange.end.clone();
      const fragment = document.createDocumentFragment();
      while (start.isBefore(end)) {
        const el2 = document.createElement("span");
        let classes = "";
        el2.style.width = this.minSpanWidth + "px";
        if (start.isSame(moment_default(), this.spanUnit)) {
          classes += " current";
        }
        if (this.spanUnit === "days") {
          const dayOfWeek = start.day();
          const isDayOff = dayOfWeek === 6 || dayOfWeek === 0;
          if (isDayOff) {
            el2.style.backgroundColor = "#f8f8f8";
          }
          if (this.minSpanWidth > 20 || this.minSpanWidth <= 20 && this.minSpanWidth > 8 && dayOfWeek === 0 || this.minSpanWidth <= 8 && start.date() === 1) {
            classes += " with-separator";
          }
          if (start.date() === 1 && this.minSpanWidth > 20) {
            classes += " with-month";
          }
        } else if (this.spanUnit === "weeks") {
          const elWeekNumber = document.createElement("span");
          elWeekNumber.className = "first-day-of-week";
          elWeekNumber.innerText = start.format("W");
          el2.appendChild(elWeekNumber);
          classes += " with-separator";
        } else if (this.spanUnit === "months") {
          classes += " with-separator";
        }
        el2.className = classes;
        fragment.appendChild(el2);
        start.add(1, this.spanUnit);
      }
      this.backgroundElement[0].innerHTML = "";
      this.backgroundElement[0].appendChild(fragment);
    }
    updateDates(dateRange) {
      const start = dateRange.start.clone();
      const end = dateRange.end.clone();
      const fragment = document.createDocumentFragment();
      while (start.isBefore(end)) {
        const el2 = document.createElement("span");
        const elContent = document.createElement("span");
        const width = this.minSpanWidth;
        let classes = "";
        const isCurrentSpanUnit = start.isSame(moment_default(), this.spanUnit);
        if (isCurrentSpanUnit) {
          classes = "current";
        }
        el2.style.width = width + "px";
        if (this.spanUnit === "days") {
          const dayOfWeek = start.day();
          const isDayOff = dayOfWeek === 6 || dayOfWeek === 0;
          if (isDayOff && this.minSpanWidth > 8) {
            el2.style.color = "#b2b2b2";
            el2.style.backgroundColor = "#f2f2f2";
          }
          if (start.date() === 1 && this.minSpanWidth > 20) {
            const elMontName = document.createElement("span");
            elMontName.className = "month-name";
            elMontName.innerText = start.format("MMMM YYYY");
            classes += " with-month";
            el2.appendChild(elMontName);
          }
          if (isCurrentSpanUnit) {
            elContent.innerText = start.format("D");
          } else {
            if (this.minSpanWidth <= 8) {
              if (start.date() === 1) {
                elContent.innerText = start.format("ll").slice(0, -5);
                classes += " first-day-of-week";
              }
            } else if (this.minSpanWidth <= 20) {
              if (dayOfWeek === 1) {
                elContent.innerText = start.format("ll").slice(0, -5);
                classes += " first-day-of-week";
              }
            } else {
              elContent.innerText = start.format("D");
            }
          }
          el2.appendChild(elContent);
        } else if (this.spanUnit === "weeks") {
          classes += " week";
          elContent.innerText = start.clone().startOf("isoWeek").format("ll").slice(0, -5);
          el2.appendChild(elContent);
        } else if (this.spanUnit === "months") {
          classes += " month";
          elContent.innerText = start.format(start.month() === 0 ? "MMMM YYYY" : "MMMM");
          el2.appendChild(elContent);
        }
        el2.className = classes;
        fragment.appendChild(el2);
        start.add(1, this.spanUnit);
      }
      this.datesElement[0].innerHTML = "";
      this.datesElement[0].appendChild(fragment);
    }
    updateViewportWidth() {
      const totalDateRangePeriodInDays = this.computeDateRangePeriod(this.totalDateRange, this.spanUnit);
      const viewportWidth = this.minSpanWidth * totalDateRangePeriodInDays;
      this.viewportElement.width(viewportWidth + "px");
    }
    updateBackgroundHeight() {
      const scrollbarThickness = 22;
      const timelineHeight = jquery_default(this.$element).height();
      this.backgroundElement.height(timelineHeight - scrollbarThickness);
    }
    // SCROLLING UTILS
    // depending on span Unit, current can be a day, a week, or a month
    scrollToSpan(current) {
      const currentPos = current.diff(this.totalDateRange.start, this.spanUnit) * this.minSpanWidth;
      this.containerElement.scrollLeft(Math.min(currentPos - this.containerElement[0].clientWidth / 2, this.maxScrollLeft));
    }
    scrollToCurrent() {
      this.scrollToSpan(moment_default().startOf(this.spanUnit));
    }
    scrollToObject(object2) {
      const objectDateRangePeriod = object2.dateRange.end.diff(object2.dateRange.start, this.spanUnit) + 1;
      const center = object2.dateRange.start.clone().add(Math.round(objectDateRangePeriod / 2), this.spanUnit);
      this.scrollToSpan(center.startOf(this.spanUnit));
    }
    scrollToDateRange() {
      const distanceFromBeginning = this.dateRange.start.diff(this.totalDateRange.start, this.spanUnit, this.spanUnit !== "days") * this.minSpanWidth;
      this.containerElement.scrollLeft(Math.min(this.maxScrollLeft, Math.max(0, distanceFromBeginning - this._DISPLAY_MARGIN)));
    }
    onScroll() {
      requestAnimationFrame(() => {
        const scrollTop = this.containerElement.scrollTop();
        this.backgroundElement.css({
          "margin-top": scrollTop
        });
        this.datesElement.css({
          "margin-top": scrollTop
        });
        if (this.spanUnit === "days" && this.minSpanWidth > 20) {
          this.refreshMonthNamesPosition();
        }
      });
      const scrollLeft = this.containerElement.scrollLeft();
      if (scrollLeft === this.scrollLeft) return;
      this.scrollLeft = scrollLeft;
      this.$scope.$evalAsync(() => {
        const currentPos = moment_default().startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit).diff(this.totalDateRange.start, this.spanUnit) * Math.floor(this.minSpanWidth);
        if (currentPos + Math.floor(this.minSpanWidth) < scrollLeft) {
          this.currentScrolledToLeft = true;
        } else if (currentPos > scrollLeft + this.containerElement.get(0).clientWidth) {
          this.currentScrolledToRight = true;
        } else {
          this.currentScrolledToLeft = false;
          this.currentScrolledToRight = false;
        }
        const newDateRangeStartDiff = scrollLeft ? Math.floor(scrollLeft / this.minSpanWidth) : 0;
        const newDateRangeEndDiff = newDateRangeStartDiff + this.computeDateRangePeriod(this.dateRange, this.spanUnit);
        const dateRange = {
          start: this.totalDateRange.start.clone().add(newDateRangeStartDiff, this.spanUnit),
          end: this.totalDateRange.start.clone().add(newDateRangeEndDiff, this.spanUnit)
        };
        if (this.onUpdateDateRange) {
          this.debounceUpdateDateRange(dateRange);
        }
        {
          this.dateRange = dateRange;
          this.dateRangePeriod = this.computeDateRangePeriod(this.dateRange, this.spanUnit);
        }
        if (this.infiniteScrollingFatigue) {
          return;
        }
        let needRefreshUI = false;
        if (scrollLeft <= 0) {
          needRefreshUI = true;
          this.totalDateRange = Object.assign({}, this.totalDateRange, {
            start: this.totalDateRange.start.clone().subtract(this.dateRangePeriod, this.spanUnit).startOf("months").startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit)
          });
        } else if (scrollLeft >= this.maxScrollLeft) {
          needRefreshUI = true;
          this.totalDateRange = Object.assign({}, this.totalDateRange, {
            end: this.totalDateRange.end.clone().add(this.dateRangePeriod, this.spanUnit).startOf(this.spanUnit === "weeks" ? "isoWeek" : this.spanUnit)
          });
        }
        if (needRefreshUI) {
          this.refreshUI();
          if (this._IStimer) {
            this.$timeout.cancel(this._IStimer);
          }
          this.infiniteScrollingFatigue = true;
          this._IStimer = this.$timeout(() => {
            this.infiniteScrollingFatigue = false;
          }, 200, false);
          this.$timeout(() => this.scrollToDateRange(), 0, false);
        }
      });
    }
    refreshMonthNamesPosition() {
      const startYear = this.totalDateRange.start.year();
      const endYear = this.totalDateRange.end.year();
      const startMonth = this.totalDateRange.start.month();
      const endMonth = this.totalDateRange.end.month() + (endYear - startYear) * 12;
      const monthFirstDaysPositions = new Array(endMonth - startMonth + 1).fill(void 0).map((_5, i3) => i3 + startMonth).map((month) => {
        return this.totalDateRange.start.clone().month(month).startOf("months").startOf("days").diff(this.totalDateRange.start, this.spanUnit);
      }).filter((diff) => diff >= 0).map((diff) => diff * Math.floor(this.minSpanWidth));
      this.datesElement.find("> .with-month").toArray().forEach((dateElement, index2) => {
        const monthPosition = monthFirstDaysPositions[index2];
        const monthNameElement = jquery_default(dateElement).find(".month-name");
        if (monthPosition < this.scrollLeft) {
          const nextMonthPosition = monthFirstDaysPositions[index2 + 1];
          monthNameElement.css({
            "margin-left": (nextMonthPosition ? Math.min(this.scrollLeft, nextMonthPosition - monthNameElement[0].offsetWidth - 10) : this.scrollLeft) - monthPosition
          });
        } else {
          monthNameElement.removeAttr("style");
        }
      });
    }
    onResize() {
      this.$scope.$evalAsync(() => {
        this.setContainerWidth();
        this.setSpanUnitWidth();
        this.refreshUI(true);
        this.scrollToDateRange();
      });
    }
    onWheel(event2) {
      if (event2.shiftKey) {
        event2.stopPropagation();
        this.containerElement.scrollLeft(this.scrollLeft + event2.originalEvent.deltaY);
      }
    }
  }
});

// public/app/apps/cards/timeline/ng-components/mouse-drag-scrollable-container.js
angular_default.module("kantree").component("mouseDragScrollableContainer", {
  template: "<ng-transclude></ng-transclude>",
  bindings: {
    dragDisabled: "<"
  },
  transclude: true,
  controller: class extends AngularClass {
    static $inject = ["$element", "$document"];
    $onInit() {
      this.maxScrollPos = {};
      this.cachedMousePosition = {};
      this.onMouseDown = (event2) => this.start(event2);
      this.onMouseMove = (event2) => this.drag(event2);
      this.onMouseUp = (event2) => this.end(event2);
    }
    $postLink() {
      this.$element.on("mousedown", this.onMouseDown);
    }
    $onDestroy() {
      this.$element.off("mousedown", this.onMouseDown);
    }
    start(event2) {
      if (this.dragDisabled) return;
      this.maxScrollPos = {
        x: this.$element[0].scrollWidth - this.$element[0].clientWidth,
        y: this.$element[0].scrollHeight - this.$element[0].clientHeight
      };
      if (this.maxScrollPos.x > 0) {
        this.cachedMousePosition.x = event2.pageX;
      }
      if (this.maxScrollPos.y > 0) {
        this.cachedMousePosition.y = event2.pageY;
      }
      if (this.maxScrollPos.x > 0 || this.maxScrollPos.y > 0) {
        jquery_default("body").addClass("mouse-drag-scrolling");
        this.$document.on("mousemove", this.onMouseMove);
        this.$document.on("mouseup", this.onMouseUp);
      }
    }
    drag(event2) {
      event2.stopPropagation();
      event2.preventDefault();
      const mousePosition = {
        x: this.maxScrollPos.x > 0 ? event2.pageX : void 0,
        y: this.maxScrollPos.y > 0 ? event2.pageY : void 0
      };
      const delta = {
        x: this.maxScrollPos.x > 0 ? this.cachedMousePosition.x - mousePosition.x : void 0,
        y: this.maxScrollPos.y > 0 ? this.cachedMousePosition.y - mousePosition.y : void 0
      };
      const scrollPos = {
        x: this.maxScrollPos.x > 0 ? this.$element.scrollLeft() : void 0,
        y: this.maxScrollPos.y > 0 ? this.$element.scrollTop() : void 0
      };
      const isScrollable = {
        x: this.maxScrollPos.x > 0 ? delta.x > 0 && scrollPos.x < this.maxScrollPos.x || delta.x < 0 && scrollPos.x > 0 : false,
        y: this.maxScrollPos.y > 0 ? delta.y > 0 && scrollPos.y < this.maxScrollPos.y || delta.y < 0 && scrollPos.y > 0 : false
      };
      if (isScrollable.x) {
        this.$element.scrollLeft(scrollPos.x + delta.x);
      }
      if (isScrollable.y) {
        this.$element.scrollTop(scrollPos.y + delta.y);
      }
      this.cachedMousePosition = mousePosition;
    }
    end() {
      this.cachedMousePosition = {};
      this.maxScrollPos = {};
      jquery_default("body").removeClass("mouse-drag-scrolling");
      this.$document.off("mousemove", this.onMouseMove);
      this.$document.off("mouseup", this.onMouseUp);
    }
  }
});

// public/app/apps/cards/timeline/ng-components/nav.js
angular_default.module("kantree").component("cardsAppNavTimeline", {
  templateUrl: "/static/app/apps/cards/timeline/ng-components/templates/nav.html",
  bindings: {
    mode: "<?",
    board: "<?",
    store: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    groupByChoices: "<",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$rootScope", "$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.pickerOptions = {
        opens: "center",
        autoApply: true,
        ranges: this.getPickerRanges(),
        showCustomRangeLabel: false,
        alwaysShowCalendars: true
      };
      this.refreshDateRange();
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const optionChanged = (optionLabel) => optionsChanged && !equals((this.options || {})[optionLabel], (changes.options.previousValue || {})[optionLabel]);
      if (optionChanged("dateRange") || optionChanged("compactMode")) {
        this.refreshDateRange();
      }
    }
    refreshDateRange() {
      const localDateRange = (this.options || {}).dateRange || DEFAULT_PERIOD;
      this.dateRange = {
        start: moment_default(localDateRange.start),
        end: moment_default(localDateRange.end)
      };
    }
    updateDateRange(range2) {
      if (isDateRangesEqual(this.dateRange, range2)) return;
      const newDate = formatPeriodToString(range2);
      const newModeOptions = { ...this.options };
      newModeOptions["dateRange"] = newDate;
      return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
    }
    getPickerRanges() {
      const ranges = {};
      for (let date of specialDateRanges) {
        ranges[date.displayedName] = [date.startDate, date.endDate];
      }
      return ranges;
    }
    updateDate(start, end) {
      const activeRange = dateRangeToActiveRange({ start, end });
      this.updateDateRange(activeRange);
    }
  }
});

// public/app/apps/cards/timeline/ng-components/sidebar-group.js
angular_default.module("kantree").directive("cardsAppTimelineSidebarGroup", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<?",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        sortChoices: "<?",
        hideHeader: "<?",
        onChange: "&?"
      },
      require: {
        cardsAppTimeline: "^^cardsAppTimeline"
      },
      templateUrl: "/static/app/apps/cards/timeline/ng-components/templates/sidebar-group.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin, CardsAppCardCreatorMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element", "$rootScope"]);
        }
        $onInit() {
          this.modeOptionsKeyPrefix = "timeline_group_";
          this.groupColorTheme = "/static/app/apps/cards/timeline/ng-components/templates/timeline-group-color.css.html";
          this.handleCards = true;
          this.freeSortDisabled = true;
          this.timelineSpec = {
            watch: (scope, callback) => {
              return this.$scope.$watch("$ctrl.cardsAppTimeline.activeDateAttribute", (newVal, oldVal) => {
                if (availablesEquals(newVal, oldVal)) return;
                callback();
              });
            },
            filterChildrenPredicate: (card) => {
              return areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute);
            },
            goToCard: (card) => {
              const activeAttr = this.cardsAppTimeline.activeDateAttribute;
              if (!activeAttr) return;
              const attr = getCardAvailableAttributes(card, activeAttr)[0];
              if (!attr) return;
              const dateRange = extractCardDateRangeFromAttribute(card, attr);
              if (dateRange) {
                this.cardsAppTimeline.centerTimelineOnDateRange(dateRange);
              }
            },
            cardHasDateRange: (card) => {
              const activeAttr = this.cardsAppTimeline.activeDateAttribute;
              if (!activeAttr) return false;
              return getCardAvailableAttributes(card, activeAttr).some((attr) => {
                return extractCardDateRangeFromAttribute(card, attr, { parse: false });
              });
            }
          };
          this.$scope.$watch("$ctrl.cardsAppTimeline.activeDateAttribute", (newVal, oldVal) => {
            if (availablesEquals(newVal, oldVal)) return;
            this.refreshCardsWatcher();
          });
          this.initGroupMixin();
          this.initCardCreatorMixin();
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
          this.changeCardCreatorMixin(changes);
        }
        // OVERWRITES MIXIN METHOD
        queryCards() {
          return sortCardQuery(this.cardStore.query(), this.sortBy, !this.group, {
            modelStore: getScopedModelStore(this.project, this.cardStore),
            groupTypeStore: getScopedGroupTypeStore(this.project, this.cardStore)
          }).filter((card) => areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute));
        }
        // OVERWRITES MIXIN METHOD
        get _allCards() {
          return (this.shouldRenderFilteredCards ? this.cards || [] : this.formatStore(true).query()).filter(
            (card) => areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute)
          );
        }
        // OVERWRITES MIXIN METHOD
        get _matchingCards() {
          return (this.shouldRenderFilteredCards && this.filtered && Array.isArray(this.matchingCardIds) ? (this.cards || []).filter((c3) => this.matchingCardIds.includes(c3.id)) : this.cards || []).filter(
            (card) => areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute)
          );
        }
        onToggleChildren(card, toggleState) {
          this.$rootScope.$broadcast("project-timeline-card:toggleChildren", card.id, toggleState);
        }
        onEditingCard() {
          const height = jquery_default(this.$element).find("cards-app-card-creator").height();
          this.$rootScope.$broadcast("project-timeline-group:addingCard", this.group, this.title, height);
        }
        $onDestroy() {
          this.destroyGroupMixin();
          this.destroyCardCreatorMixin();
          if (this._cardStoreWatcherOff) {
            this._cardStoreWatcherOff();
          }
        }
      }
    };
  }
]);

// public/app/apps/cards/timeline/compact-row.js
var defaultRowHeight = 39;
function getDefaultRowHeight(isSubcard) {
  var height = defaultRowHeight;
  if (isSubcard) {
    height -= 10;
  }
  return height;
}
function buildCompactRows(store2, options2) {
  if (!store2 || !store2.count()) {
    return [];
  }
  options2 = options2 || {};
  return store2.query().filter(function(obj) {
    return !!obj.globalDateRange;
  }).sort(function(a3, b3) {
    return a3.globalDateRange.start.valueOf() - b3.globalDateRange.start.valueOf();
  }).reduce(function(accu, obj, idx) {
    if (idx === 0) {
      obj = store2.update(obj, { row: 0, height: obj.height || getDefaultRowHeight(options2.subCards) });
      accu.push({
        height: obj.height,
        objects: [obj]
      });
      return accu;
    }
    for (var i3 = 0; i3 < accu.length; i3++) {
      var rowObjects = accu[i3].objects;
      var lastObjEndDate = rowObjects[rowObjects.length - 1].globalDateRange.end.clone().endOf("day");
      var objStartDate = obj.globalDateRange.start;
      if (lastObjEndDate.valueOf() <= objStartDate.valueOf()) {
        obj = store2.update(obj, { row: i3, height: obj.height || getDefaultRowHeight(options2.subCards) });
        accu[i3].objects.push(obj);
        accu[i3].height = Math.max(accu[i3].height, obj.height);
        return accu;
      }
    }
    obj = store2.update(obj, { row: accu.length, height: obj.height || getDefaultRowHeight(options2.subCards) });
    accu.push({
      height: obj.height,
      objects: [obj]
    });
    return accu;
  }, []);
}

// public/app/apps/cards/timeline/inject-timeline-controls.js
function injectTimelineControls($ctrl, $scope2, $element2) {
  var creationDragInitState = null;
  var onCreationDraggingStart = function(event2) {
    if (!$ctrl.object.dateRange && !event2.shiftKey) {
      $scope2.$apply(function() {
        $ctrl.timeline.isObjectDragging = true;
        $element2.addClass("dragging-timeline-object");
        jquery_default("body").addClass("timeline-object-creating");
        var elementOffset = jquery_default($element2).find("> .timeline-object").offset().left;
        var momentDiffRounded = Math.floor((event2.pageX - elementOffset) / $ctrl.timeline.minSpanWidth);
        creationDragInitState = {
          offset: momentDiffRounded * $ctrl.timeline.minSpanWidth + elementOffset,
          left: momentDiffRounded * $ctrl.timeline.minSpanWidth,
          date: $ctrl.timeline.totalDateRange.start.clone().startOf($ctrl.timeline.spanUnit === "weeks" ? "isoWeek" : $ctrl.timeline.spanUnit).add(momentDiffRounded, $ctrl.timeline.spanUnit),
          object: Object.assign({}, $ctrl.object)
        };
        $ctrl.position = {
          left: creationDragInitState.left,
          width: $ctrl.timeline.minSpanWidth * 1
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: creationDragInitState.date,
            end: creationDragInitState.date.clone().endOf($ctrl.timeline.spanUnit === "weeks" ? "isoWeek" : $ctrl.timeline.spanUnit)
          }
        });
        jquery_default(document).on("mousemove", onCreationDragging);
        jquery_default(document).on("mouseup", onCreationDraggingEnd);
      });
    }
  };
  var onCreationDragging = function(event2) {
    event2.stopPropagation();
    event2.preventDefault();
    $scope2.$apply(function() {
      var mousePos = event2.pageX;
      var momentDiff = Math.floor((mousePos - creationDragInitState.offset) / $ctrl.timeline.minSpanWidth);
      if (momentDiff > 0) {
        $ctrl.position = {
          left: creationDragInitState.left,
          width: $ctrl.timeline.minSpanWidth * (momentDiff + 1)
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: creationDragInitState.date,
            end: creationDragInitState.date.clone().add(momentDiff, $ctrl.timeline.spanUnit).endOf($ctrl.timeline.spanUnit === "weeks" ? "isoWeek" : $ctrl.timeline.spanUnit)
          }
        });
      } else if (momentDiff < 0) {
        $ctrl.position = {
          left: creationDragInitState.left + $ctrl.timeline.minSpanWidth * momentDiff,
          width: $ctrl.timeline.minSpanWidth * -momentDiff
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: creationDragInitState.date.clone().subtract(-momentDiff, $ctrl.timeline.spanUnit),
            end: creationDragInitState.date.clone().subtract(1, $ctrl.timeline.spanUnit).endOf($ctrl.timeline.spanUnit === "weeks" ? "isoWeek" : $ctrl.timeline.spanUnit)
          }
        });
      } else if (momentDiff === 0) {
        $ctrl.position = {
          left: creationDragInitState.left,
          width: $ctrl.timeline.minSpanWidth * 1
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: creationDragInitState.date,
            end: creationDragInitState.date.clone().endOf($ctrl.timeline.spanUnit === "weeks" ? "isoWeek" : $ctrl.timeline.spanUnit)
          }
        });
      }
    });
  };
  var onCreationDraggingEnd = function(event2) {
    $scope2.$apply(function() {
      $ctrl.timeline.isObjectDragging = false;
      $element2.removeClass("dragging-timeline-object");
      if ($ctrl.object.dateRange && !$ctrl.object.dateRange.start.isAfter($ctrl.object.dateRange.end, $ctrl.timeline.spanUnit)) {
        $ctrl.parentStore.update({ id: $ctrl.object.id }, { dateRange: $ctrl.object.dateRange });
        $ctrl.timeline.applyObjectChange($ctrl.object, creationDragInitState.object);
      }
    });
    jquery_default("body").removeClass("timeline-object-creating");
    creationDragInitState = null;
    jquery_default(document).off("mousemove", onCreationDragging);
    jquery_default(document).off("mouseup", onCreationDraggingEnd);
  };
  var fullDragInitState = null;
  var onFullDraggingStart = function(event2) {
    if (!event2.shiftKey) {
      $scope2.$apply(function() {
        $ctrl.timeline.isObjectDragging = true;
        $element2.addClass("dragging-timeline-object");
      });
      jquery_default("body").addClass("timeline-object-full-dragging");
      fullDragInitState = {
        offset: event2.pageX,
        left: $ctrl.position.left,
        object: Object.assign({}, $ctrl.object)
      };
      jquery_default(document).on("mousemove", onFullDragging);
      jquery_default(document).on("mouseup", onFullDraggingEnd);
    }
  };
  var onFullDragging = function(event2) {
    event2.stopPropagation();
    event2.preventDefault();
    $scope2.$apply(function() {
      var momentDiff = Math.round((event2.pageX - fullDragInitState.offset) / $ctrl.timeline.minSpanWidth);
      var newLeft = fullDragInitState.left + $ctrl.timeline.minSpanWidth * momentDiff;
      if (newLeft >= 0) {
        $ctrl.position = {
          left: newLeft,
          width: $ctrl.position.width
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: fullDragInitState.object.dateRange.start.clone().add(momentDiff, $ctrl.timeline.spanUnit),
            end: fullDragInitState.object.dateRange.end.clone().add(momentDiff, $ctrl.timeline.spanUnit)
          }
        });
      }
    });
  };
  var onFullDraggingEnd = function(event2) {
    $scope2.$apply(function() {
      $ctrl.timeline.isObjectDragging = false;
      $element2.removeClass("dragging-timeline-object");
      if (!$ctrl.object.dateRange.start.isSame(fullDragInitState.object.dateRange.start, $ctrl.timeline.spanUnit)) {
        $ctrl.parentStore.update({ id: $ctrl.object.id }, { dateRange: $ctrl.object.dateRange });
        $ctrl.timeline.applyObjectChange($ctrl.object, fullDragInitState.object);
      }
    });
    jquery_default("body").removeClass("timeline-object-full-dragging");
    fullDragInitState = null;
    jquery_default(document).off("mousemove", onFullDragging);
    jquery_default(document).off("mouseup", onFullDraggingEnd);
  };
  var leftDragInitState = null;
  var onLeftDraggingStart = function(event2) {
    if (!event2.shiftKey) {
      $scope2.$apply(function() {
        $ctrl.timeline.isObjectDragging = true;
        $element2.addClass("dragging-timeline-object");
      });
      jquery_default("body").addClass("timeline-object-left-resizing");
      leftDragInitState = {
        offset: jquery_default($element2).find("> .timeline-object .timeline-object-container").offset().left,
        left: $ctrl.position.left,
        width: $ctrl.position.width,
        object: Object.assign({}, $ctrl.object)
      };
      jquery_default(document).on("mousemove", onLeftDragging);
      jquery_default(document).on("mouseup", onLeftDraggingEnd);
    }
  };
  var onLeftDragging = function(event2) {
    event2.stopPropagation();
    event2.preventDefault();
    $scope2.$apply(function() {
      var mousePos = event2.pageX;
      var momentDiff = Math.round((leftDragInitState.offset - mousePos) / $ctrl.timeline.minSpanWidth);
      var changeInPx = $ctrl.timeline.minSpanWidth * momentDiff;
      var newWidth = Math.max(0, leftDragInitState.width + changeInPx);
      if ($ctrl.position.width !== newWidth) {
        $ctrl.position = {
          left: Math.min(leftDragInitState.left - changeInPx, leftDragInitState.left + leftDragInitState.width),
          width: newWidth
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: leftDragInitState.object.dateRange.start.clone().add(-momentDiff, $ctrl.timeline.spanUnit),
            end: $ctrl.object.dateRange.end.clone()
          }
        });
      }
    });
  };
  var onLeftDraggingEnd = function(event2) {
    $scope2.$apply(function() {
      $ctrl.timeline.isObjectDragging = false;
      $element2.removeClass("dragging-timeline-object");
      if (!$ctrl.object.dateRange.start.isSame(leftDragInitState.object.dateRange.start, $ctrl.timeline.spanUnit)) {
        $ctrl.parentStore.update({ id: $ctrl.object.id }, { dateRange: $ctrl.object.dateRange });
        $ctrl.timeline.applyObjectChange($ctrl.object, leftDragInitState.object);
      }
    });
    jquery_default("body").removeClass("timeline-object-left-resizing");
    leftDragInitState = null;
    jquery_default(document).off("mousemove", onLeftDragging);
    jquery_default(document).off("mouseup", onLeftDraggingEnd);
  };
  var rightDragInitState = null;
  var onRightDraggingStart = function(event2) {
    if (!event2.shiftKey) {
      $scope2.$apply(function() {
        $ctrl.timeline.isObjectDragging = true;
        $element2.addClass("dragging-timeline-object");
      });
      jquery_default("body").addClass("timeline-object-right-resizing");
      rightDragInitState = {
        offset: jquery_default($element2).find("> .timeline-object .timeline-object-container").offset().left + $ctrl.position.width,
        width: $ctrl.position.width,
        object: Object.assign({}, $ctrl.object)
      };
      jquery_default(document).on("mousemove", onRightDragging);
      jquery_default(document).on("mouseup", onRightDraggingEnd);
    }
  };
  var onRightDragging = function(event2) {
    event2.stopPropagation();
    event2.preventDefault();
    $scope2.$apply(function() {
      var mousePos = event2.pageX;
      var momentDiff = Math.round((mousePos - rightDragInitState.offset) / $ctrl.timeline.minSpanWidth);
      var changeInPx = $ctrl.timeline.minSpanWidth * momentDiff;
      var newWidth = Math.max(0, rightDragInitState.width + changeInPx);
      if ($ctrl.position.width !== newWidth) {
        $ctrl.position = {
          left: $ctrl.position.left,
          width: newWidth
        };
        $ctrl.object = Object.assign({}, $ctrl.object, {
          dateRange: {
            start: $ctrl.object.dateRange.start.clone(),
            end: rightDragInitState.object.dateRange.end.clone().add(momentDiff, $ctrl.timeline.spanUnit)
          }
        });
      }
    });
  };
  var onRightDraggingEnd = function(event2) {
    $scope2.$apply(function() {
      $ctrl.timeline.isObjectDragging = false;
      $element2.removeClass("dragging-timeline-object");
      if (!$ctrl.object.dateRange.end.isSame(rightDragInitState.object.dateRange.end, $ctrl.timeline.spanUnit)) {
        $ctrl.parentStore.update({ id: $ctrl.object.id }, { dateRange: $ctrl.object.dateRange });
        $ctrl.timeline.applyObjectChange($ctrl.object, rightDragInitState.object);
      }
    });
    jquery_default("body").removeClass("timeline-object-right-resizing");
    rightDragInitState = null;
    jquery_default(document).off("mousemove", onRightDragging);
    jquery_default(document).off("mouseup", onRightDraggingEnd);
  };
  var editableWatcherOff = $scope2.$watch(function() {
    return $ctrl.timeline.editable && $ctrl.objectEditable;
  }, function(value2, oldValue) {
    if (value2) {
      jquery_default($element2).find("> .timeline-object").on("mousedown", onCreationDraggingStart);
      jquery_default($element2).find("> .timeline-object .js-expand-left").on("mousedown", onLeftDraggingStart);
      jquery_default($element2).find("> .timeline-object .js-expand-right").on("mousedown", onRightDraggingStart);
      jquery_default($element2).find("> .timeline-object .timeline-object-content").on("mousedown", onFullDraggingStart);
    } else {
      if (value2 !== oldValue) {
        jquery_default($element2).find("> .timeline-object").off("mousedown", onCreationDraggingStart);
        jquery_default($element2).find("> .timeline-object .js-expand-left").off("mousedown", onLeftDraggingStart);
        jquery_default($element2).find("> .timeline-object .js-expand-right").off("mousedown", onRightDraggingStart);
        jquery_default($element2).find("> .timeline-object .timeline-object-content").off("mousedown", onFullDraggingStart);
      }
    }
  });
  $scope2.$on("$destroy", function() {
    if (editableWatcherOff) editableWatcherOff();
    jquery_default($element2).find("> .timeline-object").off("mousedown", onCreationDraggingStart);
    jquery_default($element2).find("> .timeline-object .js-expand-left").off("mousedown", onLeftDraggingStart);
    jquery_default($element2).find("> .timeline-object .js-expand-right").off("mousedown", onRightDraggingStart);
    jquery_default($element2).find("> .timeline-object .timeline-object-content").off("mousedown", onFullDraggingStart);
  });
}

// public/app/apps/cards/timeline/ng-components/timeline-card.js
angular_default.module("kantree").component("cardsAppTimelineCard", {
  bindings: {
    object: "<",
    verticalPosition: "<"
  },
  require: {
    cardsAppTimeline: "^^cardsAppTimeline",
    timeline: "^^timeline",
    cardsAppTimelineGroup: "?^^cardsAppTimelineGroup",
    cardsAppTimelineCard: "?^^cardsAppTimelineCard"
  },
  templateUrl: "/static/app/apps/cards/timeline/ng-components/templates/timeline-card.html",
  controller: [
    "$scope",
    "cardModal",
    "$element",
    "stylesheetManager",
    "$rootScope",
    "$q",
    function($scope2, cardModal, $element2, stylesheetManager, $rootScope, $q) {
      var $ctrl = this;
      var childrenWatcherOff;
      $ctrl.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        $ctrl.onRowsUpdated = $ctrl.cardsAppTimelineCard ? (...args) => $ctrl.cardsAppTimelineCard.onChildRowsUpdated(...args) : (...args) => $ctrl.cardsAppTimelineGroup.onChildRowsUpdated(...args);
        $ctrl.parentStore = $ctrl.cardsAppTimelineCard ? $ctrl.cardsAppTimelineCard.timelineObjectStore : $ctrl.cardsAppTimelineGroup.timelineObjectStore;
        $ctrl.canToggleChildren = canToggleChildren();
        $ctrl.rows = [];
        $ctrl.timelineObjectStore = new Store({
          getForCard: function(card) {
            return this.get("card_" + card.id);
          }
        });
        $ctrl.childrenCardStore = cardStore.scopedByParent(
          cardStore.isValidMirror($ctrl.object._card) ? $ctrl.object._card.link : $ctrl.object._card
        );
        $ctrl.timelineObjects = [];
        $ctrl.localStorageKeyForChildrenDisplay = "project-timeline-card." + (cardStore.isValidMirror($ctrl.object._card) ? $ctrl.object._card.link.id : $ctrl.object._card.id) + ".show-children";
        $ctrl.showChildren = jsonLocalStorage.getItem($ctrl.localStorageKeyForChildrenDisplay);
        cardStore.$watch($scope2, $ctrl.object._card, "updated", function(card) {
          $ctrl.parentStore.update({ id: $ctrl.object.id }, { _card: card });
        }, false);
        $ctrl.parentStore.$watch($scope2, $ctrl.object, "updated", function(object2) {
          var oldDateRange = $ctrl.object.dateRange;
          var oldGlobalDateRange = $ctrl.object.globalDateRange;
          $ctrl.object = angular_default.copy(object2);
          $ctrl.canDisplayGlobalDateRangeObject = canDisplayGlobalDateRangeObject();
          if (!isDateRangesEqual(object2.dateRange, oldDateRange)) {
            updateObjectHorizontalPosition();
          }
          if (!isDateRangesEqual(object2.globalDateRange, oldGlobalDateRange)) {
            updateChildrenBackgroundHorizondalPosition();
          }
          updateCardModelAndColor();
          updateCardState();
          refreshEditable();
          if ($ctrl.object._card.nb_children && !childrenWatcherOff) {
            childrenWatcherOff = initChildrenHandlers();
          } else if (!$ctrl.object._card.nb_children && childrenWatcherOff) {
            childrenWatcherOff();
            childrenWatcherOff = null;
          }
        });
      };
      function initChildrenHandlers() {
        updateStoreAndRows();
        return offMany([
          $ctrl.childrenCardStore.subscribe(["inserted", "updated", "removed"], debounce2(function() {
            $scope2.$evalAsync(function() {
              updateStoreAndRows();
            });
          }, 16)),
          $scope2.$on("projectArchivesToggled", function() {
            updateStoreAndRows();
          }),
          $scope2.$watch("$ctrl.cardsAppTimeline.activeDateAttribute", function(newVal, oldVal) {
            if (availablesEquals(newVal, oldVal)) {
              return;
            }
            if ($ctrl.parentStore.exists($ctrl.object.id)) {
              updateStoreAndRows();
            }
          }),
          $ctrl.timelineObjectStore.$watchAll($scope2, function() {
            $ctrl.timelineObjects = $ctrl.timelineObjectStore.query({}, { sortBy: "_card.position", sortCastToInt: true });
            $ctrl.canDisplayBackground = canDisplayBackground();
            var newDescendantsDateRange = getDescendantsDateRange();
            if (!isDateRangesEqual(newDescendantsDateRange, $ctrl.object.descendantsDateRange)) {
              $ctrl.parentStore.update({ id: $ctrl.object.id }, {
                descendantsDateRange: newDescendantsDateRange,
                globalDateRange: getMinMaxFromDateRanges([newDescendantsDateRange, $ctrl.object.dateRange])
              });
            }
          }),
          $scope2.$watch("$ctrl.timeline.compactMode", function(newValue, oldValue) {
            if (newValue === oldValue) {
              return;
            }
            if ($ctrl.timeline.compactMode) {
              updateRows();
            } else {
              resetRows();
            }
          })
        ]);
      }
      $ctrl.$onChanges = function(changes) {
        if (changes.verticalPosition && !changes.verticalPosition.isFirstChange()) {
          updateObjectVerticalPosition();
        }
      };
      var $creationTooltip;
      var $container;
      $ctrl.$postLink = function() {
        updateCardModelAndColor();
        updateCardState();
        updateObjectVerticalPosition();
        $scope2.$watch("$ctrl.object.dateRange", function(value2) {
          $element2.find("> .timeline-object").toggleClass("without-daterange", value2 ? false : true);
        });
        $scope2.$watchGroup(["$ctrl.timeline.minSpanWidth", "$ctrl.timeline.totalDateRange"], function() {
          updateObjectHorizontalPosition();
          updateChildrenBackgroundHorizondalPosition();
        });
        $creationTooltip = jquery_default($element2).find(".timeline-object-creation-tooltip");
        $container = jquery_default($ctrl.timeline.$element).find(".timeline-container");
        moveCreationTooltipElement();
        $container.on("scroll", moveCreationTooltipElementDebounced);
        injectTimelineControls($ctrl, $scope2, $element2);
        if ($ctrl.canToggleChildren) {
          toggleChildrenList($ctrl.showChildren);
          $scope2.$on("project-timeline-card:toggleChildren", function(event2, parentId, forcedState) {
            var cardId = cardStore.isValidMirror($ctrl.object._card) ? $ctrl.object._card.link.id : $ctrl.object._card.id;
            if (parentId === cardId) {
              $scope2.$applyAsync(function() {
                toggleChildrenList(forcedState);
                if ($ctrl.showChildren && cardStore.isValidMirror($ctrl.object._card) && $ctrl.object._card.link.project_id !== ($ctrl.cardsAppTimeline.project || {}).id) {
                  var card = $ctrl.object._card.link;
                  $q.digest(loadChildCardsOf(card));
                  if (($ctrl.cardsAppTimeline.options || {}).include_archived) {
                    $q.digest(loadArchivedChildCardsOf(card));
                  }
                }
              });
            }
          });
          $scope2.$on("showAllChildren", function() {
            toggleChildrenList(true);
          });
          $scope2.$on("hideAllChildren", function() {
            toggleChildrenList(false);
          });
        }
      };
      function canToggleChildren() {
        return (!$ctrl.cardsAppTimeline.project || !$ctrl.cardsAppTimeline.project.is_portfolio) && (!cardStore.isValidMirror($ctrl.object._card) || !cardStore.isCardDescendantOf($ctrl.object._card, $ctrl.object._card.link));
      }
      function updateCardModelAndColor() {
        $q.when(getOrLoadModelForCard($ctrl.object._card), () => {
          $ctrl.model = getCardCompositeModel($ctrl.object._card);
          var tinyCardColor;
          var themeName2 = "";
          if ($ctrl.model && $ctrl.model.card_color) {
            tinyCardColor = tinycolor($ctrl.model.card_color);
            themeName2 = "card-model-theme-" + tinyCardColor.toHex();
            stylesheetManager.createTheme(
              themeName2,
              tinyCardColor.toHexString(),
              "/static/app/ui/card-models/ng-components/templates/card.css.html"
            );
          }
          jquery_default($element2).removeClassRegex("card-model-theme-");
          if (themeName2.length) {
            jquery_default($element2).addClass(themeName2);
          }
        });
      }
      function updateCardState() {
        $ctrl.state = cardStateStore.getForCard($ctrl.object._card);
      }
      function refreshEditable() {
        $ctrl.objectEditable = !$ctrl.object._card.is_archived && !$ctrl.object._card.is_parent_archived;
      }
      function getDescendantsDateRange() {
        if (!$ctrl.timelineObjectStore || !$ctrl.timelineObjectStore.count()) return;
        return getMinMaxFromDateRanges($ctrl.timelineObjectStore.query().map(function(obj) {
          return obj.globalDateRange;
        }));
      }
      function updateStoreAndRows() {
        $ctrl.timelineObjectStore.transaction(function() {
          var children2 = $ctrl.childrenCardStore.query({
            is_archived: (v3) => ($ctrl.cardsAppTimeline.options || {}).include_archived ? true : !v3
          }, { sortBy: "position", sortCastToInt: true });
          var objects = $ctrl.timelineObjectStore.upsertMany(convertCardsToTimelineObjects(
            children2,
            $ctrl.cardsAppTimeline.activeDateAttribute,
            ($ctrl.cardsAppTimeline.options || {}).include_archived
          ));
          $ctrl.timelineObjectStore.removeAllNotMatching(objects);
          if ($ctrl.timeline.compactMode) {
            updateRows();
          }
        });
      }
      function updateObjectVerticalPosition() {
        jquery_default($element2).css({
          "transform": $ctrl.verticalPosition === null ? "" : "translate3D(0, " + $ctrl.verticalPosition + "px, 0)"
        });
      }
      function updateObjectHorizontalPosition() {
        if ($ctrl.object.dateRange) {
          $ctrl.position = $ctrl.timeline.getObjectPosition($ctrl.object);
        }
      }
      function updateChildrenBackgroundHorizondalPosition() {
        if (!$ctrl.canDisplayBackground) {
          return;
        }
        var backgroundCSS = $ctrl.object.globalDateRange ? $ctrl.timeline.getDateRangePosition($ctrl.object.globalDateRange) : { left: 0, right: 0 };
        $element2.find(
          "> .cards-app-timeline-card-children-list > .cards-app-timeline-cards-background"
        ).css(backgroundCSS);
      }
      function updateRows() {
        $ctrl.timelineObjectStore.transaction(function() {
          $ctrl.rows = buildCompactRows($ctrl.timelineObjectStore, { subCards: true });
          updateContentHeight();
        });
      }
      function resetRows() {
        $ctrl.rows = [];
        updateContentHeight();
      }
      function updateContentHeight() {
        if ($ctrl.showChildren && $ctrl.timeline.compactMode) {
          $ctrl.contentHeight = $ctrl.rows.reduce(function(accu, row) {
            return accu + row.height;
          }, 0);
        } else $ctrl.contentHeight = null;
        $ctrl.onRowsUpdated(
          $ctrl.object,
          ($ctrl.contentHeight || 0) + getDefaultRowHeight(!!$ctrl.cardsAppTimelineCard)
        );
      }
      var scrollLeft;
      function moveCreationTooltipElement(event2) {
        if (scrollLeft === $ctrl.timeline.scrollLeft) return;
        scrollLeft = $ctrl.timeline.scrollLeft;
        requestAnimationFrame(function() {
          $creationTooltip.css({
            "margin-left": scrollLeft
          });
        });
      }
      var moveCreationTooltipElementDebounced = debounce2(moveCreationTooltipElement, 200);
      function toggleChildrenList(forcedState) {
        var updateLocalData = function(forcedState2) {
          var currentState = jsonLocalStorage.getItem($ctrl.localStorageKeyForChildrenDisplay) || false;
          var newState = forcedState2 !== void 0 ? forcedState2 : !currentState;
          if (newState !== currentState) {
            jsonLocalStorage.setItem($ctrl.localStorageKeyForChildrenDisplay, newState);
          }
          return newState;
        };
        $ctrl.showChildren = updateLocalData(forcedState);
        $ctrl.canDisplayGlobalDateRangeObject = canDisplayGlobalDateRangeObject();
        $element2.toggleClass("children-shown", !!($ctrl.showChildren && $ctrl.object._card.nb_children));
        $element2.find("> .timeline-object .cards-app-timeline-card-container .js-toggle-children").toggleClass("is-opened", !!$ctrl.showChildren);
        updateContentHeight();
      }
      $ctrl.onMouseEnter = function(event2) {
        if ($ctrl.timeline.editable && $ctrl.objectEditable) {
          $element2.addClass("hovering-timeline-object");
        }
      };
      $ctrl.onMouseLeave = function(event2) {
        if ($ctrl.timeline.editable && $ctrl.objectEditable) {
          $element2.removeClass("hovering-timeline-object");
        }
      };
      var cachedMousePos;
      $ctrl.handleMouseDown = function(event2) {
        cachedMousePos = {
          x: event2.pageX,
          y: event2.pageY
        };
      };
      $ctrl.handleClick = function(event2) {
        if (jquery_default(event2.target).closest(".js-toggle-children").get(0)) {
          cachedMousePos = null;
          return;
        }
        if (cachedMousePos && Math.max(
          Math.abs(cachedMousePos.x - event2.pageX),
          Math.abs(cachedMousePos.y - event2.pageY)
        ) <= 2) {
          event2.preventDefault();
          cardModal.open($ctrl.object._card, { showArchived: ($ctrl.cardsAppTimeline.options || {}).include_archived });
        }
        cachedMousePos = null;
      };
      $ctrl.toggleChildCards = function(event2, isFakeObject) {
        var card = cardStore.isValidMirror($ctrl.object._card) ? cardStore.get($ctrl.object._card.link.id) : $ctrl.object._card;
        if (!card.nb_children) {
          return;
        }
        if (isFakeObject || cachedMousePos && Math.max(
          Math.abs(cachedMousePos.x - event2.pageX),
          Math.abs(cachedMousePos.y - event2.pageY)
        ) <= 2) {
          event2.stopPropagation();
          event2.preventDefault();
          $rootScope.$broadcast("project-timeline-card:toggleChildren", card.id, !$ctrl.showChildren);
        }
        cachedMousePos = null;
      };
      function canDisplayBackground() {
        return $ctrl.timelineObjectStore.query().some(function(obj) {
          return !!obj.dateRange || !!obj.descendantsDateRange;
        });
      }
      $ctrl.canDisplayFakeObject = function() {
        return $ctrl.timeline.compactMode && $ctrl.timelineObjectStore.count() && !$ctrl.object.dateRange;
      };
      function canDisplayGlobalDateRangeObject() {
        return $ctrl.showChildren || !isDateRangesEqual($ctrl.object.dateRange, $ctrl.object.globalDateRange);
      }
      $ctrl.canDisplayBackgroundInner = function() {
        return $ctrl.showChildren && $ctrl.canToggleChildren;
      };
      $ctrl.onChildRowsUpdated = function(updatedChildObject, height) {
        $ctrl.timelineObjectStore.transaction(function() {
          var timelineObj = $ctrl.timelineObjectStore.update({ id: updatedChildObject.id }, { height });
          var row = $ctrl.rows[timelineObj.row];
          if (!row) return;
          row.height = Math.max(...pluck($ctrl.timelineObjectStore.query({ row: timelineObj.row }), "height"));
          updateContentHeight();
        });
      };
      $ctrl.getCardVerticalPosition = function(obj) {
        if ($ctrl.timeline.compactMode) {
          return $ctrl.rows.slice(0, $ctrl.timelineObjectStore.get(obj.id).row).reduce(function(accu, row) {
            return accu + row.height;
          }, 0);
        } else return null;
      };
      $ctrl.$onDestroy = function() {
        $container.off("scroll", moveCreationTooltipElementDebounced);
        if (childrenWatcherOff) childrenWatcherOff();
      };
    }
  ]
});

// public/app/apps/cards/timeline/ng-components/timeline-group.js
var TimelineObjectStore = class extends Store {
  getForCard(card) {
    return this.get("card_" + card.id);
  }
};
angular_default.module("kantree").directive("cardsAppTimelineGroup", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        group: "<?",
        customTitle: "@?",
        store: "<?",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        sortChoices: "<?",
        hideHeader: "<?",
        onChange: "&?"
      },
      require: {
        cardsAppTimeline: "^^cardsAppTimeline",
        timeline: "^^timeline"
      },
      templateUrl: "/static/app/apps/cards/timeline/ng-components/templates/timeline-group.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupMixin, CardsAppCardCreatorMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element", "$rootScope"]);
        }
        $onInit() {
          this.rows = [];
          this.contentHeight = null;
          this.timelineObjects = [];
          this.timelineObjectStore = new TimelineObjectStore();
          this.$scope.$watch("$ctrl.cardsAppTimeline.activeDateAttribute", (newVal, oldVal) => {
            if (availablesEquals(newVal, oldVal)) return;
            this.refreshCardsWatcher();
          });
          this.modeOptionsKeyPrefix = "timeline_group_";
          this.groupColorTheme = "/static/app/apps/cards/timeline/ng-components/templates/timeline-group-color.css.html";
          this.freeSortDisabled = true;
          this.handleCards = true;
          this.initGroupMixin();
          this.debouncedRefreshTimelineObjects = debounce2(() => {
            this.timelineObjects = this.timelineObjectStore.query().sort((a3, b3) => getCardCompareFunc(this.sortBy, {
              modelStore: getScopedModelStore(this.project, this.cardStore),
              groupTypeStore: getScopedGroupTypeStore(this.project, this.cardStore)
            })(a3._card, b3._card));
            this.$scope.$applyAsync();
          }, 50);
          this.timelineObjectStore.subscribe(() => this.debouncedRefreshTimelineObjects());
          this.$scope.$watch("$ctrl.timeline.compactMode", (newValue, oldValue) => {
            if (newValue === oldValue) return;
            this.$element.toggleClass("mod-compact", !!this.timeline.compactMode);
            if (this.timeline.compactMode) {
              this.updateRows();
            } else {
              this.resetRows();
            }
          });
          this.$scope.$on("project-timeline-group:addingCard", (event2, group2, title, height) => {
            if (this.group && group2 === this.group || this.title === title) {
              requestAnimationFrame(() => {
                jquery_default(this.$element).find(".cards-app-timeline-group-card-creator")[0].style.height = height ? height + "px" : null;
              });
            }
          });
        }
        $onChanges(changes) {
          this.changeGroupMixin(changes);
        }
        $postLink() {
          this.groupHeaderElement = jquery_default(this.$element).find(".cards-app-timeline-group-header");
          this.containerElement = jquery_default(this.$element).parents(".timeline-container");
          this.$element.toggleClass("mod-compact", !!this.timeline.compactMode);
          const onScroll = () => {
            if (this.scrollLeft === this.timeline.scrollLeft) return;
            this.scrollLeft = this.timeline.scrollLeft;
            requestAnimationFrame(() => this.groupHeaderElement.css({ "margin-left": this.scrollLeft }));
          };
          onScroll();
          this.containerElement.on("scroll", onScroll);
          this.$scope.$on("$destroy", () => {
            this.containerElement && this.containerElement.off("scroll", onScroll);
          });
        }
        // OVERWRITES MIXIN METHOD
        queryCards() {
          return sortCardQuery(this.cardStore.query(), this.sortBy, !this.group, {
            modelStore: getScopedModelStore(this.project, this.cardStore),
            groupTypeStore: getScopedGroupTypeStore(this.project, this.cardStore)
          }).filter(
            (card) => areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute)
          );
        }
        // OVERWRITES MIXIN METHOD
        get _allCards() {
          return (this.shouldRenderFilteredCards ? this.cards || [] : this.formatStore(true).query()).filter(
            (card) => areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute)
          );
        }
        // OVERWRITES MIXIN METHOD
        get _matchingCards() {
          return (this.shouldRenderFilteredCards && this.filtered && Array.isArray(this.matchingCardIds) ? (this.cards || []).filter((c3) => this.matchingCardIds.includes(c3.id)) : this.cards || []).filter(
            (card) => areAttributesAvailableForCard(card, this.cardsAppTimeline.activeDateAttribute)
          );
        }
        // OVERWRITES MIXIN METHOD
        refreshAfterCardsUpdate(oldCards) {
          super.refreshAfterCardsUpdate(oldCards);
          this.updateTimelineObjectStore(() => {
            if (this.timeline.compactMode) {
              this.updateRows();
            }
          });
        }
        updateTimelineObjectStore(callback) {
          this.timelineObjectStore.transaction(() => {
            const objects = this.timelineObjectStore.upsertMany(convertCardsToTimelineObjects(
              this.cards,
              this.cardsAppTimeline.activeDateAttribute,
              (this.options || {}).include_archived
            ));
            this.timelineObjectStore.removeAllNotMatching(objects);
            if (callback) callback();
          });
        }
        getCardVerticalPosition(obj) {
          if (this.timeline.compactMode) {
            return this.rows.slice(0, this.timelineObjectStore.get(obj.id).row).reduce((accu, row) => accu + row.height, 0);
          } else return null;
        }
        updateRows() {
          this.timelineObjectStore.transaction(() => {
            this.rows = buildCompactRows(this.timelineObjectStore);
          });
          this.updateGroupCardsListHeight();
        }
        resetRows() {
          this.rows = [];
          this.contentHeight = null;
        }
        onToggleChildren(card, toggleState) {
          this.$rootScope.$broadcast("project-timeline-card:toggleChildren", card.id, toggleState);
        }
        // Sums rows' heights
        updateGroupCardsListHeight() {
          this.contentHeight = this.rows.reduce((accu, row) => accu + row.height, 0);
        }
        onChildRowsUpdated(updatedChildObject, height) {
          if (!this.timelineObjectStore.exists(updatedChildObject.id)) return;
          const timelineObj = this.timelineObjectStore.update({ id: updatedChildObject.id }, { height });
          const row = this.rows[timelineObj.row];
          if (!row) return;
          row.height = Math.max(...pluck(this.timelineObjectStore.query({ row: timelineObj.row }), "height"));
          this.updateGroupCardsListHeight();
        }
        // getDescendantsDateRange() {
        //   if (!this.timelineObjectStore || !this.timelineObjectStore.count()) return;
        //   return getMinMaxFromDateRanges(this.timelineObjectStore.query().map(obj => obj.globalDateRange));
        // }
        // updateGroupBackground(checkChanges) {
        //   const _minMaxDateRange = getDescendantsDateRange();
        //   if (!checkChanges || !isDateRangesEqual(_minMaxDateRange, this.minMaxDateRange)) {
        //     const backgroundCSS = _minMaxDateRange ? this.timeline.getDateRangePosition(_minMaxDateRange) : { left: 0, right: 0 };
        //     $element.find('> .timeline-group-content > .board-timeline-cards-background').css(backgroundCSS);
        //   }
        //   this.minMaxDateRange = _minMaxDateRange;
        // }
        $onDestroy() {
          this.destroyGroupMixin();
          if (this._cardStoreWatcherOff) this._cardStoreWatcherOff();
        }
      }
    };
  }
]);

// public/app/apps/cards/timeline/ng-components/timeline.js
angular_default.module("kantree").directive("cardsAppTimeline", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        store: "<",
        board: "<?",
        filter: "<?",
        filterScopes: "<?",
        groupBy: "<?",
        options: "<?",
        matchingCardIds: "<?",
        onChange: "&"
      },
      templateUrl: "/static/app/apps/cards/timeline/ng-components/templates/timeline.html",
      controller: class extends angularClassMixin(AngularClass, CardsAppGroupableMixin, CardsAppDateMixin) {
        static get $inject() {
          return (super.$inject || []).concat(["$scope", "$element", "$q", "$timeout"]);
        }
        constructor() {
          super(...arguments);
          this.maxDateRangeInDays = { month: 12 };
        }
        $onInit() {
          this.modeOptionsKeyPrefix = "timeline_group";
          injectI18nHelpersIntoScope(this.$scope);
          this.isScreensizeXS = isScreensizeXS;
          this.initGroupableMixin();
          this.initDateMixin();
          this.refreshTimelineOptions();
          this.$scope.$on("maximizeAllCards", () => this.$scope.$broadcast("showAllChildren"));
          this.$scope.$on("minimizeAllCards", () => this.$scope.$broadcast("hideAllChildren"));
        }
        $onChanges(changes) {
          this.changeGroupableMixin(changes);
          this.changeDateMixin(changes);
          const storeChanged = changes.store && !changes.store.isFirstChange();
          const boardChanged = changes.board && !changes.board.isFirstChange();
          const projectChanged = boardChanged && (projectStore.tryGetForCard(this.board) || {}).id !== (this.project || {}).id;
          const optionsChanged = changes.options && !changes.options.isFirstChange();
          const optionChanged = (optionLabel) => optionsChanged && !equals((this.options || {})[optionLabel], (changes.options.previousValue || {})[optionLabel]);
          if (optionChanged("dateRange") || optionChanged("compactMode")) {
            this.refreshTimelineOptions();
          }
        }
        $postLink() {
          let $container;
          let $sidebar;
          let $sidebarContainer;
          let isSyncContainerScroll = false;
          let isSyncSidebarScroll = false;
          function onContainerScroll() {
            if (!isSyncContainerScroll) {
              isSyncSidebarScroll = true;
              $sidebarContainer.scrollTop($container.scrollTop());
            }
            isSyncContainerScroll = false;
          }
          function onSidebarScroll() {
            if (!isSyncSidebarScroll) {
              isSyncContainerScroll = true;
              $container.scrollTop($sidebarContainer.scrollTop());
            }
            isSyncSidebarScroll = false;
          }
          this.$timeout(() => {
            $container = this.$element.find(".timeline-container");
            $sidebar = this.$element.find(".cards-app-timeline-sidebar");
            $sidebarContainer = this.$element.find(".cards-app-timeline-sidebar-container");
            onContainerScroll();
            $container.on("scroll", onContainerScroll);
            $sidebarContainer.on("scroll", onSidebarScroll);
            this.$scope.$watch("$ctrl.timelineOptions.compactMode", (newVal, oldVal) => {
              if (newVal === oldVal) return;
              this.$timeout(() => {
                const maxScrollLeft = $container[0].scrollWidth - $container[0].clientWidth;
                const sidebarWidth = $sidebar.width();
                const scrollLeft = $container.scrollLeft();
                if (newVal) {
                  $container.scrollLeft(Math.max(scrollLeft - sidebarWidth, 0));
                } else {
                  $container.scrollLeft(Math.min(scrollLeft + sidebarWidth, maxScrollLeft));
                }
              }, 0, false);
              $container.scrollTop(0);
            });
            this.$scope.$on("$destroy", () => {
              $container.off("scroll", onContainerScroll);
              $sidebarContainer.off("scroll", onSidebarScroll);
            });
          }, 1e3, false);
        }
        attachTimelineOptionsWatcher() {
          return offMany([
            this.$scope.$watch("$ctrl.timelineOptions.dateRange", (newVal, oldVal) => {
              if (newVal === oldVal) {
                return;
              }
              this.updateDateRange(oldVal);
            }),
            this.$scope.$watch("$ctrl.timelineOptions.compactMode", (newVal, oldVal) => {
              if (newVal === oldVal) {
                return;
              }
              this.updateMode(newVal);
            })
          ]);
        }
        refreshTimelineOptions() {
          if (this.timelineOptionsWatcherOff) this.timelineOptionsWatcherOff();
          const localDateRange = (this.options || {}).dateRange || DEFAULT_PERIOD;
          const opts = {
            dateRange: {
              start: moment_default(localDateRange.start),
              end: moment_default(localDateRange.end)
            },
            compactMode: (this.options || {}).compactMode !== false
          };
          if (isScreensizeXS()) {
            opts.compactMode = true;
          }
          this.timelineOptions = opts;
          this.timelineOptionsWatcherOff = this.attachTimelineOptionsWatcher();
        }
        updateActiveDateAttrName(name2) {
          const newModeOptions = { ...this.options };
          newModeOptions["activeDateAttrName"] = name2;
          return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
        }
        updateDateRange(range2) {
          if (isDateRangesEqual(this.timelineOptions.dateRange, range2)) return;
          const newDate = formatPeriodToString(range2);
          const newModeOptions = { ...this.options };
          newModeOptions["dateRange"] = newDate;
          return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
        }
        updateMode(compact2) {
          const newModeOptions = { ...this.options };
          newModeOptions["compactMode"] = compact2;
          return this.onChange && this.onChange({ $changes: { options: newModeOptions } });
        }
        updateCard(data2) {
          const card = cardStore.isValidMirror(data2.newObject._card) ? cardStore.tryGet(data2.newObject._card.link.id) : data2.newObject._card;
          if (!card) throw Error("The mirrored card is not in store");
          const attr = getCardAvailableAttributes(card, this.activeDateAttribute)[0];
          if (!attr) return;
          if (data2.newObject.dateRange.start.isAfter(data2.newObject.dateRange.end, "day")) {
            this.$q.digest(clearCardAttribute(card, attr.id));
          } else {
            const start = data2.newObject.dateRange.start;
            const end = data2.newObject.dateRange.end;
            this.$q.digest(setCardAttribute(card, attr.id, formatServerDateRange(attr, start, end)));
          }
        }
        centerTimelineOnDateRange(dateRange) {
          if (dateRange) {
            const periodInDays = dateRange.end.diff(dateRange.start, "days");
            const centerDay = dateRange.start.clone().add(Math.round(periodInDays / 2), "day");
            const dateRangePeriodInDays = this.timelineOptions.dateRange.end.diff(this.timelineOptions.dateRange.start, "days");
            if (dateRangePeriodInDays <= periodInDays + 10) {
              this.updateDateRange({
                start: dateRange.start.clone().subtract(5, "days"),
                end: dateRange.end.clone().add(5, "days")
              });
            } else {
              this.updateDateRange({
                start: centerDay.clone().subtract(Math.floor(dateRangePeriodInDays / 2), "days"),
                end: centerDay.clone().add(Math.round(dateRangePeriodInDays / 2), "days")
              });
            }
          }
        }
        toggleCompactMode() {
          this.timelineOptions.compactMode = !this.timelineOptions.compactMode;
        }
        $onDestroy() {
          if (this.timelineOptionsWatcherOff) this.timelineOptionsWatcherOff();
          this.destroyGroupableMixin();
          this.destroyDateMixin();
        }
      }
    };
  }
]);

// public/app/ui/quadrant/quadrant-utils/isMobile.tsx
function useIsMobile() {
  const [isMobile, setIsMobile] = createSignal(window.matchMedia("(max-width: 768px)").matches);
  const updateIsMobile = () => {
    setIsMobile(window.matchMedia("(max-width: 768px)").matches);
  };
  const mediaQuery = window.matchMedia("(max-width: 768px)");
  mediaQuery.addEventListener("change", updateIsMobile);
  onCleanup(() => {
    mediaQuery.removeEventListener("change", updateIsMobile);
  });
  return isMobile;
}

// public/app/apps/cards/quadrant/quadrant-view.tsx
var _tmpl$160 = /* @__PURE__ */ template(`<div class="quadrant-sidebar-content"></div>`, 2);
var _tmpl$277 = /* @__PURE__ */ template(`<aside><div class="quadrant-sidebar-header"><i></i><span></span></div></aside>`, 8);
var _tmpl$353 = /* @__PURE__ */ template(`<div class="canvas-container"></div>`, 2);
var _tmpl$438 = /* @__PURE__ */ template(`<div class="quadrant-content"></div>`, 2);
var _tmpl$532 = /* @__PURE__ */ template(`<div class="quadrant-view"></div>`, 2);
var _tmpl$625 = /* @__PURE__ */ template(`<div class="legend-container top"></div>`, 2);
var _tmpl$721 = /* @__PURE__ */ template(`<div class="legend-container left"></div>`, 2);
var _tmpl$818 = /* @__PURE__ */ template(`<div class="legend-container right"></div>`, 2);
var _tmpl$916 = /* @__PURE__ */ template(`<div class="legend-container bottom"></div>`, 2);
var QuadrantView = (props2) => {
  const quadrantViewContext = useQuadrantViewContext();
  const options2 = useOptions();
  const _cards = useCards();
  const activeSeries = useActiveAxisSeries();
  const quadrantStore = QuadrantStore.create({});
  let owner;
  const isMobile = useIsMobile();
  const cards = createMemo(mapArray(() => {
    owner = getOwner();
    return _cards();
  }, (card) => {
    return CardQuadrantItemStore.create({
      id: card.id,
      title: card.title,
      card,
      childrenLoader: () => {
        return cardStore.scopedByParent({
          id: card.id
        }).react({}, () => {
        });
      }
    }, getOwner());
  }));
  const shouldDisplay = createMemo(() => activeSeries().length > 0 && activeSeries()[0].x.cardAttribute.length > 0 && activeSeries()[0].y.cardAttribute.length > 0);
  const [isSidebarCollapsed, setIsSidebarCollapsed] = createSignal(false);
  const toggleSidebar = () => {
    setIsSidebarCollapsed(!isSidebarCollapsed());
  };
  const matchingCardIds = createMemo(() => {
    return quadrantViewContext.matchingCardIds() || [];
  });
  function gatherDisplayIds(groups, idsSet, path = []) {
    groups.forEach((group2) => {
      let addToPath = false;
      if (group2.card && matchingCardIds().includes(group2.card.id)) {
        idsSet.add(group2.card.id);
        addToPath = true;
      }
      const children2 = group2.state?.children;
      if (children2 && children2.length > 0) {
        const childIdsSet = /* @__PURE__ */ new Set();
        gatherDisplayIds(children2, childIdsSet, [...path, group2.card?.id].filter(Boolean));
        if (childIdsSet.size > 0) {
          addToPath = true;
          childIdsSet.forEach((id) => idsSet.add(id));
        }
      }
      if (addToPath) {
        path.forEach((id) => idsSet.add(id));
      }
    });
  }
  const displayIds = createMemo(() => {
    const idsSet = /* @__PURE__ */ new Set();
    return options2.filter?.length > 0 ? [] : null;
  });
  return createComponent(QuadrantProvider, {
    value: quadrantStore,
    get children() {
      const _el$ = _tmpl$532.cloneNode(true);
      insert(_el$, createComponent(Show, {
        get when() {
          return shouldDisplay();
        },
        get children() {
          return [createComponent(Show, {
            get when() {
              return !isMobile();
            },
            get children() {
              const _el$2 = _tmpl$277.cloneNode(true), _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling;
              _el$2.$$click = (e3) => isSidebarCollapsed() && toggleSidebar();
              _el$3.$$click = (e3) => {
                toggleSidebar();
                e3.stopPropagation();
              };
              insert(_el$5, () => _4("Unplaced cards"));
              insert(_el$2, createComponent(Show, {
                get when() {
                  return !isSidebarCollapsed();
                },
                get children() {
                  const _el$6 = _tmpl$160.cloneNode(true);
                  insert(_el$6, () => createComponent(For, {
                    get each() {
                      return cards();
                    },
                    children: (root3) => createComponent(NodeItemProvider2, {
                      store: root3,
                      get children() {
                        return createComponent(SidebarGroup, {
                          get displayIds() {
                            return displayIds();
                          }
                        });
                      }
                    })
                  }));
                  return _el$6;
                }
              }), null);
              createRenderEffect((_p$) => {
                const _v$ = `quadrant-sidebar ${isSidebarCollapsed() ? "collapsed" : ""}`, _v$2 = isSidebarCollapsed() ? "bi-caret-down-square" : "bi-caret-left-square", _v$3 = isSidebarCollapsed() ? "collapsed" : "";
                _v$ !== _p$._v$ && className(_el$2, _p$._v$ = _v$);
                _v$2 !== _p$._v$2 && className(_el$4, _p$._v$2 = _v$2);
                _v$3 !== _p$._v$3 && className(_el$5, _p$._v$3 = _v$3);
                return _p$;
              }, {
                _v$: void 0,
                _v$2: void 0,
                _v$3: void 0
              });
              return _el$2;
            }
          }), (() => {
            const _el$7 = _tmpl$438.cloneNode(true);
            insert(_el$7, createComponent(Show, {
              get when() {
                return activeSeries().length > 0;
              },
              get children() {
                return [createComponent(For, {
                  get each() {
                    return activeSeries();
                  },
                  children: (pair2, index2) => [createComponent(Show, {
                    get when() {
                      return pair2.x.position === "top";
                    },
                    get children() {
                      const _el$9 = _tmpl$625.cloneNode(true);
                      insert(_el$9, createComponent(Legend, {
                        position: "top",
                        get axis() {
                          return pair2.x;
                        },
                        axisPair: pair2
                      }));
                      return _el$9;
                    }
                  }), createComponent(Show, {
                    get when() {
                      return pair2.y.position === "left";
                    },
                    get children() {
                      const _el$10 = _tmpl$721.cloneNode(true);
                      insert(_el$10, createComponent(Legend, {
                        position: "left",
                        get axis() {
                          return pair2.y;
                        },
                        axisPair: pair2
                      }));
                      return _el$10;
                    }
                  }), createComponent(Show, {
                    get when() {
                      return pair2.y.position === "right";
                    },
                    get children() {
                      const _el$11 = _tmpl$818.cloneNode(true);
                      insert(_el$11, createComponent(Legend, {
                        position: "right",
                        get axis() {
                          return pair2.y;
                        },
                        axisPair: pair2
                      }));
                      return _el$11;
                    }
                  }), createComponent(Show, {
                    get when() {
                      return pair2.x.position === "bottom";
                    },
                    get children() {
                      const _el$12 = _tmpl$916.cloneNode(true);
                      insert(_el$12, createComponent(Legend, {
                        position: "bottom",
                        get axis() {
                          return pair2.x;
                        },
                        axisPair: pair2
                      }));
                      return _el$12;
                    }
                  })]
                }), (() => {
                  const _el$8 = _tmpl$353.cloneNode(true);
                  insert(_el$8, createComponent(Canvas, {
                    cards
                  }));
                  return _el$8;
                })()];
              }
            }));
            return _el$7;
          })()];
        }
      }));
      return _el$;
    }
  });
};
delegateEvents(["click"]);

// public/app/apps/cards/quadrant/ng-components/quadrant.jsx
var optionStore = new OptionStore2();
angular_default.module("kantree").directive("cardsAppQuadrant", [function() {
  return {
    //---act as component
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    //---
    bindToController: {
      store: "<",
      board: "<?",
      filter: "<?",
      filterScopes: "<?",
      groupBy: "<?",
      options: "<?",
      matchingCardIds: "<?",
      onChange: "&",
      showEmptyNotice: "<?"
    },
    templateUrl: "/static/app/apps/cards/quadrant/ng-components/templates/quadrant.html",
    controller: class extends AngularClass {
      static get $inject() {
        return (super.$inject || []).concat(["$scope", "$element", "$q", "$timeout", "cardModal"]);
      }
      constructor() {
        super(...arguments);
      }
      $onInit() {
        this.modeOptionsKeyPrefix = "quadrant_group";
        optionStore = new OptionStore2(this.options ?? {});
        this.matchingCardIdsSignal = createSignal(this.matchingCardIds);
        injectI18nHelpersIntoScope(this.$scope);
        if (this.withEmptyNotice === void 0) {
          this.withEmptyNotice = true;
        }
        const _self$ = this;
        this.QuadrantView = () => createComponent(KeyboardProvider, {
          get children() {
            return createComponent(ProjectProvider, {
              get board() {
                return _self$.board;
              },
              get children() {
                return createComponent(OptionContext2.Provider, {
                  value: optionStore,
                  get children() {
                    return createComponent(QuadrantViewProvider, {
                      get scope() {
                        return _self$.$scope;
                      },
                      get cardModal() {
                        return _self$.$cardModal;
                      },
                      get store() {
                        return _self$.store;
                      },
                      options: optionStore,
                      get board() {
                        return _self$.board;
                      },
                      get filter() {
                        return _self$.filter;
                      },
                      get filterScopes() {
                        return _self$.filterScopes;
                      },
                      get matchingCardIds() {
                        return _self$.matchingCardIdsSignal[0]();
                      },
                      onChange: (changes) => _self$.onChange({
                        $changes: changes
                      }),
                      get children() {
                        return createComponent(CardsProvider, {
                          get store() {
                            return _self$.store;
                          },
                          get children() {
                            return createComponent(ActiveAxisSeriesProvider, {
                              get children() {
                                return createComponent(QuadrantView, {
                                  get store() {
                                    return _self$.store;
                                  }
                                });
                              }
                            });
                          }
                        });
                      }
                    });
                  }
                });
              }
            });
          }
        });
      }
      $onChanges(changes) {
        if (changes.options && !changes.options.isFirstChange()) {
          optionStore.updateOptions(changes.options.currentValue);
        }
        if (changes.matchingCardIds && !changes.matchingCardIds.isFirstChange()) {
          this.matchingCardIdsSignal[1](changes.matchingCardIds.currentValue);
        }
      }
    }
  };
}]);

// public/app/apps/cards/quadrant/ng-components/nav.js
angular_default.module("kantree").component("cardsAppNavQuadrant", {
  templateUrl: "/static/app/apps/cards/quadrant/ng-components/templates/nav.html",
  bindings: {
    mode: "<?",
    board: "<?",
    store: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    groupByChoices: "<",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$rootScope", "$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const optionChanged = (optionLabel) => optionsChanged && !equals((this.options || {})[optionLabel], (changes.options.previousValue || {})[optionLabel]);
    }
  }
});

// public/app/apps/cards/planning/ng-components/nav.js
angular_default.module("kantree").component("cardsAppNavPlanning", {
  templateUrl: "/static/app/apps/cards/planning/ng-components/templates/nav.html",
  bindings: {
    mode: "<?",
    board: "<?",
    store: "<?",
    filter: "<?",
    filterRepr: "<?",
    filterScopes: "<?",
    groupBy: "<?",
    options: "<?",
    matchingCardIds: "<?",
    groupByChoices: "<",
    readonly: "<?",
    shrinked: "<?",
    onChange: "&"
  }
});

// public/app/apps/cards/common/timeline/stores/planning-timeline-item.ts
var PlanningTimelineItemStore = class extends CardTimelineItemStore {
  constructor() {
    super(...arguments);
    this.config = usePlanningConfig();
  }
  get hasActiveDateField() {
    return this.areAttributesAvailable?.() ?? false;
  }
  get hasChildWithActiveDateField() {
    return this.children.some(
      (child) => child.hasActiveDateField || child.hasChildWithActiveDateField
    );
  }
  onInit() {
    super.onInit();
    this.areAttributesAvailable = createMemo(() => {
      if (!this.options.relationship) return false;
      const attrGroup = this.config?.relationAttrGroupMap();
      if (!attrGroup) return false;
      return areAttributesAvailableForCard(this.card, attrGroup);
    });
    if (this.card && !this.isRoot) {
      setupPlanningItemPeriod(this);
    }
  }
};

// public/app/apps/cards/planning/PlanningView.tsx
var _tmpl$161 = /* @__PURE__ */ template(`<div class="timeline-sticky-sidebar-bg-panel"><div></div></div>`, 4);
var _tmpl$278 = /* @__PURE__ */ template(`<div class="timeline-view"></div>`, 2);
function PlanningView() {
  const groups = useTimelineGroups();
  const timelineStore = useTimelineStore();
  const periodSelectable = usePeriodSelectable();
  const relationSelectable = useRelationSelectable();
  const options2 = useAppOptions();
  setupTimelineSelectable(timelineStore, periodSelectable, relationSelectable);
  return (() => {
    const _el$ = _tmpl$278.cloneNode(true);
    insert(_el$, createComponent(Timeline, {
      get displayDensity() {
        return options2?.displayDensity;
      },
      get children() {
        return [createComponent(SidebarHeader, {}), _tmpl$161.cloneNode(true), createComponent(For, {
          get each() {
            return groups();
          },
          children: (root3) => createComponent(NodeItemProvider, {
            store: root3,
            get children() {
              return createComponent(RootNodeTimelineItem, {
                rowOffset: 1,
                children: (rowOffset) => createComponent(NodeTimelineItem2, {
                  rowOffset
                })
              });
            }
          })
        })];
      }
    }));
    return _el$;
  })();
}
function NodeTimelineItem2(props2) {
  let ref;
  const virtualContainerApi = useVirtualContainer();
  const timelineStore = useTimelineStore();
  const viewContext = useTimelineViewContext();
  const itemStore = useTimelineItem();
  const options2 = useAppOptions();
  const nbChildren = createMemo(() => itemStore.children.length);
  createEffect(() => {
    const periods = itemStore.periods;
    periods.forEach((p4) => {
      p4.start;
      p4.end;
    });
    itemStore.computeStackLevels();
  });
  const stackedRowCount = createMemo(() => itemStore.stackedRowCount);
  const onNewItem = (e3) => {
    const clickedDate = getNewItemDate(e3, timelineStore);
    console.log(moment_default(clickedDate).format("DD/MM/YYYY"));
  };
  const onPeriodCreated = (payload) => {
    viewContext.backend.createPeriod(payload);
  };
  onMount(() => {
    const obs = new ResizeObserver((entries2) => {
      if (itemStore.parent.isRoot && entries2[0]) {
        const height = entries2[0].contentRect.height;
        virtualContainerApi?.itemHeightSetter?.(height);
      }
    });
    if (itemStore.parent.isRoot) {
      obs.observe(ref);
    }
    onCleanup(() => obs.disconnect());
  });
  onCleanup(() => {
    itemStore.unhoverise();
  });
  return createComponent(TimelineRow, {
    ref: (elt) => ref = elt,
    "class": "group",
    get ["data-title"]() {
      return itemStore.title ?? itemStore.card?.title ?? itemStore.id;
    },
    get classList() {
      return {
        hovered: itemStore.isHovered
      };
    },
    get rowOffset() {
      return props2.rowOffset ?? 0;
    },
    get displayAllItems() {
      return options2.displayAllItems;
    },
    get children() {
      return [createComponent(SidebarItem, {}), createComponent(TimelineRow, {
        row: 0,
        "class": "timeline-card-row",
        get classList() {
          return {
            moving: itemStore.moving,
            resizing: itemStore.resizing,
            group: nbChildren() > 0
          };
        },
        get style() {
          return {
            "--stack-count": stackedRowCount()
          };
        },
        onMouseEnter: () => itemStore.hoverise(),
        onMouseLeave: () => itemStore.unhoverise(),
        onDblClick: onNewItem,
        get displayAllItems() {
          return options2.displayAllItems;
        },
        get children() {
          return [createComponent(ReferencedCardPeriodCreator, {
            onPeriodCreated
          }), createComponent(Show, {
            get when() {
              return nbChildren() === 0;
            },
            get fallback() {
              return createComponent(NodeTimelinePeriods, {
                get periods() {
                  return itemStore.periods;
                }
              });
            },
            get children() {
              return createComponent(For, {
                get each() {
                  return itemStore.periods;
                },
                children: (period) => createComponent(NodePeriodProvider, {
                  store: period,
                  get children() {
                    return createComponent(NodeTimelinePeriod, {});
                  }
                })
              });
            }
          })];
        }
      }), createComponent(Show, {
        get when() {
          return itemStore.visibleChild && itemStore.hasChildrenMatchingFilter;
        },
        get children() {
          return createComponent(For, {
            get each() {
              return itemStore.children;
            },
            children: (childStore, index2) => createComponent(NodeItemProvider, {
              store: childStore,
              get children() {
                return createComponent(NodeTimelineItem2, {
                  get rowOffset() {
                    return index2() + 1;
                  }
                });
              }
            })
          });
        }
      })];
    }
  });
}

// public/app/apps/cards/planning/PlanningViewWrapper.tsx
var _tmpl$164 = /* @__PURE__ */ template(`<div class="gantt-wizard-wrapper"><p></p></div>`, 4);
function PlanningViewWrapper(props2) {
  const options2 = useAppOptions();
  const availableDateAttributes = useAvailableAttributesOfType("date");
  return createComponent(Show, {
    get when() {
      return options2.relationship && options2.dateField;
    },
    get fallback() {
      return createComponent(Unconfigured2, {});
    },
    get children() {
      return createComponent(PlanningConfigProvider, {
        get children() {
          return createComponent(CommonCardTimelineWrapper, mergeProps(props2, {
            get timelineItemCreateFn() {
              return PlanningTimelineItemStore.create.bind(PlanningTimelineItemStore);
            },
            frontend: {
              onPeriodClick(_5, period) {
                const card = cardStore.get(period.id);
                props2.cardModal?.open(card, period);
              }
            },
            backend: {
              movePeriods(payloads) {
                const planningViewPayloads = payloads.map((payload) => {
                  const root3 = payload.item.getRoot();
                  const item = getTimelineItemStoreFromWeakMap(cardStore.get(payload.period.id), root3.group.id);
                  return {
                    ...payload,
                    item
                  };
                });
                updateReferencedDateAttributes(availableDateAttributes(), planningViewPayloads, options2.dateField).catch(autoCatchAsRequestErrorDialog([400]));
              },
              resizePeriod(start, end, payload) {
                const card = cardStore.get(payload.period.id);
                updateDateAttribute(card, getDateAttr(options2.dateField, availableDateAttributes(), card), start, end).catch(autoCatchAsRequestErrorDialog([400]));
              },
              createPeriod(payload) {
                const card = cardStore.get(payload.id);
                updateDateAttribute(card, getDateAttr(options2.dateField, availableDateAttributes(), card), payload.start, payload.end).catch(autoCatchAsRequestErrorDialog([400]));
              },
              deletePeriod(period, _5) {
                const card = cardStore.get(period.id);
                updateDateAttribute(card, getDateAttr(options2.dateField, availableDateAttributes(), card), void 0, void 0).catch(autoCatchAsRequestErrorDialog([400]));
              }
            },
            get children() {
              return createComponent(PlanningView, {});
            }
          }));
        }
      });
    }
  });
}
function Unconfigured2() {
  return (() => {
    const _el$ = _tmpl$164.cloneNode(true), _el$2 = _el$.firstChild;
    insert(_el$2, () => _4("To display the Planning view, you need to configure the date field and relationships from the appearance menu."));
    return _el$;
  })();
}

// public/app/apps/cards/planning/ng-components/planning.jsx
angular_default.module("kantree").directive("cardsAppPlanning", [function() {
  return {
    //---act as component
    scope: {},
    controllerAs: "$ctrl",
    restrict: "E",
    //---
    bindToController: {
      store: "<",
      board: "<?",
      filter: "<?",
      filterScopes: "<?",
      groupBy: "<?",
      options: "<?",
      matchingCardIds: "<?",
      onChange: "&"
    },
    templateUrl: "/static/app/apps/cards/planning/ng-components/templates/planning.html",
    controller: class extends angularClassMixin(AngularClass, CardsAppDateMixin) {
      static get $inject() {
        return (super.$inject || []).concat(["$scope", "$element", "$q", "$timeout", "cardModal"]);
      }
      $onInit() {
        injectI18nHelpersIntoScope(this.$scope);
        this.optionStore = PlanningAppOptions.create(this.options ?? {});
        this.groupBySignal = createSignal(this.groupBy);
        this.matchingCardIdsSignal = createSignal(this.matchingCardIds);
        this.datesEditableSignal = createSignal(this.datesEditable);
        const _self$ = this;
        this.PlanningView = () => createComponent(KeyboardProvider, {
          get children() {
            return createComponent(BoardProvider, {
              get board() {
                return _self$.board;
              },
              get children() {
                return createComponent(ProjectProvider, {
                  get board() {
                    return _self$.board;
                  },
                  get children() {
                    return createComponent(CardStoreProvider, {
                      get store() {
                        return _self$.store;
                      },
                      get children() {
                        return createComponent(ScopedModelStoreProvider, {
                          get children() {
                            return createComponent(ScopedGroupTypeStoreProvider, {
                              get children() {
                                return createComponent(AppOptionsProvider, {
                                  get store() {
                                    return _self$.optionStore;
                                  },
                                  get children() {
                                    return createComponent(AvailableAttributesProvider, {
                                      get children() {
                                        return createComponent(PlanningViewWrapper, {
                                          get cardModal() {
                                            return _self$.$cardModal;
                                          },
                                          get onChange() {
                                            return _self$.onChange;
                                          },
                                          get groupBySignal() {
                                            return _self$.groupBySignal;
                                          },
                                          get matchingCardIdsSignal() {
                                            return _self$.matchingCardIdsSignal;
                                          },
                                          get datesEditableSignal() {
                                            return _self$.datesEditableSignal;
                                          }
                                        });
                                      }
                                    });
                                  }
                                });
                              }
                            });
                          }
                        });
                      }
                    });
                  }
                });
              }
            });
          }
        });
      }
      $onChanges(changes) {
        if (changes.options && !changes.options.isFirstChange()) {
          this.optionStore.updateOptions(changes.options.currentValue);
        }
        if (changes.groupBy && !changes.groupBy.isFirstChange()) {
          this.groupBySignal[1](changes.groupBy.currentValue);
        }
        if (changes.matchingCardIds && !changes.matchingCardIds.isFirstChange()) {
          this.matchingCardIdsSignal[1](changes.matchingCardIds.currentValue);
        }
      }
    }
  };
}]);

// public/app/apps/global/cards/ng-components/cards.js
angular_default.module("kantree").component("globalCardsApp", {
  templateUrl: "/static/app/apps/global/cards/ng-components/templates/cards.html",
  bindings: {
    context: "<",
    withCount: "<",
    withEmptyNotice: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    constructor(...args) {
      super(...args);
      this.debounceRefreshGroupBy = debounce2(() => {
        this.refreshGroupBy();
        this.$scope.$applyAsync();
      }, 60);
    }
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      if (changes.context) {
        if (this.deregisterContextWatchers) this.deregisterContextWatchers();
        this.deregisterContextWatchers = offMany([
          this.context.watch("appOptions", (newVal, oldVal) => {
            this.mode = this.context.appOptions.mode;
            if (!equals((newVal || {}).include_archived, (oldVal || {}).include_archived)) {
              this.debounceRefreshGroupBy();
            }
          }),
          this.context.watch("cardStore", (newVal, oldVal) => {
            const oldResultsCount = this.resultsCount;
            this.resultsCount = this.context.cardStore ? this.context.cardStore.count() : null;
            this.refreshGroupBy();
            this.$scope.$applyAsync();
          }),
          this.context.watch("groupByGroups", (newVal, oldVal) => {
            this.debounceRefreshGroupBy();
          })
        ]);
      }
    }
    refreshGroupBy() {
      if (!this.context.cardStore || !this.context.groupByGroups) {
        this.groupBy = null;
        return;
      }
      this.groupBy = create2(
        this.context.appOptions.group_by,
        this.context.cardStore,
        null,
        this.context.appOptions.include_archived,
        this.context.groupByGroups
      );
    }
    updateContext(changes) {
      if (changes.options) {
        this.context.appOptions = { ...this.context.appOptions, ...changes.options };
      }
    }
    $onDestroy() {
      this.deregisterContextWatchers();
    }
  }
});

// public/app/apps/global/cards/ng-components/nav.js
angular_default.module("kantree").component("globalCardsAppNav", {
  templateUrl: "/static/app/apps/global/cards/ng-components/templates/nav.html",
  bindings: {
    context: "<",
    shrinked: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    constructor(...args) {
      super(...args);
      this.debounceRefreshGroupBy = debounce2(() => {
        this.refreshGroupBy();
        this.$scope.$applyAsync();
      }, 60);
    }
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isScreensizeXS = isScreensizeXS;
    }
    $onChanges(changes) {
      if (changes.context) {
        if (this.deregisterContextWatchers) this.deregisterContextWatchers();
        this.deregisterContextWatchers = offMany([
          this.context.watch("appOptions", (newVal, oldVal) => {
            this.mode = this.context.appOptions.mode;
            if (!equals((newVal || {}).include_archived, (oldVal || {}).include_archived)) {
              this.debounceRefreshGroupBy();
            } else {
              this.$scope.$applyAsync();
            }
          }),
          this.context.watch("cardStore", (newVal, oldVal) => {
            const oldResultsCount = this.resultsCount;
            this.resultsCount = this.context.cardStore ? this.context.cardStore.count() : null;
            if (oldResultsCount || this.resultsCount) {
              this.debounceRefreshGroupBy();
            }
          }),
          this.context.watch("groupByGroups", (newVal, oldVal) => {
            this.debounceRefreshGroupBy();
          })
        ]);
      }
    }
    get modeName() {
      return globalAppRegistry.get(this.mode)?.title;
    }
    get editable() {
      return !this.context.readonly && isConnected();
    }
    get showFilterScopesSelector() {
      return this.context.filterScopes?.[0]?.[0] !== "portfolio";
    }
    refreshGroupBy() {
      if (!this.context.cardStore || !this.context.groupByGroups) {
        this.groupBy = null;
        return;
      }
      this.groupBy = create2(
        this.context.appOptions.group_by,
        this.context.cardStore,
        null,
        this.context.appOptions.include_archived,
        this.context.groupByGroups
      );
    }
    updateContext(changes) {
      this.context.appOptions = { ...this.context.appOptions, ...changes.options };
    }
    refreshAll() {
      this.context.trigger("fetchAll");
    }
    $onDestroy() {
      this.deregisterContextWatchers();
    }
  }
});

// public/app/apps/global/cards/ng-components/projects-btn.js
angular_default.module("kantree").component("globalCardsAppProjectsBtn", {
  template: `
    <user-project-selector-btn class="btn btn-topbar"
      selected-projects-is-null-for-all="true"
      filter-scopes="$ctrl.context.filterScopes"
      is-multiple="true"
      readonly="$ctrl.context.readonly || !$ctrl.isConnected()"
      show-empty-warning="true"
      force-open-menu="$ctrl.forceOpenMenu"
      on-change="$ctrl.onFilterScopesChange($filterScopes)"
    ></user-project-selector-btn>
  `,
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.isConnected = isConnected;
      this.forceOpenMenu = this.context.filterScopes && this.context.filterScopes.length === 0;
      this.context.hideNav = this.context.filterScopes?.length === 0;
    }
    onFilterScopesChange(filterScopes) {
      this.context.filterScopes = filterScopes;
      this.context.hideNav = this.context.filterScopes?.length === 0;
    }
  }
});

// public/app/config/apps.js
var globalReportAppFilters = [
  {
    title: _lazy("Overdue cards"),
    filter: "{$date}<today() state!=done"
  }
];
var projectReportAppFilters = [
  {
    title: _lazy("Overdue cards"),
    filter: "{$date}<today() state!=done"
  }
];
var projectReportAppQueries = [
  {
    title: _lazy("Total number of cards"),
    query: {
      compute: "count"
    }
  },
  {
    title: _lazy("Number of remaining cards"),
    query: {
      compute: "query",
      query: "query(state!=done, count())"
    }
  },
  {
    title: _lazy("Number of completed cards"),
    query: {
      compute: "query",
      query: "query(state=done, count())"
    }
  },
  {
    title: _lazy("Number of overdue cards"),
    query: {
      compute: "query",
      query: "query({$date}<today(), count())"
    }
  },
  {
    title: _lazy("Workspace progression"),
    query: {
      "value_query": "query(state=done, count())",
      "total_query": "count()"
    },
    chart: "progressbar_query"
  }
];

// public/app/apps/global/report/ng-components/nav.js
angular_default.module("kantree").component("globalReportAppNav", {
  templateUrl: "/static/app/apps/global/report/ng-components/templates/nav.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$timeout", "$scope", "addReportWidgetModal", "$rootScope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.onForceRefreshAllWidgets = onForceRefreshAllWidgets;
    }
    $onChanges(changes) {
      if (changes.context) {
        if (this.deregisterContextWatcher) this.deregisterContextWatcher();
        this.widgets = (this.context.appOptions || {}).widgets || [];
        this.deregisterContextWatcher = this.context.watch("appOptions", (newVal, oldVal) => {
          if (!equals((newVal || {}).widgets, (oldVal || {}).widgets)) {
            this.widgets = (this.context.appOptions || {}).widgets || [];
            this.$scope.$applyAsync();
          }
        }, false);
      }
    }
    get editable() {
      return !this.context.readonly;
    }
    openChartLibrary() {
      const filterScopes = this.context.filterScopes || (this.widgets && this.widgets.length > 0 ? this.widgets[this.widgets.length - 1].filter_scopes : get(currentUser2.app_params, "myWorkFilterScopes", [["pinned"]]));
      const filter4 = this.widgets && this.widgets.length > 0 ? this.widgets[this.widgets.length - 1].filter : "state!=finished";
      const modalInstance = this.$addReportWidgetModal.open(filterScopes, filter4, { filters: globalReportAppFilters });
      modalInstance.result.then((widget) => {
        this.context.updateReportWidgets([...this.widgets, widget]);
      });
    }
    clearReport() {
      this.context.updateReportWidgets();
    }
    toggleFullscreen() {
      toggleFullscreen(jquery_default("global-report-app")[0]);
    }
    $onDestroy() {
      if (this.deregisterContextWatcher) this.deregisterContextWatcher();
    }
  }
});

// public/app/apps/global/report/ng-components/report.js
angular_default.module("kantree").component("globalReportApp", {
  templateUrl: "/static/app/apps/global/report/ng-components/templates/report.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$rootScope", "addReportWidgetModal", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isConnected = isConnected;
      this.isConnectionManagerDisabled = isConnectionManagerDisabled();
      this.$q.when(loadCharts(), (charts) => {
        this.charts = charts;
        this.refreshReportWidgets();
      });
      this.titleForEmpty = this.portfolioScoped ? _4("Create dashboard for your Portfolio using data from all its Workspaces.") : _4("Create global dashboards spanning multiple workspaces.");
    }
    $onChanges(changes) {
      if (changes.context) {
        if (this.deregisterContextWatcher) this.deregisterContextWatcher();
        this.refreshReportWidgets();
        this.deregisterContextWatcher = this.context.watch("appOptions", (newVal, oldVal) => {
          if (!equals(newVal?.widgets, oldVal?.widgets)) {
            this.refreshReportWidgets();
            this.$scope.$applyAsync();
          }
        }, false);
      }
    }
    get portfolioScoped() {
      return this.context.filterScopes?.[0]?.[0] === "portfolio";
    }
    get fetching() {
      return this._fetching;
    }
    set fetching(value2) {
      value2 = Boolean(value2);
      const oldValue = this._fetching;
      this._fetching = value2;
      if (this._fetching !== oldValue) {
        this.context.fetching = this._fetching;
      }
    }
    refreshReportWidgets() {
      this.widgets = this.formatWidgetsForDisplay(this.context.appOptions?.widgets);
    }
    formatWidgetsForDisplay(widgets = []) {
      return widgets.map((widget) => {
        const _widget = Object.assign({}, formatWidgetForDisplay(widget, this.charts));
        if (this.context.filterScopes) {
          _widget.filter_scopes = this.context.filterScopes;
        }
        return _widget;
      });
    }
    updateWidgets(widgets) {
      this.context.updateReportWidgets(widgets);
    }
    get editable() {
      return !this.context.readonly;
    }
    createFromAutoReport(report) {
      this.context.updateReportWidgets(report.widgets, report.title);
    }
    addWidget() {
      const filterScopes = this.context.filterScopes || get(currentUser2.app_params, "myWorkFilterScopes", [["pinned"]]);
      const modalInstance = this.$addReportWidgetModal.open(filterScopes, "state!=finished", { filters: globalReportAppFilters });
      modalInstance.result.then((widget) => {
        this.context.updateReportWidgets([widget]);
      });
    }
    $onDestroy() {
      if (this.deregisterContextWatcher) this.deregisterContextWatcher();
    }
  }
});

// public/app/config/default-activity-actions.js
var defaultActivityActions = [
  {
    display_name: _lazy("Created cards"),
    queryParams: {
      verb: "CREATE",
      object: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Updated cards"),
    queryParams: {
      verb: "UPDATE",
      object: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Moved cards"),
    queryParams: {
      verb: "MOVE",
      object: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Archived/Restored cards"),
    queryParams: {
      verb: ["ARCHIVE", "RESTORE"],
      object: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Deleted cards"),
    queryParams: {
      verb: "DELETE",
      object: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Assigned to cards"),
    queryParams: {
      verb: "UPDATE",
      object: { type: "Attribute" },
      sub_object: { type: "User" },
      target: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Attached files on cards"),
    queryParams: {
      verb: "UPDATE",
      object: { type: "Attribute" },
      sub_object: { type: "File" },
      target: { type: "Card" }
    }
  },
  {
    display_name: _lazy("Commented on cards"),
    queryParams: {
      verb: "CREATE",
      object: { type: "CardComment" }
    }
  },
  // {
  //   display_name: 'Log on card'
  // },
  {
    display_name: _lazy("Changed card state"),
    queryParams: {
      verb: "UPDATE",
      object: { type: "Card" },
      origin: true,
      target: true
    }
  },
  {
    display_name: _lazy("Changed card type"),
    queryParams: {
      verb: "UPDATE",
      object: { type: "Card" },
      target: { type: "CardModel" }
    }
  },
  {
    display_name: _lazy("Deleted card type"),
    queryParams: {
      verb: "DELETE",
      object: { type: "CardModel" }
    }
  },
  // {
  //   display_name: 'Subscribe/Unsubscribe to card'
  // },
  {
    display_name: _lazy("Created groups"),
    queryParams: {
      verb: "CREATE",
      object: { type: "CardGroup" }
    }
  },
  {
    display_name: _lazy("Updated groups"),
    queryParams: {
      verb: "UPDATE",
      object: { type: "CardGroup" }
    }
  },
  {
    display_name: _lazy("Archived/Restored groups"),
    queryParams: {
      verb: ["ARCHIVE", "RESTORE"],
      object: { type: "CardGroup" }
    }
  },
  {
    display_name: _lazy("Deleted groups"),
    queryParams: {
      verb: "DELETE",
      object: { type: "CardGroup" }
    }
  },
  {
    display_name: _lazy("Join/Leave workspaces"),
    queryParams: {
      verb: ["JOIN", "LEFT"]
    }
  }
];

// public/app/apps/project/activities/menus/filters.js
angular_default.module("kantree").service("projectActivitiesAppFilterMenu", class extends AngularClass {
  static $inject = ["$sanitize", "$sce"];
  getActorItems(project, filters, onFilterChange) {
    return projectMemberStore.scopedByProject(project).query().map((m3) => {
      return {
        label: m3.user.display_name,
        selected: function() {
          return filters && filters.actors && filters.actors.indexOf(m3.user.id) !== -1;
        },
        img: userAvatarUrl(m3.user),
        action: () => {
          let actors = filters && filters.actors || [];
          if (actors.indexOf(m3.user.id) !== -1) {
            actors = actors.filter((id) => id !== m3.user.id);
          } else {
            actors = actors.concat([m3.user.id]);
          }
          onFilterChange({ ...filters || {}, actors });
        },
        noCloseAfterAction: true,
        enableActionOnselected: true
      };
    }).concat([
      { label: "--" },
      {
        label: _4("Deselect all"),
        action: () => {
          onFilterChange({ ...filters || {}, actors: [] });
        }
      }
    ]);
  }
  getActionItems(project, filters, onFilterChange) {
    return defaultActivityActions.map((action) => {
      return {
        label: action.display_name,
        selected: () => {
          if (!filters || !filters.actions) return false;
          return !!filters.actions.find((queryParams) => equals(queryParams, action.queryParams));
        },
        action: () => {
          let actions2 = filters && filters.actions || [];
          if (actions2.find((a3) => equals(a3, action.queryParams))) {
            actions2 = actions2.filter((a3) => !equals(a3, action.queryParams));
          } else {
            actions2 = actions2.concat([action.queryParams]);
          }
          onFilterChange({ ...filters || {}, actions: actions2 });
        },
        noCloseAfterAction: true,
        enableActionOnselected: true
      };
    }).concat([
      { label: "--" },
      {
        label: _4("Deselect all"),
        action: () => {
          onFilterChange({ ...filters || {}, actions: [] });
        }
      }
    ]);
  }
  getButtonLabel(project, filters, highlightSelection) {
    if (!filters || (!filters.actors || !filters.actors.length) && (!filters.actions || !filters.actions.length)) {
      return _4("Showing all actions for everybody");
    }
    let actions2 = [], actors = [];
    if (filters.actors) {
      actors = filters.actors.map((userId) => {
        const m3 = projectMemberStore.scopedByProject(project).getByUserId(userId);
        if (m3) {
          return this.$sanitize(m3.user.display_name);
        }
      }).filter(Boolean);
      if (actors.length > 3) {
        actors = actors.slice(0, 3).concat(["..."]);
      }
    }
    if (filters.actions) {
      actions2 = filters.actions.map((queryParams) => {
        return defaultActivityActions.find((action) => equals(queryParams, action.queryParams)).display_name.toLowerCase();
      });
      if (actions2.length > 3) {
        actions2 = actions2.slice(0, 3).concat(["..."]);
      }
    }
    const actionsLabel = actions2.length ? actions2.join(", ") : _4("all actions");
    const actorsLabel = actors.length ? actors.join(", ") : _4("everybody");
    return this.$sce.trustAsHtml(_4("Only showing {actions} for {actors}", {
      actions: highlightSelection ? `<strong>${actionsLabel}</strong>` : actionsLabel,
      actors: highlightSelection ? `<strong>${actorsLabel}</strong>` : actorsLabel
    }));
  }
  getTabs(project, filters, onFilterChange) {
    return [
      {
        title: _4("Members"),
        items: this.getActorItems(project, filters, onFilterChange)
      },
      {
        title: _4("Actions"),
        items: this.getActionItems(project, filters, onFilterChange)
      }
    ];
  }
  get(project, filters, onFilterChange) {
    return {
      config: () => () => this.getTabs(project, filters, onFilterChange),
      options: {
        watch: (cb2, scope) => projectMemberStore.scopedByProject(project).$watchAll(scope, cb2, false),
        withTabs: true
      }
    };
  }
});

// public/app/apps/project/activities/ng-components/activities.js
angular_default.module("kantree").component("projectActivitiesApp", {
  template: `
    <date-navigator range="$ctrl.activeDateRange" on-change="$ctrl.onDatesChange($range)"
      show-arrows="!$ctrl.context.shareMode" show-datepicker="!$ctrl.context.shareMode"></date-navigator>
    <div class="activities-stream" ng-if="!!$ctrl.filteredStore">
      <activities store="$ctrl.filteredStore" limit="false" empty-message="{{$ctrl.noActivityLabel}}"
        hours-only="true" grouped-by-date="{{ $ctrl.groupedByDate }}"></activities>
    </div>
  `,
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    unixToServerFormat(date) {
      return parseTimestamp(date).format(this.serverDateFormat);
    }
    get filters() {
      return this.context.appOptions?.filters || {};
    }
    $onInit() {
      this.serverDateFormat = "YYYY-MM-DD HH:mm:ss";
      this.loadedDateRange = {};
      this.noActivityLabel = _4("No activity");
      this.debouncedRefreshFilteredStore = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshFilteredStore();
        });
      }, 30);
      this.loadActivities(this.filters.dates || "today");
      this.refreshActiveActions();
      this.refreshActiveDates();
      projectMemberStore.scopedByProject(this.context.project).$watchAll(this.$scope, () => {
        this.members = projectMemberStore.scopedByProject(this.context.project).query().map((m3) => m3.user);
        this.refreshActiveActors();
        this.debouncedRefreshFilteredStore();
      });
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        const oldFilters = oldVal?.filters;
        if (!equals(oldFilters?.dates, this.filters?.dates)) {
          this.loadActivities(this.filters?.dates || "today");
          this.refreshActiveDates();
          this.debouncedRefreshFilteredStore();
        }
        if (!equals(oldFilters?.actors, this.filters?.actors)) {
          this.refreshActiveActors();
          this.debouncedRefreshFilteredStore();
        }
        if (!equals(oldFilters?.actions, this.filters?.actions)) {
          this.refreshActiveActions();
          this.debouncedRefreshFilteredStore();
        }
      }, false);
    }
    loadActivities(dateRange) {
      if (!dateRange) return;
      let specialDateRange;
      let newDateRange = {};
      let newStartDate, newEndDate;
      if (angular_default.isString(dateRange)) {
        specialDateRange = specialDateRanges.find((date) => dateRange === date.name);
        newDateRange = {
          start: specialDateRange.startDate.clone().startOf("day").unix(),
          end: specialDateRange.endDate.clone().endOf("day").unix()
        };
      } else {
        newDateRange = dateRange;
      }
      if (!this.loadedDateRange.start || newDateRange.start < this.loadedDateRange.start) {
        newStartDate = newDateRange.start;
      }
      if (!this.loadedDateRange.end || newDateRange.end > this.loadedDateRange.end) {
        newEndDate = newDateRange.end;
      }
      if (typeof newStartDate !== "undefined" || typeof newEndDate !== "undefined") {
        if (this.context.project) {
          this.$q.digest(loadAllActivitiesForProjectBetweenDates(
            this.context.project,
            this.unixToServerFormat(newStartDate || this.loadedDateRange.end),
            this.unixToServerFormat(newEndDate || this.loadedDateRange.start)
          ));
          this.loadedDateRange.end = newEndDate || this.loadedDateRange.end;
          this.loadedDateRange.start = newStartDate || this.loadedDateRange.start;
        }
      }
    }
    refreshFilteredStore() {
      const queryFilters = [];
      if (this.activeActors && this.activeActors.length) {
        queryFilters.push(query_exports.objMatch({
          // Testing nullity for Trello, Slack, Gitlab, etc actor
          actor: query_exports.and(query_exports.notNull(), query_exports.objMatch({ id: query_exports.any(this.activeActors.map((a3) => a3.id)) }))
        }));
      }
      if (this.activeActions && this.activeActions.length) {
        queryFilters.push(query_exports.or.apply(this, this.activeActions.map((action) => {
          var queryParams = action.queryParams;
          var tmpQuery = {};
          if (queryParams.verb) {
            tmpQuery.verb = angular_default.isArray(queryParams.verb) ? query_exports.any(queryParams.verb) : queryParams.verb;
          }
          if (queryParams.object) {
            tmpQuery.object = query_exports.objMatch(queryParams.object);
          }
          if (queryParams.sub_object) {
            tmpQuery.sub_object = query_exports.objMatch(queryParams.sub_object);
          }
          if (queryParams.origin === true) {
            tmpQuery.origin = query_exports.notNull();
          }
          if (queryParams.target) {
            if (isObject2(queryParams.target)) {
              tmpQuery.target = query_exports.objMatch(queryParams.target);
            }
            if (queryParams.target === true) {
              tmpQuery.target = query_exports.notNull();
            }
          }
          return query_exports.objMatch(tmpQuery);
        })));
      }
      queryFilters.push(query_exports.objMatch({
        date: (prop2) => {
          return !this.activeDateRange || parseTimestamp(prop2).isBetween(this.activeDateRange.start, this.activeDateRange.end, "day", "[]");
        }
      }));
      this.filteredStore = activityStore.scopedByProject(this.context.project).scopedByActivitiesOnly().scoped(() => query_exports.and(...queryFilters));
    }
    refreshActiveActors() {
      if (this.members && this.filters && this.filters.actors) {
        this.activeActors = this.members.filter((member) => this.filters.actors.indexOf(member.id) !== -1);
      } else {
        this.activeActors = [];
      }
    }
    refreshActiveActions() {
      if (this.filters && this.filters.actions) {
        this.activeActions = defaultActivityActions.filter((defaultAction) => {
          return this.filters.actions.find((actionFilters) => equals(actionFilters, defaultAction.queryParams));
        });
      } else {
        this.activeActions = [];
      }
    }
    refreshActiveDates() {
      this.activeDateRange = dateRangeToActiveRange(this.filters && this.filters.dates);
      this.groupedByDate = !this.activeDateRange.start.isSame(this.activeDateRange.end, "day");
    }
    onDatesChange(dates) {
      this.context.appOptions = { ...this.context.appOptions, filters: { ...this.filters, dates } };
    }
  }
});

// public/app/actions/activity.ts
function exportActivities(project, fromDate, toDate) {
  return api_default.projects.export_activities.post({
    project_id: project.id,
    from_date: fromDate.format("YYYY-MM-DD"),
    to_date: toDate.format("YYYY-MM-DD")
  });
}

// public/app/apps/project/activities/ng-components/nav.js
angular_default.module("kantree").component("projectActivitiesAppNav", {
  template: `
    <button class="btn btn-topbar" drop-menu="$ctrl.menu" ng-if="$ctrl.menu">
      <i class="fa fa-filter"></i><span>{{$ctrl.label}}</span>
      <span class="bi-caret-down-fill"></span>
    </button>
    <button class="btn btn-topbar" drop-menu="$ctrl.exportMenu" ng-show="$ctrl.canExportData" hide-offline>
      <i class="fa fa-download"></i> {{::$ctrl.exportBtnLabel}}
    </button>
  `,
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "projectActivitiesAppFilterMenu", "$rootScope", "$q"];
    $onInit() {
      this.exportBtnLabel = _4("Export");
      this.debounceRefreshFilterMenu = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshFilterMenu();
        });
      }, 30);
      this.options = this.context.appOptions;
      this.filters = (this.options || {}).filters || {};
      this.debounceRefreshFilterMenu();
      this.refreshActiveDates();
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        const oldFilters = this.options.filters;
        this.options = this.context.appOptions;
        this.filters = (this.context.appOptions || {}).filters;
        this.debounceRefreshFilterMenu();
        if (!equals((oldFilters || {}).dates, (this.filters || {}).dates)) {
          this.refreshActiveDates();
        }
      }, false);
      this.exportMenu = { config: [{
        label: _4("Export to CSV"),
        icon: "download",
        action: () => {
          this.$q.when(exportActivities(this.context.project, this.activeDateRange.start, this.activeDateRange.end), (id) => {
            waitForAsyncDownload(id, _4("Your export is being processed"));
          });
        }
      }] };
      this.canExportData = !this.context.shareMode && canExportData(this.context.project);
    }
    refreshFilterMenu() {
      this.menu = this.$projectActivitiesAppFilterMenu.get(this.context.project, this.filters, (filters) => {
        this.context.appOptions = { ...this.options || {}, filters };
      });
      this.label = this.$projectActivitiesAppFilterMenu.getButtonLabel(true, this.context.project, this.filters);
    }
    refreshActiveDates() {
      this.activeDateRange = dateRangeToActiveRange(this.filters && this.filters.dates);
      this.groupedByDate = !this.activeDateRange.start.isSame(this.activeDateRange.end, "day");
    }
    $onDestroy() {
      if (this.deregisterContextWatcher) this.deregisterContextWatcher();
    }
  }
});

// public/app/apps/project/automations/modals/share.js
angular_default.module("kantree").service("automationRuleShareModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(project, rule) {
    const instance = this.$uibModal.open({
      windowClass: "automation-rule-share-modal",
      component: "automationRuleShareModal",
      resolve: {
        rule: () => rule,
        project: () => project
      }
    });
    return instance.result;
  }
});
angular_default.module("kantree").component("automationRuleShareModal", {
  templateUrl: "/static/app/apps/project/automations/ng-components/templates/share-modal.html",
  bindings: {
    close: "&",
    dismiss: "&",
    resolve: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.rule = this.resolve.rule;
      this.refreshURL();
      this.runnable = false;
      this.$q.when(loadAvailableAutomationEvents(), (eventTypes) => {
        const triggerEvent = eventTypes.find((t3) => t3.name === this.rule.trigger_event);
        this.runnable = triggerEvent && triggerEvent.trigger_only && !triggerEvent.provides_card;
      });
    }
    refreshURL() {
      this.$q.when(createAutomationRunToken(this.resolve.project, this.rule), (token) => {
        this.url = makeUrlAbsolute(`/trigger-automation/${token}`);
      });
    }
    invalidate() {
      confirmDeleteDialog2(
        null,
        _4("All existing URLs will become unusable"),
        _4("Invalidate")
      ).then(() => {
        this.$q.when(invalidAutomationRunTokens(this.resolve.project, this.rule), () => this.refreshURL());
      });
    }
  }
});

// public/app/apps/project/automations/components/rule-tile.jsx
var _tmpl$165 = /* @__PURE__ */ template(`<span class="badge badge-sm ms-2 bg-danger"><i class="bi-exclamation-triangle-fill"></i> </span>`, 4);
var _tmpl$279 = /* @__PURE__ */ template(`<span class="badge badge-sm ms-2"><i class="bi-pause"></i> </span>`, 4);
var _tmpl$354 = /* @__PURE__ */ template(`<div><span class="date"></span></div>`, 4);
var _tmpl$439 = /* @__PURE__ */ template(`<button drop-menu class="btn btn-icon"><i class="bi-three-dots-vertical"></i></button>`, 4);
var _tmpl$533 = /* @__PURE__ */ template(`<div class="automation-rule-tile"><div><div class="inner"><div><span class="title"></span><span class="trigger"></span></div><div></div><div></div></div></div></div>`, 16);
var _tmpl$626 = /* @__PURE__ */ template(`<i></i>`, 2);
function RuleTile(props2) {
  const [icon, setIcon] = createSignal(null);
  const [runnable, setRunnable] = createSignal(false);
  const [running, setRunning] = createSignal(false);
  const [eventTypes, setEventTypes] = createSignal(null);
  const canManage = canManageAutomations(props2.project);
  const canRun = canRunAutomations(props2.project);
  const canAddToToolbar = canManageAttributes(props2.project) && props2.rule.trigger_event === "manual_card";
  const $actionsAppearanceEditorMenuFactory = ngApp.$injector.get("actionsAppearanceEditorMenuFactory");
  const appearanceDropMenu = $actionsAppearanceEditorMenuFactory.get(props2.rule, props2.project);
  const dropState = new DropdownState();
  function getDropMenu() {
    return [{
      label: _4("Duplicate"),
      icon: "clone",
      action: () => {
        dropState.close();
        duplicateAutomationRule(props2.project, props2.rule);
      }
    }, {
      label: _4("Edit appearance"),
      icon: "pencil",
      submenu: appearanceDropMenu.config,
      options: appearanceDropMenu.options
    }, {
      label: "--"
    }, {
      label: _4("Delete"),
      icon: "trash",
      action: () => {
        dropState.close();
        confirmDeleteDialog2().then(() => deleteAutomationRule(props2.project, props2.rule));
      }
    }];
  }
  function getRuleIcon(triggerEvent) {
    if (props2.rule.icon) {
      return props2.rule.icon;
    }
    if (props2.rule.trigger_event === "scheduled") {
      return "bi-calendar-week";
    } else if (props2.rule.trigger_event === "manual_card") {
      return "bi-hand-index";
    } else if (triggerEvent && triggerEvent.trigger_only) {
      return "bi-play-circle";
    }
    return "bolt";
  }
  createEffect(async () => {
    if (!eventTypes()) setEventTypes(await loadAvailableAutomationEvents());
    const triggerEvent = eventTypes().find((t3) => t3.name === props2.rule.trigger_event);
    setRunnable(canRun && triggerEvent && triggerEvent.trigger_only && !triggerEvent.provides_card && (canManage || triggerEvent.name != "scheduled"));
    let icon2 = props2.rule.icon;
    if (!icon2) {
      icon2 = getRuleIcon(triggerEvent);
    }
    setIcon(icon2);
  });
  async function run3() {
    setRunning(true);
    await runAutomationRule(props2.project, props2.rule);
    setTimeout(() => {
      setRunning(false);
      toastNotify(_4("Triggered automation"), "success");
    }, 500);
  }
  const getTextColor = createMemo(() => {
    return props2.rule.background_color ? textColor(props2.rule.background_color) : null;
  });
  return (() => {
    const _el$ = _tmpl$533.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.firstChild, _el$12 = _el$5.nextSibling, _el$13 = _el$4.nextSibling, _el$16 = _el$13.nextSibling;
    _el$2.$$click = () => canManage && props2.onRuleClick(props2.rule);
    _el$2.disabled = !canManage;
    insert(_el$2, createComponent(Icon, {
      get name() {
        return icon();
      },
      get style() {
        return {
          color: getTextColor()
        };
      }
    }), _el$3);
    insert(_el$5, () => props2.rule.name, null);
    insert(_el$5, createComponent(Show, {
      get when() {
        return props2.rule.is_erroring;
      },
      get children() {
        const _el$6 = _tmpl$165.cloneNode(true), _el$7 = _el$6.firstChild, _el$8 = _el$7.nextSibling;
        insert(_el$6, () => _4("Error"), null);
        return _el$6;
      }
    }), null);
    insert(_el$5, createComponent(Show, {
      get when() {
        return !props2.rule.active;
      },
      get children() {
        const _el$9 = _tmpl$279.cloneNode(true), _el$10 = _el$9.firstChild, _el$11 = _el$10.nextSibling;
        insert(_el$9, () => _4("Paused"), null);
        return _el$9;
      }
    }), null);
    insert(_el$12, () => props2.rule.trigger_title);
    _el$13.style.setProperty("flex", "1");
    insert(_el$3, createComponent(Show, {
      get when() {
        return props2.rule.last_trigger_at;
      },
      get children() {
        const _el$14 = _tmpl$354.cloneNode(true), _el$15 = _el$14.firstChild;
        insert(_el$15, () => _4(`Last triggered {fromNowTime}`, {
          fromNowTime: fromNow(props2.rule.last_trigger_at)
        }));
        createRenderEffect(() => _el$15.style.setProperty("color", getTextColor()));
        return _el$14;
      }
    }), _el$16);
    insert(_el$16, createComponent(Show, {
      get when() {
        return runnable();
      },
      get children() {
        return createComponent(Button, {
          onClick: (event2) => {
            event2.stopPropagation();
            run3();
          },
          "class": "btn btn-default btn-sm",
          get disabled() {
            return running();
          },
          get label() {
            return [(() => {
              const _el$19 = _tmpl$626.cloneNode(true);
              createRenderEffect(() => className(_el$19, running() ? "fa fa-spin fa-spinner" : "bi-play-fill"));
              return _el$19;
            })(), createMemo(() => _4("Run now"))];
          }
        });
      }
    }), null);
    insert(_el$16, createComponent(Show, {
      when: canAddToToolbar,
      get children() {
        return createComponent(Button, {
          onClick: async (event2) => {
            event2.stopPropagation();
            await api_default.project_automations.add_toolbar_action.post({
              project_id: props2.project.id,
              rule_id: props2.rule.id
            });
            $invoke(["cardModal", function(cardModal) {
              cardModal.openEmpty(props2.project.top_level_card, {
                title: _4("Example card")
              });
            }]);
          },
          "class": "btn btn-default btn-sm",
          get label() {
            return [createComponent(Icon, {
              name: "bi-plus-square"
            }), createMemo(() => _4("Add to card toolbar"))];
          }
        });
      }
    }), null);
    insert(_el$, createComponent(Show, {
      when: canManage,
      get children() {
        return createComponent(DropdownContext.Provider, {
          value: dropState,
          get children() {
            return [createComponent(DropdownTrigger, {
              get children() {
                const _el$17 = _tmpl$439.cloneNode(true), _el$18 = _el$17.firstChild;
                createRenderEffect((_p$) => {
                  const _v$ = props2.rule.background_color ? lightenColor(props2.rule.background_color) : "#f5f5f5", _v$2 = getTextColor();
                  _v$ !== _p$._v$ && _el$17.style.setProperty("--hover-color", _p$._v$ = _v$);
                  _v$2 !== _p$._v$2 && _el$18.style.setProperty("color", _p$._v$2 = _v$2);
                  return _p$;
                }, {
                  _v$: void 0,
                  _v$2: void 0
                });
                return _el$17;
              }
            }), createComponent(DropdownContent, {
              get children() {
                return createComponent(PrettyMenu, {
                  get config() {
                    return getDropMenu();
                  }
                });
              }
            })];
          }
        });
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$3 = props2.rule.background_color, _v$4 = getTextColor(), _v$5 = getTextColor(), _v$6 = getTextColor();
      _v$3 !== _p$._v$3 && _el$.style.setProperty("background-color", _p$._v$3 = _v$3);
      _v$4 !== _p$._v$4 && _el$.style.setProperty("color", _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && _el$4.style.setProperty("color", _p$._v$5 = _v$5);
      _v$6 !== _p$._v$6 && _el$5.style.setProperty("color", _p$._v$6 = _v$6);
      return _p$;
    }, {
      _v$3: void 0,
      _v$4: void 0,
      _v$5: void 0,
      _v$6: void 0
    });
    return _el$;
  })();
}
delegateEvents(["click"]);

// public/app/apps/project/automations/components/automations.jsx
var _tmpl$166 = /* @__PURE__ */ template(`<div class="project-automations-app"><div class="project-automations-app-list"></div></div>`, 4);
var _tmpl$280 = /* @__PURE__ */ template(`<div class="board-empty-notice"><p></p><video autoplay loop muted><source type="video/mp4"><source type="video/webm"></video></div>`, 8);
var _tmpl$355 = /* @__PURE__ */ template(`<div><div><div class="category-accordion-header"><i></i><h3></h3></div></div></div>`, 10);
var _tmpl$440 = /* @__PURE__ */ template(`<br>`, 1);
function AutomationsApp(props2) {
  const automaticCardRules = () => props2.rules.filter((rule) => !["manual", "manual_card", "scheduled"].includes(rule.trigger_event));
  const manualCardRules = () => props2.rules.filter((rule) => rule.trigger_event === "manual_card");
  const manualWorkspaceRules = () => props2.rules.filter((rule) => rule.trigger_event === "manual");
  const scheduledRules = () => props2.rules.filter((rule) => rule.trigger_event === "scheduled");
  function onRuleEditorChange($valid) {
    props2.context.trigger("onEditorChange", $valid);
  }
  onRuleEditorChange.$inject = ["$valid"];
  return [createComponent(Show, {
    get when() {
      return !props2.editing && props2.rules.length > 0;
    },
    get children() {
      const _el$ = _tmpl$166.cloneNode(true), _el$2 = _el$.firstChild;
      insert(_el$2, createComponent(Show, {
        get when() {
          return automaticCardRules().length > 0;
        },
        get children() {
          return createComponent(AutomationsAppCategory, {
            id: "automatic",
            get name() {
              return _4("Automatic actions on cards");
            },
            get automations() {
              return automaticCardRules();
            },
            get onClick() {
              return props2.onRuleClick;
            },
            get project() {
              return props2.context.project;
            },
            get onCreateRule() {
              return props2.onCreateRule;
            }
          });
        }
      }), null);
      insert(_el$2, createComponent(Show, {
        get when() {
          return manualCardRules().length > 0;
        },
        get children() {
          return createComponent(AutomationsAppCategory, {
            id: "manual_card",
            get name() {
              return _4("Manual actions on cards");
            },
            get automations() {
              return manualCardRules();
            },
            get onClick() {
              return props2.onRuleClick;
            },
            get project() {
              return props2.context.project;
            },
            get onCreateRule() {
              return props2.onCreateRule("manual_card");
            },
            get introBanner() {
              return createComponent(ManualActionsOnCardsIntroBanner, {});
            }
          });
        }
      }), null);
      insert(_el$2, createComponent(Show, {
        get when() {
          return manualWorkspaceRules().length > 0;
        },
        get children() {
          return createComponent(AutomationsAppCategory, {
            id: "manual",
            get name() {
              return _4("Manual actions on workspace");
            },
            get automations() {
              return manualWorkspaceRules();
            },
            get onClick() {
              return props2.onRuleClick;
            },
            get project() {
              return props2.context.project;
            },
            get onCreateRule() {
              return props2.onCreateRule("manual");
            },
            get introBanner() {
              return createComponent(ManualActionsOnProjectsIntroBanner, {});
            }
          });
        }
      }), null);
      insert(_el$2, createComponent(Show, {
        get when() {
          return scheduledRules().length > 0;
        },
        get children() {
          return createComponent(AutomationsAppCategory, {
            id: "scheduled",
            get name() {
              return _4("Scheduled actions");
            },
            get automations() {
              return scheduledRules();
            },
            get onClick() {
              return props2.onRuleClick;
            },
            get project() {
              return props2.context.project;
            },
            get onCreateRule() {
              return props2.onCreateRule("scheduled");
            }
          });
        }
      }), null);
      return _el$;
    }
  }), createComponent(Show, {
    get when() {
      return !props2.editing && !props2.rules.length && !props2.loading;
    },
    get children() {
      const _el$3 = _tmpl$280.cloneNode(true), _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling, _el$6 = _el$5.firstChild, _el$7 = _el$6.nextSibling;
      createRenderEffect((_p$) => {
        const _v$ = _4("From workflow automations to business apps,<br>use our no-code automations to boot your workspace"), _v$2 = prependBaseUrl("/static/assets/tour/videos/placeholder-automations.mp4"), _v$3 = prependBaseUrl("/static/assets/tour/videos/placeholder-automations.webm");
        _v$ !== _p$._v$ && (_el$4.innerHTML = _p$._v$ = _v$);
        _v$2 !== _p$._v$2 && setAttribute(_el$6, "src", _p$._v$2 = _v$2);
        _v$3 !== _p$._v$3 && setAttribute(_el$7, "src", _p$._v$3 = _v$3);
        return _p$;
      }, {
        _v$: void 0,
        _v$2: void 0,
        _v$3: void 0
      });
      return _el$3;
    }
  })];
}
function AutomationsAppCategory(props2) {
  const [showAccordion, setShowAccordion] = createSignal(localStorage.getItem(`automationCollapse_${props2.id}`) === null ? true : localStorage.getItem(`automationCollapse_${props2.id}`) === "true");
  function toggleAccordion() {
    setShowAccordion((prev) => !prev);
    localStorage.setItem(`automationCollapse_${props2.id}`, showAccordion());
  }
  return (() => {
    const _el$8 = _tmpl$355.cloneNode(true), _el$9 = _el$8.firstChild, _el$10 = _el$9.firstChild, _el$11 = _el$10.firstChild, _el$12 = _el$11.nextSibling;
    _el$9.style.setProperty("display", "flex");
    _el$9.style.setProperty("gap", "0.5rem");
    _el$10.$$click = () => {
      toggleAccordion();
    };
    insert(_el$12, () => props2.name);
    insert(_el$10, (() => {
      const _c$ = createMemo(() => !!canManageAutomations(props2.project));
      return () => _c$() && createComponent(IconButton, {
        icon: "bi-plus",
        "class": "header-button hidden-xs",
        onClick: (event2) => {
          event2.stopPropagation();
          props2.onCreateRule();
        }
      });
    })(), null);
    insert(_el$8, createComponent(Show, {
      get when() {
        return showAccordion();
      },
      get children() {
        return [createComponent(Show, {
          get when() {
            return props2.introBanner;
          },
          get children() {
            return props2.introBanner;
          }
        }), createComponent(For, {
          get each() {
            return props2.automations;
          },
          children: (rule) => createComponent(RuleTile, {
            get onRuleClick() {
              return props2.onClick;
            },
            rule,
            get project() {
              return props2.project;
            }
          })
        })];
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$4 = `bi bi-caret-${showAccordion() ? "down" : "up"}-fill`, _v$5 = props2.id;
      _v$4 !== _p$._v$4 && className(_el$11, _p$._v$4 = _v$4);
      _v$5 !== _p$._v$5 && setAttribute(_el$12, "id", _p$._v$5 = _v$5);
      return _p$;
    }, {
      _v$4: void 0,
      _v$5: void 0
    });
    return _el$8;
  })();
}
function ManualActionsOnCardsIntroBanner() {
  return createComponent(Tip, {
    onboardingMarker: "automations_card_actions_business_apps",
    get children() {
      return [createMemo(() => _4("Use manual actions on cards combined with card toolbars to create workflow driven business apps.")), _tmpl$440.cloneNode(true), createComponent(HelpLink, {
        guide: "business-apps",
        get children() {
          return _4("Learn more about creating business apps in Kantree");
        }
      })];
    }
  });
}
function ManualActionsOnProjectsIntroBanner() {
  return createComponent(Tip, {
    onboardingMarker: "automations_project_actions_business_apps",
    get children() {
      return [createMemo(() => _4("Use manual actions on projects combined with locked view toolbars to create workflow driven workspaces.")), _tmpl$440.cloneNode(true), createComponent(HelpLink, {
        guide: "customization",
        anchor: "save-views",
        get children() {
          return _4("Learn more about customizing views");
        }
      })];
    }
  });
}
delegateEvents(["click"]);

// public/app/apps/project/automations/ng-components/automations.js
angular_default.module("kantree").component("projectAutomationsApp", {
  templateUrl: "/static/app/apps/project/automations/ng-components/templates/automations.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.SolidAutomations = AutomationsApp;
      this.editRuleFun = this.editRule.bind(this);
      this.createRuleFun = this.createRule.bind(this);
      this.loading = true;
      this.canManageAutomations = canManageAutomations(this.context.project);
      this.$q.all([loadAvailableAutomationEvents(), loadAvailableAutomationActions()]);
      this.loadRules();
      this.context.$on(this.$scope, "addRule", (event2) => this.createRule(event2));
      this.context.$on(this.$scope, "stopEdit", () => {
        this.editing = null;
        setTimeout(() => {
          this.$element[0].scrollTo({ left: 0, top: this.scrollPosition, behavior: "instant" });
        }, 5);
      });
      this.context.$on(this.$scope, "editRule", (ruleId) => {
        if (!this.canManageAutomations) return;
        const rule = this.rules.find((r3) => r3.id === ruleId);
        this.editRule(rule);
      });
      this.context.$on(this.$scope, "createGroupRule", (group2) => {
        this.createRule();
        let gt = cardGroupTypeStore.tryGet(group2.type_id);
        if (gt.attribute_id) {
          this.editing.trigger_event = "card_field_updated";
          this.editing.trigger_options = { attribute: { id: gt.attribute_id, name: gt.name } };
          this.editing.sequence.push({ branches: [[
            `"${group2.title}" in {${gt.name}}`,
            []
          ]] });
        } else {
          this.editing.trigger_event = "card_added_to_group";
          this.editing.trigger_options = { group: { id: group2.id, name: group2.title } };
        }
      });
    }
    loadRules() {
      const store2 = automationRuleStore.scopedByProject(this.context.project);
      store2.$watchAll(this.$scope, () => {
        this.rules = store2.query();
      });
      this.$q.when(loadAutomationRulesForProject(this.context.project), () => {
        this.loading = false;
      });
    }
    createRule(triggerEvent = null) {
      this.scrollPosition = this.$element[0].scrollTop;
      this.editing = {
        name: _4("Automation {count}", { count: this.rules.length + 1 }),
        trigger_event: triggerEvent,
        trigger_options: {},
        sequence: [],
        active: true
      };
      this.isNew = true;
      this.context.trigger("startEdit", this.editing, this.isNew);
    }
    editRule(rule) {
      this.scrollPosition = this.$element[0].scrollTop;
      this.editing = angular_default.copy(rule);
      this.isNew = false;
      this.context.trigger("startEdit", this.editing, this.isNew);
    }
    $postLink() {
      activateViewScroll(
        this.$element,
        null,
        "automation-rule-editor, automation-rule-editor-sequence, automation-rule-editor-sequence > div, automation-rule-editor-branches > div",
        true
      );
    }
  }
});
angular_default.module("kantree").component("projectAutomationsAppNav", {
  templateUrl: "/static/app/apps/project/automations/ng-components/templates/nav.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$rootScope", "$q", "$timeout", "automationRuleShareModal", "menuDropdown"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.canManageAutomations = canManageAutomations(this.context.project);
      this.canRunAutomations = canRunAutomations(this.context.project);
      this.context.$on(this.$scope, "startEdit", (rule, isNew) => {
        this.isNew = isNew;
        this.editing = rule;
        this.saveDisabled = false;
        this.modified = false;
        this.refreshRunnable();
      });
      this.context.$on(this.$scope, "onEditorChange", (valid2) => {
        this.saveDisabled = !valid2;
        this.modified = true;
        this.refreshRunnable();
      });
      this.shareMenu = {
        config: [
          {
            checkbox: true,
            label: _4("Can be triggered from other workspaces"),
            offline: false,
            value: () => this.editing.exposed,
            toggle: () => {
              this.editing.exposed = !this.editing.exposed;
              this.$q.digest(saveAutomationRule(this.context.project, { id: this.editing.id, exposed: this.editing.exposed }));
            }
          },
          {
            label: "--"
          },
          {
            label: _4("Share via link"),
            icon: "bi-link",
            help: _4("Trigger the rule via a link"),
            action: () => this.$automationRuleShareModal.open(this.context.project, this.editing)
          }
        ]
      };
    }
    refreshRunnable() {
      this.$q.when(loadAvailableAutomationEvents(), (eventTypes) => {
        const triggerEvent = eventTypes.find((t3) => t3.name === this.editing.trigger_event);
        this.shareable = this.canRunAutomations && this.editing.id && triggerEvent && triggerEvent.trigger_only;
        this.pausable = this.canRunAutomations && triggerEvent && (!triggerEvent.trigger_only || triggerEvent.name === "scheduled");
        this.runnable = this.shareable && !triggerEvent.provides_card;
      });
    }
    addRule() {
      this.context.trigger("addRule");
    }
    saveRule(stopEdit = true) {
      return this.$q.when(saveAutomationRule(this.context.project, this.editing), () => {
        if (stopEdit) {
          this.editing = null;
          this.context.trigger("stopEdit");
        }
      });
    }
    deleteRule() {
      confirmDeleteDialog2().then(() => {
        this.$q.when(deleteAutomationRule(this.context.project, this.editing), () => {
          this.editing = null;
          this.context.trigger("stopEdit");
        });
      });
    }
    runRule() {
      this.$q.when(this.modified ? this.saveRule(false) : null, () => {
        this.running = true;
        this.$q.when(runAutomationRule(this.context.project, this.editing), () => {
          this.$timeout(() => {
            this.running = false;
            toastNotify(_4("Triggered automation"), "success");
          }, 500);
        });
      });
    }
    toggleActive() {
      this.$q.when(saveAutomationRule(this.context.project, { id: this.editing.id, active: !this.editing.active }), () => {
        this.editing.active = !this.editing.active;
      });
    }
    cancelEdit() {
      this.editing = null;
      this.context.trigger("stopEdit");
    }
    openAddAutomationMenu(event2) {
      this.$menuDropdown.open(event2.currentTarget, this.menu, this.$scope, {
        classes: "drop-theme-menu drop-theme-arrow"
      });
    }
    get menu() {
      return {
        config: () => [
          {
            label: _4("When something happens"),
            //help: _('Run when something happens on a card'),
            icon: "bolt",
            action: () => this.context.trigger("addRule", null)
          },
          {
            label: _4("Manual action on cards"),
            //help: _('Triggered manually from a card'),
            icon: "bi-hand-index",
            action: () => this.context.trigger("addRule", "manual_card")
          },
          {
            label: _4("Manual action on workspace"),
            //help: _('Triggered manually from the automations page'),
            icon: "bi-hand-index-thumb",
            action: () => this.context.trigger("addRule", "manual")
          },
          {
            label: _4("Scheduled action"),
            //help: _('Triggered automatically at specific times'),
            icon: "bi-calendar-week",
            action: () => this.context.trigger("addRule", "scheduled")
          }
        ],
        options: {
          "title": _4("Add automation"),
          "icon": "bi-plus-lg"
        }
      };
    }
  }
});

// public/app/apps/project/cards/ng-components/cards.js
angular_default.module("kantree").component("projectCardsApp", {
  templateUrl: "/static/app/apps/project/cards/ng-components/templates/cards.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isConnected = isConnected;
      this.isConnectionManagerDisabled = isConnectionManagerDisabled();
      this.$scope.$on("screensize:changed", () => {
        this.refreshModeAndOptions();
        this.screensizeConstraintNoticeClosed = !isScreensizeXS();
      });
      this.refresh();
    }
    refresh() {
      this.refreshModeAndOptions();
      this.deregisterContextWatcher = offMany([
        this.context.watch("cardStore", (newVal, oldVal) => {
          this.refreshGroupBy();
        }),
        this.context.watch("appOptions", (newVal, oldVal) => {
          this.refreshModeAndOptions();
          if (!equals((newVal || {}).group_by, (oldVal || {}).group_by) || !equals((newVal || {}).include_archived, (oldVal || {}).include_archived)) {
            this.refreshGroupBy();
          }
          this.$scope.$applyAsync();
        }, false)
      ]);
    }
    $onChanges(changes) {
      if (changes.context && !changes.context.isFirstChange()) {
        this.deregisterContextWatcher();
        this.refresh();
      }
    }
    refreshModeAndOptions() {
      this.mode = this.context.appOptions.mode;
      if (isScreensizeXS() && this.mode === "kanban") {
        this.options = { ...this.context.appOptions, stretched: false, wide: false };
      } else {
        this.options = this.context.appOptions;
      }
    }
    get screenizeConstraint() {
      return isScreensizeXS() && this.options && this.options.group_by && this.options.group_by.length > 1 && formatSpec(this.options.group_by[1]).type !== "nothing";
    }
    refreshGroupBy() {
      let spec;
      if (this.screenizeConstraint) {
        spec = [this.options.group_by[0], {}];
      } else {
        spec = this.options.group_by || [{}, {}];
      }
      this.groupBy = create2(spec, this.context.cardStore, this.context.board, this.options.include_archived);
      if (this.deregisterGroupByRemovalWatcher) this.deregisterGroupByRemovalWatcher();
      this.deregisterGroupByRemovalWatcher = getScopedGroupTypeStore(this.context.project, this.context.cardStore, true).subscribe(() => {
        const removedIdx = [];
        this.groupBy.forEach((gBy, idx) => {
          const groupType = gBy.getGroupType();
          if (groupType && !getScopedGroupTypeStore(this.context.project, this.context.cardStore, true).exists(groupType.id)) {
            removedIdx.push(idx);
          }
        });
        if (removedIdx.length) {
          this.context.appOptions = {
            ...this.options,
            group_by: this.groupBy.map((gby, idx) => {
              if (removedIdx.includes(idx)) return formatSpec(null);
              return gby.spec;
            })
          };
        }
      }, false);
    }
    updateContext(changes) {
      if (changes && changes.options) {
        const doesFilterChange = (this.context.appOptions || {}).filter !== (changes.options || {}).filter;
        this.context.transaction(() => {
          this.context.appOptions = { ...this.context.appOptions, ...changes.options };
          if (doesFilterChange) {
            this.context.shouldRenderFilteredCards = doesFilterChange;
          }
        });
      }
    }
    $onDestroy() {
      this.deregisterContextWatcher();
    }
  }
});

// public/app/apps/project/cards/ng-components/nav.js
angular_default.module("kantree").component("projectCardsAppNav", {
  template: `
    <cards-app-nav board="$ctrl.context.board" store="$ctrl.context.cardStore" filter="$ctrl.context.appOptions.filter"
      mode="$ctrl.mode" group-by="$ctrl.groupBy" group-by-choices="$ctrl.groupByChoices" options="$ctrl.context.appOptions"
      on-change="$ctrl.updateContext($changes)" class="hidden-xs" filter-repr="$ctrl.context.filterRepr"
      shrinked="$ctrl.shrinked"></cards-app-nav>
  `,
  bindings: {
    context: "<",
    shrinked: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.mode = this.context.appOptions.mode;
      this.refresh();
    }
    $onChanges(changes) {
      if (changes.context && !changes.context.isFirstChange()) {
        this.deregisterContextWatcher();
        this.refresh();
      }
    }
    refresh() {
      this.deregisterContextWatcher = offMany([
        this.context.$watch(this.$scope, "project", () => {
          this.refreshGroupByChoicesWatchers();
        }),
        this.context.$watch(this.$scope, "board", () => {
          this.refreshGroupBy();
        }),
        this.context.$watch(this.$scope, "cardStore", () => {
          this.refreshGroupBy();
        }, false),
        this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
          this.mode = this.context.appOptions.mode;
          if (!equals((newVal || {}).group_by, (oldVal || {}).group_by) || !equals((newVal || {}).include_archived, (oldVal || {}).include_archived)) {
            this.refreshGroupBy();
          }
        }, false)
      ]);
    }
    refreshGroupByChoices() {
      this.groupByChoices = cardGroupTypeStore.scopedByEnabled(this.context.project).query({}, { sortBy: "name" }).map((gt) => {
        return {
          id: gt.id,
          obj: gt,
          type: "group_type"
        };
      }).concat(cardModelStore.scopedByEnabled(this.context.project).getGroupableAttributes().sort().map((attr) => {
        return {
          id: attr.id,
          obj: attr,
          type: "attribute"
        };
      }));
      this.$scope.$applyAsync();
    }
    refreshGroupByChoicesWatchers() {
      if (this.deregisterGroupByChoicesWatchers) this.deregisterGroupByChoicesWatchers();
      this.deregisterGroupByChoicesWatchers = offMany([
        cardGroupTypeStore.scopedByEnabled(this.context.project).subscribe(() => {
          this.refreshGroupByChoices();
        }),
        cardModelStore.scopedByEnabled(this.context.project).subscribe(() => {
          this.refreshGroupByChoices();
        }, true)
      ]);
    }
    get screenizeConstraint() {
      return isScreensizeXS() && this.options && this.options.group_by && this.options.group_by.length > 1 && formatSpec(this.options.group_by[1]).type !== "nothing";
    }
    refreshGroupBy() {
      let spec;
      if (this.screenizeConstraint) {
        spec = [this.context.appOptions.group_by[0], {}];
      } else {
        spec = this.context.appOptions.group_by || [{}, {}];
      }
      this.groupBy = create2(spec, this.context.cardStore, this.context.board, this.context.appOptions.include_archived);
    }
    updateContext(changes) {
      const doesFilterChange = (this.context.appOptions || {}).filter !== (changes.options || {}).filter;
      this.context.transaction(() => {
        this.context.appOptions = { ...this.context.appOptions, ...changes.options };
        if (doesFilterChange) {
          this.context.shouldRenderFilteredCards = doesFilterChange;
        }
      });
    }
    $onDestroy() {
      this.deregisterContextWatcher();
      this.deregisterGroupByChoicesWatchers();
    }
  }
});

// public/app/apps/project/cards/ng-components/search-btn.js
angular_default.module("kantree").component("cardsAppSearchBtn", {
  template: `
    <button class="btn btn-topbar btn-icon" ng-class="{'searching': $ctrl.searching}" uib-tooltip="{{::$ctrl.tooltipLabel}}" tooltip-placement="bottom">
      <i class="bi-search"></i>
    </button>
  `,
  bindings: {
    context: "<",
    onResult: "&",
    onNext: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "dropdown", "$element", "hotkeys"];
    $onInit() {
      this.tooltipLabel = _4("Search in current board");
    }
    $postLink() {
      const dropHtml = `
        <cards-app-search-btn-drop context="$ctrl.context" drop="$ctrl.drop"
          on-search="$ctrl.searching = true" on-clear="$ctrl.searching = false"></cards-app-search-btn-drop>
      `;
      this.drop = this.$dropdown.openCompile(this.$element.find("button")[0], dropHtml, this.$scope, {
        _autoOpen: false,
        _destroyOnClose: false,
        classes: "cards-app-search-btn-drop drop-theme-menu",
        tetherOptions: {
          constraints: [{
            to: "window",
            pin: true,
            attachment: "together none"
          }]
        }
      });
      this.drop.on("open", () => {
        this.$scope.$broadcast("dropOpen");
      });
      this.$hotkeys.bindTo(this.$scope).add({
        combo: "ctrl+f",
        callback: (event2) => {
          event2.stopPropagation();
          event2.preventDefault();
          this.drop.open();
        }
      });
    }
    $onDestroy() {
      if (this.drop) {
        this.drop.destroy();
        this.drop.tether = null;
      }
    }
  }
});
angular_default.module("kantree").component("cardsAppSearchBtnDrop", {
  template: `
    <form ng-submit="$ctrl.submit()">
      <input type="text" ng-model="$ctrl.search" ng-attr-placeholder="{{$ctrl.placeholderLabel}}" ng-keydown="$ctrl.onKeyDown($event)">
      <button type="button" ng-click="$ctrl.clear()"><i class="bi-x-lg"></i></button>
    </form>
    <div ng-show="$ctrl.nbResultsLabel">
      <span>
        {{$ctrl.nbResultsLabel}}
        <a href ng-click="$ctrl.$projectPage.selectAllHighlightedCards()" ng-show="$ctrl.$projectPage.highlightedCardIds.length">{{$ctrl.selectAllLabel}}</a>
      </span>
      <button type="button" ng-click="$ctrl.goto(-1)" ng-show="$ctrl.$projectPage.highlightedCardIds.length"><i class="bi-chevron-left"></i></button>
      <button type="button" ng-click="$ctrl.goto(1)" ng-show="$ctrl.$projectPage.highlightedCardIds.length"><i class="bi-chevron-right"></i></button>
    </div>
  `,
  bindings: {
    context: "<",
    drop: "<",
    onSearch: "&",
    onClear: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "projectPage", "$element", "dropdown"];
    $onInit() {
      this.search = "";
      this.placeholderLabel = _4("Search");
      this.selectAllLabel = _4("Select all");
      this.debounceSubmit = debounce2(() => this.submit(), 500);
    }
    $postLink() {
      this.$element.find("input").focus();
      this.$scope.$on("dropOpen", () => {
        this.$element.find("input").focus().select();
      });
    }
    onKeyDown(event2) {
      if (event2.keyCode === 27) {
        this.clear(true);
      }
    }
    submit() {
      if (!this.search) {
        return;
      }
      let search = this.search;
      if (this.context.appOptions.filter) {
        search = `(${this.context.appOptions.filter}) AND (${this.search})`;
      }
      this.$q.when(api_default.projects.list_cards.get({
        project_id: this.context.project.id,
        filter: search,
        with_archived: this.context.appOptions.include_archived,
        only_ids: true
      }, { ignoreErrorHandlers: true }), (ids) => {
        if (this.context.appOptions.include_descendants) {
          if (this.context.board.parent_id) {
            const boardScopedCardIds = pluck(this.context.cardStore.query({
              path: query_exports.arrayOfObjMatch({ id: this.context.board.id.toString() })
            }), "id");
            ids = ids.filter((id) => boardScopedCardIds.includes(id));
          }
        } else {
          const boardScopedCardIds = pluck(this.context.cardStore.query({
            parent_id: this.context.board.id
          }), "id");
          ids = ids.filter((id) => boardScopedCardIds.includes(id));
        }
        this.$projectPage.hightlightCards(ids.sort());
        this.currentMatchIdx = 0;
        this.nbResultsLabel = _4("{count} matches", { count: ids.length });
        this.goto(0);
        this.onSearch();
      }, () => {
        this.$projectPage.hightlightCards([]);
        this.nbResultsLabel = _4("{count} matches", { count: 0 });
        this.currentMatchIdx = 0;
        this.onSearch();
      });
    }
    goto(delta) {
      if (!this.$projectPage.highlightedCardIds.length) return;
      this.currentMatchIdx = this.currentMatchIdx + delta;
      if (this.currentMatchIdx >= this.$projectPage.highlightedCardIds.length) {
        this.currentMatchIdx = 0;
      }
      const cardId = this.$projectPage.highlightedCardIds[this.currentMatchIdx];
      this.$projectPage.broadcast("scrollToCard", cardId);
    }
    clear(forceCloseDrop) {
      let closeDrop = this.search === "";
      this.$projectPage.hightlightCards([]);
      this.search = "";
      this.nbResultsLabel = null;
      this.onClear();
      this.$element.find("input").focus();
      if (closeDrop || forceCloseDrop) {
        this.$dropdown.close(this.drop);
      }
    }
  }
});

// public/app/apps/project/files/ng-components/files.js
angular_default.module("kantree").component("projectFilesApp", {
  templateUrl: "/static/app/apps/project/files/ng-components/templates/files.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.files = new FileStore();
      this.loading = true;
      this.debouncedLoadFiles = debounce2(() => {
        this.loadFiles();
      }, 60);
      this.options = this.context.appOptions;
      this.filter = (this.options || {}).filter;
      this.debouncedLoadFiles();
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        const oldFilters = this.options.filter;
        this.options = this.context.appOptions;
        this.filter = (this.options || {}).filter;
        if (!equals(oldFilters, this.filter)) {
          this.debouncedLoadFiles();
        }
      }, false);
    }
    loadFiles() {
      this.$q.when(api_default.project_files.list_files.get({ project_id: this.context.project.id, search: this.filter }), (files) => {
        this.files.replace(files);
        this.loading = false;
        this.$scope.$applyAsync();
      });
    }
  }
});
angular_default.module("kantree").component("projectFilesAppNav", {
  templateUrl: "/static/app/apps/project/files/ng-components/templates/nav.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isScreensizeXS = isScreensizeXS;
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        this.filter = (this.context.appOptions || {}).filter;
      });
    }
    doFilter() {
      this.context.appOptions = { ...this.context.appOptions || {}, filter: this.filter };
    }
  }
});

// public/app/apps/project/forms/ng-components/form-editor.js
angular_default.module("kantree").component("requestFormEditor", {
  templateUrl: "/static/app/apps/project/forms/ng-components/templates/form-editor.html",
  bindings: {
    form: "<",
    scopedToParent: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.serverConfig = serverConfig;
      this.dynamicFields = [
        {
          action: _4("Capture user agent"),
          label: _4("user agent"),
          type: "user_agent"
        },
        {
          action: _4("Capture browser name"),
          label: _4("browser name"),
          type: "browser"
        },
        {
          action: _4("Capture browser version"),
          label: _4("browser version"),
          type: "browser_version"
        },
        {
          action: _4("Capture os name"),
          label: _4("os name"),
          type: "os"
        },
        {
          action: _4("Capture os version"),
          label: _4("os version"),
          type: "os_version"
        },
        {
          action: _4("Capture referrer"),
          label: _4("referrer"),
          type: "referrer"
        },
        {
          action: _4("Capture IP"),
          label: _4("ip"),
          type: "remote_addr"
        },
        {
          action: _4("Capture country from IP"),
          label: _4("country"),
          type: "country"
        },
        {
          action: _4("Capture utm_source parameter"),
          label: _4("UTM source"),
          type: "utm_source"
        },
        {
          action: _4("Capture the query string"),
          label: _4("query string"),
          type: "query_string"
        },
        {
          action: _4("Save the email of the requester"),
          label: _4("requester email"),
          type: "requester_email"
        }
      ];
      this.dynamicFieldTypes = this.dynamicFields.map((field2) => field2.type);
      this.permissions = [
        { perm: 0, label: _4("Only workspace members") },
        { perm: 1, label: _4("Members of the organization") },
        // not for user personal workspace
        { perm: 2, label: _4("Anybody with the link (publicly accessible)") }
      ];
      this.colorPickerOptions = {
        config: [{ subheader: _4("Header color") }, {
          colorpicker: true,
          getValue: () => this.form.header_color || null,
          action: (event2, color) => {
            this.$scope.$applyAsync(() => {
              this.form.header_color = color;
            });
          },
          noCloseAfterAction: true,
          hasColorPalette: true,
          watcher: (callback, scope) => scope.$watch(() => scope.$ctrl.item.getValue(), callback)
        }]
      };
      this.trackingGroupsMenu = { config: () => () => {
        return this.trackingGroups.map((g3) => {
          return {
            checkbox: true,
            value: () => this.selectedGroups[g3.id],
            label: g3.title,
            toggle: (isChecked) => {
              this.selectedGroups[g3.id] = isChecked;
              this.updateIdsList(this.selectedGroups, "tracking_group_ids");
            }
          };
        });
      } };
      this.publicUploadRestrictions = false;
      if (serverConfig.max_public_upload_size) {
        this.publicUploadRestrictions = _4("maximum size of {file_size}", { file_size: serverConfig.max_public_upload_size });
      }
      if (serverConfig.limit_public_upload_file_types) {
        this.publicUploadRestrictions = this.publicUploadRestrictions ? `${this.publicUploadRestrictions} and ` : "";
        this.publicUploadRestrictions += _4("only {file_types}", { file_types: serverConfig.limit_public_upload_file_types });
      }
      this.refresh();
    }
    $onChanges(changes) {
      if (changes.form && !changes.form.isFirstChange()) {
        this.refresh();
      }
    }
    refresh() {
      this.saving = false;
      this.project = projectStore.get(this.form.project_id);
      this.fields = null;
      this.selectedGroups = null;
      this.showProcessSteps = "tracking_group_type_id" in this.form && this.form.tracking_group_type_id !== null;
      this.afterSubmittingCollapsed = true;
      this.hideDescription = !this.form.description;
      this.canDelete = this.form.id && isAllowedInProject(this.project, "request_form", "DELETE", this.form.id);
      if (this.project?.owner.type === "user") {
        if (this.form.public_permission === 1) {
          this.form.public_permission = 0;
        }
        this.permissions = this.permissions.filter((p4) => p4.perm !== 1);
      }
      this.groupTypes = [];
      const scopedCardGroupTypeStore = cardGroupTypeStore.scopedByEnabled(this.project, true);
      scopedCardGroupTypeStore.$watchAll(this.$scope, () => {
        this.groupTypes = scopedCardGroupTypeStore.query({}, { sortBy: "name" });
        if (this.selectedGroups === null) {
          this.refreshGroups();
          if (this.form.tracking_groups) {
            this.form.tracking_groups.forEach((g3) => {
              this.selectedGroups[g3.id] = true;
              this.form.tracking_group_ids.push(g3.id);
            });
          }
        }
      });
      this.groups = [];
      const scopedCardGroupStore = cardGroupStore.scopedByAvailableForChildren(this.project.top_level_card, false);
      scopedCardGroupStore.$watchAll(this.$scope, () => {
        this.groups = scopedCardGroupStore.query().map((g3) => {
          var gt = cardGroupTypeStore.tryGet(g3.type_id);
          if (!gt) {
            return false;
          }
          return Object.assign({ group_type: gt.name }, g3);
        }).filter(Boolean);
      });
      this.models = [];
      const scopedCardModelStore = cardModelStore.scopedByEnabled(this.project, true);
      scopedCardModelStore.$watchAll(this.$scope, () => {
        this.models = scopedCardModelStore.query().map(
          (model) => Object.assign({
            real_id: model.base_model_id ? null : model.id
          }, model)
        );
        if (this.fields === null) {
          this.fields = (this.form.fields || []).map((field2) => {
            let f3 = angular_default.copy(field2);
            if (f3.attribute) {
              f3.attribute_id = f3.attribute.id;
            }
            if (this.dynamicFieldTypes.includes(f3.type)) {
              f3.label = this.dynamicFields.find((d3) => d3.type === f3.type).label;
            }
            return f3;
          });
          this.onFieldChange();
          this.refreshAttributes();
          this.refreshReferencedFields();
        }
      });
      this.parents = [];
      const scopedCardStore = cardStore.scopedByProject(this.project).scoped({ parent_id: query_exports.notNull(), board_created: true });
      scopedCardStore.$watchAll(this.$scope, () => {
        this.parents = scopedCardStore.query({}, { sortBy: "ref" });
      });
    }
    showDescription() {
      this.hideDescription = false;
    }
    toggleAfterSubmittingCollapse() {
      this.afterSubmittingCollapsed = !this.afterSubmittingCollapsed;
    }
    removeTracking() {
      this.showProcessSteps = false;
      this.form.tracking_group_type_id = null;
    }
    removeField(field2) {
      this.fields.splice(this.fields.indexOf(field2), 1);
      this.onFieldChange();
      this.refreshReferencedFields();
    }
    onFieldChange() {
      this.form.fields = this.fields.filter((field2) => {
        if (this.dynamicFieldTypes.includes(field2.type)) {
          return !!field2.attribute_id;
        }
        return true;
      }).map((field2) => {
        var f3 = angular_default.copy(field2);
        if (f3.type === "attribute") {
          f3.attribute_id = f3.attribute.id;
          delete f3.attribute;
        }
        if (this.dynamicFieldTypes.includes(field2.type)) {
          delete f3.label;
          if (f3.attribute) {
            delete f3.attribute;
          }
        }
        return f3;
      });
    }
    updateIdsList(values2, prop2) {
      this.form[prop2] = [];
      angular_default.forEach(values2, (enabled, id) => {
        if (enabled) {
          this.form[prop2].push(parseInt(id, 10));
        }
      });
    }
    refreshGroups(selectAll3) {
      if (!this.form.tracking_group_type_id) {
        this.form.tracking_group_ids = [];
        return;
      }
      var gt = cardGroupTypeStore.tryGet(this.form.tracking_group_type_id);
      if (!gt) {
        this.form.tracking_group_type_id = null;
        this.form.tracking_group_ids = [];
        return;
      }
      this.trackingGroups = cardGroupStore.scopedByType(gt, this.project.top_level_card, false).query({}, { sortBy: "position" });
      this.selectedGroups = {};
      if (selectAll3) {
        this.trackingGroups.forEach((g3) => {
          this.selectedGroups[g3.id] = true;
        });
      }
      this.updateIdsList(this.selectedGroups, "tracking_group_ids");
    }
    refreshReferencedFields() {
      this.refreshAnonymousEmailField();
      this.refreshInboundEmailFields();
    }
    refreshAnonymousEmailField() {
      this.anonymousEmailFields = [];
      this.fields.forEach((field2, idx) => {
        if (field2.type === "title" || field2.type === "attribute" && field2.attribute.type === "email") {
          this.anonymousEmailFields.push({ idx, label: field2.label });
        }
      });
      if (!this.anonymousEmailFields.length) {
        this.form.anonymous_email_field_idx = null;
      }
    }
    refreshInboundEmailFields() {
      this.inboundEmailFields = [];
      this.inboundEmailFileFields = [];
      this.fields.forEach((field2, idx) => {
        if (field2.type === "title" || field2.type === "attribute" && ["text", "content"].includes(field2.attribute.type)) {
          this.inboundEmailFields.push({ idx, label: field2.label });
        } else if ((field3) => field3.type === "attribute" && field3.attribute.type === "files") {
          this.inboundEmailFileFields.push({ idx, label: field2.label });
        }
      });
      let isSubjectFieldEmpty = this.form.email_subject_field_idx === null || this.form.email_subject_field_idx === void 0;
      let isBodyFieldEmpty = this.form.email_body_field_idx === null || this.form.email_body_field_idx === void 0;
      if (!this.inboundEmailFields.length) {
        this.form.email_subject_field_idx = null;
        this.form.email_body_field_idx = null;
      } else if (isSubjectFieldEmpty && isBodyFieldEmpty) {
        this.form.email_subject_field_idx = this.inboundEmailFields[0].idx;
      }
      if ((this.form.email_attachments_field_idx === null || this.form.email_attachments_field_idx === void 0) && this.inboundEmailFileFields.length) {
        this.form.email_attachments_field_idx = this.inboundEmailFileFields[0].idx;
      } else if (!this.inboundEmailFileFields.length) {
        this.form.email_attachments_field_idx = null;
      }
    }
    addField(options2) {
      this.fields.push(options2);
      this.refreshReferencedFields();
      this.onFieldChange();
    }
    refreshAttributes(model) {
      this.attributes = cardModelStore.getExtendedModelAttributes(
        cardModelStore.tryGet(this.form.card_model_id),
        this.project
      ).filter((attr) => {
        var attrType = attributeTypeRegistry.get(attr.type);
        if (attrType) {
          return typeof attrType.availableFor === "undefined" || attrType.availableFor.indexOf("form") !== -1;
        }
        return false;
      });
      this.specialFieldAttributes = this.attributes.filter((attr) => ["text", "group_type", "url", "email"].includes(attr.type));
      const $ctrl = this;
      this.addFieldMenu = { config: () => [
        {
          label: _4("Title"),
          enabled: () => {
            for (var i3 = 0; i3 < $ctrl.fields.length; i3++) {
              if ($ctrl.fields[i3].type === "title") {
                return false;
              }
            }
            return true;
          },
          action: () => {
            $ctrl.addField({
              type: "title",
              label: _4("Title"),
              description: "",
              required: true
            });
          }
        }
      ].concat($ctrl.attributes.map((attr) => {
        return {
          label: attr.name,
          enabled: function() {
            for (var i3 = 0; i3 < $ctrl.fields.length; i3++) {
              if ($ctrl.fields[i3].type === "attribute" && $ctrl.fields[i3].attribute.id === attr.id) {
                return false;
              }
            }
            return true;
          },
          action: function() {
            $ctrl.addField({
              type: "attribute",
              label: attr.name,
              description: "",
              required: false,
              attribute: attr
            });
          }
        };
      })).concat([
        { label: "--" },
        {
          label: _4("Heading"),
          action: function() {
            $ctrl.addField({
              type: "header",
              label: ""
            });
          }
        },
        {
          label: _4("Text content"),
          action: function() {
            $ctrl.addField({
              type: "text",
              description: ""
            });
          }
        },
        {
          label: _4("Dynamic fields"),
          submenu: $ctrl.dynamicFields.map((data2) => {
            return {
              label: data2.action,
              action: function() {
                $ctrl.addField({
                  type: data2.type,
                  label: data2.label,
                  attribute_id: null
                });
              }
            };
          })
        }
      ]) };
    }
    $postLink() {
      var dragScrollHelperInstance = new DragScrollHelper({
        scrollable: ".board-forms-view",
        threshold: {
          default: { top: 50, bottom: 50 },
          xs: { top: 30, bottom: 30 }
        },
        tolerance: "border"
      });
      var animId;
      const $viewport = jquery_default(".board-forms-view");
      const $ctrl = this;
      this.uiSortableOptions = {
        helper: "clone",
        items: ">.request-form-editor-field",
        handle: ".request-form-editor-field-move-handle",
        intersectTolerance: 0.3,
        distance: 6,
        scroll: false,
        zIndex: 0,
        placeholder: "sortable-placeholder",
        axis: "y",
        start: function(event2, ui) {
          ui.placeholder.width(ui.helper.outerWidth());
          ui.placeholder.height(ui.helper.outerHeight());
          dragScrollHelperInstance.update("scrollable");
          if (animId) {
            cancelAnimationFrame(animId);
          }
          animId = requestAnimationFrame(function() {
            var rect = ui.placeholder[0].getBoundingClientRect();
            dragScrollHelperInstance.update("draggable", {
              width: ui.helperProportions.width,
              height: ui.helperProportions.height,
              mousePosition: {
                x: event2.clientX - rect.left,
                y: event2.clientY - rect.top
              }
            });
          });
        },
        sort: function(event2, ui) {
          if (animId) {
            cancelAnimationFrame(animId);
            animId = 0;
            var rect = ui.placeholder[0].getBoundingClientRect();
            dragScrollHelperInstance.update("draggable", {
              width: ui.helperProportions.width,
              height: ui.helperProportions.height,
              mousePosition: {
                x: event2.clientX - rect.left,
                y: event2.clientY - rect.top
              }
            });
          }
          if ($viewport[0].scrollHeight > $viewport[0].clientHeight) {
            dragScrollHelperInstance.updateScroll(event2.pageX, event2.pageY, getScreensize());
          }
        },
        stop: function(event2, ui) {
          if (animId) {
            cancelAnimationFrame(animId);
            animId = 0;
          }
          dragScrollHelperInstance.reset();
          $ctrl.onFieldChange();
          $ctrl.refreshReferencedFields();
          if (!ui.item.sortable.droptarget) {
            return;
          }
        }
      };
    }
  }
});

// public/app/apps/project/forms/ng-components/form.js
angular_default.module("kantree").component("projectFormApp", {
  templateUrl: "/static/app/apps/project/forms/ng-components/templates/form.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.editing = false;
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        this.refreshForm(oldVal);
      });
      this.context.$on(this.$scope, "edit", () => this.edit());
      this.context.$on(this.$scope, "save", () => this.save());
      this.context.$on(this.$scope, "cancel", () => this.stopEdit());
    }
    refreshForm(oldOptions) {
      this.scopedToParent = this.context.project.top_level_card_id !== this.context.board.id;
      if (!equals((oldOptions || {}).formId, (this.context.appOptions || {}).formId)) {
        this.$q.when(getOrLoadRequestForm(this.context.project.id, (this.context.appOptions || {}).formId), (form) => {
          this.form = form;
          this.context.appState.form = form;
          if (!form.fields.length) {
            this.edit();
          } else if (this.editing) {
            this.stopEdit();
          }
        });
      } else if (this.form && this.context.appOptions.name !== this.form.name && (!this.editing || this.editing.name === this.form.name)) {
        this.form.name = this.context.appOptions.name;
        if (this.editing) {
          this.editing.name = this.context.appOptions.name;
        }
      }
    }
    edit() {
      this.editing = { ...this.form };
      this.context.trigger("startEdit", this.editing);
    }
    stopEdit() {
      this.editing = false;
      this.context.trigger("stopEdit");
    }
    save() {
      this.$q.when(saveRequestForm(this.editing), (form) => {
        this.form = form;
        this.stopEdit();
        let view = viewStore.query({ mode_options: query_exports.objMatch({ formId: form.id }) })?.[0];
        if (view) {
          viewStore.update(view, { name: form.name });
        }
      });
    }
    get canSubmit() {
      if (!this.context.project || this.context.project.is_archived) return false;
      const org2 = orgStore.tryGet(this.context.project.owner.id);
      if (this.context.project.owner.type === "org" && (!org2 || isOrgLocked(org2))) return false;
      if (currentUser2.is_unlicensed && (this.form.public_permission < 2 || this.context.project.is_template)) return false;
      if (isAuthenticated() && currentUser2.is_kantree_admin) return true;
      if (this.context.project.is_template) return isCurrentUserMemberOfProject(this.context.project);
      if (this.form.public_permission === 0) return isCurrentUserMemberOfProject(this.context.project);
      if (this.form.public_permission === 1) {
        return this.context.project.owner.type === "user" || // temporary fix because perm = 1 should not be valid for personal workspace
        isCurrentUserMemberOf(org2);
      }
      return true;
    }
    get disableSubmitMessage() {
      if (this.context.project.is_archived) {
        return _4("You can't submit this form as this workspace is archived");
      }
      const org2 = orgStore.tryGet(this.context.project.owner.id);
      if (this.context.project.owner.type === "org" && (!org2 || isOrgLocked(org2))) {
        return _4("You can't submit this form as the organization is locked");
      }
      if (currentUser2.is_unlicensed && (this.form.public_permission < 2 || this.context.project.is_template)) {
        return _4("You can't submit this form as you are an unlicensed user");
      }
      if (this.context.project.is_template && !isCurrentUserMemberOfProject(this.context.project)) {
        return _4("You can't submit this form as you are not a template member");
      }
      if (this.form.public_permission === 0 && !isCurrentUserMemberOfProject(this.context.project)) {
        return _4("You can't submit this form as you are not a member of this workspace");
      }
      if (this.form.public_permission === 1 && this.context.project.owner.type === "org" && !isCurrentUserMemberOf(org2)) {
        return _4("You can't submit this form as you are not a member of this organization");
      }
    }
    onSubmit(request2) {
      this.$q.digest(getOrLoadCard(request2.card_id, { ignoreErrorHandlers: true }));
      successDialog(_4("Your request has been successfully submitted"));
    }
    $onDestroy() {
      if (this.deregisterFormNameWatcher) this.deregisterFormNameWatcher();
    }
  }
});
angular_default.module("kantree").component("projectFormAppNav", {
  templateUrl: "/static/app/apps/project/forms/ng-components/templates/nav.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$rootScope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.shareMenuConfig = { config: () => () => [{
        component: "form-links-menu-component",
        params: { form: this.context.appState.form }
      }] };
      this.context.$on(this.$scope, "startEdit", (form) => {
        this.editing = form;
        this.isNew = !form.fields.length;
      });
      this.context.$on(this.$scope, "stopEdit", () => {
        this.editing = false;
      });
    }
    edit() {
      this.context.trigger("edit");
    }
    save() {
      this.context.trigger("save");
    }
    cancel() {
      this.editing = false;
      this.context.trigger("cancel");
    }
    get canEdit() {
      return !!(this.context.appState || {}).form && !!this.context.project && !this.context.project.is_archived && isConnected() && isAllowedInProject(
        this.context.project,
        "request_form",
        "EDIT",
        this.context.appState.form.id
      );
    }
    get canShare() {
      const org2 = orgStore.tryGet(this.context.project.owner.id);
      return !!(this.context.appState || {}).form && !!this.context.project && !this.context.project.is_archived && (this.context.appState.form.public_permission === 2 || this.context.appState.form.public_permission === 1 && !isCurrentUserPersonalOrg(org2) && isCurrentUserMemberOf(org2));
    }
  }
});

// public/app/apps/project/forms/ng-components/forms.js
angular_default.module("kantree").component("projectFormsApp", {
  templateUrl: "/static/app/apps/project/forms/ng-components/templates/forms.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$state", "shareEmbedModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.editingForm = null;
      this.requestForms = [];
      this.debounceRefreshFillForm = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshFillForm();
        });
      }, 30);
      const store2 = requestFormStore.scopedByProject(this.context.project);
      store2.$watchAll(this.$scope, () => {
        this.requestForms = store2.query({}, { sortBy: "id" });
      });
      this.options = this.context.appOptions;
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        this.options = this.context.appOptions;
        if (!equals((oldVal || {}).requestFormId, (newVal || {}).requestFormId)) {
          this.debounceRefreshFillForm();
        }
      });
      this.$scope.$on("connectivityChanged", (e3, connected) => {
        if (connected) {
          this.$q.when(loadAllRequestFormsForProject(this.context.project), () => {
            this.debounceRefreshFillForm();
          });
        }
      });
    }
    refreshFillForm() {
      if (this.options.requestFormId && requestFormStore.exists(this.options.requestFormId)) {
        this.fillForm = requestFormStore.get(this.options.requestFormId);
        this.editingForm = null;
      } else {
        this.fillForm = null;
        this.editingForm = null;
      }
    }
    canCreate() {
      return isAllowedInProject(this.context.project, "request_form", "CREATE");
    }
    canEdit(form) {
      const objId = form ? form.id : null;
      return isAllowedInProject(this.context.project, "request_form", "EDIT", objId);
    }
    canDelete(form) {
      const objId = form ? form.id : null;
      return isAllowedInProject(this.context.project, "request_form", "DELETE", objId);
    }
    edit(form) {
      if (form) {
        this.editingForm = { ...form };
        this.fillForm = null;
      } else {
        this.editingForm = null;
        this.fillForm = null;
        this.context.appOptions = { ...this.options || {}, requestFormId: null };
      }
    }
    fill(form) {
      if (isConnected()) {
        this.context.appOptions = { ...this.options || {}, requestFormId: form.id };
      }
    }
    getFormURL(form) {
      return makeUrlAbsolute(this.$state.href("request_form", { formSlug: form.slug }));
    }
    delete(form) {
      confirmDeleteDialog2().then(() => {
        this.$q.digest(deleteRequestForm(form));
      });
    }
    create() {
      this.edit({
        project_id: this.context.project.id,
        card_model_id: null,
        public_permission: 2,
        allow_anonymous: true,
        allow_comments: true,
        send_confirmation_email: true,
        notify_requester_of_group_change: true
      });
    }
    afterSubmit(request2) {
      this.$q.digest(getOrLoadCard(request2.card_id, { ignoreErrorHandlers: true }));
      this.edit();
      window.open(this.$state.href("request", { requestToken: request2.token, as: 1, confirm: 1 }));
    }
    focus(e3) {
      e3.target.select();
    }
    viewRequests(form) {
      this.context.appOptions = { mode: "kanban", filter: `form="${form.name}"` };
    }
    addToOrgFeaturedItems(form) {
      this.$q.when(
        addFeaturedOrgItem(this.context.project.owner, "request_form", form.id),
        () => {
          form.featured = true;
        }
      );
    }
    canFeatureItem() {
      const org2 = orgStore.tryGet(this.context.project.owner.id);
      return org2 ? org2.permission >= 3 : false;
    }
    openEmbedModal(form) {
      this.$shareEmbedModal.open(this.getFormURL(form));
    }
  }
});

// public/app/apps/project/integrations/ng-components/features.js
angular_default.module("kantree").component("integrationFeatureEmail", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/feature-email.html",
  bindings: {
    project: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.canManageSettings = canManageSettings(this.project);
      this.allowAnon = this.project.allow_anon_inbound_emails;
      if (serverConfig.email_inbound_domain) {
        this.url = this.project.slug + "@" + serverConfig.email_inbound_domain;
      }
    }
    updateAllowAnon() {
      this.$q.digest(updateProject(this.project, { allow_anon_inbound_emails: this.allowAnon }));
    }
  }
});
angular_default.module("kantree").component("integrationFeatureEmbed", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/feature-embed.html",
  bindings: {
    project: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
  }
});
angular_default.module("kantree").component("integrationFeatureExport", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/feature-export.html",
  bindings: {
    project: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "projectExportModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.url = makeUrlAbsolute(api_default.projects.export_project_stream.url({ project_id: this.project.id }));
    }
    openExportModal() {
      this.$projectExportModal.open(this.project);
      this.dismiss();
    }
  }
});
angular_default.module("kantree").component("integrationFeatureForm", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/feature-form.html",
  bindings: {
    project: "<",
    board: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    create() {
      this.$q.when(createFromLocalView("", {
        mode: "form",
        project_id: this.project.id,
        card_ref: this.board.ref,
        limit_to_ref: true
      }, true), (view) => {
        $navigateToView(view);
        this.dismiss();
      });
    }
  }
});
angular_default.module("kantree").component("integrationFeatureExternalData", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/feature-external-data.html",
  bindings: {
    project: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
  }
});

// public/app/actions/project-integration.ts
async function activateProjectIntegration(project, integration, options2) {
  let scope = await api_default.project_integrations.activate_integration.post({
    project_id: project.id,
    instance_id: integration.id,
    options: options2
  });
  scope = projectIntegrationStore.insert(scope);
  await loadProject(project.id);
  return scope;
}
async function updateProjectIntegration(integration, options2) {
  const scope = await api_default.project_integrations.update_integration.put({
    project_id: integration.project_id,
    instance_id: integration.instance_id,
    options: options2
  });
  return projectIntegrationStore.upsert(scope);
}
async function removeProjectIntegration(integration) {
  await api_default.project_integrations.remove_integration.delete({
    project_id: integration.project_id,
    instance_id: integration.instance_id
  });
  projectIntegrationStore.remove(integration);
  const projectModel = cardModelStore.getProjectModel({ id: integration.project_id });
  cardModelStore.removeAttributesFromIntegration(projectModel);
}

// public/app/loaders/integration-type.js
function loadAllIntegrationType() {
  return loadMany(integrationTypeStore, api_default.integrations.list_integrations);
}

// public/app/loaders/integration.js
function getOrLoadIntegration(org2, id) {
  return getOrLoad(integrationStore, id, api_default.org_integrations.get_integration, { org_id: org2.id, integration_id: id });
}
function loadAllIntegrations(org2) {
  return loadMany(integrationStore, api_default.org_integrations.list_integrations, { org_id: org2.id });
}
function loadAllIntegrationsForProject(project) {
  return loadMany(integrationStore, api_default.project_integrations.list_available_integrations, { project_id: project.id });
}

// public/app/actions/integration.ts
async function activateOrgIntegration(org2, integration) {
  if (integration.needs_authorization) {
    const url2 = api_default.org_integrations.authorize_integration.url({
      org_id: org2.id,
      name: integration.name
    }) + "?next=" + browserPopup.getCallbackUrl();
    await browserPopup.open(url2, 800, 600);
    await loadAllIntegrations(org2);
    return integrationStore.scopedByOrg(org2).query({ name: integration.name }, { sortBy: "-id" })?.[0];
  } else {
    const data2 = await api_default.org_integrations.create_integration.post({
      org_id: org2.id,
      name: integration.name
    });
    return integrationStore.insert(data2);
  }
}
async function reauthorizeOrgIntegration(org2, integration) {
  const url2 = api_default.org_integrations.reauthorize_integration.url({
    org_id: org2.id,
    instance_id: integration.id
  }) + "?next=" + browserPopup.getCallbackUrl();
  await browserPopup.open(url2, 800, 600);
  return getOrLoadIntegration(org2, integration.id);
}
async function removeOrgIntegration(integration) {
  await api_default.org_integrations.remove_integration.delete({
    org_id: integration.org_id,
    instance_id: integration.id
  });
  integrationStore.remove(integration);
  projectIntegrationStore.removeManyMatching({ instance_id: integration.id });
}
function clearIntegrationError(integration) {
}

// public/app/apps/project/integrations/ng-components/integration-modal.js
angular_default.module("kantree").component("projectIntegrationModal", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/integration-modal.html",
  bindings: {
    project: "<?",
    integration: "<",
    close: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.options = angular_default.copy(this.integration.options || {});
      this.availableOptions = [];
      this.activable = false;
      this.usable = this.integration.org_id && this.integration.authorized;
      this.isOwnerOfProjectOwner = isCurrentUserOwnerOf(this.project);
      this.$q.when(loadAllIntegrationType(), () => {
        const integrationType = integrationTypeStore.query({ name: this.integration.name })?.[0];
        if (integrationType) {
          this.activable = integrationType.activable;
          this.availableOptions = integrationType.options;
        }
      });
    }
    remove() {
      confirmDeleteDialog().then(() => {
        this.$q.when(removeProjectIntegration(this.integration), () => this.close());
      });
    }
    authorize() {
      this.$q.when(activateOrgIntegration(this.project.owner, this.integration), (integration) => {
        this.integration = integration;
        this.$q.when(activateProjectIntegration(this.project, this.integration, this.options), (integration2) => {
          this.integration = integration2;
        });
      });
    }
    clearError() {
      this.$q.digest(clearIntegrationError(this.integration));
    }
    save() {
      if (this.integration.project_id) {
        this.$q.when(updateProjectIntegration(this.integration, this.options), () => this.close());
      } else {
        this.$q.when(activateProjectIntegration(this.project, this.integration, this.options), () => this.close());
      }
    }
  }
});

// public/app/apps/project/integrations/ng-components/integrations.js
var projectIntegrationsPanels = [
  {
    title: _lazy("Services"),
    component: "project-integrations-services"
  },
  {
    title: _lazy("Webhooks"),
    component: "project-integrations-webhooks",
    enabled: (project) => !project.is_template && !project.is_archived && canManageSettings(project)
  }
];
angular_default.module("kantree").component("projectIntegrationsApp", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/integrations.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.panels = projectIntegrationsPanels.filter((p4) => !p4.enabled || p4.enabled(this.context.project));
      this.currentPanel = this.panels[0];
    }
    activate(panel) {
      this.currentPanel = panel;
    }
  }
});

// public/app/loaders/project-integration.js
function loadAllProjectIntegrations(project) {
  return loadMany(projectIntegrationStore, api_default.project_integrations.list_integrations, { project_id: project.id });
}

// public/app/config/integrations.js
var integrationFeatures = [
  {
    icon: "bi-envelope",
    title: _lazy("Create cards by email"),
    component: "integration-feature-email",
    enabled: () => serverConfig.email_inbound_domain
  },
  {
    icon: "bi-calendar-plus",
    title: _lazy("Add to your calendar"),
    action: [
      "cardICalendarModal",
      "context",
      function(cardICalendarModal, context) {
        cardICalendarModal.open(context.project.top_level_card);
      }
    ]
  },
  {
    icon: "kfi-form",
    title: _lazy("Collect data using forms"),
    component: "integration-feature-form"
  },
  {
    icon: "bi-cloud-arrow-up-fill",
    title: _lazy("Import cards from spreadsheets"),
    action: [
      "projectImportModal",
      "context",
      function(projectImportModal, context) {
        projectImportModal.open(context.project);
      }
    ]
  },
  {
    icon: "bi-cloud-arrow-down-fill",
    title: _lazy("Export to spreadsheet & BI tools"),
    component: "integration-feature-export"
  },
  {
    icon: "bi-code-square",
    title: _lazy("Embed on other web pages"),
    component: "integration-feature-embed"
  },
  {
    icon: "bi-hdd-network-fill",
    title: _lazy("Connect to external data sources"),
    component: "integration-feature-external-data"
  }
];

// public/app/apps/project/integrations/ng-components/services.js
angular_default.module("kantree").component("projectIntegrationsServices", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/services.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$rootScope", "$uibModal", "$q", "$injector"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.opts = {};
      this.projectIntegrations = [];
      this.orgIntegrations = [];
      this.availableIntegrations = [];
      this.editable = canManageSettings(this.context.project) && !this.context.project.is_archived;
      this.integrationFeatures = integrationFeatures.filter((i3) => !i3.enabled || i3.enabled());
      const scopedPojectIntegrationStore = projectIntegrationStore.scopedByProject(this.context.project);
      scopedPojectIntegrationStore.$watchAll(this.$scope, () => {
        this.projectIntegrations = scopedPojectIntegrationStore.query();
        this.refresh();
      });
      this.$q.digest(loadAllProjectIntegrations(this.context.project));
      const scopedIntegrationStore = integrationStore.scopedByOrg(this.context.project.owner).scoped({ has_hooks: true });
      scopedIntegrationStore.$watchAll(this.$scope, () => {
        this.orgIntegrations = scopedIntegrationStore.query();
        this.refresh();
      });
      if (this.editable) {
        this.$q.digest(loadAllIntegrationsForProject(this.context.project));
      }
      this.$q.when(loadAllIntegrationType(), () => {
        this.availableIntegrations = integrationTypeStore.query({}, { sortBy: "title" });
        this.refresh();
      });
    }
    refresh() {
      this.integrations = [];
      this.availableIntegrations.filter((inte) => !this.projectIntegrations.some((i3) => i3.name === inte.name)).forEach((inte) => {
        const orgIntegrations = this.orgIntegrations.filter((i3) => i3.name === inte.name);
        if (orgIntegrations.length > 0) {
          this.integrations.push(orgIntegrations[0]);
        } else {
          this.integrations.push(inte);
        }
      });
    }
    open(integration) {
      if (integration.action) {
        this.$injector.invoke(integration.action, integration, { context: this.context });
        return;
      }
      const scope = this.$rootScope.$new();
      scope.project = this.context.project;
      scope.board = this.context.board;
      scope.org = this.context.project.owner;
      scope.integration = integration;
      const component = integration.component || "project-integration-modal";
      const instance = this.$uibModal.open({
        windowClass: "integration-modal",
        scope,
        template: `<${component} project="project" board="board" integration="integration" close="$close" dismiss="$dismiss"></${component}>`
      });
      instance.result.finally(() => scope.$destroy());
    }
  }
});
angular_default.module("kantree").directive("projectIntegrationsServiceTile", function() {
  return {
    template: `
      <a href ng-click="onOpen()">
        <i ng-class="::integration.icon|iconClass" ng-if="::integration.icon"></i>
        <img ng-src="{{::integration.logo}}" ng-if="::integration.logo" alt="{{integration.title|capitalize}}">
        {{::integration.logo ? '' : integration.title|capitalize}}
      </a>
    `,
    replace: true,
    scope: {
      integration: "<",
      onOpen: "&"
    }
  };
});

// public/app/apps/project/integrations/ng-components/webhooks.js
angular_default.module("kantree").component("projectIntegrationsWebhooks", {
  templateUrl: "/static/app/apps/project/integrations/ng-components/templates/webhooks.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.availableEvents = [
        ["card_*", _4("Cards")],
        ["model_*", _4("Card types")],
        ["request_*", _4("Requests")],
        ["view_*", _4("Views")],
        ["project_*", _4("Workspaces")],
        ["recurring_*", _4("Recurring cards")],
        ["group_*", _4("Groups")],
        ["comment_*", _4("Comments")],
        ["log_*", _4("Logs")]
      ];
      this.refresh();
    }
    refresh() {
      this.$q.when(api_default.project_webhooks.list_webhooks.get({ project_id: this.context.project.id }), (webhooks) => {
        this.webhooks = webhooks;
      });
    }
    add() {
      this.selected = { active: true };
      this.events = {};
      this.availableEvents.forEach((e3) => {
        this.events[e3[0]] = true;
      });
    }
    edit(webhook) {
      this.selected = angular_default.copy(webhook);
      this.events = {};
      webhook.events.forEach((e3) => {
        this.events[e3] = true;
      });
    }
    save() {
      const data2 = {
        "project_id": this.context.project.id,
        "url": this.selected.url,
        "active": this.selected.active,
        "events": Object.keys(this.events).filter((e3) => this.events[e3])
      };
      let p4;
      if (this.selected.id) {
        p4 = api_default.project_webhooks.update_webhook.put(Object.assign({
          webhook_id: this.selected.id
        }, data2));
      } else {
        p4 = api_default.project_webhooks.create_webhook.post(data2);
      }
      this.$q.when(p4, () => {
        this.selected = null;
        this.refresh();
      });
    }
    delete(webhook) {
      confirmDeleteDialog2().then(() => {
        this.$q.when(api_default.project_webhooks.delete_webhook.delete({ project_id: this.context.project.id, webhook_id: webhook.id }), () => this.refresh());
      });
    }
  }
});

// public/app/apps/project/logs/menus/types.js
angular_default.module("kantree").service("projectLogsAppFilterMenu", class extends AngularClass {
  getItems(project, logsTypeId, onChange) {
    const types2 = projectLogTypeStore.scopedByProject(project).query({}, { sortBy: "name" });
    return types2.map((type) => {
      return {
        label: type.name,
        action: () => {
          onChange(type.id);
        },
        selected: () => logsTypeId === type.id
      };
    });
  }
  get(project, logsTypeId, onChange) {
    return {
      config: () => () => this.getItems(project, logsTypeId, onChange),
      options: {
        watch: (cb2, scope) => projectLogTypeStore.scopedByProject(project).$watchAll(scope, cb2, false),
        title: _4("Filter by category...")
      }
    };
  }
});

// public/app/actions/log-type.ts
async function createLogTypeInProject(project, name2) {
  const logType = await api_default.log_types.create_log_type.post({ project_id: project.id, name: name2 });
  return projectLogTypeStore.insert(logType);
}
async function disableOrDeleteLogType(project, logType) {
  await api_default.project_log_types.disable_or_delete_log_type.delete({ project_id: project.id, type_id: logType.id });
  projectLogTypeStore.remove(logType);
  activityStore.removeManyMatching({ stream_type: "log", type_id: logType.id });
}
function exportLogs(logType, project, fromDate, toDate) {
  return api_default.log_types.export_logs.post({
    type_id: logType.id,
    project_id: project ? project.id : null,
    from_date: fromDate ? fromDate.format("YYYY-MM-DD") : null,
    to_date: toDate ? toDate.format("YYYY-MM-DD") : null
  });
}

// public/app/stores/utils/activity.js
var dataProps = ["stream_type", "project_id", "verb", "message"];
var objProps = ["object", "sub_object", "target", "origin"];
var allObjectsOfTypesAreEquals = ["CardLog"];
var allObjectsOfTypesCantBeAggregated = ["CardComment"];
function aggregateActivities(activities, force = false) {
  return activities.reduce((accu, activity, idx) => {
    if (!accu.length) {
      return accu.concat(activity);
    }
    const lastActivity = accu[accu.length - 1];
    if (activity.stream_type !== "activity" || !force && activity.date > lastActivity.date + 60 * 15 || !canBeAggregated(activity)) {
      return accu.concat(activity);
    }
    if (activityEquals(activity, lastActivity)) {
      accu[accu.length - 1] = activity;
      return accu;
    }
    if (activityEquals(activity, lastActivity, ["object"])) {
      accu[accu.length - 1] = makeAggregatedActivity(
        activity,
        lastActivity,
        _4(activity.message.replace(/\{object\}/gi, "{aggrObjects}"))
      );
      return accu;
    }
    if (force && canBeAggregated(lastActivity) && idx < activities.length - 1) {
      const c3 = (lastActivity.aggregated || [lastActivity]).length + 1;
      accu[accu.length - 1] = makeAggregatedActivity(
        activity,
        lastActivity,
        _4("{count} activities", { count: c3 }),
        true
      );
      return accu;
    }
    return accu.concat(activity);
  }, []);
}
function groupActivitiesByDate(activities) {
  return activities.reduce((accu, activity) => {
    let activityDate = parseTimestamp(activity.date);
    if (!accu.length || !activityDate.isSame(accu[accu.length - 1].date, "day")) {
      return accu.concat({
        date: activityDate.startOf("day"),
        formattedDate: activityDate.format("LL"),
        activities: [].concat(activity)
      });
    }
    accu[accu.length - 1].activities.push(activity);
    return accu;
  }, []);
}
function makeAggregatedActivity(activity, lastActivity, message, removeActor) {
  return Object.assign({}, activity, {
    aggregated: (lastActivity.aggregated || [lastActivity]).concat(activity),
    aggr_message: message || activity.message
  }, removeActor ? { actor: null } : {});
}
function canBeAggregated(activity) {
  return !activity.object || !allObjectsOfTypesCantBeAggregated.includes(activity.object.type);
}
function activityEquals(a3, b3, excludeProps, reverseExclude) {
  excludeProps = excludeProps || [];
  const isIncluded = (prop2) => {
    return !excludeProps.length || !reverseExclude && excludeProps.indexOf(prop2) === -1 || reverseExclude && excludeProps.indexOf(prop2) !== -1;
  };
  for (let dataProp of dataProps) {
    if (isIncluded(dataProp) && a3[dataProp] !== b3[dataProp]) {
      return false;
    }
  }
  if (isIncluded("actor") && !activityActorEquals(a3.actor, b3.actor)) {
    return false;
  }
  for (let objProp of objProps) {
    if (isIncluded(objProp) && !activityObjEquals(a3[objProp], b3[objProp])) {
      return false;
    }
  }
  return true;
}
function activityActorEquals(a3, b3) {
  return !a3 && !b3 || a3 && b3 && a3.id === b3.id;
}
function activityObjEquals(a3, b3) {
  return !a3 && !b3 || a3 && b3 && a3.type === b3.type && (allObjectsOfTypesAreEquals.includes(a3.type) || a3.id && b3.id && a3.id === b3.id);
}

// public/app/apps/project/logs/ng-components/logs.js
angular_default.module("kantree").component("projectLogsApp", {
  templateUrl: "/static/app/apps/project/logs/ng-components/templates/logs.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$sce", "cardModal", "$sanitize", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.logTypes = [];
      this.attrReprWidgetsOptions = { expanded: true, expandable: true };
      this.debouncedRefreshLogs = debounce2(() => {
        this.refreshLogs();
        this.$scope.$applyAsync();
      }, 30);
      this.debounceLoadLogs = debounce2(() => {
        this.loadLogs();
        this.$scope.$applyAsync();
      }, 30);
      this.options = this.context.appOptions;
      this.refreshActiveDates();
      this.scopedLogTypeStore = projectLogTypeStore.scopedByProject(this.context.project);
      this.scopedLogTypeStore.$watchAll(this.$scope, () => {
        this.logTypes = this.scopedLogTypeStore.query();
        this.refreshLogType();
      });
      this.debounceLoadLogs();
      this.deregisterAppOptionsWatcher = this.context.watch("appOptions", (newVal, oldVal) => {
        this.options = this.context.appOptions;
        if (!equals((oldVal || {}).logsDateRange, (newVal || {}).logsDateRange)) {
          this.refreshActiveDates();
          this.refreshLogType();
          this.debouncedRefreshLogs();
        }
        if (!equals((oldVal || {}).logsTypeId, (newVal || {}).logsTypeId)) {
          this.refreshLogType();
          this.debounceLoadLogs();
          this.debouncedRefreshLogs();
        }
      });
      this.$scope.$on("boardViewLogsExport", () => {
        this.$q.when(exportLogs($scope.logType, $scope.project, $scope.activeDateRange.start, $scope.activeDateRange.end), (id) => {
          waitForAsyncDownload(id, _4("Your export is being processed"));
        });
      });
    }
    loadLogs() {
      if (this.logType && !this.context.shareMode) {
        ensureConnectivity(() => {
          this.$q.digest(loadLogsForProject(this.context.project, this.logType));
        });
      }
    }
    refreshLogType() {
      const oldLogType = this.logType;
      if (this.options.logsTypeId && this.scopedLogTypeStore.exists(this.options.logsTypeId)) {
        this.logType = this.scopedLogTypeStore.get(this.options.logsTypeId);
      } else if (this.logTypes.length > 0) {
        this.logType = this.logTypes[0];
      } else {
        this.logType = null;
      }
      if ((this.logType || {}).id !== (oldLogType || {}).id) {
        this.hasAggregAttrs = this.logType.attributes.filter((a3) => attributeTypeRegistry.get(a3.type).aggregates).length > 0;
        this.debouncedRefreshLogs();
      }
    }
    refreshLogs() {
      if (this.deregisterLogStoreWatcher) this.deregisterLogStoreWatcher();
      this.deregisterLogStoreWatcher = null;
      if (this.logType) {
        const store2 = activityStore.scoped({
          project_id: this.context.project.id,
          stream_type: "log",
          type_id: this.logType.id
        });
        this.deregisterLogStoreWatcher = store2.$watchAll(this.$scope, () => {
          this.logs = store2.query({
            date: (date) => {
              return !this.activeDateRange || parseTimestamp(date).isBetween(this.activeDateRange.start, this.activeDateRange.end, "day", "[]");
            }
          }, { sortBy: "date" });
          this.afterLogsChange();
        });
      } else {
        this.logs = [];
        this.afterLogsChange();
      }
    }
    afterLogsChange() {
      this.refreshDailyLogs();
      this.refreshUsers();
    }
    refreshUsers() {
      this.users = [];
      if (this.logs && this.logs.length > 0) {
        const userIds = [];
        this.logs.forEach((log2) => {
          if (log2.user && userIds.indexOf(log2.user.id) === -1) {
            this.users.push(log2.user);
            userIds.push(log2.user.id);
          }
        });
      }
    }
    refreshDailyLogs() {
      if (this.logs && this.logs.length > 0) {
        this.dailyLogs = groupActivitiesByDate(this.logs);
      } else {
        this.dailyLogs = [];
      }
    }
    refreshActiveDates() {
      this.activeDateRange = dateRangeToActiveRange(this.options.logsDateRange, "last_thirty_days");
    }
    updateDateRange(range2) {
      this.context.appOptions = { ...this.options || {}, logsDateRange: range2 };
    }
    getUserCell(log2) {
      var m3 = projectMemberStore.scopedByProject(this.context.project).getByUserId(log2.user.id);
      return this.$sce.trustAsHtml('<img src="' + userAvatarUrl(m3.user) + '" class="avatar me-1">' + this.$sanitize(m3.user.display_name));
    }
    getCardCell(log2) {
      const card = cardStore.tryGet(log2.card_id);
      return card ? this.$sce.trustAsHtml(this.$sanitize(card.title) + " (#" + card.ref + ")") : "";
    }
    openCard(log2) {
      const card = cardStore.tryGet(log2.card_id);
      if (card) this.$cardModal.open(card);
    }
    getSum(logs, attr) {
      if (!attributeTypeRegistry.get(attr.type).aggregates) return "";
      const values2 = logs.map((log2) => {
        return (log2.attributes.find((a3) => a3.id === attr.id) || {}).value;
      }).filter((v3) => v3 !== void 0);
      return attributeTypeRegistry.get(attr.type).aggregates.sum(values2);
    }
    getUserSum(user, logs, attr) {
      return this.getSum(logs.filter((log2) => log2.user && log2.user.id === user.id), attr);
    }
    $onDestroy() {
      if (this.deregisterAppOptionsWatcher) this.deregisterAppOptionsWatcher();
    }
  }
});

// public/app/apps/project/logs/ng-components/nav.js
angular_default.module("kantree").component("projectLogsAppNav", {
  templateUrl: "/static/app/apps/project/logs/ng-components/templates/nav.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "projectLogsAppFilterMenu", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.logTypes = [];
      this.canExportData = !this.context.shareMode && canExportData(this.context.project);
      this.debounceRefreshFilterMenu = debounce2(() => {
        this.refreshFilterMenu();
        this.$scope.$applyAsync();
      }, 30);
      this.options = this.context.appOptions;
      this.refreshActiveDates();
      this.scopedLogTypeStore = projectLogTypeStore.scopedByProject(this.context.project);
      this.scopedLogTypeStore.$watchAll(this.$scope, () => {
        this.logTypes = this.scopedLogTypeStore.query();
        this.refreshLogType();
      });
      this.debounceRefreshFilterMenu();
      this.deregisterAppOptionsWatcher = this.context.watch("appOptions", (newVal, oldVal) => {
        this.options = this.context.appOptions;
        if (!equals((oldVal || {}).logsDateRange, (newVal || {}).logsDateRange)) {
          this.refreshActiveDates();
          this.refreshLogType();
        }
        if (!equals((oldVal || {}).logsTypeId, (newVal || {}).logsTypeId)) {
          this.refreshLogType();
        }
      }, false);
      this.exportMenu = { config: [{
        label: _4("Export to CSV"),
        icon: "download",
        action: () => {
          this.$q.when(exportLogs(this.logType, this.context.project, this.activeDateRange.start, this.activeDateRange.end), (id) => {
            waitForAsyncDownload(id, _4("Your export is being processed"));
          });
        }
      }] };
    }
    refreshLogType() {
      const oldLogType = this.logType;
      if (this.options.logsTypeId && this.scopedLogTypeStore.exists(this.options.logsTypeId)) {
        this.logType = this.scopedLogTypeStore.get(this.options.logsTypeId);
      } else if (this.logTypes.length > 0) {
        this.logType = this.logTypes[0];
      } else {
        this.logType = null;
      }
      if ((this.logType || {}).id !== (oldLogType || {}).id) {
        this.debounceRefreshFilterMenu();
      }
    }
    refreshFilterMenu() {
      if (this.logType) {
        this.menu = this.$projectLogsAppFilterMenu.get(this.context.project, this.logType.id, (logsTypeId) => {
          this.context.appOptions = { ...this.options || {}, logsTypeId };
        });
      } else {
        this.menu = null;
      }
    }
    refreshActiveDates() {
      this.activeDateRange = dateRangeToActiveRange(this.options.logsDateRange, "last_thirty_days");
    }
    $onDestroy() {
      if (this.deregisterAppOptionsWatcher) this.deregisterAppOptionsWatcher();
    }
  }
});

// public/app/apps/project/overview/ng-components/overview.js
angular_default.module("kantree").component("projectOverviewApp", {
  templateUrl: "/static/app/apps/project/overview/ng-components/templates/overview.html",
  bindings: {
    context: "<"
  }
});

// public/app/apps/project/overview/ng-components/overview-header.js
angular_default.module("kantree").component("projectOverviewAppHeader", {
  templateUrl: "/static/app/apps/project/overview/ng-components/templates/overview-header.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
    }
    $onChanges() {
    }
    $onDestroy() {
    }
  }
});

// public/app/apps/project/overview/ng-components/overview-attributes.js
angular_default.module("kantree").component("projectOverviewAppAttributes", {
  templateUrl: "/static/app/apps/project/overview/ng-components/templates/overview-attributes.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.org = orgStore.get(this.context.project.owner?.id);
      cardStore.$watch(this.$scope, this.context.project.top_level_card?.id, () => {
        this.topLevelCard = cardStore.get(this.context.project.top_level_card?.id);
      });
      cardModelStore.$watch(this.$scope, cardModelStore.getTopLevelCardModel(this.org, this.context.project).id, () => {
        this.topLevelCardModel = getCardCompositeModel(this.topLevelCard, false);
      });
    }
    get topLevelCardEditable() {
      return isConnected();
    }
  }
});

// public/app/actions/project-members.ts
function listProjectInvites(project) {
  return api_default.project_members.list_invites.get({ project_id: project.id });
}
async function addProjectMember(project, user) {
  const member = await api_default.project_members.add_user.post({ project_id: project.id, user_id: user.id });
  return projectMemberStore.insert(Object.assign({ project_id: project.id }, member));
}
async function removeProjectMember(project, member) {
  try {
    await api_default.project_members.remove_member.delete({ project_id: project.id, member_id: member.id }, { ignoreErrorHandlers: true });
    return projectMemberStore.remove(member);
  } catch (error2) {
    autoCatchAsRequestErrorDialog([400])(error2);
    return Promise.reject(error2);
  }
}
async function updateProjectMember(project, member, roleId) {
  try {
    const m3 = await api_default.project_members.update_member.put({ project_id: project.id, member_id: member.id, role_id: roleId }, { ignoreErrorHandlers: true });
    return projectMemberStore.update(member, m3);
  } catch (error2) {
    autoCatchAsRequestErrorDialog([400])(error2);
    return Promise.reject(error2);
  }
}
async function addProjectInvites(project, emailOrUsernames, message) {
  try {
    const invites = await api_default.project_members.invite.post({
      project_id: project.id,
      email_or_usernames: emailOrUsernames,
      message
    }, { ignoreErrorHandlers: true });
    projectMemberStore.transaction(() => {
      for (const invite of invites) {
        if (invite.user) {
          projectMemberStore.insert(Object.assign({ project_id: project.id }, invite));
        }
      }
    });
    return invites;
  } catch (error2) {
    autoCatchAsRequestErrorDialog([400, 403])(error2);
    return Promise.reject(error2);
  }
}
function resendProjectInvite(project, invite) {
  return api_default.project_members.invite.post({ project_id: project.id, email_or_usernames: invite.email });
}
async function removeProjectInvite(project, invite) {
  try {
    await api_default.project_members.remove_member.delete({ project_id: project.id, member_id: invite.id }, { ignoreErrorHandlers: true });
  } catch (error2) {
    autoCatchAsRequestErrorDialog([400, 403])(error2);
    return Promise.reject(error2);
  }
}

// public/app/apps/project/overview/ng-components/overview-members.js
angular_default.module("kantree").component("projectOverviewAppMembers", {
  templateUrl: "/static/app/apps/project/overview/ng-components/templates/overview-members.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "projectPage"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.MemberList = MemberList;
      this.invites = [];
      this.members = [];
      this.roles = [];
      this.sideLoaded = false;
      if (!this.context.project.is_template) {
        this.$q.digest(loadAllProjectMembers(this.context.project, false, { ignoreErrorHandlers: true }));
        projectMemberStore.scopedByProject(this.context.project).$watchAll(this.$scope, () => {
          this.members = Object.assign({}, this.members, projectMemberStore.getAll(this.context.project));
        });
        const scopedRoleStore = roleStore.scopedByOrg(this.context.project.owner);
        scopedRoleStore.$watchAll(this.$scope, () => {
          this.roles = Object.assign({}, roleStore.getAllForProject(this.context.project));
        });
        projectStore.$watch(this.$scope, this.context.project, () => {
          this.canManageMembers = canManageMembers(this.context.project) && !this.context.project.is_archived && !this.context.project.is_template;
          if (this.canManageMembers && !this.sideLoaded) {
            this.$q.digest(loadAllRolesForProject(this.context.project));
            this.$q.when(listProjectInvites(this.context.project), (invites) => {
              this.invites = invites;
            });
            this.sideLoaded = true;
          }
        });
      }
    }
    get presenceManager() {
      return this.$projectPage.scopeManager?.presenceManager;
    }
    // Need to use anonymous function to preserve this when calling the function in solidjs component
    resendInvite = (invite) => {
      this.$q.digest(resendProjectInvite(this.context.project, invite));
    };
    removeInvite = (invite) => {
      this.$q.when(removeProjectInvite(this.context.project, invite), () => {
        this.invites = this.invites.filter((i3) => i3.id !== invite.id);
      });
    };
    removeMember = (member) => {
      this.$q.digest(removeProjectMember(this.context.project, member));
    };
    updateMemberRole = (member, roleId) => {
      this.$q.digest(updateProjectMember(this.context.project, member, roleId));
    };
  }
});

// public/app/apps/project/overview/ng-components/nav.js
angular_default.module("kantree").component("projectOverviewAppNav", {
  template: `
    <quick-global-search-toggle
      search-obj-types="$ctrl.searchObjTypes"
      cover-toggle="true"
      show-preview="true"
      filter-scopes="$ctrl.filterScopes"
      go-to-search="$ctrl.openView($filter)"
    ></quick-global-search-toggle>
  `,
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.filterScopes = [["project", this.context.project.id]];
      this.searchObjTypes = ["card"];
    }
    openView(filter4) {
    }
  }
});

// public/app/apps/project/report/auto-reports.js
function buildAutoReports(project) {
  return [
    ...buildReportsForDefaultGroupType(project),
    ...buildReportsForAttributes(project),
    ...buildReportsForLogTypes(project)
  ];
}
function buildReportsForDefaultGroupType(project) {
  let defaultGroupType = null;
  const groupTypes = cardGroupTypeStore.scopedByEnabled(project).query();
  if (groupTypes.length) {
    defaultGroupType = groupTypes[0];
  }
  return [
    {
      name: "workload",
      title: _4("Workload"),
      icon: "heartbeat",
      widgets: [
        {
          "chart": "workload",
          "options": {},
          "position": { "height": 4, "x": 0, "y": 2, "width": 7 },
          "title": _4("Workload")
        },
        {
          "chart": "assignees_breakdown",
          "options": {},
          "position": { "height": 4, "x": 8, "y": 6, "width": 4 },
          "title": _4("Assignees breakdown")
        },
        {
          "chart": "cycle_times",
          "options": { "group_type": defaultGroupType ? defaultGroupType.id : null },
          "position": { "height": 4, "x": 0, "y": 6, "width": 8 },
          "title": _4("Time between groups")
        },
        {
          "chart": "cards",
          "options": { "filter": "{$date}<today() state!=done" },
          "position": { "height": 4, "x": 7, "y": 2, "width": 5 },
          "title": _4("Overdue cards")
        },
        {
          "chart": "query",
          "options": { "compute": "count" },
          "position": { "height": 2, "x": 0, "y": 0, "width": 3 },
          "title": _4("Total number of cards")
        },
        {
          "chart": "query",
          "options": { "compute": "query", "query": "query(state!=done, count())" },
          "position": { "height": 2, "x": 3, "y": 0, "width": 3 },
          "title": _4("Number of remaining cards")
        },
        {
          "chart": "query",
          "options": { "compute": "query", "query": "query({$date}<today(), count())" },
          "position": { "height": 2, "x": 6, "y": 0, "width": 3 },
          "title": _4("Number of overdue cards")
        }
      ]
    },
    {
      name: "progress",
      title: _4("Progress overview"),
      icon: "line-chart",
      widgets: [
        {
          "chart": "progressbar_query",
          "options": { "total_query": "count()", "value_query": "query(state=done, count())" },
          "position": { height: 1, width: 12, x: 0, y: 2 },
          "title": _4("Workspace progression")
        },
        {
          "chart": "query",
          "options": { "compute": "count" },
          "position": { height: 2, width: 2, x: 0, y: 0 },
          "title": _4("Total number of cards")
        },
        {
          "chart": "query",
          "options": { "compute": "query", "query": "query(state!=done, count())" },
          "position": { height: 2, width: 2, x: 2, y: 0 },
          "title": _4("Number of remaining cards")
        },
        {
          "chart": "query",
          "options": { "compute": "query", "query": "query(state=done, count())" },
          "position": { height: 2, width: 2, x: 4, y: 0 },
          "title": _4("Number of completed cards")
        },
        {
          "chart": "query",
          "options": { "compute": "query", "query": "query({$date}<today(), count())" },
          "position": { height: 2, width: 2, x: 6, y: 0 },
          "title": _4("Number of overdue cards")
        },
        {
          "chart": "cumulative_flow_diagram",
          "options": { "group_type": defaultGroupType ? defaultGroupType.id : null },
          "position": { height: 8, width: 7, x: 0, y: 3 },
          "title": _4("Cumulative Flow Diagram")
        },
        {
          "chart": "groups",
          "options": { "group_type": defaultGroupType ? defaultGroupType.id : null },
          "position": { height: 8, width: 5, x: 7, y: 3 },
          "title": _4("Groups")
        }
      ]
    }
  ];
}
function buildReportsForAttributes(project) {
  const attributes = cardModelStore.scopedByEnabled(project).getAttributesFromModels();
  const widgets = [];
  attributes.forEach((attr) => {
    const attrType = attributeTypeRegistry.get(attr.type);
    if (attrType.aggregates || attrType.name === "formula") {
      widgets.push({
        "chart": "query",
        "options": { "compute": "sum", "field": attr },
        "title": _4("{attributeName} sum", { attributeName: attr.name })
      });
    } else if (attrType.groupable) {
      widgets.push({
        "chart": "query",
        "options": { "compute": "count", "group_by": "attribute:" + attr.id, "viz": "pie" },
        "title": _4("Repartition of cards in {attributeName}", { attributeName: attr.name })
      });
    }
  });
  var y3 = 0, x3 = 0;
  widgets.forEach((widget) => {
    widget.position = {
      height: 4,
      width: 4,
      x: x3,
      y: y3
    };
    x3 += 4;
    if (x3 >= 12) {
      x3 = 0;
      y3 += 4;
    }
  });
  return [{
    name: "fields",
    title: _4("Fields overview"),
    icon: "pie-chart",
    widgets
  }];
}
function buildReportsForLogTypes(project) {
  return projectLogTypeStore.scopedByProject(project).query().map((logType) => {
    return {
      name: "logs",
      title: _4("{logType} logs", { logType: logType.name }),
      icon: "list-ul",
      widgets: [
        {
          "chart": "logs_number_sum",
          "options": { "log_type": logType.id },
          "position": { "height": 4, "x": 0, "y": 0, "width": 6 },
          "title": _4("Total")
        },
        {
          "chart": "logs_number_daily",
          "options": { "log_type": logType.id },
          "position": { "height": 4, "x": 6, "y": 0, "width": 6 },
          "title": _4("Daily totals")
        },
        {
          "chart": "logs_number_sum_by_user",
          "options": { "log_type": logType.id },
          "position": { "height": 4, "x": 0, "y": 4, "width": 6 },
          "title": _4("Amount logged per user")
        },
        {
          "chart": "logs_count",
          "options": { "log_type": logType.id },
          "position": { "height": 4, "x": 6, "y": 4, "width": 6 },
          "title": _4("Number of time a {logType} was logged per day", { logType: logType.name })
        }
      ]
    };
  });
}

// public/app/apps/project/report/ng-components/nav.js
angular_default.module("kantree").component("projectReportAppNav", {
  templateUrl: "/static/app/apps/project/report/ng-components/templates/nav.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$timeout", "$scope", "addReportWidgetModal", "$rootScope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.onForceRefreshAllWidgets = onForceRefreshAllWidgets;
      projectStore.$watch(this.$scope, this.context.project, (project) => {
        this.autoReports = buildAutoReports(project);
      });
      this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
        this.options = this.context.appOptions;
        this.widgets = this.options.widgets || [];
        if (this.options.auto_report && !this.widgets.length) {
          const report = this.autoReports.find((r3) => r3.name === this.options.auto_report);
          this.widgets = report.widgets;
        }
      });
    }
    get editable() {
      return !this.context.readonly && isConnected();
    }
    openChartLibrary() {
      if (!this.options.locked) {
        loadCharts().then((charts) => {
          const modalInstance = this.$addReportWidgetModal.open([["project", this.context.project.id]], null, {
            charts,
            queries: projectReportAppQueries,
            filters: projectReportAppFilters,
            project: this.context.project,
            board: this.context.board
          });
          modalInstance.result.then((widget) => {
            this.context.updateReportWidgets([...this.widgets, widget]);
          });
        });
      }
    }
    toggleFullscreen() {
      toggleFullscreen(jquery_default("project-report-app")[0]);
    }
  }
});

// public/app/apps/project/report/ng-components/report.js
angular_default.module("kantree").component("projectReportApp", {
  templateUrl: "/static/app/apps/project/report/ng-components/templates/report.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$rootScope", "$timeout", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isConnected = isConnected;
      this.isConnectionManagerDisabled = isConnectionManagerDisabled();
      this.$q.when(loadCharts(), (charts) => {
        this.charts = charts;
        projectStore.$watch(this.$scope, this.context.project, (project) => {
          this.autoReports = buildAutoReports(project);
        });
        this.context.$watch(this.$scope, "appOptions", (newVal, oldVal) => {
          this.options = this.context.appOptions;
          this.refreshReportWidgets();
          if (this.options.auto_report && !this.widgets.length) {
            const report = this.autoReports.find((r3) => r3.name === this.options.auto_report);
            this.refreshReportWidgets(report.widgets);
          }
        });
      });
    }
    refreshReportWidgets(widgets) {
      this.widgets = this.formatWidgetsForDisplay(widgets || this.context.appOptions?.widgets);
    }
    formatWidgetsForDisplay(widgets = []) {
      return widgets.map((widget) => {
        return Object.assign({}, formatWidgetForDisplay(widget, this.charts, this.context.shareModeData?.analytics), {
          filter_scopes: [["project", this.context.project.id]]
        });
      });
    }
    get editable() {
      return !this.context.readonly && isConnected() && !this.options.locked;
    }
    createFromAutoReport = function(report) {
      this.context.updateReportWidgets(report.widgets, report.title);
    };
    updateWidgets(widgets) {
      this.context.updateReportWidgets(widgets);
    }
  }
});

// public/app/apps/reports/menus/add-widget.js
angular_default.module("kantree").factory("addChartWidgetMenuFactory", [
  function() {
    return {
      getItems: function(addWidget, isSelected2, charts, queries, filters, project, board) {
        var groupTypes = [];
        var attributes = [];
        var logTypes = [];
        if (project) {
          groupTypes = cardGroupTypeStore.scopedByEnabled(project, true).query();
          attributes = cardModelStore.scopedByEnabled(project).getAttributesFromModels();
          logTypes = projectLogTypeStore.scopedByProject(project).query();
        }
        var queryChart, queryProgressChart, cardsChart, chartsFor = {};
        var categories = {};
        var items = (charts || []).filter((c3) => !c3.hidden).map(function(c3) {
          if (c3.name === "query") {
            queryChart = c3;
            return;
          }
          if (c3.name === "cards") {
            cardsChart = c3;
            return;
          }
          if (c3.name === "progressbar_query") {
            queryProgressChart = c3;
            return;
          }
          if (c3.available_for) {
            if (!chartsFor[c3.available_for]) {
              chartsFor[c3.available_for] = [];
            }
            chartsFor[c3.available_for].push(c3);
            return;
          }
          var item;
          if (groupTypes.length) {
            for (var i3 = 0; i3 < c3.options.length; i3++) {
              if (c3.options[i3].name === "group_type_id" && c3.options[i3].required) {
                item = {
                  type: "expandable-items",
                  label: c3.title,
                  items: groupTypes.map(function(gt) {
                    return {
                      label: gt.name,
                      action: function() {
                        addWidget(c3, { group_type_id: gt.id });
                      }
                    };
                  })
                };
                break;
              }
            }
          }
          if (!item) {
            item = {
              label: c3.title,
              action: function() {
                addWidget(c3);
              }
            };
          }
          if (c3.category) {
            if (typeof categories[c3.category] === "undefined") {
              categories[c3.category] = [];
            }
            categories[c3.category].push(item);
          } else {
            return item;
          }
        }).filter(Boolean);
        angular_default.forEach(categories, function(subItems2, category) {
          items.push({
            type: "expandable-items",
            label: category,
            items: subItems2
          });
        });
        var makeQueryItem = function(label, compute, field2 = null, query2 = null, name2) {
          return {
            label,
            action: function() {
              const chart = { ...name2 ? charts.find((c3) => c3.name === name2) : queryChart };
              chart.title = label;
              addWidget(chart, isObject2(query2) ? query2 : {
                compute,
                field: field2,
                query: query2
              });
            }
          };
        };
        var makeGroupSubmenu = function(groupType, query2) {
          var groups = cardGroupStore.scopedByType(groupType, board).query();
          if (!groups.length) {
            return;
          }
          return groups.map(function(group2) {
            return makeQueryItem(group2.title, "query", null, query2 = "query(#{" + group2.title.replace(" ", "").toLowerCase() + "}, " + query2 + ")");
          });
        };
        var makeAttributesMenu = function() {
          var items2 = [];
          attributes.forEach(function(attr) {
            var attrType = attributeTypeRegistry.get(attr.type);
            if (attrType.aggregates) {
              items2.push({
                type: "expandable-items",
                label: attr.name,
                items: [
                  makeQueryItem(_4("Sum across all cards"), "sum", attr),
                  makeQueryItem(_4("Average across all cards"), "avg", attr),
                  makeQueryItem(_4("Maximum across all cards"), "max", attr),
                  makeQueryItem(_4("Minimum across all cards"), "min", attr),
                  { label: "--" }
                ].concat((groupTypes || []).map(function(gt) {
                  var items3 = makeGroupSubmenu(gt, "sum({" + attr.name + "})");
                  if (items3) {
                    return {
                      type: "expandable-items",
                      label: _4("Sum for cards in {grouptype}", { grouptype: gt.name }),
                      items: items3
                    };
                  }
                }).filter(Boolean))
              });
            } else if (attrType.groupable) {
              items2.push({
                type: "expandable-items",
                label: attr.name,
                items: [
                  makeQueryItem(_4("Count cards by value"), {
                    compute: "count",
                    group_by: "attribute:" + attr.id,
                    viz: "bar"
                  })
                ]
              });
            }
          });
          return items2;
        };
        var makeLogTypesMenu = function() {
          var items2 = [];
          logTypes.forEach(function(logType) {
            items2.push({
              type: "expandable-items",
              label: logType.name,
              items: (chartsFor["logs"] || []).map(function(c3) {
                return {
                  label: c3.title,
                  action: function() {
                    addWidget(c3, { log_type_id: logType.id });
                  }
                };
              })
            });
          });
          return items2;
        };
        var separator3 = false;
        if (queries || attributes.length) {
          var subItems = [];
          if (queries) {
            subItems = queries.map(function(q) {
              if (q.label) {
                return q;
              }
              return makeQueryItem(q.title, null, null, q.query, q.chart);
            });
          }
          if (attributes.length) {
            var attributeItems = makeAttributesMenu();
            if (subItems.length && attributeItems.length) {
              subItems.push({ label: "--" });
            }
            subItems = subItems.concat(attributeItems);
          }
          if (subItems.length) {
            subItems.push({ label: "--" });
          }
          subItems.push({
            label: _4("Custom query"),
            action: function() {
              addWidget(queryChart);
            }
          }, {
            label: _4("Query as progress bar"),
            action: function() {
              addWidget(queryProgressChart);
            }
          });
          items.push(
            { label: "--" },
            {
              type: "expandable-items",
              label: _4("Query"),
              items: subItems
            }
          );
          separator3 = true;
        } else {
          items.push({
            label: _4("Query"),
            action: function() {
              addWidget(queryChart);
            }
          }, {
            label: _4("Query as progress bar"),
            action: function() {
              addWidget(queryProgressChart);
            }
          });
        }
        if (project && board) {
          if (filters) {
            var subItems = filters.map(function(f3) {
              if (f3.label) {
                return f3;
              }
              return {
                label: f3.title,
                action: function() {
                  const chart = { ...cardsChart };
                  chart.title = f3.title;
                  addWidget(chart, { filter: f3.filter, mode: "list" });
                }
              };
            }).concat([
              { label: "--" },
              {
                label: _4("Custom filter"),
                action: function() {
                  addWidget(cardsChart, { mode: "list" });
                }
              }
            ]);
            if (!separator3) {
              items.push({ label: "--" });
              separator3 = true;
            }
            items.push({
              type: "expandable-items",
              label: _4("Cards"),
              items: subItems
            });
          } else {
            items.push({
              label: _4("Cards"),
              action: function() {
                addWidget(cardsChart, { mode: "list" });
              }
            });
          }
        }
        if (logTypes.length) {
          if (!separator3) {
            items.push({ label: "--" });
            separator3 = true;
          }
          items.push({
            type: "expandable-items",
            label: _4("Logs"),
            items: makeLogTypesMenu()
          });
        }
        function makeFilterable(items2) {
          return items2.map((i3) => {
            const item = { ...i3 };
            if (item.items) {
              item.items = makeFilterable(item.items);
            }
            item.filterable = true;
            return item;
          });
        }
        function makeSelectable(items2) {
          return items2.map((i3) => {
            const item = { ...i3 };
            if (item.items) {
              item.items = makeSelectable(item.items);
            }
            item.selected = () => isSelected2(item);
            return item;
          });
        }
        return makeSelectable(makeFilterable(items));
      },
      get: function(addWidget, charts, queries, filters, project, board) {
        return { config: this.getItems(addWidget, charts, queries, filters, project, board) };
      }
    };
  }
]);

// public/app/apps/reports/modals/add-widget.js
angular_default.module("kantree").service("addReportWidgetModal", class extends AngularClass {
  static $inject = ["$rootScope", "$uibModal"];
  open(filterScopes, filter4, chartLibraryOptions) {
    let scope = this.$rootScope.$new();
    scope.filterScopes = filterScopes;
    scope.filter = filter4;
    scope.chartLibraryOptions = chartLibraryOptions;
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/apps/reports/modals/templates/add-widget-modal.html",
      windowClass: "add-report-widget-modal",
      controller: "addReportWidgetModalCtrl",
      controllerAs: "$ctrl",
      bindToController: true,
      scope
    });
    instance.result.finally(function() {
      scope.$destroy();
    });
    return instance;
  }
});
angular_default.module("kantree").controller("addReportWidgetModalCtrl", class extends AngularClass {
  static $inject = ["$scope", "$q", "cardFilterMenuFactory", "addChartWidgetMenuFactory"];
  $onInit() {
    injectI18nHelpersIntoScope(this.$scope);
    this.$q.when(loadCharts(), (charts) => {
      this.filterScopes = this.$scope.filterScopes;
      this.filter = this.$scope.filter;
      const { queries, filters = [], project, board } = this.$scope.chartLibraryOptions;
      this.widgetTypes = [{
        icon: "bar-chart",
        title: _4("Chart"),
        onSelect: () => {
          this.widget = {
            title: _4("Query"),
            chart: charts.find((c3) => c3.name === "query"),
            options: { compute: "count" },
            filter: this.filter,
            filter_scopes: this.filterScopes
          };
        }
      }].concat(...getAvailableCardsApps(project).map((mode) => {
        return {
          icon: mode.icon,
          title: mode.title,
          onSelect: () => {
            this.widget = {
              title: mode.title,
              chart: charts.find((c3) => c3.name === "cards"),
              options: { mode: mode.name, filter: this.filter },
              filter_scopes: this.filterScopes
            };
          }
        };
      }));
      this.suggestedWidgets = [];
      if (filters.length) {
        filters.push({ label: "--" });
      }
      filters.push(...this.$cardFilterMenuFactory.getExpandableItems(project, board, false, (filter4) => {
        this.widget = {
          chart: charts.find((c3) => c3.name === "cards"),
          options: { mode: "list", filter: filter4 },
          filter_scopes: this.filterScopes
        };
        this.filter = filter4;
      }));
      const onLibItemSelect = (chart, options2) => {
        this.widget = {
          chart,
          options: options2 || [],
          filter: this.filter,
          filter_scopes: this.filterScopes
        };
      };
      const isLibItemSelected = (item) => {
        if (!this.widget) return false;
        return (this.widget.title || this.widget.chart.title) === item.label;
      };
      this.chartLibraryConfig = () => this.$addChartWidgetMenuFactory.getItems(
        onLibItemSelect,
        isLibItemSelected,
        charts,
        queries,
        filters,
        project,
        board
      );
      if (this.projectScoped) {
        this.widget = {
          title: _4("Query"),
          chart: charts.find((c3) => c3.name === "query"),
          options: { compute: "count" },
          filter_scopes: this.filterScopes
        };
      }
    });
  }
  get projectScoped() {
    return this.filterScopes?.some((scope) => scope[0] === "project");
  }
  get missingReqs() {
    return missingReqsForWidget(this.widget);
  }
  onWidgetChange(widget) {
    this.widget = widget;
    this.filterScopes = this.widget.filter_scopes;
    this.filter = this.widget.chart && this.widget.chart.name === "cards" ? this.widget.options?.filter : this.widget.filter;
  }
  reset() {
    this.widget = null;
  }
  delete() {
    this.$scope.$close(null);
  }
  save() {
    this.$scope.$close(this.widget);
  }
});

// public/app/apps/reports/modals/widget-editor.js
angular_default.module("kantree").service("reportWidgetEditorModal", class extends AngularClass {
  static $inject = ["$rootScope", "$uibModal"];
  open(widget, editorOptions = {}) {
    let scope = this.$rootScope.$new();
    scope.widget = widget;
    scope.editorOptions = editorOptions;
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/apps/reports/modals/templates/widget-editor-modal.html",
      windowClass: "report-widget-editor-modal",
      controller: "reportWidgetEditorModalCtrl",
      controllerAs: "$ctrl",
      bindToController: true,
      scope
    });
    instance.result.finally(function() {
      scope.$destroy();
    });
    return instance;
  }
});
angular_default.module("kantree").controller("reportWidgetEditorModalCtrl", class extends AngularClass {
  static $inject = ["$scope"];
  $onInit() {
    injectI18nHelpersIntoScope(this.$scope);
    this.widget = this.$scope.widget;
    this.editorOptions = this.$scope.editorOptions;
  }
  get missingReqs() {
    return missingReqsForWidget(this.widget);
  }
  onWidgetChange(widget) {
    this.widget = widget;
  }
  delete() {
    this.$scope.$close(null);
  }
  save() {
    this.$scope.$close(this.widget);
  }
});

// public/app/apps/reports/ng-components/cards-app-editor.js
angular_default.module("kantree").component("reportCardsAppWidgetEditor", {
  template: `
  <div class="editor">
    <global-cards-app-nav context="$ctrl.context"></global-cards-app-nav>
  </div>
  <div class="preview">
    <input type="text" class="form-control" ng-model="$ctrl.titleInput" ng-model-options="{debounce: 100}" ng-required="true"
      ng-change="$ctrl._onChange()" ng-attr-placeholder="{{::$ctrl.titlePlaceholder}}" auto-grow min-width="250">
    <report-widget-cards config="$ctrl.chartConfig" options="$ctrl.widget.options" filter-scopes="$ctrl.widget.filter_scopes"></report-widget-cards>
  </div>
  `,
  bindings: {
    widget: "<",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      this.titlePlaceholder = _4("Title required...");
      this.widget = this.widget || {};
      this.titleInput = this.widget.title || this.widget.options && this.widget.options.mode;
      const { filterScopes, appName, appOptions } = getContextParamsFromView({
        ...globalViewsDefaultProps,
        mode: "list",
        ...this.widget.options,
        filter_scopes: this.widget.filter_scopes,
        mode_options: { ...globalViewsDefaultProps.mode_options, ...this.widget.options.mode_options }
      });
      const app = cardsAppRegistry.get(appName);
      this.context = new GlobalContext({ filterScopes }, app, appOptions);
      if (this.deregisterContextWatchers) this.deregisterContextWatchers();
      this.deregisterContextWatchers = offMany([
        this.context.filterScopes?.[0]?.[0] !== "portfolio" ? this.context.watch("filterScopes", (newVal, oldVal) => {
          this.onCardsAppChange({ filter_scopes: newVal, options: this.context.appOptions });
        }) : () => {
        },
        this.context.watch("appOptions", (newVal, oldVal) => {
          this.onCardsAppChange({ filter_scopes: this.context.filterScopes, options: newVal });
        })
      ]);
      this.chartConfig = { context: this.context };
    }
    $postLink() {
      this.$element.toggleClass("is-project-scoped", !!this.projectScoped);
    }
    get projectScoped() {
      return this.widget && Array.isArray(this.widget.filter_scopes) && this.widget.filter_scopes.some((scope) => scope[0] === "project");
    }
    get missingReqs() {
      return missingReqsForWidget(this.widget);
    }
    onCardsAppChange(changes) {
      const options2 = applyAppChangesToView(null, changes, globalViewsDefaultProps, globalViewsAvailableProps);
      const filterScopes = options2.filter_scopes;
      delete options2.filter_scopes;
      const _changes = {};
      if (!equals(this.widget.options, options2)) {
        _changes.options = options2;
      }
      if (!equals(filterScopes, this.widget.filter_scopes)) {
        _changes.filter_scopes = filterScopes;
      }
      if (Object.keys(_changes).length > 0) {
        this._onChange({ ..._changes });
      }
    }
    _onChange(newWidgetProps) {
      this.onChange({
        $widget: { ...this.widget, ...newWidgetProps, title: this.titleInput }
      });
    }
    $onDestroy() {
      this.context.destroy();
    }
  }
});

// public/app/apps/reports/ng-components/chart-editor.js
angular_default.module("kantree").component("reportChartWidgetEditor", {
  templateUrl: "/static/app/apps/reports/ng-components/templates/chart-editor.html",
  bindings: {
    widget: "<",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.dropConfig = {
        classes: "drop-theme-menu drop-theme-arrow project-selector-dropdown"
      };
      this.refreshAll();
    }
    $onChanges(changes) {
      const widgetChanged = changes.widget && !changes.widget.isFirstChange();
      if (widgetChanged) {
        this.refreshAll();
      }
    }
    get projectScoped() {
      return this.widget?.filter_scopes?.[0]?.[0] === "project";
    }
    get portfolioScoped() {
      return this.widget.filter_scopes?.[0]?.[0] === "portfolio";
    }
    get projectCount() {
      return getLabelForFilterScopes(this.widget.filter_scopes || [], this.projects?.length);
    }
    get showFilterScopesSelector() {
      return !this.projectScoped && !this.portfolioScoped;
    }
    get noProjectSelected() {
      return this.projects && this.projects.length === 0;
    }
    refreshAll() {
      this.projects = getProjectsFromFilterScopes(this.widget.filter_scopes || []);
      this.project = this.projects.length === 1 ? this.projects[0] : null;
      this.title = this.widget.title;
      this.chart = this.widget.chart;
      this.options = this.widget.options;
      this.filter = this.widget.filter;
      this.filterScopes = this.widget.filter_scopes;
      this.formatChartOptions();
    }
    formatChartOptions() {
      if (this.chart) {
        this.titleInput = this.title || this.chart.title;
        let chartOptions = [...this.chart.options];
        if (!this.projectScoped) {
          chartOptions = chartOptions.filter((o3) => o3.name !== "filter").map((o3) => {
            return { ...o3, widget_options: { ...o3.widget_options, filter_scopes: this.widget.filter_scopes, filter: this.filter } };
          });
        }
        if (this.chart.name === "query") {
          chartOptions = chartOptions.map((o3) => {
            if (o3.name === "query") {
              return { ...o3, helplink: serverConfig.help_site_url };
            }
            return o3;
          });
        }
        this.chartOptions = chartOptions;
      } else {
        this.titleInput = null;
        this.chartOptions = [];
      }
    }
    _onChange(newProps = {}) {
      if (newProps.options) {
        if (!!newProps.options["group_by"] && !newProps.options["viz"]) {
          newProps.options["viz"] = "table";
        }
        if (!newProps.options["group_by"] && !!newProps.options["viz"]) {
          newProps.options["viz"] = null;
        }
      }
      this.onChange({
        $widget: {
          title: this.titleInput,
          chart: this.chart,
          options: this.options,
          filter: this.filter,
          filter_scopes: this.filterScopes,
          ...newProps
        }
      });
    }
    applyProjectSelection(filterScopes) {
      if (!equals(this.filterScopes, filterScopes)) {
        this.$scope.$evalAsync(() => {
          this._onChange({ filter_scopes: filterScopes });
        });
      }
    }
  }
});

// virtual-ns:gridstack
var gridstack_default = GridStack;

// public/app/apps/reports/ng-components/gridstack.js
gridstack_default.prototype.removeWidget = function(e3, t3 = true) {
  return this.getElements(e3).forEach((e4) => {
    let i3 = e4.gridstackNode;
    i3 || (i3 = this.engine.nodes.find((t4) => e4 === t4.el)), i3 && (delete e4.gridstackNode, this.dd.draggable(e4, "destroy").resizable(e4, "destroy"), this.engine.removeNode(i3, t3, true));
  }), this._triggerRemoveEvent(), this._triggerChangeEvent(), this;
};
angular_default.module("kantree").component("gridStack", {
  bindings: {
    editable: "<?",
    onWidgetChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$rootScope", "$element"];
    $postLink() {
      this.$element.addClass("grid-stack");
      this.gridstack = gridstack_default.init({
        handle: ".drag-handle",
        float: false
      }, this.$element[0]);
      if (!this.editable) {
        this.gridstack.disable();
      }
      this.gridstack.on("change", (event2, items) => {
        const changes = [];
        for (const item of items) {
          const id = jquery_default(item.el).attr("widget-id");
          changes.push({ id, position: { x: item.x, y: item.y, width: item.width, height: item.height } });
        }
        this.onWidgetChange({ $changes: changes });
      });
      this.rootScopeEventListenerOff = offMany([
        this.$rootScope.$on("gridstackBatchUpdate", () => {
          if (this.gridstack) {
            this.gridstack.batchUpdate();
          }
        }),
        this.$rootScope.$on("gridstackCommit", () => {
          if (this.gridstack) {
            this.gridstack.commit();
          }
        })
      ]);
    }
    $onChanges(changes) {
      if (changes.editable && !changes.editable.isFirstChange()) {
        if (!changes.editable.currentValue) {
          this.gridstack.disable();
        } else {
          this.gridstack.enable();
        }
      }
    }
    $onDestroy() {
      this.gridstack.destroy(false);
      this.gridstack = null;
      if (this.rootScopeEventListenerOff) {
        this.rootScopeEventListenerOff();
      }
    }
  }
});
angular_default.module("kantree").component("gridstackWidget", {
  bindings: {
    widgetId: "@",
    position: "<?"
  },
  require: {
    gridstackCtrl: "^gridStack"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    updatePositionAtts() {
      let pos = this.position;
      if (!pos) {
        pos = { width: 6, height: 5 };
      } else if (typeof pos.left !== "undefined") {
        pos = {
          x: Math.floor((pos.left - 1) * 12 / 30),
          y: Math.floor((pos.top - 1) * 11 / 20),
          width: Math.floor(pos.width * 12 / 30),
          height: Math.floor(pos.height * 11 / 20)
        };
      }
      this._position = pos;
      if (typeof pos.x !== "undefined") {
        this.$element.attr("data-gs-x", pos.x);
      }
      if (typeof pos.y != "undefined") {
        this.$element.attr("data-gs-y", pos.y);
      }
      this.$element.attr("data-gs-width", pos.width);
      this.$element.attr("data-gs-height", pos.height);
    }
    $postLink() {
      this.updatePositionAtts();
      this.gridstackCtrl.gridstack.makeWidget(this.$element[0]);
    }
    $onChanges(changes) {
      if (changes.position && !changes.position.isFirstChange()) {
        this.updatePositionAtts();
        this.gridstackCtrl.gridstack.update(this.$element[0], this._position.x, this._position.y, this._position.width, this._position.height);
      }
    }
    $onDestroy() {
      if (this.gridstackCtrl.gridstack) {
        this.gridstackCtrl.gridstack.removeWidget(this.$element[0], false);
      }
    }
  }
});

// public/app/apps/reports/ng-components/report.js
angular_default.module("kantree").component("report", {
  templateUrl: "/static/app/apps/reports/ng-components/templates/report.html",
  bindings: {
    editable: "<?",
    widgets: "<?",
    widgetEditorOptions: "<?",
    onWidgetsUpdate: "&?",
    onFetchDataStart: "&?",
    onFetchDataEnd: "&?"
  },
  controller: class extends AngularClass {
    static $inject = ["$rootScope", "$timeout"];
    _fetchingWidgetCount = 0;
    $onChanges(changes) {
      if (changes.widgets) {
        this.$rootScope.$broadcast("gridstackBatchUpdate");
        this._widgets = changes.widgets.currentValue.map((widget) => {
          return Object.assign({}, widget, { id: widget.id || uuid4() });
        });
        this.$timeout(() => this.$rootScope.$broadcast("gridstackCommit"));
      }
    }
    get expandedWidget() {
      return this._widgets.find((w3) => w3.id === this._expandedWidgetId);
    }
    set expandedWidget(widget) {
      this._expandedWidgetId = widget?.id;
    }
    get fetching() {
      return this._fetching;
    }
    set fetching(value2) {
      value2 = Boolean(value2);
      const oldValue = this._fetching;
      if (value2) {
        this._fetchingWidgetCount += 1;
      } else {
        this._fetchingWidgetCount = Math.max(this._fetchingWidgetCount - 1, 0);
      }
      this._fetching = this._fetchingWidgetCount > 0;
      if (this._fetching !== oldValue) {
        this._fetching ? this.onFetchDataStart?.() : this.onFetchDataEnd?.();
      }
    }
    onGridstackUpdate(changes) {
      let updated = false;
      const widgets = this._widgets.map((widget) => {
        let w3 = { ...widget };
        for (const change of changes) {
          if (change.id === w3.id && !equals(w3.position, change.position)) {
            w3.position = change.position;
            updated = true;
            return w3;
          }
        }
        return w3;
      });
      if (updated) {
        this.onWidgetsUpdate({ $widgets: widgets });
        this.$rootScope.$broadcast("gridstackChange");
      }
    }
    updateWidget(widget, newWidget) {
      this.onWidgetsUpdate({ $widgets: this._widgets.map((w3) => {
        if (w3.id === widget.id) {
          return Object.assign({}, w3, newWidget);
        }
        return w3;
      }) });
    }
    removeWidget(widget) {
      this.onWidgetsUpdate({ $widgets: this._widgets.filter((w3) => w3 !== widget) });
    }
  }
});

// virtual-ns:chart.js
var chart_default = Chart;

// virtual-ns:chartjs-plugin-datalabels
var chartjs_plugin_datalabels_default = ChartDataLabels;

// public/app/apps/reports/chartjs.js
chart_default.register(chartjs_plugin_datalabels_default);
chart_default.defaults.maintainAspectRatio = false;
chart_default.defaults.plugins.datalabels.display = false;
chart_default.defaults.interaction.mode = "nearest";
var TimedeltaScale = class extends chart_default.Scale {
  getLabelForValue(value2) {
    return moment_default.duration(value2).humanize();
  }
};
TimedeltaScale.id = "timedelta";
TimedeltaScale.defaults = { position: "left" };
chart_default.register(TimedeltaScale);

// public/app/apps/reports/ng-components/widget.js
angular_default.module("kantree").component("reportWidget", {
  templateUrl: "/static/app/apps/reports/ng-components/templates/widget.html",
  bindings: {
    widgetTitle: "@",
    chart: "<",
    options: "<?",
    filter: "<?",
    filterScopes: "<?",
    chartConfig: "<?",
    editable: "<?",
    onChange: "&",
    onRemove: "&",
    onFetchDataStart: "&?",
    onFetchDataEnd: "&?",
    onToggleExpand: "&?",
    expanded: "<?",
    showHeader: "<?",
    editorOptions: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$q", "$timeout", "$element", "$scope", "reportWidgetEditorModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.options = this.options || {};
      this.errorRetry = 0;
      if (this.chartConfig) {
        if (this.chartConfig.processing) this.loading = true;
        this.formatData(this.chartConfig, true);
      } else {
        this.fetchData(true);
      }
      this.debounceFetchData = debounce2((forceRefresh) => this.$scope.$evalAsync(() => this.fetchData(forceRefresh)), 1e3);
      this.disposeOnForceRefreshAllWidgetsEventListener = onForceRefreshAllWidgets.subscribe(() => {
        this.debounceFetchData.clear();
        this.fetchData(true);
      });
    }
    $onChanges(changes) {
      const chartChanged = changes.chart && !changes.chart.isFirstChange() && !equals(this.chart, changes.chart.previousValue);
      const optionsChanged = changes.options && !changes.options.isFirstChange() && !equals(this.options, changes.options.previousValue);
      const filterChanged = changes.filter && !changes.filter.isFirstChange() && !equals(this.filter, changes.filter.previousValue);
      const filterScopesChanged = changes.filterScopes && !changes.filterScopes.isFirstChange() && !equals(this.filterScopes, changes.filterScopes.previousValue);
      if (optionsChanged) {
        this.options = { ...this.options };
      }
      if ((filterScopesChanged || filterChanged || chartChanged || optionsChanged) && !this.chartConfig) {
        if (this.doesWidgetWrapperManageDataFetch || chartChanged || filterScopesChanged || filterChanged) {
          this.resetData();
          this.loading = true;
          this.debounceFetchData(true);
        }
      }
      if (changes.chartConfig && !changes.chartConfig.isFirstChange()) {
        this.resetData();
        this.loading = !!this.chartConfig.processing;
        this.formatData(this.chartConfig, true);
      }
    }
    get projectScoped() {
      return this.filterScopes?.some((scope) => scope[0] === "project");
    }
    get widget() {
      return {
        title: this.widgetTitle,
        chart: this.chart,
        options: this.options,
        filter: this.filter,
        filter_scopes: this.filterScopes
      };
    }
    get doesWidgetWrapperManageDataFetch() {
      return this.chart.name !== "cards";
    }
    get title() {
      return this.widgetTitle || (this.chart ? this.chart.title : "");
    }
    get missingReqs() {
      return missingReqsForWidget({ chart: this.chart, filter_scopes: this.filterScopes, options: this.options });
    }
    get loading() {
      return this._loading;
    }
    set loading(value2) {
      value2 = Boolean(value2);
      const oldValue = this._loading;
      this._loading = value2;
      if (oldValue !== this._loading) {
        value2 ? this.onFetchDataStart?.() : this.onFetchDataEnd?.();
      }
    }
    openWidgetEditor() {
      if (this.loading) {
        this.loading = false;
      }
      const modalInstance = this.$reportWidgetEditorModal.open(this.widget, this.editorOptions);
      modalInstance.result.then((widget) => {
        if (!widget || !widget.chart) {
          this.remove();
          return;
        }
        const newWidget = {};
        if (widget.title !== this.title) {
          newWidget.title = widget.title;
        }
        if (!equals(widget.options, this.options)) {
          newWidget.options = widget.options;
        }
        if (!this.projectScoped) {
          if (!equals(widget.filter_scopes, this.filterScopes)) {
            newWidget.filter_scopes = widget.filter_scopes;
          }
          if (!equals(widget.filter, this.filter)) {
            newWidget.filter = widget.filter;
          }
        }
        if (Object.keys(newWidget).length) {
          this.onChange({ $widget: { ...this.widget, ...newWidget } });
        }
      });
    }
    fetchData(forceRefresh, waitTime = 500) {
      if (this.missingReqs || !this.chart) {
        this.loading = false;
        this.resetData();
        this.formatData();
        return;
      }
      ;
      if (forceRefresh) {
        this.resetData();
        this.loading = true;
      }
      if (this.loading) {
        const params = { "name": this.chart.name, "options": { ...this.options }, "refresh": !!forceRefresh };
        let method = "get_chart_data";
        if (this.filterScopes?.some((scope) => scope[0] === "project")) {
          params["project_id"] = this.filterScopes.find((scope) => scope[0] === "project")[1];
          method = "get_project_chart_data";
        } else if (this.filterScopes?.some((scope) => scope[0] === "portfolio")) {
          params["project_id"] = this.filterScopes.find((scope) => scope[0] === "portfolio")[1];
          params["filter"] = this.filter;
          method = "get_portfolio_chart_data";
        } else {
          params["filter_scopes"] = this.filterScopes;
          params["filter"] = this.filter;
        }
        if (!this.doesWidgetWrapperManageDataFetch) {
          this.loading = false;
          this.formatData({ type: this.chart.name }, true);
        } else {
          this.$q.when(api_default.reporting[method].post(params, { ignoreErrorHandlers: true }), (data2) => {
            if (data2.processing && this.loading) {
              this.$timeout(() => {
                if (this.loading) this.fetchData(false, Math.min(waitTime * 1.5, 5e3));
              }, waitTime);
              return;
            }
            this.loading = false;
            this.formatData(data2);
          }, () => {
            if (this.errorRetry++ < 5) {
              this.$timeout(() => {
                if (this.loading) this.fetchData(false, Math.min(waitTime * 1.5, 5e3));
              }, 1500);
            } else {
              this.loading = false;
            }
          });
        }
      } else {
        this.resetData();
        this.formatData();
      }
    }
    formatData(data2, skipDataCheck) {
      if (skipDataCheck) {
        data2 = data2 || {};
      }
      if (!data2) {
        if (this.missingReqs) {
          this.error = true;
          this.errorReason = _4("Missing requirements");
        } else {
          this.error = true;
          this.loadingInterrupted = true;
          this.errorReason = _4("Something went wrong during data loading. Please, reload the widget");
        }
        return;
      }
      if (data2.processing) {
        return;
      }
      this.updatedAt = moment_default.utc(data2.updated_at || /* @__PURE__ */ new Date()).fromNow();
      if (data2.error) {
        this.error = true;
        this.errorReason = data2.reason || "";
      } else {
        this.chartData = data2;
        if (this.chartConfig && this.chartConfig.context) {
          this.chartData.context = this.chartConfig.context;
        }
        this.chartType = ["table", "value", "progress", "cards"].includes(data2.type) ? data2.type : "chart";
      }
    }
    resetData() {
      this.error = false;
      this.errorReason = null;
      this.loadingInterrupted = false;
      this.chartData = null;
      this.chartType = null;
      this.errorRetry = 0;
    }
    remove() {
      this.onRemove && this.onRemove();
    }
    $destroy() {
      this.loading = false;
      this.disposeOnForceRefreshAllWidgetsEventListener();
    }
  }
});
angular_default.module("kantree").component("reportWidgetChart", {
  template: "<canvas></canvas>",
  bindings: {
    config: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $postLink() {
      this.refresh();
    }
    $onChanges() {
      this.refresh();
    }
    refresh() {
      if (this.chart) {
        this.chart.destroy();
      }
      if (this.config) {
        if (!this.config.options) {
          this.config.options = {};
        }
        if (this.config.options.tooltips && this.config.options.tooltips.callbacks && this.config.options.tooltips.callbacks.label === "timedelta") {
          this.config.options.tooltips.callbacks.label = function(tooltipItem, data2) {
            return data2.datasets[tooltipItem.datasetIndex].label + ": " + tooltipItem.yLabel;
          };
        }
        if (this.config.options.plugins && this.config.options.plugins.datalabels && this.config.options.plugins.datalabels.formatter === "timedelta") {
          this.config.options.plugins.datalabels.formatter = function(value2, context) {
            return moment_default.duration(value2).humanize();
          };
        }
        this.chart = new chart_default(this.$element.children()[0], this.config);
      }
    }
  }
});
angular_default.module("kantree").component("reportWidgetTable", {
  templateUrl: "/static/app/apps/reports/ng-components/templates/table.html",
  bindings: {
    config: "<",
    filterScopes: "<"
  },
  controller: [
    "$sce",
    "$sanitize",
    function($sce, $sanitize) {
      var $ctrl = this;
      $ctrl.formatLabel = function(v3, format2) {
        if (format2 === "user" && $ctrl.filterScopes?.some((scope) => scope[0] === "project")) {
          const projectId = $ctrl.filterScopes.find((scope) => scope[0] === "project")[1];
          var member = projectMemberStore.scopedByProject({ id: projectId }).query({
            user: query_exports.objMatch({ id: parseInt(v3) })
          })?.[0];
          if (member) {
            v3 = '<img src="' + userAvatarUrl(member.user) + '" class="avatar me-1">' + $sanitize(member.user.display_name);
          } else {
            v3 = "?";
          }
        }
        return $sce.trustAsHtml(v3 || "");
      };
      $ctrl.formatValue = function(v3) {
        if (v3 === null) {
          return "";
        }
        if ($ctrl.config.options && $ctrl.config.options.formatValue === "time") {
          return formatSeconds(v3, "");
        }
        return v3;
      };
    }
  ]
});
angular_default.module("kantree").component("reportWidgetValue", {
  template: `
    <span ng-if="::!$ctrl.isLink" data-fittext data-fittext-min="10" data-fittext-max="inherit">{{$ctrl.config.data}}</span>
    <a href ng-click="$ctrl.navigate()" ng-if="::$ctrl.isLink" data-fittext data-fittext-min="10" data-fittext-max="inherit">{{$ctrl.config.data}}</a>
  `,
  bindings: {
    config: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$state"];
    $onChanges() {
      this.isLink = this.config.url || this.config.filter && !isConnectionManagerDisabled();
    }
    get projectScoped() {
      return this.filterScopes?.some((scope) => scope[0] === "project");
    }
    get projectId() {
      if (this.projectScoped) {
        return this.filterScopes.find((scope) => scope[0] === "project")[1];
      }
      return null;
    }
    navigate() {
      if (this.config.url) {
        this.$state.go(this.config.url);
      } else if (this.config.filter && !isConnectionManagerDisabled()) {
        let view;
        const viewProps = { mode: "kanban", filter: this.config.filter };
        if (this.projectScoped) {
          view = viewStore.scopedByProject({ id: this.projectId }).upsertDraftFromView(
            null,
            viewProps,
            projectViewsDefaultProps,
            projectViewsAvailableProps
          );
        } else {
          view = viewStore.scopedByGlobal().upsertDraftFromView(
            null,
            viewProps,
            globalViewsDefaultProps,
            globalViewsAvailableProps
          );
        }
        if (view.id.toString() !== this.$state.params.v.toString()) {
          this.$state.go("search", { view: view.id }, { inherit: false });
        }
      }
    }
  }
});
angular_default.module("kantree").component("reportWidgetProgress", {
  template: `<div class="progress"><div class="progress-bar" style="min-width: 2em" ng-style="{'width': $ctrl.barWidth + '%'}">{{$ctrl.barWidth}}%</div></div>`,
  bindings: {
    config: "<"
  },
  controller: [
    function() {
      var $ctrl = this;
      $ctrl.$onChanges = function() {
        $ctrl.barWidth = 0;
        if ($ctrl.config.data.total) {
          $ctrl.barWidth = Math.ceil(100 * $ctrl.config.data.value / $ctrl.config.data.total);
        }
      };
    }
  ]
});
angular_default.module("kantree").component("reportWidgetCards", {
  template: `
    <div class="loading" ng-show="$ctrl.loading"><i class="fa fa-spin fa-spinner"></i></div>
    <global-cards-app context="$ctrl.context" ng-show="!$ctrl.loading" ng-if="$ctrl.cardsCount > 0"></global-cards-app>
    <div class="report-widget-empty" ng-show="!$ctrl.loading" ng-if="$ctrl.cardsCount === 0">{{::$ctrl.emptyDesc}}</div>
  `,
  bindings: {
    config: "<",
    options: "<?",
    filterScopes: "<?",
    onFetchDataStart: "&",
    onFetchDataEnd: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    emptyDesc = _4("No cards");
    fetchCards = debounce2(() => this.context.fetchCards(), 60);
    fetchGroupByChoices = debounce2(() => this.context.fetchGroupByChoices(), 60);
    fetchGroupByGroups = debounce2(() => this.context.fetchGroupByGroups(), 60);
    refreshUI = debounce2(() => this.$scope.$applyAsync(), 60);
    $onInit() {
      this.setupContext();
    }
    $onChanges(changes) {
      const filterScopesChanged = changes.filterScopes && !changes.filterScopes.isFirstChange() && !equals(this.filterScopes, changes.filterScopes.previousValue);
      if (changes.config && !changes.config.isFirstChange()) {
        this.fetchAll();
      }
      if (changes.options && !changes.options.isFirstChange() || filterScopesChanged) {
        const { filterScopes, appName, appOptions } = this.contextParams;
        const newApp = cardsAppRegistry.get(appName);
        this.context.update({ filterScopes }, newApp, appOptions);
      }
    }
    get projectScoped() {
      return this.filterScopes?.some((scope) => scope[0] === "project");
    }
    get contextParams() {
      return getContextParamsFromView({
        ...globalViewsDefaultProps,
        mode: "list",
        ...this.options,
        filter_scopes: this.filterScopes,
        mode_options: Object.assign({}, globalViewsDefaultProps.mode_options, this.options.mode_options)
      });
    }
    get loading() {
      return this._loading;
    }
    set loading(value2) {
      value2 = Boolean(value2);
      const oldValue = this._loading;
      this._loading = value2;
      if (oldValue !== this._loading) {
        value2 ? this.onFetchDataStart?.() : this.onFetchDataEnd?.();
      }
    }
    setupContext() {
      if (this.config.context) {
        this.context = this.config.context;
      } else {
        const { filterScopes, appName, appOptions } = this.contextParams;
        const app = cardsAppRegistry.get(appName);
        this.context = new GlobalContext({ filterScopes }, app, appOptions);
      }
      if (this.deregisterContextWatchers) this.deregisterContextWatchers();
      this.deregisterContextWatchers = offMany([
        this.context.watch("cardStore", () => this.onCardStoreChange(), false),
        this.context.watch("groupByChoices", () => this.refreshUI(), false),
        this.context.watch("groupByGroups", () => this.refreshUI(), false),
        this.context.watch("app", (newApp, oldApp) => {
          if (this.deregisterAppOptionsWatcher) this.deregisterAppOptionsWatcher();
          this.deregisterAppOptionsWatcher = this.context.watch("appOptions", (newVal, oldVal) => {
            if (!equals((newVal || {}).filter, (oldVal || {}).filter)) {
              this.fetchAll();
            } else if (!equals((newVal || {}).group_by, (oldVal || {}).group_by)) {
              this.fetchGroupByGroups();
            }
          }, false);
          if (this.deregisterFilterScopesWatcher) {
            this.deregisterFilterScopesWatcher();
            this.deregisterFilterScopesWatcher = null;
          }
          if (this.deregisterFetchAllWatcher) {
            this.deregisterFetchAllWatcher();
            this.deregisterFetchAllWatcher = null;
          }
          this.deregisterFilterScopesWatcher = this.context.watch("filterScopes", (newVal, oldVal) => this.fetchAll());
          this.deregisterFetchAllWatcher = this.context.on("fetchAll", () => this.fetchAll());
        }),
        this.context.on("destroy", () => {
          this.fetchCards.clear();
          this.fetchGroupByChoices.clear();
          this.fetchGroupByGroups.clear();
          this.refreshUI.clear();
        })
      ]);
    }
    fetchAll() {
      if (!!this.config.cards) {
        this.context.cardStore = this.config.cards;
        this.cardsCount = this.config.cards.length;
        this.$scope.$applyAsync();
      } else {
        this.loading = true;
        this.cardsCount = 0;
        this.fetchCards();
        this.fetchGroupByChoices();
        if (!this.context.needsGroupByGroupRefreshWhenCardStoreChange) {
          this.fetchGroupByGroups();
        }
      }
    }
    onCardStoreChange() {
      this.cardsCount = this.context.cardStore ? this.context.cardStore.count() : 0;
      this.loading = false;
      if (this.context.needsGroupByGroupRefreshWhenCardStoreChange) {
        this.fetchGroupByGroups();
      } else {
        this.$scope.$applyAsync();
      }
    }
    $onDestroy() {
      if (!this.config.context) {
        this.context.destroy();
      }
    }
  }
});

// public/app/actions/portfolio.ts
async function removeProjectFromPorfolio(portfolio, projectToRemove) {
  projectToRemove = await api_default.project_portfolio.remove_project_from_portfolio.delete({
    project_id: portfolio.id,
    portfolio_project_id: projectToRemove.id
  });
  portfolio = projectStore.update(portfolio, {
    portfolio_project_ids: portfolio.portfolio_project_ids.filter((pId) => pId !== projectToRemove.id)
  });
  return portfolio;
}
async function setPortfolioProjects(portfolio, setProjects) {
  setProjects = await api_default.project_portfolio.set_portfolio_projects.post({
    project_id: portfolio.id,
    set_project_ids: pluck(setProjects, "id")
  });
  portfolio = projectStore.update(portfolio, { portfolio_project_ids: pluck(setProjects, "id") });
  return portfolio;
}

// public/app/apps/portfolio/overview/ng-components/overview.js
angular_default.module("kantree").component("portfolioOverviewApp", {
  templateUrl: "/static/app/apps/portfolio/overview/ng-components/templates/overview.html",
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "orgProjectSelectorModal", "projectPage"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.ProjectTile = ProjectTile;
      if (!this.sortBy) {
        this.sortBy = projectAvailableSorts[0].predicate;
      }
      this.disposeProjectsListener = null;
      projectStore.$watch(this.$scope, this.context.project, (project) => {
        if (this.disposeProjectsListener) this.disposeProjectsListener();
        this.disposeProjectsListener = projectStore.scopedByPortfolio(project).$watchAll(this.$scope, () => {
          this.projects = projectStore.scopedByPortfolio(project).query();
        });
      });
    }
    addProjects() {
      this.$q.digest(this.$orgProjectSelectorModal.open({
        org: orgStore.get(this.context.project.owner.id),
        team: this.context.project.team ? teamStore.tryGet(this.context.project.team.id) : null,
        selectedProjects: this.projects,
        isMultiple: true
      }).then(
        (projects) => setPortfolioProjects(this.context.project, projects)
      ));
    }
    removeProject(project) {
      this.$q.digest(removeProjectFromPorfolio(this.context.project, project));
    }
  }
});

// public/app/attributes/ng-components/automation-trigger-btn.js
angular_default.module("kantree").directive("attributeTypeAutomationTriggerBtn", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/automation-trigger-btn.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        attributeEditable: "<?"
      },
      controller: [
        "$scope",
        "$timeout",
        function($scope2, $timeout2) {
          injectI18nHelpersIntoScope($scope2);
          const project = projectStore.get($scope2.obj.project_id);
          $scope2.canRun = canRunAutomations(project);
          $scope2.$watchCollection("attribute.options", function() {
            $scope2.disabled = !$scope2.attribute.valid_options || !$scope2.attribute.options || !$scope2.attribute.options.rule;
            $scope2.label = _4("Run action");
            if ($scope2.attribute.options && $scope2.attribute.options.label) {
              $scope2.label = $scope2.attribute.options.label;
            } else if (!$scope2.disabled) {
              $scope2.label = _4("Run {rule}", { rule: $scope2.attribute.options.rule.name });
            }
            if (!$scope2.canRun) {
              $scope2.disabledTooltip = _4("You don't have the permission to run this automation rule");
            } else if ($scope2.disabled) {
              $scope2.disabledTooltip = _4("This button is not configured correctly. Check the field options");
            }
          });
          $scope2.call = function() {
            $scope2.calling = true;
            api_default.project_automations.trigger_automation_rule.post({
              project_id: project.id,
              rule_id: $scope2.attribute.options.rule.id,
              card_id: $scope2.obj.id
            }).then(() => {
              toastNotify(_4("Triggered automation"), "success");
            });
            $timeout2(() => {
              $scope2.calling = false;
            }, 1e3);
          };
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/bool.js
angular_default.module("kantree").directive("attributeTypeBool", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/bool.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        onDone: "&"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          var self2 = this;
          $scope2.$watch("value", function(value2, oldVal) {
            if (self2.$input) {
              var toggle = self2.$input.data("bs.toggle");
              if (toggle) {
                toggle[value2 ? "on" : "off"](true);
              }
              if (!$scope2.editable && value2 !== oldVal) {
                self2.$input[0].disabled = true;
              }
            }
          });
          $scope2.setValue = function(value2) {
            $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, value2), $scope2.onDone);
          };
        }
      ],
      link: function(scope, element2, attrs2, ctrl) {
        var $input = ctrl.$input = jquery_default(element2).find("input");
        $input.bootstrapToggle({
          on: _4("Yes"),
          off: _4("No")
        }).change(function() {
          scope.setValue(this.checked);
        });
      }
    };
  }
]);

// public/app/attributes/ng-components/content.js
angular_default.module("kantree").directive("attributeTypeContent", [
  "cardModal",
  "$window",
  function(cardModal, $window) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/content.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          var draftId = $scope2.obj?.id + "-" + $scope2.attribute.id;
          $scope2.edit = function(discard) {
            if (discard) {
              $scope2.draft = null;
              jsonLocalStorage.setItem(draftId, null);
            }
            $scope2.editorEnabled = true;
          };
          $scope2.refreshDraft = function(draftedText) {
            $scope2.draft = jsonLocalStorage.getItem(draftId);
          };
          $scope2.onEditorDone = function() {
            $scope2.editorEnabled = false;
          };
          $scope2.refreshDraft();
          $scope2.editorEnabled = false;
        }
      ],
      link: function(scope, element2, attrs2, ctrl) {
        jquery_default(element2).on("click", ".js-attribute-content a", function(e3) {
          e3.preventDefault();
          e3.stopPropagation();
          if (jquery_default(this).hasClass("card-ref")) {
            var project = projectStore.getForCard(scope.obj);
            cardModal.loadByRef(project, this.rel);
          } else {
            $window.open(this.href);
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeContentEditor", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-content-editor"><content-composer class="content-composer"
          on-submit="saveContent(submittedText)" on-cancel="onDone()" on-edit="onUpdate()"
          on-draft-change="onDraftChange && onDraftChange({draftedText: draftedText})"
          content="value" options="editorOptions"></content-composer></div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        onDone: "&",
        onUpdate: "&",
        onDraftChange: "&",
        defaultActiveEditor: "@?",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.saveContent = function(content2) {
            var deferred = $q.defer();
            if (($scope2.value || "") !== content2) {
              $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, content2), () => {
                deferred.resolve();
                $scope2.onDone();
              });
            } else {
              deferred.resolve();
              $scope2.onDone();
            }
            return deferred.promise;
          };
          $scope2.editorOptions = {
            data: {
              project_id: $scope2.obj.project_id,
              card_id: $scope2.obj.id,
              attribute_id: $scope2.attribute.id
            },
            defaultActiveEditor: $scope2.defaultActiveEditor === "false" ? null : "markdown",
            type: "content",
            buttons: [{
              on: "submit"
            }]
          };
          if ($scope2.attributeGroup instanceof ModelAttributeGroup) {
            $scope2.editorOptions.draftDelay = 1e3;
            $scope2.editorOptions.uuid = $scope2.obj.id + "-" + $scope2.attribute.id;
          }
          if ($scope2.embedded) {
            $scope2.editorOptions.on = {
              blur: null
            };
          }
        }
      ],
      link: function(scope, element2, attrs2, ctrl) {
        scope.onUpdate();
      }
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeContentForm", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-content-form"><content-editor class="content-editor"
          editor-data="editorData" force-editor="markdown" ng-model="inputValue"></content-editor></div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $q.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], (value2) => {
            $scope2.inputValue = value2;
            $scope2.editorData = {
              project_id: $scope2.obj.project_id,
              card_id: $scope2.obj.id,
              attribute_id: $scope2.attribute.id
            };
            $scope2.$watch("inputValue", (nV, oV) => {
              if (nV !== oV) {
                if (nV) {
                  $q.digest($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, nV));
                } else {
                  $q.digest($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute));
                }
              }
            });
          });
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/date.ts
var import_air_datepicker = __toESM(require_air_datepicker());

// public/app/attributes/utils/airdatepicker-locale.js
var import_en = __toESM(require_en());
var import_fr = __toESM(require_fr());
var import_de = __toESM(require_de());
var import_es = __toESM(require_es());
var import_it = __toESM(require_it());
var import_pt = __toESM(require_pt());
function airdatepickerLocale() {
  switch (getCurrentLocale()) {
    case "en":
      return import_en.default;
    case "fr":
      return import_fr.default;
    case "de":
      return import_de.default;
    case "es":
      return import_es.default;
    case "it":
      return import_it.default;
    case "pt":
      return import_pt.default;
    default:
      return import_en.default;
  }
}

// public/app/attributes/ng-components/date.ts
angular_default.module("kantree").directive("attributeTypeDate", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/date.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<",
      isTemplate: "<?"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.$watchGroup([
          () => $scope2.value?.start,
          () => $scope2.value?.end,
          () => $scope2.value,
          () => $scope2.attribute?.options?.precision
        ], () => {
          let txt = null, diffLabel = null;
          let value2 = $scope2.value;
          if (value2) {
            if ($scope2.isTemplate && typeof value2 == "string") {
              $scope2.date = { "value": value2, "diffLabel": null };
              return;
            }
            if (!isObject2(value2)) {
              value2 = { start: null, end: value2 };
            }
            const { start, end } = parseDateRange($scope2.attribute, value2.start, value2.end);
            txt = formatDateRange($scope2.attribute, start, end, false);
            diffLabel = getDateDiffLabel(end);
          }
          $scope2.date = { "value": txt, "diffLabel": diffLabel };
        });
        $scope2.unsetDate = function() {
          $q.digest($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute));
        };
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeDateEditor", [
  "$q",
  function($q) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/date-editor.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        onDone: "&",
        onUpdate: "&",
        embedded: "<?",
        isTemplate: "<?"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.relativeAmount = "";
          $scope2.relativeUnit = "d";
          $scope2.relativeUnits = [
            ["d", _4("Day")],
            ["w", _4("Week")],
            ["m", _4("Month")],
            ["y", _4("Year")]
          ];
          $scope2.showRelativeUnit = true;
          if ($scope2.value && !isObject2($scope2.value)) {
            $scope2.value = { start: null, end: $scope2.value };
          }
          if ($scope2.value && $scope2.value.end.match(/^[+-]/)) {
            $scope2.relativeAmount = $scope2.value.end;
            if ($scope2.value.start) {
              $scope2.relativeAmount = $scope2.value.start + " -> " + $scope2.value.end;
            }
          }
          $scope2.setAbsoluteDate = function(start, end) {
            $q.when($scope2.attributeGroup.setObjAttribute(
              $scope2.obj,
              $scope2.attribute,
              formatServerDateRange($scope2.attribute, start, end)
            ), $scope2.onDone);
          };
          $scope2.setRelativeDate = function() {
            if (!$scope2.relativeAmount) return;
            const sign = $scope2.relativeAmount.indexOf("+") === -1 && $scope2.relativeAmount.indexOf("-") === -1 ? "+" : "";
            $q.when(
              $scope2.attributeGroup.setObjAttribute(
                $scope2.obj,
                $scope2.attribute,
                $scope2.showRelativeUnit ? sign + $scope2.relativeAmount + $scope2.relativeUnit : $scope2.relativeAmount
              ),
              $scope2.onDone
            );
          };
          $scope2.$watch("relativeAmount", function(value2) {
            $scope2.showRelativeUnit = !value2 || value2.indexOf("->") === -1;
          });
        }
      ],
      link: function(scope, element2, attrs2, ctrl) {
        const applyButton = {
          content: "Apply",
          className: "applyBtn btn btn-success",
          onClick: (dp2) => {
            if (scope.attribute.options?.daterange && !dp2.selectedDates[1]) {
              return;
            }
            if (scope.attribute.options?.daterange) {
              scope.setAbsoluteDate(moment_default(dp2.selectedDates[0]), moment_default(dp2.selectedDates[1]));
            } else {
              scope.setAbsoluteDate(moment_default(dp2.selectedDates[0]), moment_default(dp2.selectedDates[0]));
            }
            dp2.destroy();
          }
        };
        const clearButton = {
          content: "Clear",
          className: "btn",
          onClick: (dp2) => {
            if (typeof dp2.selectedDates === "object") {
              if (dp2.selectedDates.length <= 0) return;
              dp2.unselectDate(dp2.selectedDates[1]);
              dp2.unselectDate(dp2.selectedDates[0]);
            } else {
              dp2.unselectDate(dp2.selectedDates);
            }
            $q.digest(scope.attributeGroup.clearObjAttribute(scope.obj, scope.attribute));
          }
        };
        const dp = new import_air_datepicker.default(element2[0].children[0], {
          classes: "daterangepicker",
          range: scope.attribute.options?.daterange ?? false,
          view: scope.attribute.options?.precision === "days_time" ? "days" : scope.attribute.options?.precision,
          minView: scope.attribute.options?.precision === "days_time" ? "days" : scope.attribute.options?.precision,
          selectedDates: getSelectedDates(),
          timepicker: scope.attribute.options?.precision === "days_time" || false,
          selectOtherMonths: false,
          locale: airdatepickerLocale(),
          autoClose: false,
          buttons: getDatepickerButtons(),
          altField: "textField",
          toggleSelected: ({ datepicker, date }) => {
            if (datepicker.selectedDates.length === 1 && datepicker.selectedDates.includes(date)) return false;
            return true;
          },
          minutesStep: 15,
          onSelect: ({ date }) => {
            if (scope.attribute.options?.precision === "days_time") return;
            if (scope.attribute.options?.daterange && !date[1]) {
              return;
            }
            if (Array.isArray(date)) {
              scope.setAbsoluteDate(moment_default(date[0]), moment_default(date[1]));
            } else {
              scope.setAbsoluteDate(moment_default(date), moment_default(date));
            }
          }
        });
        requestAnimationFrame(() => {
          scope.onUpdate();
        });
        function parse4(v3) {
          return parseDate(scope.attribute, v3);
        }
        function getSelectedDates() {
          let dates = [];
          if (scope.value && isObject2(scope.value)) {
            dates[0] = scope.value.start ? parse4(scope.value.start) : parse4(scope.value.end);
            dates[1] = parse4(scope.value.end);
          } else {
            dates = [void 0, void 0];
          }
          return dates;
        }
        function getDatepickerButtons() {
          let buttons = [];
          if (scope.attribute.options?.precision === "days_time") {
            return [applyButton, clearButton];
          } else {
            buttons = false;
          }
          return buttons;
        }
      }
    };
  }
]);

// public/app/attributes/ng-components/decorators.js
angular_default.module("kantree").directive("attributeTypeSeparator", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `<div class="attribute-type-separator"><hr ng-hide="attribute.options['invisible']"></div>`
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeStatictext", [
  function() {
    return {
      restrict: "E",
      replace: true,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        attributeEditable: "<?"
      },
      template: `<div class="attribute-type-statictext markdown" ng-bind-html="attribute.name|markdown" open-links-in-tab></div>`
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeHeader", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/header.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        attributeEditable: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.editing = false;
          $scope2.title = "";
          $scope2.edit = function() {
            if ($scope2.attributeEditable) {
              $scope2.editing = true;
              $scope2.title = $scope2.attribute.name;
            }
          };
          $scope2.save = function() {
            $q.when($scope2.attributeGroup.update($scope2.attribute, { name: $scope2.title }), () => {
              $scope2.editing = false;
            });
          };
        }
      ],
      link: function(scope, el2) {
        el2.find("input").on("keypress", function(e3) {
          if (e3.keyCode === 13) {
            scope.save();
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeSpacer", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `<div class="attribute-type-spacer"></div>`
    };
  }
]);

// virtual-ns:js-sha256
var js_sha256_default = sha256;

// virtual-ns:aes-js
var aes_js_default = aesjs;

// public/app/attributes/utils/encrypted.js
var AESJS_COUNTER_INIT = 1;
function passwordToKey(password) {
  var hash = js_sha256_default.create();
  hash.update(password);
  return hash.array();
}
function encrypt(value2, password) {
  var key2 = passwordToKey(password);
  var valueBytes = aes_js_default.utils.utf8.toBytes(value2);
  var aesCtr = new aes_js_default.ModeOfOperation.ctr(key2, new aes_js_default.Counter(AESJS_COUNTER_INIT));
  var encryptedBytes = aesCtr.encrypt(valueBytes);
  return aes_js_default.utils.hex.fromBytes(encryptedBytes);
}
function decrypt(value2, password) {
  var key2 = passwordToKey(password);
  var encryptedBytes = aes_js_default.utils.hex.toBytes(value2);
  var aesCtr = new aes_js_default.ModeOfOperation.ctr(key2, new aes_js_default.Counter(AESJS_COUNTER_INIT));
  var decryptedBytes = aesCtr.decrypt(encryptedBytes);
  return aes_js_default.utils.utf8.fromBytes(decryptedBytes);
}
async function askPassword() {
  const password = await sweetalert2_default({
    title: _4("Enter your password"),
    input: "password",
    showCancelButton: true
  });
  if (!password) {
    throw new Error("No password provided");
  }
  return password;
}
async function askPasswordAndEncrypt(value2) {
  const password = await askPassword();
  return encrypt(value2, password);
}
async function askPasswordAndDecrypt(value2) {
  const password = await askPassword();
  return [decrypt(value2, password), password];
}

// public/app/attributes/ng-components/encrypted.js
angular_default.module("kantree").directive("attributeTypeEncrypted", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/encrypted.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.edit = false;
        $scope2.toggleEdit = function(edit2) {
          $scope2.edit = $scope2.editable && edit2;
        };
        $scope2.clearValue = function() {
          $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), () => {
            $scope2.value = "";
          });
        };
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeEncryptedEditor", [
  "$timeout",
  "$q",
  function($timeout2, $q) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/encrypted-editor.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        onDone: "&",
        noAutoFocus: "@?",
        embedded: "<?"
      },
      controller: [
        "$scope",
        function($scope2) {
          $scope2.dirty = false;
          $scope2.inputValue = "";
          $scope2.decrypted = !$scope2.value;
          if ($scope2.value) {
            $scope2.inputValue = "*******";
            $q.when(askPasswordAndDecrypt($scope2.value), ([value2, password]) => {
              $scope2.inputValue = value2;
              $scope2.decrypted = true;
              $scope2.password = password;
              $timeout2(() => {
                $scope2.focus();
              });
            }, () => {
              $scope2.onDone();
            });
          }
        }
      ],
      link: function(scope, element2) {
        const $el = jquery_default(element2);
        const $input = $el.find("input");
        let saving = false;
        function save() {
          if (saving) return;
          saving = true;
          $timeout2(function() {
            if (isEmptyValue(scope.inputValue)) {
              if (scope.value) {
                $q.when(scope.attributeGroup.clearObjAttribute(scope.obj, scope.attribute), scope.onDone);
              }
              return;
            }
            let p4;
            if (scope.password) {
              p4 = $q.resolve(encrypt(scope.inputValue, scope.password));
            } else {
              p4 = $q.when(askPasswordAndEncrypt(scope.inputValue));
            }
            p4.then((value2) => {
              $q.when(scope.attributeGroup.setObjAttribute(scope.obj, scope.attribute, value2, scope.onDone), () => {
                $input.addClass("has-error");
              });
            });
          }, 100);
        }
        let canceling = false;
        function cancel() {
          if (canceling) return;
          canceling = true;
          scope.$evalAsync(() => {
            scope.onDone();
          });
        }
        scope.focus = function() {
          $input[0].focus();
          $input[0].select();
        };
        $input.on("keydown", (e3) => {
          if (e3.keyCode === 13) {
            e3.stopPropagation();
            e3.preventDefault();
            if (scope.dirty) {
              save();
            } else {
              cancel();
            }
          } else if (e3.keyCode === 27) {
            e3.stopPropagation();
            e3.preventDefault();
            cancel();
          } else if (!e3.ctrlKey) {
            scope.dirty = true;
          }
        }).on("blur", (e3) => {
          setTimeout(() => {
            if (!scope.decrypted) return;
            if (scope.dirty) {
              save();
            } else {
              cancel();
            }
          }, 150);
        });
        if (!isIE()) {
          $input.on("input", () => {
            scope.dirty = true;
          });
          if ($input.prop("type") === "number") {
            $input.on("click", function() {
              jquery_default(this).focus();
            });
          }
        }
      }
    };
  }
]);

// public/app/attributes/ng-components/files.js
angular_default.module("kantree").directive("attributeTypeFiles", [
  "attributeDropdown",
  function(attributeDropdown) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/files.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.fileType = _4("files");
          if (!isAuthenticated() && serverConfig.limit_public_upload_file_types) {
            $scope2.fileType = serverConfig.limit_public_upload_file_types;
          } else if ($scope2.attribute.options?.limit_type) {
            $scope2.fileType = $scope2.attribute.options.limit_type;
          }
          $scope2.maxFileSize = serverConfig.max_upload_size;
          if (!isAuthenticated() && serverConfig.max_public_upload_size) {
            $scope2.maxFileSize = serverConfig.max_public_upload_size;
          }
          $scope2.files = new FileStore();
          $scope2.$watchCollection("value", function(value2) {
            $scope2.files.replace((value2 || []).map((f3) => ({ ...f3 || {} })));
          });
          $scope2.canShowCoverBtn = $scope2.attributeGroup instanceof ModelAttributeGroup;
          $scope2.updateProgress = function(progress2) {
            $scope2.uploadInProgress = true;
            $scope2.progress = progress2;
          };
          $scope2.upload = function(files) {
            if (!files || files.length === 0) return;
            $q.when($scope2.attributeGroup.appendFilesObjAttribute($scope2.obj, $scope2.attribute, files, (evt) => {
              $scope2.updateProgress(parseInt(100 * evt.loaded / evt.total));
            }, true), () => {
              $scope2.uploadInProgress = false;
            });
          };
          $scope2.removeFile = function(file) {
            $q.digest($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, file));
          };
          $scope2.showProgress = false;
        }
      ],
      link: function(scope, element2) {
        var html5 = `
          <div class="attribute-editor">
            <attribute-type-files-editor
              attribute-group="attributeGroup" attribute="attribute" obj="obj" value="files" on-files-chosen="onUpload($files)"
              no-upload-handling="noUploadHandling" on-progress="updateProgress($progress)" on-done="onDone()" on-init="onInit()"
              show-progress="showProgress">
            </attribute-type-files-editor>
          </div>`;
        jquery_default(element2).find(".attribute-editor-opener").on("click", function() {
          if (typeof scope.editable === "undefined" || scope.editable) {
            var editorScope = scope.$new();
            editorScope.noUploadHandling = true;
            editorScope.updateProgress = scope.updateProgress;
            editorScope.onUpload = scope.upload;
            attributeDropdown.open(this, scope, editorScope, html5);
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeFilesEditor", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/files-editor.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        onDone: "&",
        onInit: "&",
        onFilesChosen: "&?",
        onProgress: "&?",
        noUploadHandling: "<?",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "camera",
        "$injector",
        "$q",
        function($scope2, camera, $injector, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.camera = camera;
          $scope2.fileProviders = fileProviders.filter(function(provider) {
            return !provider.requireAuth || isAuthenticated();
          });
          $scope2.updateProgress = function(loaded, total) {
            $scope2.uploadInProgress = true;
            $scope2.progress = parseInt(100 * loaded / total);
            if ($scope2.onProgress) {
              $scope2.onProgress({ $progress: $scope2.progress });
            }
          };
          $scope2.upload = function(files) {
            if (!files || files.length === 0) return;
            if ($scope2.onFilesChosen) {
              $scope2.onFilesChosen({ $files: files });
            }
            if ($scope2.noUploadHandling) {
              $scope2.onDone();
              return;
            }
            $q.when($scope2.attributeGroup.appendFilesObjAttribute($scope2.obj, $scope2.attribute, files, (evt) => {
              $scope2.updateProgress(evt.loaded, evt.total);
            }, true), () => {
              $scope2.uploadInProgress = false;
              $scope2.onDone();
            });
          };
          $scope2.captureWithCamera = function() {
            camera.capture().then(function(blob) {
              $scope2.upload([blob]);
            });
            $scope2.onDone();
          };
          $scope2.execProvider = function(provider) {
            $injector.invoke(provider.execute, provider, {
              finishCallback: function(files) {
                $q.all(files.map((file) => {
                  return $scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, file);
                })).then(() => {
                  $scope2.uploadInProgress = false;
                  $scope2.onDone();
                });
              },
              progressCallback: $scope2.updateProgress
            });
          };
          $scope2.attachLink = function(url2, name2) {
            $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, { name: name2 || null, url: url2 }), () => {
              $scope2.attachLinkUrl = "";
              $scope2.onDone();
            });
          };
          $scope2.attachLinkWithName = function(url2) {
            $q.when(inputDialog(_4("Provide a name for this link:")), (name2) => {
              $scope2.attachLink(url2, name2);
            });
          };
        }
      ],
      link: function(scope, element2) {
        scope.onInit();
        jquery_default(element2).find('label[for="file"]').on("click", function() {
          jquery_default(element2).find('input[name="file"]').trigger("click");
        });
      }
    };
  }
]);

// public/app/attributes/ng-components/formula-editor.js
angular_default.module("kantree").component("attributeTypeFormulaEditor", {
  template: `
    <formula-editor on-save="$ctrl.save($value)" value="$ctrl.value" project="$ctrl.project"
      card="$ctrl.obj" on-editor-resize="$ctrl.onUpdate()"></formula-editor>
  `,
  bindings: {
    project: "<",
    attributeGroup: "<",
    attribute: "<",
    obj: "<",
    value: "<",
    onDone: "&",
    onUpdate: "&",
    noAutoFocus: "@?",
    embedded: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$q"];
    save(value2) {
      if (isEmptyValue(value2)) {
        if (value2) {
          this.$q.when(this.attributeGroup.clearObjAttribute(this.obj, this.attribute), this.onDone);
        }
        return;
      }
      this.$q.when(this.attributeGroup.update(
        this.attribute,
        { options: Object.assign({}, this.attribute.options, { query: value2 }) }
      ), this.onDone);
    }
  }
});

// public/app/attributes/ng-components/group-type.js
angular_default.module("kantree").directive("attributeTypeGroupType", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/group-type.html",
      scope: {
        project: "<",
        attributeGroup: "<",
        attribute: "<",
        card: "<?obj",
        editable: "<"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2._editable = () => $scope2.editable && isConnected();
          $scope2.groupsMenuFactoryParams = null;
          function refreshGroups() {
            $scope2.groups = $scope2.card.groups.map((cg) => {
              var g3 = cardGroupStore.tryGet(cg.id);
              if (!g3) {
                return Object.assign({ is_archived: true }, cg);
              }
              return g3;
            }).filter((g3) => g3 && g3.type_id === $scope2.groupType.id && !g3.is_archived).sort((a3, b3) => cmp2(a3.title, b3.title));
          }
          ;
          let cardWatcherOff;
          let cardGroupsWatcherOff;
          function refreshGroupType(gt) {
            $scope2.groupType = gt;
            if ($scope2.card.id) {
              if (cardWatcherOff) cardWatcherOff();
              cardWatcherOff = cardStore.$watch($scope2, $scope2.card, refreshGroups);
              var parent = $scope2.card.parent_id ? cardStore.get($scope2.card.parent_id) : $scope2.card;
              $scope2.groupsMenuFactoryParams = {
                card: $scope2.card,
                parent,
                groupType: $scope2.groupType,
                noCloseAfterToggle: !$scope2.groupType.one_group_per_card,
                canSort: true
              };
            } else {
              if (cardGroupsWatcherOff) {
                cardGroupsWatcherOff();
              }
              cardGroupsWatcherOff = $scope2.$watchCollection("card.groups", refreshGroups);
            }
          }
          ;
          if ($scope2.card) {
            if (!$scope2.card.id) {
              const deregister = $scope2.$watch("card.id", (newVal, oldVal) => {
                if (Number.isInteger(newVal)) {
                  refreshGroupType($scope2.groupType);
                  deregister();
                }
              });
            }
            cardGroupTypeStore.$watch($scope2, { id: $scope2.attribute.group_type_id }, (gt) => refreshGroupType(gt), false);
            $q.when(getOrLoadGroupType($scope2.project, $scope2.attribute.group_type_id), (gt) => {
              refreshGroupType(gt);
            });
          }
          $scope2.removeGroup = function(group2) {
            $q.digest(removeCardFromGroup($scope2.card, group2));
          };
          $scope2.textColor = textColor;
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeGroupTypeEditor", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-group-type-editor">
          <pretty-menu class="pretty-menu" config="groupMenu.config" options="groupMenu.options"
            on-close="onDone()" on-update="onMenuUpdate($menuEvent)">
          </pretty-menu>
        </div>`,
      scope: {
        project: "<",
        attributeGroup: "<",
        attribute: "<",
        card: "<obj",
        onDone: "&",
        onUpdate: "&",
        onInit: "&",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "$q",
        "groupsMenuFactory",
        function($scope2, $q, groupsMenuFactory) {
          let isInit = false;
          const parent = $scope2.card.parent_id ? cardStore.get($scope2.card.parent_id) : $scope2.card;
          const debouncedUpdate = debounce2(function() {
            if (angular_default.isFunction($scope2.onUpdate)) {
              $scope2.onUpdate();
            }
          }, 100);
          $scope2.onMenuUpdate = function(menuEvent) {
            if (!isInit && menuEvent === "panelInit") {
              $scope2.onInit();
              isInit = true;
            } else {
              debouncedUpdate();
            }
          };
          $scope2.groupMenu = { config: [] };
          $q.when(getOrLoadGroupType($scope2.project, $scope2.attribute.group_type_id), (gt) => {
            $scope2.groupType = gt;
            $scope2.groupMenu = groupsMenuFactory.get({
              card: $scope2.card,
              parent,
              groupType: $scope2.groupType || null,
              noCloseAfterToggle: $scope2.groupType && !$scope2.groupType.one_group_per_card
            });
          });
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeGroupTypeForm", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/group-type.html",
      scope: {
        project: "<",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.groupMenu = {};
          $scope2._editable = () => true;
          var watcher = angular_default.noop;
          function refreshGroups(groups) {
            $scope2.groups = (groups || []).map((cg) => {
              var g3 = cardGroupStore.tryGet(cg.id);
              if (!g3) {
                return Object.assign({ is_archived: true }, cg);
              }
              return g3;
            }).filter((g3) => g3 && g3.type_id === $scope2.groupType.id && !g3.is_archived).sort((a3, b3) => cmp2(a3.title, b3.title));
          }
          function isInGroup(group2) {
            if ($scope2.groups) {
              for (var i3 = 0; i3 < $scope2.groups.length; i3++) {
                if ($scope2.groups[i3].id === group2.id) {
                  return true;
                }
              }
            }
            return false;
          }
          $q.when(getOrLoadGroupType($scope2.project, $scope2.attribute.group_type_id), (gt) => {
            $scope2.groupType = gt;
            refreshGroups($scope2.obj.groups);
            $scope2.groupsMenuFactoryParams = {
              editable: false,
              groupType: $scope2.groupType,
              withSettings: false,
              groups: [],
              menuOpts: {
                watch: function(cb2, scope) {
                  watcher = () => {
                    $q.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], (value2) => {
                      refreshGroups(value2);
                      cb2();
                    });
                  };
                  return angular_default.noop;
                },
                fetchData: function(cb2) {
                  $q.when($scope2.attributeGroup.getAttributeChoices($scope2.obj, $scope2.attribute), (groups) => {
                    Array.prototype.splice.apply($scope2.groupsMenuFactoryParams.groups, [
                      0,
                      $scope2.groupsMenuFactoryParams.groups.length
                    ].concat(groups));
                    cb2();
                  });
                }
              },
              isInGroup,
              toggled: function(group2) {
                if (isInGroup(group2)) {
                  $q.when($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, group2), watcher);
                } else {
                  $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, group2), watcher);
                }
              },
              relocated: function(group2) {
                $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, [group2]), watcher);
              },
              removed: function(group2) {
                $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), watcher);
              }
            };
          });
          $scope2.removeGroup = function(group2) {
            $q.when($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, group2), watcher);
            $q.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], (value2) => {
              $scope2.groups = value2;
            });
          };
          $scope2.textColor = textColor;
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/indicators.js
angular_default.module("kantree").directive("attributeTypeIndicators", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/indicators.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        $scope2.colorPickerOptions = {
          change: (color, $el) => {
            var name2 = $el.find("i")[0].className.match(/fa-([a-z\-]+)/)[1];
            $q.digest($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, [name2, color.toHexString()]));
          }
        };
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeIndicatorsEditor", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/indicators-editor.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      onDone: "&",
      onInit: "&",
      embedded: "<?"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        var attrType = attributeTypeRegistry.get($scope2.attribute.type);
        if (attrType && typeof attrType.widgetOptions !== "undefined" && attrType.widgetOptions.items) {
          $scope2.choices = attrType.widgetOptions.items;
          $scope2.onInit();
        } else {
          $q.when($scope2.attributeGroup.getAttributeChoices($scope2.obj, $scope2.attribute), (choices) => {
            $scope2.choices = choices;
            $scope2.onInit();
          });
        }
        $scope2.isActive = function(name2) {
          if ($scope2.value) {
            for (var i3 = 0; i3 < $scope2.value.length; i3++) {
              if ($scope2.value[i3][0] === name2) {
                return true;
              }
            }
          }
          return false;
        };
        $scope2.toggle = function(name2) {
          if ($scope2.isActive(name2)) {
            $q.when($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, name2), $scope2.onDone);
          } else {
            $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, [name2, null]), $scope2.onDone);
          }
        };
      }
    ]
  };
});

// public/app/attributes/ng-components/labels.js
angular_default.module("kantree").directive("attributeTypeLabels", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/labels.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<"
    },
    controller: [
      "$scope",
      "$timeout",
      "dropdown",
      "$q",
      function($scope2, $timeout2, dropdown, $q) {
        injectI18nHelpersIntoScope($scope2);
        var self2 = this;
        var savedText;
        var refreshChoices;
        var resetLabelInput;
        var suggestionsDrop;
        var setLabelTextColor = function(label, bgColor) {
          var fgColor = tinycolor.mostReadable(bgColor, ["#ffffff", "#000000"]);
          var fgColorHex = fgColor.toHexString();
          if (label[2]) {
            label[2] = fgColorHex;
          } else {
            label.push(fgColorHex);
          }
        };
        $scope2.$watch("value", function(value2) {
          (value2 || []).forEach(function(label) {
            setLabelTextColor(label, label[1] || "#f5f5f5");
          });
          $scope2.labels = value2;
        });
        $scope2.suggestions = [];
        $scope2.selectedIndex = -1;
        $scope2.search = {};
        refreshChoices = function(cb2) {
          $q.when($scope2.attributeGroup.getAttributeChoices($scope2.obj, $scope2.attribute), (suggestions) => {
            var processedLabelList = [];
            angular_default.forEach(suggestions, function(suggestion) {
              setLabelTextColor(suggestion, suggestion[1]);
              var found2 = false;
              var attr = $scope2.attributeGroup.getObjAttribute($scope2.obj, $scope2.attribute);
              if (typeof attr !== "undefined") {
                attr.value.forEach(function(label) {
                  if (label[0] === suggestion[0]) {
                    found2 = true;
                  }
                });
              }
              if (!found2) processedLabelList.push(suggestion);
            });
            $scope2.suggestions = processedLabelList;
            cb2 && cb2();
          });
        };
        resetLabelInput = function() {
          savedText = "";
          $scope2.search.input = "";
          $scope2.search.presave = "";
          refreshChoices();
          if (suggestionsDrop.isOpened()) {
            dropdown.close(suggestionsDrop);
          }
        };
        $scope2.addLabel = function(label, color) {
          $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, [label, color]), () => {
            resetLabelInput();
          });
        };
        $scope2.removeLabel = function(label) {
          $q.digest($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, label));
        };
        $scope2.colorPickerOptions = {
          autoTextColor: true,
          disabled: !$scope2.editable,
          change: (color, $el) => {
            $scope2.addLabel($el.text(), color.toHexString());
          }
        };
        $scope2.isRelevant = function(suggestion) {
          if (!$scope2.search.presave) return true;
          return suggestion[0].toLowerCase().search(
            jquery_default.trim($scope2.search.presave.toLowerCase())
          ) !== -1;
        };
        $scope2.handleKeys = function(e3) {
          var value2 = jquery_default.trim($scope2.search.input);
          if (e3.keyCode === 40) {
            e3.preventDefault();
            if ($scope2.selectedIndex + 1 < $scope2.filteredSuggestions.length) {
              if ($scope2.selectedIndex === -1) {
                savedText = value2;
              }
              $scope2.selectedIndex++;
              $scope2.search.input = $scope2.filteredSuggestions[$scope2.selectedIndex][0];
            }
          } else if (e3.keyCode === 38) {
            e3.preventDefault();
            if ($scope2.selectedIndex > -1) {
              $scope2.selectedIndex--;
              $scope2.search.input = $scope2.selectedIndex === -1 ? savedText : $scope2.filteredSuggestions[$scope2.selectedIndex][0];
            }
          } else if (e3.keyCode === 13 && value2) {
            $scope2.addLabel(value2);
          } else {
            $scope2.selectedIndex = -1;
            $timeout2(function() {
              $scope2.$apply(function() {
                $scope2.search.presave = $scope2.search.input;
              });
            }, 0, false);
          }
        };
        this.initDropdown = function($el) {
          $el.on("click", ">input", function() {
            if ($scope2.editable) {
              var self3 = this;
              refreshChoices(function() {
                suggestionsDrop = dropdown.openTemplate(self3, "attribute-type-labels-drop.html", $scope2, {
                  classes: "attribute-type-labels-drop"
                });
              });
            }
          });
        };
      }
    ],
    link: function(scope, element2, attrs2, ctrl) {
      ctrl.initDropdown(jquery_default(element2));
    }
  };
});

// public/app/attributes/ng-components/likes.js
angular_default.module("kantree").directive("attributeTypeLikes", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/likes.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        onDone: "&"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.$watch("value", (value2) => {
            $scope2.liked = null;
            if (!value2) return;
            $scope2.liked = value2.likes.some((voter2) => voter2.id === currentUser2.id);
            if (!$scope2.liked && value2.dislikes.some(voter.id === currentUser2.id)) {
              $scope2.liked = false;
            }
          });
          var save = function(value2) {
            $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, value2), $scope2.onDone);
          };
          $scope2.like = function() {
            if ($scope2.liked === true) {
              save(0);
            } else {
              save(1);
            }
          };
          $scope2.dislike = function() {
            if ($scope2.liked === false) {
              save(0);
            } else {
              save(-1);
            }
          };
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/location.js
angular_default.module("kantree").directive("attributeTypeLocation", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/location.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<"
    },
    controller: [
      "$scope",
      "$q",
      "$sce",
      function($scope2, $q, $sce) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.edit = false;
        $scope2.isCard = typeof $scope2.obj?.image_cover_url !== "undefined";
        $scope2.hideMap = $scope2.attribute.options && $scope2.attribute.options.hide_map;
        $scope2.isEmpty = isEmptyValue;
        $scope2.getAddress = function() {
          if (!$scope2.value) return "";
          if (typeof $scope2.value === "string") return $scope2.value;
          return $scope2.value.address || "";
        };
        $scope2.hasCoordinates = function() {
          return $scope2.value && typeof $scope2.value === "object" && $scope2.value.lat != null && $scope2.value.lng != null;
        };
        $scope2.isValueEmpty = function() {
          if (!$scope2.value) return true;
          if (typeof $scope2.value === "string") return !$scope2.value;
          return !$scope2.value.address;
        };
        $scope2.getUrl = function() {
          const address = $scope2.getAddress();
          if (!address) return;
          if ($scope2.hasCoordinates()) {
            const params2 = new URLSearchParams();
            params2.set("q", `${$scope2.value.lat},${$scope2.value.lng}`);
            params2.set("zoom", 14);
            var key2 = "AIzaSyAQ8f4dIYwGuk4r2UcPKiA9_W7iluPGAPI";
            return $sce.trustAsResourceUrl("https://www.google.com/maps/embed/v1/place?key=" + key2 + "&" + params2.toString());
          }
          var key2 = "AIzaSyAQ8f4dIYwGuk4r2UcPKiA9_W7iluPGAPI";
          const params = new URLSearchParams();
          params.set("q", address);
          params.set("zoom", 10);
          return $sce.trustAsResourceUrl("https://www.google.com/maps/embed/v1/place?key=" + key2 + "&" + params.toString());
        };
        $scope2.toggleEdit = function(edit2) {
          $scope2.edit = edit2;
        };
        $scope2.clearValue = function() {
          $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), () => {
            $scope2.value = null;
          });
        };
      }
    ]
  };
});

// public/app/attributes/ng-components/members.js
angular_default.module("kantree").directive("attributeTypeMembers", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/members.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<",
      isTemplate: "<?"
    },
    controller: [
      "$scope",
      "$element",
      function($scope2, $element2) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.$watchCollection("value", () => {
          $scope2.members = ($scope2.value || []).map((v3) => {
            if (v3 === "@me" || isObject2(v3) && v3.id === "@me") {
              return {
                id: "@me",
                avatar: prependBaseUrl("/static/assets/guest-avatar.png"),
                display_name: _4("User performing the action"),
                username: "me"
              };
            }
            if (isObject2(v3)) {
              return v3;
            }
            const m3 = projectMemberStore.query({ user: query_exports.objMatch({ id: v3 }) })?.[0];
            if (m3) {
              return m3.user;
            }
          }).filter(Boolean);
        });
        $scope2.openAttributeEditor = () => {
          if ($scope2.editable) {
            $element2.find(".add-member a").click();
          }
        };
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeMembersEditor", function() {
  return {
    restrict: "E",
    replace: true,
    template: `
      <div class="attribute-type-members-editor">
        <pretty-menu class="pretty-menu" config="membersMenuSpec.config" options="membersMenuSpec.options"
          on-close="onDone()" on-update="onMenuUpdate($menuEvent)">
        </pretty-menu>
      </div>`,
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      onDone: "&",
      onInit: "&",
      embedded: "<?",
      isTemplate: "<?"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        let isInit = false;
        const debouncedUpdate = debounce2(() => {
          if (isFunction_default($scope2.onUpdate)) {
            $scope2.onUpdate();
          }
        }, 100);
        $scope2.onMenuUpdate = (menuEvent) => {
          if (!isInit && menuEvent === "panelInit") {
            $scope2.onInit();
            isInit = true;
          } else {
            debouncedUpdate();
          }
        };
        $scope2.membersMenuSpec = { config: [] };
        $q.when($scope2.attributeGroup.getAttributeChoices($scope2.obj, $scope2.attribute), (choices) => {
          $scope2.membersMenuSpec = {
            config: () => {
              if (choices.length <= 0) {
                return [
                  {
                    label: _4("No users found with the specified role(s)")
                  },
                  {
                    desc: _4("Check the role options of this field"),
                    enabled: () => canEditCardModel($scope2.attributeGroup.project, $scope2.attribute.model_id)
                  }
                ];
              }
              choices = choices.concat($scope2.value ? $scope2.value.filter((user) => {
                let userId = isObject2(user) ? user.id : user;
                return userId !== "@me" && !choices.some((choice) => choice.id === userId);
              }) : []);
              choices.sort((a3, b3) => a3.display_name.localeCompare(b3.display_name));
              var items = choices.map((member) => {
                return {
                  label: member.display_name,
                  small: member.display_name !== member.username ? "@" + member.username : null,
                  img: userAvatarUrl(member),
                  action: () => {
                    if (isAssigned(member)) {
                      $q.when($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, member), refreshValue);
                    } else {
                      $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, member), refreshValue);
                    }
                  },
                  classes: "mod-member",
                  noCloseAfterAction: !$scope2.isTemplate,
                  enableActionOnselected: true,
                  selected: () => isAssigned(member),
                  filterable: true,
                  filterPredicate: (filter4) => {
                    return member.display_name.toLowerCase().indexOf(filter4.toLowerCase()) >= 0 || member.username.toLowerCase().indexOf(filter4.toLowerCase()) >= 0;
                  }
                };
              });
              if ($scope2.isTemplate) {
                items.unshift({
                  label: _4("User performing the action"),
                  icon: "user",
                  classes: "mod-member",
                  noCloseAfterAction: !$scope2.isTemplate,
                  enableActionOnselected: true,
                  action: () => {
                    if (isAssigned({ "id": "@me" })) {
                      $q.when($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, { "id": "@me" }), refreshValue);
                    } else {
                      $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, { "id": "@me" }), refreshValue);
                    }
                  },
                  selected: () => isAssigned({ "id": "@me" }),
                  filterable: (filter4) => filter4 === "@me"
                });
              }
              return items;
            },
            options: { title: $scope2.embedded ? _4("Members") : null }
          };
        });
        function isAssigned(member) {
          return $scope2.value && $scope2.value.some((val) => val.id === member.id);
        }
        function refreshValue() {
          $q.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], (value2) => {
            $scope2.value = value2;
          });
        }
      }
    ]
  };
});

// public/app/attributes/ng-components/percentage.js
angular_default.module("kantree").directive("attributeTypePercentage", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-percentage">
          <solidjs-component
            component="Slider"
            value="value"
            step="attribute.options.step"
            min="attribute.options.min"
            max="attribute.options.max"
            readonly="!editable"
            classes="slider-progress-bar"
            on-change="setPercentage"
            on-change-committed="setValue"
          ></solidjs-component>
          <span>{{ percentage }} %</span>
        </div>
      `,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        onDone: "&"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.Slider = slider_default;
          $scope2.$watchGroup(["attribute.options.min", "attribute.options.max"], () => {
            $scope2.min = $scope2.attribute.options.min ?? 0;
            $scope2.max = $scope2.max ?? 100;
            $scope2.setPercentage($scope2.value);
          });
          $scope2.$watch("value", (value2, oldVal) => {
            if (value2 === oldVal) return;
            $scope2.setPercentage(value2);
          });
          $scope2.setPercentage = function(value2) {
            $scope2.percentage = Math.round(((value2 || $scope2.min) - $scope2.min) * 100 / ($scope2.max - $scope2.min));
            $scope2.$applyAsync();
          };
          $scope2.setValue = function(value2) {
            if (value2 === $scope2.value) return;
            $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, value2), $scope2.onDone);
          };
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/progress.js
angular_default.module("kantree").directive("attributeTypeProgress", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-progress">
          <solidjs-component
            component="Slider"
            value="value"
            readonly="true"
            classes="slider-progress-bar"
          ></solidjs-component>
          <span>{{ value }} %</span>
        </div>
      `,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        onDone: "&"
      },
      controller: [
        "$scope",
        function($scope2) {
          $scope2.Slider = slider_default;
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/relationships.js
angular_default.module("kantree").directive("attributeTypeRelationships", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/relationships.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      card: "<obj",
      value: "<",
      editable: "<"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.showReferencingCards = false;
        $scope2.referencingLoading = false;
        $scope2.isAuthenticated = isAuthenticated;
        $scope2.projectStore = projectStore;
        $scope2.$watchCollection("value", (value2) => {
          $scope2.cards = [];
          if (value2) {
            $scope2.loading = true;
            $q.when(Promise.allSettled(value2.map((item) => getOrLoadCard(item.id, { ignoreErrorHandlers: true })))).then((results2) => {
              const cards = [];
              for (const result2 of results2) {
                if (result2.status === "fulfilled") {
                  cards.push(result2.value);
                }
              }
              $scope2.loading = false;
              $scope2.cards = cards;
            });
          } else {
            $scope2.loading = false;
          }
        });
        $scope2.removeRelationship = function(relationship) {
          $q.when(
            $scope2.attributeGroup.popObjAttribute($scope2.card, $scope2.attribute, relationship),
            () => getOrLoadCard(relationship.id),
            autoCatchAsRequestErrorDialog([400])
          );
        };
        $scope2.toggleShowReferencingCards = () => {
          $scope2.showReferencingCards = !$scope2.showReferencingCards;
          if ($scope2.showReferencingCards) {
            $scope2.loadReferencingCards();
          }
        };
        $scope2.loadReferencingCards = () => {
          $scope2.referencingLoading = true;
          $q.when(searchCards(`${$scope2.card.id} in {${$scope2.attribute.name}}`, null, null, { ignoreErrorHandlers: true }), (cards) => {
            $scope2.referencingCards = cards;
            $scope2.referencingLoading = false;
          }, () => {
            $scope2.referencingLoading = false;
            $scope2.showReferencingCards = false;
          });
        };
        if ($scope2.card?.id && $scope2.attribute.options?.auto_display_referencing) $scope2.toggleShowReferencingCards();
      }
    ]
  };
});
angular_default.module("kantree").component("attributeTypeRelationshipsEditor", {
  templateUrl: "/static/app/attributes/ng-components/templates/relationships-editor.html",
  bindings: {
    attributeGroup: "<",
    attribute: "<",
    project: "<",
    value: "<",
    card: "<?",
    board: "<",
    onDone: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.$q.when(this.attributeGroup.getObjAttributeValue(this.card, this.attribute)[1], (value2) => {
        this.selectedCards = value2 || [];
      });
      this.options = this.attribute?.options || {};
      this.filteredCards = [this.card.id];
    }
    removeRelationship(selectedCard) {
      if (!selectedCard) return;
      this.attributeGroup.popObjAttribute(
        this.card,
        this.attribute,
        selectedCard,
        null,
        autoCatchAsRequestErrorDialog([400])
      );
    }
    handleRelationship(selectedCard) {
      if (this.options?.limit_to_one) {
        this.attributeGroup.setObjAttribute(
          this.card,
          this.attribute,
          [selectedCard],
          null,
          autoCatchAsRequestErrorDialog([400])
        );
      } else {
        this.attributeGroup.appendObjAttribute(
          this.card,
          this.attribute,
          selectedCard,
          null,
          autoCatchAsRequestErrorDialog([400])
        );
      }
    }
  }
});

// public/app/attributes/ng-components/remote.js
angular_default.module("kantree").directive("attributeTypeRemoteActionBtn", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/remote-action-btn.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        attributeEditable: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.$watchCollection("attribute.options", function() {
            $scope2.options = Object.assign({
              "label": _4("Perform action"),
              "provide_value": false,
              "value_question": _4("Input for the request")
            }, $scope2.attribute.options || {});
          });
          $scope2.call = function() {
            $scope2.value = { "status": "loading" };
            if ($scope2.options.provide_value) {
              $q.when(inputDialog($scope2.options.value_question), (value2) => {
                return $scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, value2);
              });
            } else {
              $q.digest($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, null));
            }
          };
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeRemoteValue", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `<div class="attribute-type-remote-value"><remote-call-result response="value"></remote-call-result></div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        editable: "<",
        attributeEditable: "<?"
      }
    };
  }
]);
angular_default.module("kantree").component("remoteCallResult", {
  templateUrl: "/static/app/attributes/ng-components/templates/remote-call-result.html",
  bindings: {
    response: "<"
  },
  controller: [
    "$scope",
    function($scope2) {
      var $ctrl = this;
      injectI18nHelpersIntoScope($scope2);
      $ctrl.$onChanges = function() {
        $ctrl.isDict = $ctrl.response && typeof $ctrl.response.data === "object" && !angular_default.isArray($ctrl.response.data);
        $ctrl.isList = $ctrl.response && typeof $ctrl.response.data === "object" && angular_default.isArray($ctrl.response.data);
      };
    }
  ]
});

// public/app/attributes/ng-components/state.js
angular_default.module("kantree").directive("attributeTypeState", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/attributes/ng-components/templates/state.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        card: "<obj",
        editable: "<"
      },
      controller: [
        "$scope",
        function($scope2) {
          $scope2.state = cardStateStore.getForCard($scope2.card);
          $scope2.statesMenuFactoryParams = { card: $scope2.card };
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeStateEditor", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-state-editor">
          <pretty-menu class="pretty-menu" config="stateMenu.config" options="stateMenu.options"
            on-close="onDone()" on-update="onMenuUpdate($menuEvent)">
          </pretty-menu>
        </div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        card: "<obj",
        onDone: "&",
        onUpdate: "&",
        onInit: "&",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "statesMenuFactory",
        function($scope2, statesMenuFactory) {
          $scope2.stateMenu = statesMenuFactory.get($scope2.card);
          var isInit = false;
          var debouncedUpdate = debounce2(function() {
            if (angular_default.isFunction($scope2.onUpdate)) {
              $scope2.onUpdate();
            }
          }, 100);
          $scope2.onMenuUpdate = function(menuEvent) {
            if (!isInit && menuEvent === "panelInit") {
              $scope2.onInit();
              isInit = true;
            } else {
              debouncedUpdate();
            }
          };
        }
      ]
    };
  }
]);

// public/app/attributes/ng-components/iframe.js
angular_default.module("kantree").directive("attributeTypeIframe", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/attributes/ng-components/templates/iframe.html",
    scope: {
      project: "<",
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<",
      attributeEditable: "<"
    },
    controller: [
      "$scope",
      "$q",
      "$sce",
      function($scope2, $q, $sce) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.label = null;
        $scope2.edit = false;
        $scope2.loading = false;
        $scope2.hasError = false;
        $scope2.errorMessage = _4("An error ocurred");
        $scope2.isEmpty = isEmptyValue;
        $scope2.toggleEdit = function(edit2) {
          $scope2.edit = edit2;
        };
        $scope2.getIframeUrl = function() {
          if ($scope2.value) {
            return $sce.trustAsResourceUrl($scope2.value);
          }
          return null;
        };
        $scope2.clearValue = function() {
          $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), () => {
            $scope2.value = "";
          });
        };
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeIframeEditor", [
  "$timeout",
  function($timeout2) {
    return {
      restrict: "E",
      replace: true,
      template: `<div class="attribute-type-iframe-editor">
                    <input type="text" placeholder="{{::_('Empty')}}" ng-model="inputValue"
                      ng-class="{'has-error': hasError}" class="form-control">
                    <a drop-menu="variablesMenu" uib-tooltip="{{::_('Available variables')}}"><i class="fa fa-info-circle"></i></a>
                </div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        onDone: "&",
        noAutoFocus: "@?",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.dirty = false;
          $scope2.hasError = false;
          $scope2.options = Object.assign({
            inputType: "text",
            inputPlaceholder: _4("Empty"),
            color: false,
            allowEmpty: true,
            valueIsOption: false
          }, attributeTypeRegistry.get($scope2.attribute.type).widgetOptions || {});
          if ($scope2.options.valueIsOption) {
            $scope2.inputValue = ($scope2.attribute.options || {})[$scope2.options.valueIsOption];
          } else {
            $scope2.inputValue = $scope2.value;
          }
          if ($scope2.options.color) {
            const e3 = extractColorFromText($scope2.inputValue);
            if (e3) {
              $scope2.inputValue = e3[0];
              $scope2.color = e3[1];
            }
          }
          const variablesMenu = {
            config: [
              { header: _4("Available variables:") }
            ]
          };
          for (const v3 of IFRAME_VARIABLES) {
            variablesMenu.config.push({ label: "${" + v3[1] + "}", small: v3[0] });
          }
          $scope2.variablesMenu = variablesMenu;
          $scope2.save = function() {
            if (isEmptyValue($scope2.inputValue)) {
              if (!$scope2.options.allowEmpty) {
                return;
              }
              if ($scope2.value) {
                $q.when(
                  $scope2.attributeGroup.update(
                    $scope2.attribute,
                    { options: Object.assign({}, $scope2.attribute.options, { url: "" }) }
                  ),
                  () => {
                    $scope2.value = "";
                  }
                );
              }
              return;
            }
            var value2 = $scope2.inputValue;
            if ($scope2.options.save) {
              $scope2.options.save($scope2, value2);
            } else {
              $q.when(
                this.attributeGroup.update(
                  this.attribute,
                  { options: Object.assign({}, this.attribute.options, { url: value2 }) }
                ),
                this.onDone,
                () => {
                  $scope2.hasError = true;
                }
              );
            }
          };
        }
      ],
      link: function(scope, element2, attrs2) {
        var $el = jquery_default(element2);
        var $input = $el.find("input");
        if (scope.noAutoFocus !== "true") {
          $timeout2(function() {
            $timeout2(function() {
              $el.find("input")[0].focus();
              $el.find("input")[0].select();
            }, 0, false);
          }, 0, false);
        }
        var cancel = function() {
          if (isEmptyValue(scope.inputValue)) return;
          scope.$evalAsync(function() {
            scope.onDone();
          });
        };
        scope.focus = function() {
          $input.focus();
        };
        $input.on("keydown", function(e3) {
          if (e3.keyCode === 13) {
            if (scope.dirty) {
              scope.save();
            } else {
              cancel();
            }
          } else if (e3.keyCode === 27) {
            e3.stopPropagation();
            e3.preventDefault();
            cancel();
          } else {
            scope.dirty = true;
          }
        });
        if (!scope.embedded) {
          $input.on("blur", function(e3) {
            setTimeout(function() {
              if ($el.find(">a").hasClass("drop-enabled")) return;
              if (scope.dirty) {
                scope.save();
              } else {
                cancel();
              }
            }, 500);
          });
        }
        if (!isIE()) {
          $input.on("input", function() {
            scope.dirty = true;
          });
          if ($input.prop("type") === "number") {
            $input.on("click", function() {
              jquery_default(this).focus();
            });
          }
        }
      }
    };
  }
]);

// public/app/modals/release/release.js
angular_default.module("kantree").service("releaseAnnouncementModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(release) {
    const className2 = release.version.replace(/\./g, "-");
    let locale = getCurrentLocale();
    if (!angular_default.isArray(release.modal) || !release.modal.includes(locale)) {
      locale = "en";
    }
    const instance = this.$uibModal.open({
      templateUrl: `/static/app/modals/release/versions/templates/v${release.version}-${locale}.html`,
      controller: release.controller || null,
      windowClass: `release-modal release-modal-v${className2}`
    });
    return instance;
  }
});

// public/app/modals/release/versions/v7.0.0.js
angular_default.module("kantree").controller("KantreeReleaseCtrl7_0_0", [
  "$scope",
  function($scope2) {
    $scope2.screensize = getScreensize();
    $scope2.theme = themeState.name;
    $scope2.updateTheme = function() {
      saveTheme($scope2.theme);
    };
    $scope2.getBoardColor = function() {
      return themeColor() || "#0c6442";
    };
  }
]);

// public/app/modals/assistant/assistant.jsx
var _tmpl$167 = /* @__PURE__ */ template(`<div class="context flex"><i class="bi bi-eye"></i> </div>`, 4);
var _tmpl$281 = /* @__PURE__ */ template(`<div class="flex"> </div>`, 2);
var _tmpl$356 = /* @__PURE__ */ template(`<div class="flex text-danger"> </div>`, 2);
var _tmpl$441 = /* @__PURE__ */ template(`<button type="button"></button>`, 2);
var _tmpl$534 = /* @__PURE__ */ template(`<div></div>`, 2);
var _tmpl$627 = /* @__PURE__ */ template(`<div class="response"></div>`, 2);
var _tmpl$722 = /* @__PURE__ */ template(`<div class="confirm"></div>`, 2);
var _tmpl$819 = /* @__PURE__ */ template(`<textarea rows="2"></textarea>`, 2);
var _tmpl$917 = /* @__PURE__ */ template(`<div class="modal-body"><div class="assistant-body"><div class="meta flex"><div class="status flex"></div><div class="badge badge-danger">BETA</div></div></div></div>`, 10);
var _tmpl$1013 = /* @__PURE__ */ template(`<button><i class="bi-x"></i></button>`, 4);
function Assistant(props2) {
  const context = {
    ...props2.context
  };
  const promptHistory = jsonLocalStorage.getItem("assistant-prompt-history") || [];
  let historyPosition = promptHistory.length;
  const speechSupported = "webkitSpeechRecognition" in window || "SpeechRecognition" in window;
  const defaultPlaceholder = context.card ? _4("Ask Kantree Assistant for help or to execute tasks on the current card. Press enter to execute") : _4("Ask Kantree Assistant for help or to execute tasks for you. Press enter to execute");
  let speechRecognition = null;
  let textarea;
  let timeout;
  let modalBody;
  let responseDiv;
  const [prompt, setPrompt] = createSignal("");
  const [running, setRunning] = createSignal(false);
  const [conversation, setConversation] = createSignal([]);
  const [placeholder, setPlaceholder] = createSignal(defaultPlaceholder);
  const [speechActive, setSpeechActive] = createSignal(false);
  const [response, setResponse2] = createSignal(null);
  const [runningMessage, setRunningMessage] = createSignal("");
  const [contextLabels, setContextLabels] = createSignal([]);
  updateContextLabels();
  onMount(() => focusAndSelectPrompt());
  onEvent(onAssistantFeedback, (data2) => {
    if (data2.project_id !== context.project.id || data2.card_id !== (context.card?.id || null)) {
      return;
    }
    clearTimeout(timeout);
    if (data2.status === "thinking") {
      setRunningMessage(_4("Thinking..."));
      startTimeout();
      return;
    }
    if (data2.status === "executing") {
      setRunningMessage(_4("Executing tasks..."));
      startTimeout();
      return;
    }
    if (data2.status === "navigate") {
      $invoke(["projectPage", "cardModal", function(projectPage, cardModal) {
        if (data2.to === "view") {
          projectPage.scopeManager.setActiveView(data2.to_id);
        } else if (data2.to === "card") {
          cardModal.loadByRef(context.project, data2.to_id);
          props2.onClose();
        } else {
          projectPage.gotoApp(data2.to);
        }
      }]);
      startTimeout();
      return;
    }
    if (data2.status === "context_change") {
      if (data2.context.card_ref) {
        updateCardContextFromAssistant(data2.context.card_ref);
      }
      startTimeout();
      return;
    }
    setRunning(false);
    setResponse2(data2);
    setPrompt("");
    setPlaceholder(_4("Continue the conversation or press escape to start a new conversation"));
    modalBody.closest(".modal-dialog").classList.remove("processing");
    if (data2.message || data2.error) {
      setConversation((prev) => [...prev, "Assistant:\n" + (data2.message || data2.error || "")]);
    }
    focusAndSelectPrompt();
  });
  function updateCardContextFromAssistant(cardRef, attempt = 1) {
    const card = cardStore.scopedByProject(context.project).query({
      ref: cardRef
    })?.[0];
    if (card) {
      context.card = card;
      updateContextLabels();
    } else if (attempt < 3) {
      setTimeout(() => updateCardContextFromAssistant(cardRef, attempt + 1), 1e3);
    }
  }
  function updateContextLabels() {
    const lbls = [];
    if (context.view) {
      lbls.push({
        key: "view",
        "label": _4("View {name}", {
          name: context.view.name
        })
      });
    }
    if (context.card) {
      lbls.push({
        key: "card",
        "label": _4("Card #{ref}", {
          ref: context.card.ref
        })
      });
    }
    setContextLabels(lbls);
  }
  function removeContext(key2) {
    delete context[key2];
    updateContextLabels();
  }
  function confirm(accept) {
    setRunning(true);
    setRunningMessage(_4("Confirming..."));
    api_default.assistant.confirm_assistant.post({
      resume_id: response()?.resume_id,
      confirm: accept
    });
  }
  function onKeyDown(event2) {
    setPrompt(event2.target.value);
    if (event2.keyCode === 27) {
      event2.stopPropagation();
      event2.preventDefault();
      if (response()?.status === "completed") {
        setPrompt("");
        setPlaceholder(defaultPlaceholder);
        setResponse2(null);
        setConversation([]);
      } else {
        props2.onClose();
      }
      return;
    }
    if (event2.keyCode === 38 && (!prompt() || textarea.selectionStart === 0) && promptHistory.length) {
      historyPosition = Math.max(0, Math.min(historyPosition - 1, promptHistory.length - 1));
      setPrompt(promptHistory[historyPosition]);
      return;
    }
    if (!prompt()) {
      historyPosition = promptHistory.length;
    }
    if (event2.keyCode !== 13 || event2.ctrlKey || !prompt()) {
      return;
    }
    if (speechActive()) {
      stopSpeechRecognition();
    }
    clearTimeout(timeout);
    setRunning(true);
    setRunningMessage(_4("Thinking..."));
    modalBody.closest(".modal-dialog").classList.add("processing");
    let finalPrompt = prompt();
    if (conversation().length) {
      finalPrompt = "# Previous messages in the conversation\n\n" + conversation().join("\n\n") + "\n\n---------------------------\n\n" + finalPrompt;
    }
    api_default.assistant.ask_assistant.post({
      org_id: props2.org.id,
      project_id: context.project?.id,
      card_id: context.card?.id,
      view_id: context.view?.id,
      prompt: finalPrompt
    });
    setConversation((prev) => [...prev, "User:\n" + prompt()]);
    jsonLocalStorage.setItem("assistant-prompt-history", [...promptHistory, prompt()].slice(-20));
    historyPosition = promptHistory.length;
    startTimeout();
  }
  function startTimeout() {
    timeout = setTimeout(() => {
      setRunning(false);
      setResponse2({
        "status": "completed",
        "error": _4("Timeout, please try again."),
        "timeout": true
      });
    }, 6e4);
  }
  function toggleSpeechRecognition() {
    if (!speechSupported) return;
    if (speechActive()) {
      stopSpeechRecognition();
    } else {
      startSpeechRecognition();
    }
  }
  function startSpeechRecognition() {
    if (speechRecognition) {
      speechRecognition.abort();
      speechRecognition = null;
    }
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SpeechRecognition) return;
    speechRecognition = new SpeechRecognition();
    speechRecognition.lang = {
      "fr": "fr-FR"
    }[document.querySelector("html").lang] || "en-US";
    speechRecognition.interimResults = true;
    speechRecognition.continuous = false;
    const speechRecognitionInitialPrompt = prompt() || "";
    speechRecognition.onstart = () => setSpeechActive(true);
    let finalTranscript = "";
    speechRecognition.onresult = (event2) => {
      if (typeof event2.results === "undefined" || !event2.results.length) {
        return;
      }
      let interim = "";
      for (let i3 = event2.resultIndex; i3 < event2.results.length; ++i3) {
        if (event2.results[i3].isFinal) {
          finalTranscript += event2.results[i3][0].transcript;
        } else {
          interim += event2.results[i3][0].transcript;
        }
      }
      setPrompt(this.speechRecognitionInitialPrompt + interim);
    };
    speechRecognition.onerror = (event2) => {
      setSpeechActive(false);
      speechRecognition = null;
      setPrompt(speechRecognitionInitialPrompt);
    };
    speechRecognition.onend = () => {
      setSpeechActive(false);
      speechRecognition = null;
      setPrompt(speechRecognitionInitialPrompt + finalTranscript);
      focusAndSelectPrompt();
    };
    speechRecognition.start();
  }
  function stopSpeechRecognition() {
    if (speechRecognition) {
      speechRecognition.stop();
      speechRecognition = null;
    }
    setSpeechActive(false);
  }
  function focusAndSelectPrompt() {
    textarea.focus();
    textarea.setSelectionRange(0, textarea.value.length);
  }
  createEffect(on(response, () => {
    if (responseDiv) {
      responseDiv.querySelectorAll("a.card").forEach((el2) => {
        el2.setAttribute("href", "#");
        el2.addEventListener("click", (event2) => {
          event2.preventDefault();
          const cardRef = el2.getAttribute("data-ref");
          if (cardRef) {
            $invoke(["cardModal", (cardModal) => {
              cardModal.loadByRef(context.project, cardRef);
              props2.onClose();
            }]);
          }
        });
      });
    }
  }));
  return (() => {
    const _el$ = _tmpl$917.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$7 = _el$3.firstChild, _el$15 = _el$7.nextSibling;
    const _ref$ = modalBody;
    typeof _ref$ === "function" ? use(_ref$, _el$) : modalBody = _el$;
    insert(_el$3, createComponent(Tooltip, {
      get label() {
        return _4("Context that will be provided to the Assistant");
      },
      get children() {
        const _el$4 = _tmpl$167.cloneNode(true), _el$5 = _el$4.firstChild, _el$6 = _el$5.nextSibling;
        insert(_el$4, () => _4("Workspace"), null);
        return _el$4;
      }
    }), _el$7);
    insert(_el$3, createComponent(For, {
      get each() {
        return contextLabels();
      },
      children: (ctx) => createComponent(Tooltip, {
        get label() {
          return _4("Context that will be provided to the Assistant");
        },
        get children() {
          const _el$20 = _tmpl$167.cloneNode(true), _el$21 = _el$20.firstChild, _el$22 = _el$21.nextSibling;
          insert(_el$20, () => ctx.label, null);
          insert(_el$20, createComponent(Tooltip, {
            get label() {
              return _4("Remove context");
            },
            get children() {
              const _el$23 = _tmpl$1013.cloneNode(true);
              _el$23.$$click = () => removeContext(ctx.key);
              return _el$23;
            }
          }), null);
          return _el$20;
        }
      })
    }), _el$7);
    insert(_el$7, createComponent(Show, {
      get when() {
        return running();
      },
      get children() {
        const _el$8 = _tmpl$281.cloneNode(true), _el$9 = _el$8.firstChild;
        insert(_el$8, createComponent(LoadingIndicator, {}), _el$9);
        insert(_el$8, runningMessage, null);
        return _el$8;
      }
    }), null);
    insert(_el$7, createComponent(Show, {
      get when() {
        return createMemo(() => !!(!running() && response()?.status === "completed"))() && !response().error;
      },
      get children() {
        const _el$10 = _tmpl$281.cloneNode(true), _el$11 = _el$10.firstChild;
        insert(_el$10, createComponent(Icon, {
          name: "bi-check"
        }), _el$11);
        insert(_el$10, () => _4("Job done"), null);
        return _el$10;
      }
    }), null);
    insert(_el$7, createComponent(Show, {
      get when() {
        return createMemo(() => !!(!running() && response()?.status === "completed"))() && response().error;
      },
      get children() {
        const _el$12 = _tmpl$356.cloneNode(true), _el$13 = _el$12.firstChild;
        insert(_el$12, createComponent(Icon, {
          name: "bi-exclamation-octagon-fill"
        }), _el$13);
        insert(_el$12, () => _4("An error occured"), null);
        return _el$12;
      }
    }), null);
    insert(_el$3, createComponent(Show, {
      when: speechSupported,
      get children() {
        return createComponent(Tooltip, {
          get label() {
            return createMemo(() => !!speechActive())() ? _4("Stop recording") : _4("Start voice chat");
          },
          get children() {
            const _el$14 = _tmpl$441.cloneNode(true);
            _el$14.$$click = () => toggleSpeechRecognition();
            insert(_el$14, createComponent(Icon, {
              get name() {
                return speechActive() ? "bi-mic-fill" : "bi-mic";
              }
            }));
            createRenderEffect(() => _el$14.classList.toggle("text-success", !!speechActive()));
            return _el$14;
          }
        });
      }
    }), _el$15);
    insert(_el$2, createComponent(Show, {
      get when() {
        return createMemo(() => response()?.status === "completed")() && response().error;
      },
      get children() {
        return createComponent(Alert, {
          style: "alert-danger",
          get children() {
            const _el$16 = _tmpl$534.cloneNode(true);
            createRenderEffect(() => _el$16.innerHTML = convertMarkdownToHTML(response().error));
            return _el$16;
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return createMemo(() => !!["completed", "confirm"].includes(response()?.status))() && response().message;
      },
      get children() {
        const _el$17 = _tmpl$627.cloneNode(true);
        const _ref$2 = responseDiv;
        typeof _ref$2 === "function" ? use(_ref$2, _el$17) : responseDiv = _el$17;
        createRenderEffect(() => _el$17.innerHTML = convertMarkdownToHTML(response().message));
        return _el$17;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return response()?.status === "confirm";
      },
      get children() {
        const _el$18 = _tmpl$722.cloneNode(true);
        insert(_el$18, createComponent(Button, {
          onClick: () => confirm(true),
          style: "success",
          get disabled() {
            return running();
          },
          children: "Confirm"
        }), null);
        insert(_el$18, createComponent(Button, {
          onClick: () => confirm(false),
          get disabled() {
            return running();
          },
          children: "Reject"
        }), null);
        return _el$18;
      }
    }), null);
    insert(_el$, createComponent(Show, {
      get when() {
        return response()?.status !== "confirm";
      },
      get children() {
        const _el$19 = _tmpl$819.cloneNode(true);
        _el$19.$$keydown = onKeyDown;
        const _ref$3 = textarea;
        typeof _ref$3 === "function" ? use(_ref$3, _el$19) : textarea = _el$19;
        createRenderEffect((_p$) => {
          const _v$ = running(), _v$2 = placeholder(), _v$3 = !!response();
          _v$ !== _p$._v$ && (_el$19.disabled = _p$._v$ = _v$);
          _v$2 !== _p$._v$2 && setAttribute(_el$19, "placeholder", _p$._v$2 = _v$2);
          _v$3 !== _p$._v$3 && _el$19.classList.toggle("continue", _p$._v$3 = _v$3);
          return _p$;
        }, {
          _v$: void 0,
          _v$2: void 0,
          _v$3: void 0
        });
        createRenderEffect(() => _el$19.value = prompt());
        return _el$19;
      }
    }), null);
    createRenderEffect(() => _el$2.classList.toggle("has-response", !!response()));
    return _el$;
  })();
}
delegateEvents(["click", "keydown"]);

// public/app/modals/assistant/modal.js
angular_default.module("kantree").factory("assistantModal", [
  "$uibModal",
  function($uibModal) {
    return {
      instance: null,
      open: function(org2, context) {
        if (this.instance) {
          return this.instance.result;
        }
        this.instance = $uibModal.open({
          windowClass: "assistant-modal",
          backdropClass: "assistant-modal-backdrop",
          keyboard: false,
          template: `
            <solidjs-component component="Assistant" org="org" context="context" on-close="close"></solidjs-component>
          `,
          controller: [
            "$scope",
            "$uibModalInstance",
            function($scope2, $uibModalInstance) {
              $scope2.Assistant = Assistant;
              $scope2.org = org2;
              $scope2.context = context;
              $scope2.close = $uibModalInstance.dismiss;
            }
          ]
        });
        this.instance.result.finally(() => {
          this.instance = null;
        });
        return this.instance.result;
      }
    };
  }
]);

// public/app/modals/camera/capture.js
angular_default.module("kantree").component("cameraCapture", {
  templateUrl: "/static/app/modals/camera/capture.html",
  bindings: {
    width: "<?",
    height: "<?",
    onCapture: "&"
  },
  controller: [
    "$element",
    "$scope",
    function($element2, $scope2) {
      var $ctrl = this;
      injectI18nHelpersIntoScope($scope2);
      $ctrl.width = $ctrl.width || 800;
      $ctrl.height = $ctrl.height || 600;
      $ctrl.withSwitchButton = false;
      var video, canvas, cameraMode = "environment";
      $ctrl.$postLink = function() {
        video = $element2.find("video")[0];
        canvas = $element2.find("canvas")[0];
        canvas.width = $ctrl.width;
        canvas.height = $ctrl.height;
        navigator.mediaDevices.getUserMedia({ video: { facingMode: cameraMode } }).then(function(stream) {
          video.srcObject = stream;
        });
        navigator.mediaDevices.enumerateDevices().then((devices) => {
          if (Array.isArray(devices) && devices.filter((device) => device.kind === "videoinput").length > 1) {
            $scope2.applyAsync(() => {
              $ctrl.withSwitchButton = true;
            });
          }
        });
      };
      $ctrl.$onDestroy = function() {
        video.srcObject?.getVideoTracks().forEach(function(track) {
          track.stop();
        });
      };
      $ctrl.switchCamera = function() {
        if (cameraMode === "environment") cameraMode = "user";
        else {
          cameraMode = "environment";
        }
        video.srcObject.getVideoTracks().forEach(function(track) {
          track.stop();
        });
        navigator.mediaDevices.getUserMedia({ video: { facingMode: cameraMode } }).then(function(stream) {
          video.srcObject = stream;
        });
      };
      $ctrl.capture = function() {
        var context = canvas.getContext("2d");
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        canvas.toBlob(function(blob) {
          $ctrl.onCapture({ $file: new File([blob], "capture.jpg", { type: blob.type }) });
        }, "image/jpeg");
      };
    }
  ]
});

// public/app/modals/camera/handler.js
angular_default.module("kantree").provider("camera", function() {
  var handler = "browserCamera";
  this.setHandler = function(name2) {
    handler = name2;
  };
  this.$get = [
    "$injector",
    function($injector) {
      return {
        isAvailable: function() {
          return $injector.get(handler).isAvailable();
        },
        capture: function() {
          return $injector.get(handler).capture();
        }
      };
    }
  ];
});
angular_default.module("kantree").factory("browserCamera", [
  "cameraModal",
  function(cameraModal) {
    return {
      isAvailable: function() {
        return navigator.mediaDevices && navigator.mediaDevices.getUserMedia;
      },
      capture: function() {
        return cameraModal.open();
      }
    };
  }
]);

// public/app/modals/camera/modal.js
angular_default.module("kantree").factory("cameraModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function() {
        var instance = $uibModal.open({
          templateUrl: "/static/app/modals/camera/modal.html",
          windowClass: "camera-modal",
          controller: "cameraModalCtrl"
        });
        return instance.result;
      }
    };
  }
]);
angular_default.module("kantree").controller("cameraModalCtrl", [
  "$scope",
  "$uibModalInstance",
  function($scope2, $uibModalInstance) {
    $scope2.onCapture = function(file) {
      $uibModalInstance.close(file);
    };
  }
]);

// public/app/modals/card-view/directives/change-history.js
angular_default.module("kantree").directive("cardChangeHistory", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/change-history.html",
      replace: true,
      scope: {
        card: "=",
        groupType: "=?",
        inDropdown: "@"
      },
      controller: [
        "$scope",
        "$timeout",
        "$q",
        function($scope2, $timeout2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.loading = true;
          $scope2.groupTypes = [];
          $scope2.historyByGroupType = {};
          $q.when(api_default.cards.get_change_history.get({ card_id: $scope2.card.id }), (history3) => {
            for (var i3 = 0; i3 < history3.length; i3++) {
              if (!history3[i3].group_id || !history3[i3].group_type_id) continue;
              history3[i3].created_at = parseTimestamp(history3[i3].created_at);
              if (typeof $scope2.historyByGroupType[history3[i3].group_type_id] === "undefined") {
                $scope2.historyByGroupType[history3[i3].group_type_id] = [];
              }
              var items = $scope2.historyByGroupType[history3[i3].group_type_id];
              if (items.length > 0) {
                var prev = items[items.length - 1];
                prev.duration = prev.created_at.to(history3[i3].created_at, true);
              }
              items.push(history3[i3]);
            }
            $q.all(Object.entries($scope2.historyByGroupType).map(([id, items2]) => {
              if (items2.length > 0) {
                const last3 = items2[items2.length - 1];
                last3.duration = last3.created_at.toNow(true);
              }
              return getOrLoadGroupType({ id: $scope2.card.project_id }, id);
            })).then((groupTypes) => {
              $scope2.groupTypes = groupTypes;
              $scope2.groupTypes.sort((a3, b3) => a3.name.localeCompare(b3.name));
              if (!$scope2.groupType) {
                $scope2.select($scope2.groupTypes[0]);
              } else {
                $scope2.select($scope2.groupType);
              }
              $scope2.loading = false;
            });
            if (!$scope2.historyByGroupType.length) {
              $scope2.loading = false;
            }
            $timeout2(function() {
              $scope2.$el.parent().trigger("refresh.autoDropPosition");
            }, 0, false);
          });
          $scope2.select = function(groupType) {
            $scope2.groupType = groupType;
            if (groupType && typeof $scope2.historyByGroupType[groupType.id] !== "undefined") {
              $scope2.history = $scope2.historyByGroupType[groupType.id];
            } else {
              $scope2.history = [];
            }
          };
        }
      ],
      link: function(scope, el2) {
        scope.$el = jquery_default(el2);
        if (scope.inDropdown === "true") {
          el2.on("click", "*", function(e3) {
            e3.stopPropagation();
          });
        }
      }
    };
  }
]);

// public/app/modals/card-view/directives/children.js
angular_default.module("kantree").directive("cardViewChildren", [
  "$q",
  function($q) {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/children.html",
      replace: true,
      controller: [
        "$scope",
        "projectPage",
        "$q",
        function($scope2, projectPage, $q2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.Slider = slider_default;
          if (serverConfig.email_inbound_domain) {
            $scope2.createEmail = $scope2.project.slug + ($scope2.target.parent_id ? "+create-" + $scope2.target.ref : "") + "@" + serverConfig.email_inbound_domain;
          }
          $scope2.showChildrenAttributes = null;
          $scope2.showAttributes = null;
          if ($scope2.target.model_id) {
            const targetModel = cardModelStore.tryGet($scope2.target.model_id);
            $scope2.showChildrenAttributes = targetModel.hide_children_attributes ? "none" : null;
            $scope2.showAttributes = targetModel.hide_children_attributes ? ["__ref__", "__comments__", "__children__", "__cover__"] : null;
          }
          $scope2.children = [];
          $scope2.store = cardStore.scopedByParent($scope2.target);
          if (projectPage.isActive) {
            $scope2.store = $scope2.store.scoped({
              is_archived: function(v3) {
                return $scope2.showArchived ? true : !v3;
              }
            });
          }
          $scope2.store.$watchAll($scope2, function() {
            $scope2.children = $scope2.store.query({}, { sortBy: "position", sortCastToInt: true });
          });
          if (!projectPage.isProjectActive($scope2.project) && $scope2.target.nb_children && $scope2.target.nb_children > 0 && isAuthenticated()) {
            $q2.digest(loadDescendantCardsOf($scope2.target, { ignoreErrorHandlers: true }));
            if (projectPage.isActive && $scope2.showArchived) {
              $q2.digest(loadArchivedDescendantCardsOf($scope2.target, { ignoreErrorHandlers: true }));
            }
          }
          $scope2.taskCreatorOption = {
            saveChange: function(event2, title, cb2) {
              const [tmpCards, onCardsCreatedPromise] = createManyCards($scope2.target, title);
              $q2.digest(onCardsCreatedPromise);
              cb2 && cb2();
            },
            saveOn: {
              tab: true
            },
            saveBtnLabel: _4("Add"),
            placeholder: _4("Add sub-card..."),
            enabled: false
          };
          $scope2.startAddTask = function() {
            $scope2.taskCreatorOption.enabled = true;
          };
        }
      ],
      link: function(scope, element2, attrs2, ctrl) {
        const $el = jquery_default(element2);
        let dragScrollHelper;
        scope.sortableOptions = {
          appendTo: "body",
          helper: function(event2, currentItem) {
            var h3 = currentItem.clone();
            var classes = "card-view-subcards-sortable-helper";
            h3.addClass(classes);
            return h3;
          },
          items: ".card-tile:not(.archived):not(.locked)",
          placeholder: "card-view-subcards-sortable-placeholder",
          distance: 6,
          scroll: false,
          zIndex: 0,
          start: function(event2, ui) {
            ui.placeholder.height(ui.helperProportions.height);
            ui.placeholder.width(ui.helperProportions.width);
            var hoveredScope = ui.placeholder.parents(".js-children-sortable")[0].scope();
            ui.item.sortable.sourceScope = hoveredScope;
            dragScrollHelper = new DragScrollHelper({
              scrollable: $el.parents("#card-modal-host").length ? ".card-view-body" : ".card-modal",
              threshold: {
                default: { top: 50, bottom: 50 },
                xs: { top: 30, bottom: 30 }
              },
              tolerance: "border"
            });
            var rect = ui.placeholder[0].getBoundingClientRect();
            dragScrollHelper.update("draggable", {
              width: ui.helperProportions.width,
              height: ui.helperProportions.height,
              mousePosition: {
                x: event2.clientX - rect.left,
                y: event2.clientY - rect.top
              }
            });
          },
          sort: function(e3, ui) {
            var $viewport = $el.parents("#card-modal-host").length ? $el.parents(".card-view-body") : $el.parents(".card-modal");
            if ($viewport[0].scrollHeight > $viewport[0].clientHeight) {
              dragScrollHelper.updateScroll(e3.pageX, e3.pageY, getScreensize());
            }
          },
          update: function(event2, ui) {
            var droptarget = ui.item.sortable.droptarget;
            if (!droptarget || !droptarget.length) {
              ui.item.sortable.cancel();
              return;
            }
            var targetScope = droptarget[0].scope();
            if (targetScope.sortBy && (ui.item.sortable.sourceScope.group && targetScope.group && ui.item.sortable.sourceScope.group.id === targetScope.group.id || !ui.item.sortable.sourceScope.group && !targetScope.group && ui.item.sortable.sourceScope.title === targetScope.title)) {
              ui.item.sortable.cancel();
            }
          },
          beforeStop: function(event2, ui) {
            ui.item.removeClass("pressed");
          },
          stop: function(event2, ui) {
            dragScrollHelper.reset();
            dragScrollHelper = null;
            jquery_default(event2.originalEvent.target).one("click", function(e3) {
              e3.stopImmediatePropagation();
            });
            ui.item.removeAttr("style");
            var droptarget = ui.item.sortable.droptarget;
            if (!droptarget || !droptarget.length) {
              return;
            }
            var targetScope = droptarget[0].scope();
            var card = ui.item.sortable.model;
            var position = null;
            const droptargetCards = ui.item.sortable.droptargetModel;
            function getNewPosition(dropIndex, replacing) {
              let relativeToCard, shift2 = 0, position2 = null;
              if (replacing === "upper") {
                relativeToCard = droptargetCards.slice(dropIndex + 1).find((c3) => c3.id !== card.id);
                if (!relativeToCard) {
                  shift2 = 1;
                  relativeToCard = droptargetCards.slice(0, dropIndex).reverse().find((c3) => c3.id !== card.id);
                }
              } else if (replacing === "lower") {
                relativeToCard = droptargetCards.slice(0, dropIndex).reverse().find((c3) => c3.id !== card.id);
                if (!relativeToCard) {
                  shift2 = -1;
                  relativeToCard = droptargetCards.slice(dropIndex + 1).find((c3) => c3.id !== card.id);
                }
              }
              if (relativeToCard) {
                if (shift2 === 0) {
                  if (card.position > relativeToCard.position && replacing === "lower") {
                    shift2 = 1;
                  } else if (card.position < relativeToCard.position && replacing === "upper") {
                    shift2 = -1;
                  }
                }
                position2 = relativeToCard.position + shift2;
                const highestPositionInParent = Math.max(1, ...pluck(scope.store.query(), "position"));
                const lowestPositionInParent = Math.min(...pluck(scope.store.query(), "position"), highestPositionInParent);
                if (position2 < lowestPositionInParent) {
                  position2 = lowestPositionInParent;
                } else if (position2 > highestPositionInParent) {
                  position2 = highestPositionInParent;
                }
              } else {
                position2 = card.position;
              }
              return position2;
            }
            if (droptargetCards.length <= 1) {
              position = null;
            } else {
              if (ui.item.sortable.index < ui.item.sortable.dropindex) {
                position = getNewPosition(ui.item.sortable.dropindex, "lower");
              } else if (ui.item.sortable.index > ui.item.sortable.dropindex) {
                position = getNewPosition(ui.item.sortable.dropindex, "upper");
              }
            }
            $q.digest(moveCardInUngrouped(card, position));
          }
        };
      }
    };
  }
]);

// public/app/modals/card-view/directives/log-type.js
angular_default.module("kantree").factory("logTypeMenuFactory", [
  "$q",
  function($q) {
    var getItems = function(project, createLogType) {
      var items = [];
      projectLogTypeStore.scopedByProject(project).query({}, { sortBy: "name" }).forEach(function(logType) {
        items.push({
          label: logType.name,
          action: function() {
            createLogType(logType);
          },
          buttons: [{
            icon: logType.is_project_specific ? "trash" : "times",
            action: function() {
              confirmDeleteDialog2().then(() => {
                $q.digest(disableOrDeleteLogType(project, logType));
              });
            },
            enabled: function() {
              return logType.id !== null && isAllowedInProject(project, "card_log_type", "DELETE", logType.id);
            }
          }]
        });
      });
      if (isAllowedInProject(project, "card_log_type", "CREATE")) {
        if (items.length) {
          items.push({ label: "--" });
        }
        items.push({
          input: true,
          placeholder: _4("Add new category"),
          resetOnSubmit: true,
          focusOnLoad: !items.length,
          submit: function(value2) {
            $q.when(createLogTypeInProject(project, value2), (logType) => {
              createLogType(logType);
            });
          }
        });
      }
      return items;
    };
    return {
      getItems,
      get: function(project, createLogType) {
        return {
          config: function() {
            return getItems(project, createLogType);
          },
          options: {
            watch: function(cb2, scope) {
              projectLogTypeStore.scopedByProject(project).$watchAll(scope, cb2, false);
            }
          }
        };
      }
    };
  }
]);

// public/app/modals/card-view/directives/logs.js
angular_default.module("kantree").directive("cardViewLogs", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/logs.html",
      replace: true,
      controller: [
        "$scope",
        function($scope2) {
          var logsCache = {};
          $scope2.logTypes = [];
          $scope2.users = [];
          $scope2.refreshUsersWithLogs = function() {
            $scope2.usersWithLogs = [];
            var userIdsWithLogs = [];
            $scope2.logTypes.forEach(function(logType) {
              logsCache[logType.id].forEach(function(log2) {
                if (log2.user && userIdsWithLogs.indexOf(log2.user.id) === -1) {
                  userIdsWithLogs.push(log2.user.id);
                }
              });
            });
            $scope2.usersWithLogs = $scope2.users.filter(function(user) {
              return userIdsWithLogs.indexOf(user.id) !== -1;
            });
          };
          const scopedLogTypeStore = projectLogTypeStore.scopedByProject($scope2.project);
          scopedLogTypeStore.$watchAll($scope2, function() {
            $scope2.logTypes = [];
            $scope2.attributes = [];
            $scope2.empty = true;
            scopedLogTypeStore.query().forEach(function(logType) {
              logsCache[logType.id] = activityStore.scopedForCard($scope2.target).query({ stream_type: "log", type_id: logType.id });
              if (logsCache[logType.id].length) {
                $scope2.empty = false;
              }
              var aggregAttributes = logType.attributes.filter(function(attr) {
                return attributeTypeRegistry.get(attr.type).aggregates;
              });
              if (aggregAttributes.length) {
                $scope2.logTypes.push(logType);
                $scope2.attributes = $scope2.attributes.concat(aggregAttributes.map(function(attr) {
                  return Object.assign(angular_default.copy(attr), { type_id: logType.id });
                }));
              }
            });
            $scope2.refreshUsersWithLogs();
          });
          const scopedMemberStore = projectMemberStore.scopedByProject($scope2.project);
          scopedMemberStore.$watchAll($scope2, function() {
            $scope2.users = scopedMemberStore.query().map(function(m3) {
              return m3.user;
            });
            $scope2.refreshUsersWithLogs();
          });
          $scope2.countAggregAttrs = function(logType) {
            return logType.attributes.filter(function(attr) {
              return attributeTypeRegistry.get(attr.type).aggregates;
            }).length;
          };
          var getAttrSum = function(logs, attr) {
            var values2 = logs.map(function(log2) {
              var v3 = log2.attributes.filter(function(a3) {
                return a3.id === attr.id;
              });
              if (v3.length) {
                return v3[0].value;
              }
            }).filter(function(v3) {
              return v3 !== void 0;
            });
            return attributeTypeRegistry.get(attr.type).aggregates.sum(values2);
          };
          $scope2.aggregate = function(user, attr) {
            var logType = projectLogTypeStore.get(attr.type_id);
            if (typeof logsCache[logType.id] === "undefined") {
              return "...";
            }
            return getAttrSum(logsCache[logType.id].filter(function(log2) {
              return log2.user.id === user.id;
            }), attr);
          };
          $scope2.total = function(attr) {
            var logType = projectLogTypeStore.get(attr.type_id);
            if (typeof logsCache[logType.id] === "undefined") {
              return "...";
            }
            return getAttrSum(logsCache[logType.id], attr);
          };
        }
      ]
    };
  }
]);

// public/app/modals/card-view/directives/modal-host.js
angular_default.module("kantree").directive("cardModalHost", [
  "cardModal",
  function(cardModal) {
    return {
      restrict: "E",
      template: `<div id="card-modal-host" ng-class="::{'resizable': resizable}"><div class="card-modal-host-resize-handle" ng-if="::resizable"></div></div>`,
      replace: true,
      scope: {
        resizable: "=?"
      },
      link: function(scope, el2) {
        var x3, origWidth;
        var mousemove = function(e3) {
          var w3 = origWidth + (x3 - e3.pageX);
          w3 = Math.min(w3, jquery_default(window).innerWidth() - 100);
          w3 = Math.max(w3, 570);
          cardModal.setDockWidth(w3);
          el2.css("width", w3);
        };
        var mouseup = function() {
          el2.parents().off("mousemove", mousemove).off("mouseup", mouseup);
        };
        el2.on("mousedown", ".card-modal-host-resize-handle", function(e3) {
          origWidth = el2.width(), x3 = e3.pageX;
          e3.preventDefault();
          el2.parents().on("mousemove", mousemove).on("mouseup", mouseup);
        });
        el2.css("width", cardModal.getDockWidth());
      }
    };
  }
]);

// public/app/modals/card-view/directives/panels.js
var cardViewPanels = [
  {
    builtin: true,
    name: "__stream__",
    title(card) {
      return _4("Activity");
    },
    directive: "card-view-stream",
    options: [
      {
        name: "comments",
        title: _4("Comments"),
        enabled(card) {
          var enabled = jsonLocalStorage.getItem("card-view:stream:comments:" + card.project_id);
          return enabled === null || enabled;
        },
        toggle(card) {
          jsonLocalStorage.setItem("card-view:stream:comments:" + card.project_id, !this.enabled(card));
        }
      },
      {
        name: "logs",
        title: _4("Logs"),
        enabled(card) {
          var enabled = jsonLocalStorage.getItem("card-view:stream:logs:" + card.project_id);
          return enabled === null || enabled;
        },
        toggle(card) {
          jsonLocalStorage.setItem("card-view:stream:logs:" + card.project_id, !this.enabled(card));
        }
      },
      {
        name: "activities",
        title: _4("Activities"),
        enabled(card) {
          var enabled = jsonLocalStorage.getItem("card-view:stream:activities:" + card.project_id);
          return enabled === null || enabled;
        },
        toggle(card) {
          jsonLocalStorage.setItem("card-view:stream:activities:" + card.project_id, !this.enabled(card));
        }
      },
      {
        name: "reverse",
        title: _4("Reverse"),
        enabled(card) {
          var enabled = jsonLocalStorage.getItem("card-view:stream:reverse:" + card.project_id);
          return enabled;
        },
        toggle(card) {
          jsonLocalStorage.setItem("card-view:stream:reverse:" + card.project_id, !this.enabled(card));
        }
      }
    ]
  },
  {
    builtin: true,
    name: "__children__",
    title(card) {
      return _4("Sub-cards ({finished}/{total})", {
        finished: card.nb_finished_children || 0,
        total: card.nb_children || 0
      });
    },
    directive: "card-view-children",
    enabled: function(card) {
      return !card.is_link && card.parent_id;
    }
  },
  {
    builtin: true,
    name: "__logs__",
    title(card) {
      return _4("Logs");
    },
    directive: "card-view-logs",
    enabled: function(card) {
      return card.parent_id;
    }
  }
];
function createAttributesPanel(name2) {
  return {
    name: name2,
    title: () => name2,
    directive: 'card-view-attr-group container="' + name2 + '" card="target" attributes="attributes" filter-attributes-using="filterAttributesUsing" editable="directiveEditable" attributes-editable="attributesEditable" model="model.model" project="project"'
  };
}
angular_default.module("kantree").directive("cardViewPanels", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/panels.html",
      replace: true,
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          var builtinPanels = cardViewPanels;
          $scope2.getPanel = function(name2) {
            for (const panel of cardViewPanels) {
              if (panel.name === name2) {
                return panel;
              }
            }
            return createAttributesPanel(name2);
          };
          var off;
          $scope2.$watchGroup(["model.model.id", "filterAttributesUsing"], function() {
            if (!$scope2.target) return;
            if (off) {
              off();
            }
            const projectModel = cardModelStore.getProjectModel($scope2.project);
            off = cardModelStore.scoped({ id: (id) => {
              return $scope2.model ? [$scope2.model.model.id, projectModel.id].includes(id) : id === projectModel.id;
            } }).$watchAll($scope2, () => {
              var currents;
              if ($scope2.panelGroups) {
                currents = $scope2.panelGroups.map(function(g3) {
                  return g3.current ? g3.current.name : null;
                }).filter(Boolean);
              }
              var containers;
              if ($scope2.model) {
                if ($scope2.model.model.base_model_id) {
                  containers = angular_default.copy($scope2.model.model.attribute_containers);
                } else if ($scope2.model.model.attribute_containers?.[String($scope2.project.id)]) {
                  containers = angular_default.copy($scope2.model.model.attribute_containers[String($scope2.project.id)]);
                } else if (!$scope2.filterAttributesUsing.model.disabled) {
                  containers = $scope2.filterAttributesUsing.model.baseContainers;
                } else {
                  containers = angular_default.copy(projectModel.attribute_containers);
                }
              }
              $scope2.containersNeverSet = !containers;
              if (!containers) {
                containers = [];
              }
              $scope2.flattenedContainers = [];
              containers.forEach(function(arr) {
                arr.forEach(function(c3) {
                  $scope2.flattenedContainers.push(c3);
                });
              });
              $scope2.attributeContainers.forEach(function(c3) {
                if (c3 !== $scope2.renaming && $scope2.flattenedContainers.indexOf(c3) === -1) {
                  if (containers.length === 0) {
                    containers.push([]);
                  }
                  containers[containers.length - 1].push(c3);
                  $scope2.flattenedContainers.push(c3);
                }
              });
              if ($scope2.renaming) {
                $scope2.renaming = null;
              }
              $scope2.panelGroups = [{ current: null, panels: [] }];
              containers.forEach(function(groupItems) {
                var panels = groupItems.filter((g3, idx) => groupItems.indexOf(g3) === idx).map(function(name2) {
                  return $scope2.getPanel(name2);
                }).filter(function(panel) {
                  return typeof panel.enabled === "undefined" || panel.enabled($scope2.target);
                });
                var current = panels[0];
                if (currents) {
                  panels.forEach(function(p4) {
                    if (currents.indexOf(p4.name) !== -1) {
                      current = p4;
                    }
                  });
                }
                $scope2.panelGroups.push({
                  current,
                  panels
                });
                $scope2.panelGroups.push({
                  current: null,
                  panels: []
                });
              });
            });
          });
          $scope2.updateLayout = function() {
            var containers = [];
            $scope2.panelGroups.forEach(function(g3) {
              if (g3.panels.length) {
                containers.push(g3.panels.map(function(p4) {
                  return p4.name;
                }));
              }
            });
            $q.digest(updateAttrContainers($scope2.project, $scope2.model.model, containers));
          };
          $scope2.movePanel = function(group2, panel, position) {
            $scope2.panelGroups.forEach(function(g3) {
              for (var i3 = 0; i3 < g3.panels.length; i3++) {
                if (g3.panels[i3].name === panel.name) {
                  g3.panels.splice(i3, 1);
                  break;
                }
              }
            });
            group2.panels.splice(position, 0, panel);
            group2.current = panel;
            $scope2.updateLayout();
          };
          $scope2.movePanelUpDown = function(currentGroup, panel, offset) {
            if (currentGroup.panels.length === 1) {
              if (offset < 0) {
                offset--;
              } else {
                offset++;
              }
            }
            let currentGroupIdx = $scope2.panelGroups.indexOf(currentGroup), newGroup = $scope2.panelGroups[currentGroupIdx + offset];
            if (!newGroup) {
              return;
            }
            $scope2.movePanel(newGroup, panel, newGroup.panels.length);
          };
          $scope2.togglePanelOption = function(panel, opt) {
            opt.toggle($scope2.target);
            $scope2.$broadcast("cardViewOptionToggled");
          };
          $scope2.isPanelOptionEnabled = function(panelName, name2) {
            var panel = $scope2.getPanel(panelName);
            for (var i3 = 0; i3 < panel.options.length; i3++) {
              if (panel.options[i3].name === name2) {
                return panel.options[i3].enabled($scope2.target);
              }
            }
            return null;
          };
          $scope2.addTabMenu = { config: () => () => {
            const items = [];
            if (!$scope2.containersNeverSet) {
              builtinPanels.forEach((panel) => {
                if ($scope2.flattenedContainers.indexOf(panel.name) === -1 && (typeof panel.enabled === "undefined" || panel.enabled($scope2.target))) {
                  items.push({
                    label: panel.title($scope2.target),
                    action: () => {
                      $scope2.addTabInGroup.panels.push(panel);
                      $scope2.addTabInGroup.current = panel;
                      $scope2.updateLayout();
                    }
                  });
                }
              });
            }
            if (items.length) {
              items.unshift({ subheader: _4("Hidden tabs") });
              items.push({ label: "--" });
            }
            items.push({
              input: true,
              focusOnLoad: true,
              placeholder: _4("Add a custom tab"),
              submit: (value2) => {
                $scope2.addTab($scope2.addTabInGroup, value2);
              }
            });
            return items;
          } };
          $scope2.startAddTab = function(group2) {
            $scope2.addTabInGroup = group2;
          };
          $scope2.addTab = function(group2, name2) {
            if (!name2 || $scope2.flattenedContainers.indexOf(name2) !== -1) {
              return false;
            }
            var panel = createAttributesPanel(name2);
            group2.panels.push(panel);
            group2.current = panel;
            $scope2.updateLayout();
          };
          $scope2.startEditTab = function(panel) {
            if (!panel.builtin && $scope2.attributesEditable) {
              panel.editing = true;
              $scope2.newPanelName = panel.name;
            }
          };
          $scope2.stopEditTab = function(panel) {
            panel.editing = false;
          };
          $scope2.updateTab = function(group2, panel, name2) {
            if (name2 && $scope2.flattenedContainers.indexOf(name2) === -1) {
              $scope2.renaming = panel.name;
              $q.digest(renameAttrContainer($scope2.project, $scope2.model.model, panel.name, name2));
              panel.name = name2;
              group2.current = panel;
            }
          };
          $scope2.hideTab = function(group2, panel) {
            group2.panels.splice(group2.panels.indexOf(panel), 1);
            $scope2.updateLayout();
          };
          $scope2.removeTab = function(panel) {
            confirmDeleteDialog2().then(() => {
              $q.digest(removeAttrContainer($scope2.project, $scope2.model.model, panel.name));
            });
          };
          function findPanelByName(panelGroup, name2) {
            return panelGroup.panels.find(function(panel) {
              return panel.name === name2;
            });
          }
          $scope2.$on("panel:openCommentEditorWithPastedImage", function(event2, image2) {
            var panelGroup = $scope2.panelGroups.find(function(panelGroup2) {
              return findPanelByName(panelGroup2, "__stream__");
            });
            if (panelGroup) {
              if (panelGroup.current !== "__stream__") {
                panelGroup.current = findPanelByName(panelGroup, "__stream__");
              }
              $scope2.$broadcast("stream:openCommentEditorWithPastedImage", image2);
            }
          });
        }
      ],
      link: function(scope, el2) {
        jquery_default(el2).on("mouseenter", ".tab-move-handle", function() {
          jquery_default(this).parent().addClass("highlight");
        });
        jquery_default(el2).on("mouseleave", ".tab-move-handle", function() {
          jquery_default(this).parent().removeClass("highlight");
        });
      }
    };
  }
]);
angular_default.module("kantree").directive("cardViewAttrGroup", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/attribute-group.html",
      replace: true,
      scope: {
        card: "<",
        project: "<",
        container: "@",
        attributes: "<",
        attributesEditable: "<",
        filterAttributesUsing: "<",
        editable: "<",
        model: "<"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.addAttribute = function(type, position, onlyModel) {
            var attributes = $scope2.attributes;
            if (!$scope2.model.base_model_id && !onlyModel) {
              attributes = new ModelAttributeGroup(
                $scope2.project,
                null,
                cardModelStore.getExtendedModelAttributes(null, $scope2.project)
              );
            }
            return $q.digest(attributes.create($scope2.card, type.name, $scope2.container, position));
          };
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("cardViewPanelGroup", [
  function() {
    return {
      restrict: "A",
      link: function(scope, el2) {
        var dragScrollHelper;
        var $el = jquery_default(el2);
        $el.sortable({
          helper: "clone",
          items: ">li",
          connectWith: ".card-view-panel-tabs > ul",
          tolerance: "pointer",
          distance: 6,
          forceHelperSize: true,
          scroll: false,
          zIndex: 0,
          delay: 50,
          placeholder: "nav-tab sortable-placeholder",
          start: function(e3, ui) {
            dragScrollHelper = new DragScrollHelper({
              scrollable: $el.parents("#card-modal-host").length ? ".card-view-body" : ".card-modal",
              threshold: {
                default: { top: 50, bottom: 50 },
                xs: { top: 30, bottom: 30 }
              },
              tolerance: "border"
            });
            var rect = ui.placeholder[0].getBoundingClientRect();
            dragScrollHelper.update("draggable", {
              width: ui.helperProportions.width,
              height: ui.helperProportions.height > 300 ? 300 : ui.helperProportions.height,
              mousePosition: {
                x: e3.clientX - rect.left,
                y: e3.clientY - rect.top
              }
            });
            ui.placeholder.text(scope.getPanel(ui.item.data("panel-name")).title(scope.target));
            $el.parents(".card-view-panels").addClass("sorting");
          },
          sort: function(e3, ui) {
            var $viewport = $el.parents("#card-modal-host").length ? $el.parents(".card-view-body") : $el.parents(".card-modal");
            if ($viewport[0].scrollHeight > $viewport[0].clientHeight) {
              dragScrollHelper.updateScroll(e3.pageX, e3.pageY, getScreensize());
            }
          },
          stop: function(e3, ui) {
            dragScrollHelper.reset();
            dragScrollHelper = null;
            $el.parents(".card-view-panels").removeClass("sorting");
          },
          update: function(e3, ui) {
            if (this != ui.currentContainer[0]) return;
            var panel = scope.getPanel(ui.item.data("panel-name"));
            var position = jquery_default(ui.item).index();
            var groupIndex = jquery_default(ui.currentContainer).parents(".card-view-panel-group").index();
            var group2 = scope.panelGroups[groupIndex];
            jquery_default(ui.item).remove();
            scope.$applyAsync(function() {
              scope.movePanel(group2, panel, position);
            });
          }
        });
        scope.$watch("attributesEditable", function(editable2) {
          if (editable2) {
            $el.sortable("enable");
          } else {
            $el.sortable("disable");
          }
        });
      }
    };
  }
]);

// public/app/modals/card-view/directives/stream.js
angular_default.module("kantree").directive("cardViewStream", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/stream.html",
      replace: true,
      controller: [
        "$scope",
        "logTypeMenuFactory",
        "$q",
        function($scope2, logTypeMenuFactory, $q) {
          $scope2.currentUser = currentUser2;
          $scope2.activitiesActions = [];
          if (serverConfig.email_inbound_domain) {
            $scope2.commentEmail = $scope2.project.slug + "+comment-" + $scope2.target.ref + "@" + serverConfig.email_inbound_domain;
          }
          refreshStore();
          refreshStreamFlowDirection();
          $scope2.$on("cardViewOptionToggled", function() {
            refreshStore();
            refreshStreamFlowDirection();
          });
          if ($scope2.target.id) {
            setupCommentCreatorOptions();
            setupCardStoreWatcher();
          } else {
            $scope2.$on("cardCreated", function() {
              refreshStore();
              setupCommentCreatorOptions();
              setupCardStoreWatcher();
            });
          }
          $scope2.$on("connectivityChanged", function(e3, connected) {
            $scope2.isConnected = connected;
            if (connected) {
              refreshStream();
            }
            refreshStreamActions();
            refreshActivitiesActions();
            refreshCommentButtonLabel();
          });
          $scope2.refreshCommentDraft = function() {
            $scope2.commentDraft = jsonLocalStorage.getItem(commentDraftId);
            refreshCommentButtonLabel();
          };
          var commentDraftId = $scope2.target.id + "-comment";
          $scope2.refreshCommentDraft();
          $scope2.$on("stream:openCommentEditorWithPastedImage", function(e3, image2) {
            jsonLocalStorage.setItem(commentDraftId, ($scope2.commentDraft || "") + "\n![" + image2.name + "](" + image2.url + ")");
            $scope2.openCommentEditor();
          });
          $scope2.isCommentCreating = false;
          $scope2.closeCommentEditor = function(commentText) {
            $scope2.isCommentCreating = false;
          };
          $scope2.openCommentEditor = function() {
            if (!$scope2.canComment) {
              return;
            }
            $scope2.isCommentCreating = true;
          };
          $scope2.saveComment = async function(newComment, showInRequest) {
            if (!newComment || !newComment.length) {
              return;
            }
            return $q.when(postCardComment($scope2.target, newComment, showInRequest), () => {
              $scope2.closeCommentEditor();
            });
          };
          var logCreatorDateOff;
          $scope2.openLogCreator = function(logType) {
            $scope2.isLogCreating = true;
            $scope2.logCreator = {
              obj: {},
              data: {},
              type: logType,
              attributes: new CardLogAttributeGroup($scope2.project, logType, (unwrap(logType.attributes) || []).map((attr) => structuredClone(attr))),
              editable: isAllowedInProject($scope2.project, "card_log_type", "EDIT", $scope2.project.id),
              date: moment_default(),
              dateChanged: false,
              dateLabel: _4("now"),
              datepickerOptions: {
                timePicker: true,
                timePicker24Hour: true,
                timePickerSeconds: true
              }
            };
            logCreatorDateOff && logCreatorDateOff();
            logCreatorDateOff = $scope2.$watch("logCreator.date", function(date, old) {
              if (date !== old) {
                $scope2.logCreator.dateLabel = _4("on {date}", { date: date.format("lll") });
                $scope2.logCreator.dateChanged = true;
              }
            });
          };
          $scope2.logsDropMenu = logTypeMenuFactory.get($scope2.project, $scope2.openLogCreator);
          $scope2.cancelLogCreator = function() {
            $scope2.isLogCreating = false;
            logCreatorDateOff && logCreatorDateOff();
          };
          $scope2.updateLogDate = function(start, end) {
            if (!end) {
              $scope2.logCreator.date = start;
            } else {
              $scope2.logCreator.date = { start, end };
            }
          };
          var isSubmittingLog = false;
          $scope2.submitLog = function() {
            if (isSubmittingLog) {
              return;
            }
            isSubmittingLog = true;
            const date = $scope2.logCreator.dateChanged ? $scope2.logCreator.date.utc().format("YYYY-MM-DD HH:mm:ss") : null;
            const attrs2 = [];
            for (const attr of $scope2.logCreator.attributes) {
              const newAttr = {
                name: attr.name,
                position: attr.position
              };
              if (attr.id && attr.id.toString().substring(0, 3) !== "tmp") {
                newAttr.id = attr.id;
              } else {
                newAttr.type = attr.type;
              }
              if (attr.id && $scope2.logCreator.data[attr.id]) {
                newAttr.value = $scope2.logCreator.data[attr.id];
              } else if ($scope2.logCreator.data[attr.name]) {
                newAttr.value = $scope2.logCreator.data[attr.name];
              }
              attrs2.push(newAttr);
            }
            for (const deletedAttr of $scope2.logCreator.attributes.deleted) {
              if (deletedAttr.id) {
                attrs2.push({ id: deletedAttr.id, delete: true });
              }
            }
            $q.when(addCardLog($scope2.target, $scope2.logCreator.type, attrs2, date), () => {
              $scope2.isLogCreating = false;
              isSubmittingLog = false;
            }, autoCatchAsRequestErrorDialog([400, 403])).catch(() => {
              isSubmittingLog = false;
            });
          };
          function isTargetEditable() {
            return !$scope2.target._temp && !!$scope2.target.id && !$scope2.target.is_archived && !$scope2.target.is_parent_archived;
          }
          function isDirectiveEditable() {
            return isConnected() && !$scope2.isShared && isTargetEditable();
          }
          function buildActivitiesActions() {
            if (!isDirectiveEditable()) {
              return [];
            }
            return getActionsForCardActivities($scope2.project);
          }
          function refreshActivitiesActions() {
            var newActions = buildActivitiesActions().concat("comments:collapse");
            if (!equals(newActions, $scope2.activitiesActions)) {
              $scope2.activitiesActions = newActions;
            }
          }
          function refreshStreamActions() {
            $scope2.canComment = !$scope2.isShared && isTargetEditable() && canCreateComment($scope2.project);
            $scope2.canLog = isDirectiveEditable() && $scope2.target.parent_id && canCreateLog($scope2.project);
          }
          function refreshStream() {
            if (!$scope2.target._temp && !$scope2.isShared && Object.keys($scope2.target).length > 0) {
              $q.digest(loadAllActivitiesForCard($scope2.target, { ignoreErrorHandlers: true }));
            }
          }
          ;
          function refreshCommentButtonLabel() {
            if ($scope2.commentDraft) {
              $scope2.commentButtonLabel = _4("Resume your comment editing");
            } else {
              if (isConnected()) {
                $scope2.commentButtonLabel = _4("Write a comment");
              } else {
                $scope2.commentButtonLabel = _4("Write a comment (will be synchronized when connection is established)");
              }
            }
          }
          function refreshStore() {
            var types2 = [];
            if ($scope2.isPanelOptionEnabled("__stream__", "activities")) {
              types2.push("activity");
            }
            if ($scope2.isPanelOptionEnabled("__stream__", "comments")) {
              types2.push("comment");
            }
            if ($scope2.isPanelOptionEnabled("__stream__", "logs")) {
              types2.push("log");
            }
            $scope2.store = $scope2.stream.scoped({ stream_type: query_exports.any(types2) });
          }
          function refreshStreamFlowDirection() {
            $scope2.streamReversed = $scope2.isPanelOptionEnabled("__stream__", "reverse");
          }
          function setupCardStoreWatcher() {
            cardStore.$watch($scope2, $scope2.target, function() {
              refreshStream();
              refreshStreamActions();
              refreshActivitiesActions();
              $scope2.newCommentCreatorOptions.data.card_id = $scope2.target.id;
            });
          }
          function setupCommentCreatorOptions() {
            $scope2.newCommentCreatorOptions = {
              data: {
                project_id: $scope2.target.project_id,
                card_id: $scope2.target.id
              },
              type: "comment",
              draftDelay: 1e3,
              uuid: $scope2.target.id + "-comment",
              container: ".content-composer-wrapper",
              buttons: [
                {
                  label: _4("Comment"),
                  whenTextChange: {
                    disabled: true
                  }
                }
              ]
            };
          }
        }
      ]
    };
  }
]);

// public/app/loaders/card-subscription.js
function formatSubscription(obj) {
  obj.id = obj.card_id;
  return obj;
}
async function loadSubscriptionForCard(card, options2) {
  try {
    return await load(
      cardSubscriptionStore,
      api_default.cards.get_subscription,
      { card_id: card.id },
      { ...options2, ignoreErrorHandlers: true },
      formatSubscription
    );
  } catch (r3) {
    const sub = cardSubscriptionStore.tryGet(card.id);
    if (sub) {
      cardSubscriptionStore.remove(sub);
    }
    if (r3.status !== 404 && !options2?.ignoreErrorHandlers) {
      return api_default.triggerErrorHandlers(r3);
    }
  }
}

// public/app/loaders/log-type.js
function getOrLoadLogType(logTypeId) {
  return getOrLoad(projectLogTypeStore, logTypeId, api_default.log_types.get_log_type, { type_id: logTypeId });
}
function loadAllLogTypes(project, options2) {
  return loadMany(projectLogTypeStore, api_default.project_log_types.list_enabled_log_types, {
    project_id: project.id
  }, options2);
}

// public/app/loaders/state.js
function loadAvailableStatesForCard(card, options2) {
  return loadMany(cardStateStore, api_default.cards.list_states, { card_id: card.id }, options2);
}

// public/app/modals/card-view/directives/view.js
angular_default.module("kantree").directive("cardView", [
  "imagePasteUtils",
  function(imagePasteUtils) {
    return {
      restrict: "E",
      templateUrl: "/static/app/modals/card-view/templates/view.html",
      replace: true,
      scope: {
        card: "<",
        showArchived: "<?",
        parentSelector: "<?",
        showDock: "<?",
        onDockToggle: "&",
        docked: "<?",
        showClose: "<?",
        onClose: "&",
        loadRelated: "<?"
      },
      controller: [
        "$scope",
        "$timeout",
        "cardsSelector",
        "cardModal",
        "projectPage",
        "cardViewTheme",
        "$sanitize",
        "$state",
        "$q",
        "menuDropdown",
        "actionsAppearanceEditorMenuFactory",
        function($scope2, $timeout2, cardsSelector, cardModal, projectPage, cardViewTheme, $sanitize, $state, $q, menuDropdown, actionsAppearanceEditorMenuFactory) {
          const BASE_ATTRIBUTE_CONTAINERS = ["__stream__", "__children__", "__logs__"];
          injectI18nHelpersIntoScope($scope2);
          $scope2.isConnected = isConnected;
          $scope2.isConnectionManagerDisabled = isConnectionManagerDisabled;
          $scope2.textColor = textColor;
          $scope2.capitalize = capitalize;
          $scope2.isScreensizeXS = isScreensizeXS;
          $scope2.isEmbedded = isEmbedded;
          $scope2.isAuthenticated = isAuthenticated;
          $scope2.authentication = authSession;
          $scope2.isShared = $state.is("share");
          $scope2.loaded = false;
          $scope2.parent = null;
          $scope2.themeName = "";
          $scope2.model = null;
          $scope2.attributes = [];
          $scope2.attributeContainers = [];
          $scope2.remindersCount = 0;
          $scope2.filterAttributesUsing = {
            model: {
              disabled: true,
              filter: (attr) => !(attr.is_from_integration || attr.model_is_base),
              baseContainers: [BASE_ATTRIBUTE_CONTAINERS]
              // used when containers have not been customised for the model
            }
            /*, view: false*/
          };
          $scope2.$on("interfaceThemeUpdated", () => refreshTheme());
          $scope2.$on("$destroy", projectStore.watch($scope2.project, "updated", () => refreshTheme(), false));
          if ($scope2.card.is_link && !$scope2.card.link_has_own_attributes && $scope2.card.broken_link) {
            $scope2.targetNotLoaded = true;
            $scope2.targetNotLoadedMessage = _4("The link target has been deleted");
            $scope2.linkActionsParams = {
              card: $scope2.card,
              options: {
                showSubscribe: true,
                hideOpenModal: true,
                rename: $scope2.startEditTitle
              }
            };
            $scope2.loaded = true;
            return true;
          }
          if ($scope2.card.is_link && !$scope2.card.link_has_own_attributes) {
            $q.when(getOrLoadCard($scope2.card.link.id, { ignoreErrorHandlers: true }), (link2) => {
              $scope2.target = link2;
              $q.when(getOrLoadProject($scope2.card.project_id), (project) => {
                $scope2.linkSourceProject = project;
                loadRelated();
              });
            }, catchAsRequestErrorDialog((r3) => r3.status === 403)).catch(() => {
              $scope2.targetNotLoaded = true;
              $scope2.targetNotLoadedMessage = _4("You are not allowed to access the target of the link");
              $scope2.loaded = true;
            });
          } else {
            $scope2.target = $scope2.card;
            loadRelated();
          }
          $scope2.selector = cardsSelector.push($scope2, false);
          $scope2.selector.select($scope2.card, false, true);
          if ($scope2.parentSelector) {
            cardsSelector.hotkeys($scope2, [
              {
                combo: "pageup",
                description: _4("Next card") + " (" + _4("in modal") + ")",
                needsCard: false,
                callback: function(selector, card) {
                  $scope2.parentSelector.prev();
                  cardModal.open($scope2.parentSelector.selected, { parentSelector: $scope2.parentSelector, showArchived: $scope2.showArchived });
                }
              },
              {
                combo: "pagedown",
                description: _4("Next card") + " (" + _4("in modal") + ")",
                needsCard: false,
                callback: function(selector, card) {
                  $scope2.parentSelector.next();
                  cardModal.open($scope2.parentSelector.selected, { parentSelector: $scope2.parentSelector, showArchived: $scope2.showArchived });
                }
              }
            ]);
          }
          var waitForLoadoff = $scope2.$watch("loaded", (loaded) => {
            if (loaded === true) {
              waitForLoadoff();
              if ($scope2.onLoaded) $scope2.onLoaded();
            }
          });
          $scope2.$on("$destroy", function() {
            $scope2.$broadcast("saveDraft");
          });
          $scope2.openModal = function(card, showArchived) {
            if (cardStore.exists(card.id)) {
              cardModal.open(cardStore.get(card.id), { showArchived });
            } else {
              $q.when(getOrLoadCard(card.id), (card2) => cardModal.open(card2, { showArchived }));
            }
          };
          $scope2.addAttribute = function(type, container, position, onlyModel) {
            var attributes = $scope2.attributes;
            if (!$scope2.model.model.base_model_id && !onlyModel) {
              attributes = new ModelAttributeGroup(
                $scope2.project,
                null,
                cardModelStore.getExtendedModelAttributes(null, $scope2.project)
              );
            }
            return $q.digest(attributes.create($scope2.target, type.name, container, position));
          };
          $scope2.updateAttributeGroupFilter = function() {
            $scope2.filterAttributesUsing = Object.assign({}, $scope2.filterAttributesUsing);
          };
          $scope2.cancelAutomationState = function(state) {
            $q.when(
              Promise.resolve(state.error || confirmDeleteDialog2(_4("Are you sure you want to cancel this automation?"))).then(() => api_default.cards.cancel_card_automation_state.delete({ card_id: $scope2.target.id, state_id: state.id })),
              () => refreshAutomationStates()
            );
          };
          $scope2.titleEditorOptions = {
            saveChange: function(event2, title, cb2) {
              if (!title || !title.length) {
                return cb2 && cb2();
              }
              if ($scope2.target.id) {
                $q.when(updateCard($scope2.target, { title }), cb2);
              } else {
                const [c3, onCardCreatedPromise] = createCard($scope2.parent, title, [], !$scope2.model.model.base_model_id ? $scope2.model.model : null);
                $q.when(onCardCreatedPromise, (card) => {
                  cb2();
                  onCardCreated(card);
                });
              }
            },
            cancelChange: function(event2, cb2) {
              event2.stopPropagation();
              cb2 && cb2();
              if (!$scope2.target.id) {
                $scope2.onClose();
              }
            },
            saveOn: {
              clickOutside: true,
              shiftEnter: true,
              tab: true
            },
            hideOn: { save: true },
            resetOn: { save: false },
            expandableInput: true,
            autosizeOpts: {
              append: null
            },
            enabled: false,
            placeholder: _4("Card title")
          };
          $scope2.startEditTitle = function() {
            $timeout2(function() {
              $scope2.titleEditorOptions.enabled = true;
            }, 0);
          };
          $scope2.removeGroup = function(group2) {
            $q.digest(removeCardFromGroup($scope2.target, group2));
          };
          $scope2.restore = (card) => {
            $q.digest(restoreCard(card));
          };
          function buildGroupsMenuFactoryParams(groupType) {
            var parent = $scope2.target.parent_id ? cardStore.get($scope2.target.parent_id) : $scope2.target;
            return {
              card: $scope2.target,
              parent,
              groupType
            };
          }
          function buildTypeMenuFactoryParams(activeGroupTypeIds) {
            if ($scope2.target.is_template) return null;
            $scope2.groupTypes = cardGroupTypeStore.scopedByEnabled($scope2.project).query({
              id: query_exports.not(query_exports.any(activeGroupTypeIds))
            }, { sortBy: "name" });
            if ($scope2.target && !$scope2.target.parent_id) {
              $scope2.groupTypes = $scope2.groupTypes.filter(function(groupType) {
                return groupType.scope === "org";
              });
            }
            $scope2.groupTypes = $scope2.groupTypes.filter(function(groupType) {
              return canMoveCardsInThisGroupType($scope2.project, groupType.id);
            });
            if ($scope2.groupTypes && $scope2.groupTypes.length) {
              return {
                card: $scope2.target,
                groupTypes: $scope2.groupTypes
              };
            } else {
              return null;
            }
          }
          function refreshGroups() {
            $scope2.groups = [];
            if ($scope2.target && $scope2.target.groups) {
              $scope2.groups = $scope2.target.groups.filter((cg) => cardGroupTypeStore.exists(cg.type_id)).map((cg) => {
                const g3 = cardGroupStore.tryGet(cg.id) || { id: cg.id, type_id: cg.type_id, title: cg.title, is_archived: true };
                const gt = cardGroupTypeStore.get(cg.type_id);
                const allowedToChange = isDirectiveEditable() && canMoveCardsInThisGroupType($scope2.project, gt.id) && !$scope2.target.is_template;
                return [g3, gt, buildGroupsMenuFactoryParams(gt), allowedToChange];
              }).filter((s3) => typeof s3[1].attribute_id === "undefined" || s3[1].attribute_id === null).sort((a3, b3) => a3[1].name.localeCompare(b3[1].name));
            }
            const activeGroupTypeIds = uniq($scope2.groups.map((s3) => s3[1].id));
            $scope2.groupTypesMenuFactoryParams = buildTypeMenuFactoryParams(activeGroupTypeIds);
          }
          var cardModelStoreWatchOff;
          function refreshModel() {
            getOrLoadModelForCard($scope2.target, { ignoreErrorHandlers: true }).then(() => {
              const oldModel = $scope2.model;
              $scope2.model = getCardCompositeModel($scope2.target, false);
              if ($scope2.model.model.id !== oldModel?.model?.id && $scope2.model.model.only_show_own_attributes !== !!oldModel?.model?.only_show_own_attributes) {
                $scope2.filterAttributesUsing.model.disabled = !$scope2.model.model.only_show_own_attributes;
                $scope2.filterAttributesUsing = Object.assign({}, $scope2.filterAttributesUsing);
              }
              $scope2.attributes = $scope2.model.attributes;
              $scope2.isSidebarEmpty = !isScreensizeXS() && !getAttributesInContainer($scope2.attributes, "").length;
              refreshPastePermission();
              refreshGroups();
              refreshTheme();
              var containers;
              if ($scope2.model.model.base_model_id) {
                containers = $scope2.project.attribute_containers;
              } else if ($scope2.model.model.attribute_containers) {
                containers = $scope2.model.model.attribute_containers[String($scope2.project.id)];
              }
              if (!containers) {
                $scope2.attributeContainers = BASE_ATTRIBUTE_CONTAINERS;
              } else {
                $scope2.attributeContainers = [];
              }
              angular_default.forEach($scope2.attributes, function(attr) {
                if (attr.container && attr.container !== "__top__" && $scope2.attributeContainers.indexOf(attr.container) === -1 && ($scope2.filterAttributesUsing.model.disabled || $scope2.filterAttributesUsing.model.filter(attr))) {
                  $scope2.attributeContainers.push(attr.container);
                }
              });
              if ($scope2.model) {
                cardModelStoreWatchOff && cardModelStoreWatchOff();
                cardModelStoreWatchOff = cardModelStore.scopedByEnabled($scope2.target).$watchAll($scope2, refreshModel, false);
              }
              $scope2.$applyAsync(() => {
                $scope2.loaded = true;
              });
            }, () => {
              $scope2.attributes = [];
              refreshPastePermission();
              refreshGroups();
              refreshTheme();
              $scope2.$applyAsync(() => {
                $scope2.loaded = true;
              });
            });
          }
          ;
          function buildPinnedCommentActions() {
            if (!isConnected() || $scope2.target._temp || $scope2.target.is_archived || $scope2.target.is_parent_archived) {
              return [];
            }
            return getActionsForCardComment($scope2.project, $scope2.pinnedComment);
          }
          function isTargetEditable() {
            return !$scope2.target._temp && !$scope2.target.is_archived && !$scope2.target.is_parent_archived;
          }
          function isDirectiveEditable() {
            return isConnected() && !$scope2.isShared && isTargetEditable();
          }
          function canSubscribe(card, project) {
            return isConnected() && !project.is_template && !card._temp && !card.is_template && !card.is_archived && !card.is_parent_archived && card.parent_id && isAuthenticated() && !$scope2.isShared;
          }
          function refreshEditable() {
            $scope2.directiveEditable = !!$scope2.target.id && isDirectiveEditable();
            $scope2.canEditTarget = $scope2.directiveEditable && isAllowedInProject($scope2.project, "card", "EDIT", $scope2.target.id);
            $scope2.canRenameTarget = !$scope2.target.id && !$scope2.target.title || !$scope2.card.is_link && $scope2.canEditTarget;
            $scope2.canArchiveTarget = !$scope2.target._temp && !$scope2.target.is_parent_archived && isAllowedInProject($scope2.project, "card", "ARCHIVE", $scope2.target.id);
            $scope2.canSubscribeToTarget = $scope2.target.id && canSubscribe($scope2.target, $scope2.project);
            if ($scope2.card.id !== $scope2.target.id) {
              $scope2.canEditSource = isConnected() && !$scope2.card._temp && !$scope2.card.is_archived && !$scope2.card.is_parent_archived && isAllowedInProject($scope2.linkSourceProject, "card", "EDIT", $scope2.card.id);
            } else {
              $scope2.canEditSource = $scope2.canEditTarget;
            }
            $scope2.canCreateGroups = $scope2.directiveEditable && isAllowedInProject($scope2.project, "card_group", "CREATE");
            $scope2.canRevealHiddenAttrs = canEditCardModel($scope2.project);
            $scope2.canOpenModelsMenu = $scope2.directiveEditable && $scope2.target.parent_id && (isAllowedInProject($scope2.project, "card", "SWITCH_MODEL", $scope2.target.id) || canEditCardModel($scope2.project) || canCreateCardModel($scope2.project));
            $scope2.canCreateChildren = !$scope2.isShared && $scope2.target.id && isTargetEditable() && canAddCard($scope2.project);
            $scope2.canCreateSubBoards = $scope2.directiveEditable && isAllowedInProject($scope2.project, "project", "MANAGE_SUB_BOARDS");
            if ($scope2.target.parent_id) {
              $scope2.attributesEditable = isDirectiveEditable() && canManageAttributes($scope2.project);
              $scope2.attributesMovable = isDirectiveEditable() && (!$scope2.target.model_id && $scope2.attributesEditable || $scope2.target.model_id && canEditCardModel($scope2.project, $scope2.target.model_id));
            } else {
              $scope2.attributesEditable = $scope2.attributesMovable = false;
            }
            if ($scope2.pinnedComment) {
              $scope2.pinnedCommentActions = buildPinnedCommentActions();
            }
            $scope2.canEditToolbar = !$scope2.creatingCard && ($scope2.target.model_id ? canEditCardModel($scope2.project) : canManageAttributes($scope2.project));
            refreshPastePermission();
          }
          function refreshPastePermission() {
            var fileAttrs = $scope2.attributes.filter(function(attr) {
              return attr.type === "files";
            });
            $scope2.canPaste = $scope2.directiveEditable && (canCreateComment($scope2.project) || canEditSomeAttributes($scope2.project, fileAttrs));
          }
          function refreshTheme() {
            let color;
            if ($scope2.model && $scope2.model.card_color) {
              color = $scope2.model.card_color;
            } else if ($scope2.project) {
              const project = projectStore.tryGet($scope2.project.id) || {};
              color = project.color || project.owner.color || themeColor();
            } else {
              color = themeColor();
            }
            if (color) {
              $scope2.themeName = cardViewTheme.createFromProjectColor(color);
            } else if ($scope2.themeName !== "") {
              $scope2.themeName = "";
            }
          }
          function refreshRequest() {
            if (!$scope2.target.from_request) {
              return;
            }
            $scope2.requesterNameHtml = "<em>" + $sanitize($scope2.target.from_request.user ? $scope2.target.from_request.user.username : $scope2.target.from_request.email ? $scope2.target.from_request.email : _4("anonymous")) + "</em>";
            $scope2.requestFormNameHtml = _4("Unknown");
            $scope2.requestUrl = makeUrlAbsolute($state.href("request", { requestToken: $scope2.target.from_request.token }));
            if ($scope2.isShared) return;
            ensureConnectivity(() => {
              $q.when(getOrLoadRequestForm($scope2.project.id, $scope2.target.from_request.form_id, { ignoreErrorHandlers: true }), (form) => {
                $scope2.requestFormNameHtml = "<em>" + $sanitize(form.name) + "</em>";
              });
            });
          }
          function refreshAutomationStates() {
            $scope2.automationStates = [];
            if ($scope2.isShared || !$scope2.target.id || !$scope2.target.parent_id) return;
            ensureConnectivity(() => {
              $q.when(api_default.cards.list_card_automation_states.get({ card_id: $scope2.target.id }, { ignoreErrorHandlers: true }), (states) => {
                $scope2.automationStates = states;
              });
            });
          }
          var isArchived = null, parentId = null, has_self_attributes = null;
          function onTargetChange() {
            if ($scope2.target.id) {
              $scope2.target = cardStore.tryGet($scope2.target.id) || {};
            }
            if (Object.keys($scope2.target).length === 0) {
              $scope2.onClose();
              return;
            }
            if (isArchived === null) {
              isArchived = $scope2.target.is_archived;
            } else if (isArchived !== $scope2.target.is_archived) {
              $scope2.onClose();
              return;
            }
            if (parentId === null) {
              parentId = $scope2.target.parent_id;
            } else if (parentId !== $scope2.target.parent_id) {
              $scope2.onClose();
              return;
            }
            $scope2.creatingCard = !$scope2.target.id && !$scope2.target.title;
            $scope2.isTemplate = !$scope2.target.id && !!$scope2.target.title;
            $scope2.imageCoverUrl = $scope2.target.image_cover_url ? prependBaseUrl($scope2.target.image_cover_url) : null;
            $scope2.projectRouteHref = projectRouteHref;
            $scope2.isLocked = $scope2.target.id && cardStore.isLocked($scope2.target);
            $scope2.state = cardStateStore.getForCard($scope2.target);
            if ($scope2.target.finished) {
              $scope2.finishedDuration = formatSecondsIntervalToString($scope2.target.finished_at - ($scope2.target.started_at || $scope2.target.created_at));
            }
            $scope2.targetPath = [];
            for (const parent of $scope2.target.path) {
              const newParent = Object.assign({}, parent);
              if ($scope2.isShared) {
                $scope2.targetPath.push(newParent);
                continue;
              }
              if (parent.ref == 0) {
                if (!projectPage.isActive || projectPage.project.slug !== $scope2.project.slug) {
                  newParent.href = projectRouteHref($scope2.project);
                }
                $scope2.targetPath.push(newParent);
                continue;
              }
              if (projectPage.isActive && projectPage.project.slug === $scope2.project.slug) {
                const board = cardStore.tryGet(parent.id);
                newParent.href = projectRouteHref($scope2.project, board, board.board_created ? null : projectPage.view);
              }
              $scope2.targetPath.push(newParent);
            }
            var forceRefresh = false;
            if ($scope2.target.has_self_attributes || has_self_attributes !== $scope2.target.has_self_attributes) {
              has_self_attributes = $scope2.target.has_self_attributes;
              forceRefresh = true;
            }
            $scope2.subscribedToTarget = cardSubscriptionStore.isSubscribed($scope2.target) || cardGroupSubscriptionStore.isSubscribedToCard($scope2.target);
            $scope2.showSharedIcon = $scope2.target.share_token && !$scope2.isShared && (isCurrentUserMemberOfProject($scope2.project) || canManageMembers($scope2.project));
            refreshEditable();
            refreshRequest();
            refreshAutomationStates();
            if (isAuthenticated()) {
              refreshToolbarActions();
            }
            if (!$scope2.model || $scope2.model.model.id !== $scope2.target.model_id || forceRefresh) {
              refreshModel();
            } else {
              refreshGroups();
              refreshTheme();
              $scope2.$applyAsync(() => {
                $scope2.loaded = true;
              });
            }
          }
          function setupReminders() {
            if ($scope2.isShared) {
              return;
            }
            const scopedReminderStore = cardReminderStore.scopedByCard($scope2.target);
            scopedReminderStore.$on($scope2, ["inserted", "removed"], function() {
              $scope2.remindersCount = scopedReminderStore.query().filter((reminder) => {
                if (!reminder.attribute_id) return true;
                const attr = getCardAttribute($scope2.target, reminder.attribute_id);
                return !!attr && !!attr.value;
              }).length;
            });
            $scope2.remindersCount = scopedReminderStore.query().filter((reminder) => {
              if (!reminder.attribute_id) return true;
              const attr = getCardAttribute($scope2.target, reminder.attribute_id);
              return !!attr && !!attr.value;
            }).length;
          }
          async function refreshToolbarActions() {
            $scope2.cardRules = await api_default.project_automations.list_toolbar_actions.get({
              project_id: $scope2.project.id,
              card_id: $scope2.target?.id,
              model_id: $scope2.isTemplate ? $scope2.target?.model_id : null
            }, { ignoreErrorHandlers: true });
            const rulesForToolbar = $scope2.isTemplate && $scope2.target?.model_id ? ($scope2.cardRules || []).filter((r3) => r3.for_model) : $scope2.cardRules || [];
            $scope2.toolbarActions = rulesForToolbar.sort((a3, b3) => {
              if (a3.for_model !== b3.for_model) return a3.for_model ? 1 : -1;
              return a3.position - b3.position;
            });
            $scope2.showCardToolbar = $scope2.isTemplate || $scope2.canEditToolbar && $scope2.toolbarActions.length > 0 || $scope2.toolbarActions.filter((a3) => a3.enabled).length > 0;
            $scope2.modelsMenuFactoryParams = {
              card: $scope2.target,
              options: {
                hasToolbar: $scope2.showCardToolbar,
                canEditToolbar: $scope2.canEditToolbar,
                onToggleToolbar: () => {
                  if (!$scope2.showCardToolbar) {
                    $q.when(refreshToolbarActions(), () => {
                      $scope2.showCardToolbar = true;
                    });
                  } else {
                    $q.when(confirmDeleteDialog2().then(
                      () => api_default.project_automations.remove_toolbar.delete({
                        project_id: $scope2.project.id,
                        model_id: $scope2.target?.model_id
                      })
                    ), refreshToolbarActions);
                  }
                }
              }
            };
            $scope2.$applyAsync();
          }
          function setupToolbarActions() {
            $scope2.cardToolbarMenu = {
              config: () => () => {
                const isRuleAttached = (rule) => {
                  if ($scope2.isTemplate && $scope2.target?.model_id) {
                    return $scope2.toolbarActions?.filter((r3) => r3.for_model).some((r3) => r3.id === rule.id);
                  }
                  return $scope2.toolbarActions?.some((r3) => r3.id === rule.id);
                };
                const isGlobal = (rule) => {
                  const rec = ($scope2.cardRules || []).find((r3) => r3.id === rule.id);
                  return rec ? rec.for_model === false : false;
                };
                const makeMenuItem = (rule, editable2 = true) => {
                  const actionsAppearanceEditorMenu = actionsAppearanceEditorMenuFactory.get(
                    rule,
                    $scope2.project,
                    {},
                    async (updates) => {
                      await saveAutomationRule($scope2.project, { ...rule, ...updates });
                      refreshToolbarActions();
                    }
                  );
                  const allowEditButtons = !$scope2.isTemplate && editable2 && canManageAutomations($scope2.project);
                  return {
                    checkbox: true,
                    label: rule.name,
                    icon: rule.icon || "play",
                    offline: true,
                    mobile: true,
                    value: () => isRuleAttached(rule),
                    toggle: async () => {
                      if (isRuleAttached(rule)) {
                        await api_default.project_automations.remove_toolbar_action.delete({
                          project_id: $scope2.project.id,
                          model_id: $scope2.target?.model_id,
                          rule_id: rule.id
                        });
                      } else {
                        await api_default.project_automations.add_toolbar_action.post({
                          project_id: $scope2.project.id,
                          model_id: $scope2.target?.model_id,
                          rule_id: rule.id
                        });
                      }
                      refreshToolbarActions();
                    },
                    closeAfterToggle: false,
                    submenu: allowEditButtons ? actionsAppearanceEditorMenu.config : null,
                    options: actionsAppearanceEditorMenu.options,
                    buttons: allowEditButtons ? [{
                      icon: "pencil",
                      action: "openSubmenu",
                      classes: "btn-icon btn-default btn-text",
                      enabled: () => canManageAutomations($scope2.project)
                    }] : [],
                    disabled: editable2 ? void 0 : () => true
                  };
                };
                const allRules = automationRuleStore.scopedByProject($scope2.project).query({ trigger_event: "manual_card" });
                if ($scope2.isTemplate) {
                  return allRules.map((rule) => makeMenuItem(rule, true));
                }
                const rulesForModel = [];
                const rulesGlobal = [];
                for (const rule of allRules) {
                  if ($scope2.target?.model_id && isGlobal(rule)) {
                    rulesGlobal.push(makeMenuItem(rule, false));
                  } else {
                    rulesForModel.push(makeMenuItem(rule, true));
                  }
                }
                const menu = [];
                if (!$scope2.target?.model_id) {
                  menu.push(...rulesForModel);
                } else {
                  if (rulesForModel.length) {
                    menu.push({ subheader: _4("Automations for this card type") });
                    menu.push(...rulesForModel);
                  }
                  if (rulesGlobal.length) {
                    menu.push({ subheader: _4("Automations for all cards") });
                    menu.push(...rulesGlobal);
                  }
                }
                return menu;
              },
              options: {
                title: $scope2.target?.model_id ? _4("Manage automations on card type") : _4("Manage automations on card"),
                icon: "bi-plus-lg",
                fetchData: (cb2) => $q.when(loadAutomationRulesForProject($scope2.project), cb2)
              }
            };
            $scope2.openAddAutomationMenu = function(event2) {
              menuDropdown.open(event2.currentTarget, $scope2.cardToolbarMenu, $scope2, {
                classes: "drop-theme-menu drop-theme-arrow"
              });
            };
            $scope2.runningRuleId = null;
            $scope2.runToolbarAction = function(rule) {
              if (!$scope2.card?.id) return;
              if (rule.disabled) return;
              rule.disabled = true;
              $scope2.runningRuleId = rule.id;
              runAutomationRule($scope2.project, rule, $scope2.target).then(() => {
                toastNotify(_4("Triggered automation"), "success");
              }).catch(() => {
                toastNotify(_4("Error while running automation"), "error");
              }).finally(() => {
                $timeout2(() => {
                  rule.disabled = false;
                  $scope2.runningRuleId = null;
                  refreshToolbarActions();
                }, 2e3);
              });
            };
            $scope2.toolbarActions = [];
            $scope2.showCardToolbar = false;
          }
          function setupExistingCard() {
            if ($scope2.card.id && !$scope2.target.is_archived && ($scope2.target.is_parent_archived && !$scope2.project.is_archived || !$scope2.target.is_parent_archived && $scope2.project.is_archived)) {
              $q.digest(loadCard($scope2.card.id));
            }
            if ($scope2.card.id && $scope2.card.id !== $scope2.target.id) {
              $q.digest(loadSubscriptionForCard($scope2.card));
            }
            cardStore.$watch($scope2, $scope2.target, onTargetChange);
            cardStore.$watch($scope2, $scope2.target, ["locked", "unlocked"], function() {
              $scope2.isLocked = cardStore.isLocked($scope2.target);
            });
            $scope2.stream = activityStore.getCardStream($scope2.target);
            $scope2.stream.$watchAll($scope2, function() {
              var pinnedComment = $scope2.stream.query({ is_pinned: true })?.[0];
              if (pinnedComment && !$scope2.pinnedComment || !pinnedComment && $scope2.pinnedComment || pinnedComment && $scope2.pinnedComment && pinnedComment.id !== $scope2.pinnedComment.id) {
                $scope2.pinnedComment = pinnedComment;
                $scope2.pinnedCommentActions = buildPinnedCommentActions();
              }
            });
            refreshRequest();
            setupReminders();
            setupToolbarActions();
            $scope2.targetActionsParams = {
              card: $scope2.target,
              options: {
                showSubscribe: false,
                showPrint: true,
                showCopyLink: true,
                showAddField: true,
                showFavorite: true,
                hideOpenModal: true,
                hideGroupTypes: true,
                hideBoardActions: $scope2.isShared,
                onCreateAttribute: (attrType, onlyModel) => {
                  $scope2.addAttribute(attrType, "__top__", null, onlyModel);
                },
                isDocked: $scope2.docked,
                toggleModalDock: $scope2.onDockToggle
              }
            };
            $scope2.linkActionsParams = {
              card: $scope2.card,
              options: {
                showSubscribe: true,
                hideOpenModal: true,
                hideBoardActions: $scope2.isShared
              }
            };
            $scope2.modelsMenuFactoryParams = {
              card: $scope2.target
            };
            $scope2.statesMenuFactoryParams = {
              card: $scope2.target,
              options: {
                withGroupStates: isAllowedInProjectFuzzy($scope2.project, "card_group", "MOVE_CARDS")
              }
            };
          }
          function setupCard() {
            if ($scope2.target.id) {
              setupExistingCard();
            } else {
              onTargetChange();
              $scope2.stream = activityStore.scoped(() => () => false);
              if ($scope2.target.title) {
                $scope2.modelsMenuFactoryParams = {
                  card: $scope2.target,
                  options: {
                    onSwitchModel() {
                      refreshModel();
                    }
                  }
                };
              }
              $scope2.titleEditorOptions.saveBtnLabel = _4("Create");
              setupToolbarActions();
            }
            cardGroupTypeStore.scopedByEnabled($scope2.project).$watchAll($scope2, refreshGroups, false);
            cardSubscriptionStore.$watch($scope2, $scope2.target.id, function() {
              $scope2.subscribedToTarget = cardSubscriptionStore.isSubscribed($scope2.target) || cardGroupSubscriptionStore.isSubscribedToCard($scope2.target);
            });
            cardGroupSubscriptionStore.$watchAll($scope2, function() {
              $scope2.subscribedToTarget = cardSubscriptionStore.isSubscribed($scope2.target) || cardGroupSubscriptionStore.isSubscribedToCard($scope2.target);
            });
            $scope2.$on("connectivityChanged", function(e3, connected) {
              refreshEditable();
              if (connected && $scope2.card.id) {
                $q.digest(loadCard($scope2.card.id, { ignoreErrorHandlers: true }));
                if ($scope2.target.id && $scope2.card.id !== $scope2.target.id) {
                  $q.digest(loadCard($scope2.target.id, { ignoreErrorHandlers: true }));
                }
              }
            });
            if (canManageMembers($scope2.project) || isCurrentUserMemberOfProject($scope2.project) && $scope2.target.share_token) {
              $scope2.shareMenuConfig = {
                config: [
                  {
                    component: "sharing-editor-menu-component",
                    params: {
                      object_id: $scope2.target.id,
                      object_type: "card"
                    }
                  }
                ]
              };
            }
            if (!$scope2.target.id && !$scope2.target.title) {
              $scope2.startEditTitle();
            }
          }
          function loadProject2() {
            getOrLoadProject($scope2.target.project_id).then((project) => {
              $scope2.project = project;
              $scope2.isActiveProjectPage = projectPage.isProjectActive(project);
              refreshTheme();
              if ($scope2.target.parent_id) {
                if (!$scope2.isShared && $scope2.target.id) {
                  $q.digest(loadRemindersForCard($scope2.target, { ignoreErrorHandlers: true }));
                }
                getOrLoadCard($scope2.target.parent_id).then((parent) => {
                  $scope2.parent = parent;
                  setupCard();
                });
              } else {
                setupCard();
              }
            });
          }
          function loadRelated() {
            if (!$scope2.loadRelated) {
              loadProject2();
              return;
            }
            const load2 = (parent) => {
              const loaders = [
                loadDescendantCardsOf($scope2.target, { ignoreErrorHandlers: true }),
                loadAllLogTypes({ id: $scope2.target.project_id }, { ignoreErrorHandlers: true }),
                loadAllAvailableGroupsForCard(parent, { ignoreErrorHandlers: true }),
                loadAvailableStatesForCard($scope2.target, { ignoreErrorHandlers: true }),
                loadSubscriptionForCard($scope2.target, { ignoreErrorHandlers: true })
              ];
              if ($scope2.showArchived) {
                loaders.push(loadArchivedDescendantCardsOf($scope2.target, { ignoreErrorHandlers: true }));
              }
              $q.all(loaders).then(loadProject2, loadProject2);
            };
            if ($scope2.target.parent_id) {
              $q.when(getOrLoadCard($scope2.target.parent_id), () => {
                load2(cardStore.get($scope2.target.parent_id));
              });
            } else {
              load2($scope2.target);
            }
          }
          function onCardCreated(card) {
            $scope2.card = $scope2.target = card;
            setupExistingCard();
            $scope2.titleEditorOptions.saveBtnLabel = _4("Save");
            $scope2.$broadcast("cardCreated");
          }
          $scope2.getTextColor = function(bgColor) {
            if (!bgColor) return null;
            return textColor(bgColor);
          };
        }
      ],
      link: function(scope, element2, attrs2, ctrl) {
        jquery_default("body").removeClass("is-card-view-open");
        jquery_default("body").addClass("is-card-view-open");
        function handlePasteEvent(event2) {
          if (scope.canPaste && imagePasteUtils.isFileData(event2.clipboardData)) {
            imagePasteUtils.getImageFromPasteEvent(event2, openPasteImageModal);
          }
        }
        function openPasteImageModal(imageBlob) {
          imagePasteUtils.openModal(scope.target, imageBlob, function(result2) {
            if (result2 && result2.option && result2.option.id === -1) {
              scope.$broadcast("panel:openCommentEditorWithPastedImage", result2.image);
            }
          });
        }
        document.addEventListener("paste", handlePasteEvent);
        scope.$on("$destroy", function() {
          jquery_default("body").removeClass("is-card-view-open");
          document.removeEventListener("paste", handlePasteEvent);
        });
      }
    };
  }
]);

// public/app/modals/card-view/modal.js
angular_default.module("kantree").factory("cardModal", [
  "$uibModal",
  "$rootScope",
  "$location",
  "$timeout",
  "projectPage",
  "$compile",
  "$q",
  function($uibModal, $rootScope, $location, $timeout2, projectPage, $compile, $q) {
    const cardViewTemplate = `<card-view card="card" show-archived="showArchived" parent-selector="parentSelector"
      show-dock="dockable" docked="docked" on-dock-toggle="$toggleDock()" show-close="true"
      load-related="loadRelated" on-close="$close(preventLocationChange)"></card-view>`;
    return {
      current: null,
      currentLocationHash: null,
      currentModalInstance: null,
      isDockable: function() {
        return jquery_default("#card-modal-host").length > 0;
      },
      toggleDocked: function(docked) {
        docked = docked === void 0 ? !this.isDocked() : docked;
        jsonLocalStorage.setItem("card-modal-docked", docked);
        return docked;
      },
      isDocked: function() {
        return jsonLocalStorage.getItem("card-modal-docked") || false;
      },
      getDockWidth: function() {
        return jsonLocalStorage.getItem("card-modal-dock-width") || 700;
      },
      setDockWidth: function(value2) {
        jsonLocalStorage.setItem("card-modal-dock-width", value2);
      },
      openEmpty: function(parent, card, opts = {}) {
        return this.open(Object.assign(cardStore.createBaseCardObj(parent), card || {}), opts);
      },
      open: function(card, { parentSelector, loadRelated, showClose = true, showArchived, cssClass, forceUndock = false } = {}) {
        const cardInActiveProject = projectPage.isProjectActive(projectStore.tryGetForCard(card));
        if (this.current) {
          return this.close(cardInActiveProject, true).then(() => {
            this.current = null;
            return this.open(card, { parentSelector, loadRelated, showClose, showArchived, cssClass });
          });
        }
        var dockable = this.isDockable();
        var docked = forceUndock ? false : dockable && this.isDocked();
        var scope = $rootScope.$new();
        Object.assign(scope, { card, parentSelector, dockable, docked, loadRelated, showClose, showArchived });
        scope.$toggleDock = () => {
          this.close(true).then(() => {
            this.toggleDocked();
            this.current = null;
            this.open(card, { parentSelector, loadRelated, showClose, showArchived, cssClass });
          });
        };
        let promise;
        if (docked) {
          promise = this._openDock(scope);
        } else {
          promise = this._openModal(scope, cssClass);
        }
        this.current = card;
        if (cardInActiveProject) {
          this.currentLocationHash = card.ref;
          if (this.currentLocationHash != $location.hash()) {
            updateLocationHash(this.currentLocationHash);
            updateSubtitle("#" + card.ref + " " + card.title);
          }
        }
        if (projectPage.isActive && isAuthenticated()) {
          projectPage.scopeManager.presenceManager?.updateCurrentLocation(card.title);
        }
        return promise;
      },
      close: function(preventLocationChange, keepDockOpen) {
        var d3 = $q.defer();
        if (this.current && this.closeCallback) {
          this.closeCallback(d3, preventLocationChange, keepDockOpen);
        } else {
          d3.resolve();
        }
        return d3.promise;
      },
      _onClose: function(preventLocationChange) {
        if (!preventLocationChange) {
          updateLocationHash("");
          clearSubtitle();
        }
        if (projectPage.isActive && isAuthenticated()) {
          projectPage.scopeManager.presenceManager?.updateCurrentLocation();
        }
        this.closeCallback = null;
        this.current = null;
        this.currentModalInstance = null;
        this.currentLocationHash = null;
      },
      _openModal: function(scope, cssClass) {
        this.currentModalInstance = $uibModal.open({
          template: cardViewTemplate,
          windowClass: "card-modal" + (cssClass ? " " + cssClass : ""),
          scope,
          backdrop: !isScreensizeXS()
        });
        this.closeCallback = (deferred, preventLocationChange) => {
          this.currentModalInstance.close([deferred, preventLocationChange]);
        };
        const closed = (deferred, preventLocationChange) => {
          scope.$destroy();
          this._onClose(preventLocationChange);
          if (deferred) {
            deferred.resolve();
          }
        };
        return this.currentModalInstance.result.then(function(data2) {
          if (angular_default.isArray(data2)) {
            closed(data2[0], data2[1]);
          } else {
            closed(null, data2);
          }
        }, () => closed());
      },
      _openDock: function(scope, host) {
        var view;
        const closeDefer = $q.defer();
        if (!host) {
          host = jquery_default("#card-modal-host");
          if (!host.length) {
            throw new Error("Missing #card-modal-host");
          }
        }
        this.closeCallback = (deferred, preventLocationChange, keepDockOpen) => {
          scope.$destroy();
          view.remove();
          if (!keepDockOpen) {
            host.removeClass("open");
          }
          this._onClose(preventLocationChange);
          deferred.resolve();
        };
        scope.$close = (preventLocationChange) => $timeout2(() => {
          this.close(preventLocationChange).then(() => closeDefer.resolve());
        });
        view = $compile(cardViewTemplate)(scope);
        $timeout2(() => {
          host.append(view).addClass("open");
          if (host.hasClass("resizable") && !this.current) {
            host.css("width", this.getDockWidth());
          }
        });
        return closeDefer.promise;
      },
      load: function(id, modalOptions, supressError) {
        if (isConnected()) {
          return $q.when(
            loadCard(id, { ignoreErrorHandlers: true }),
            (card) => this.open(card, { loadRelated: true, ...modalOptions }),
            () => {
              if (!supressError) {
                errorDialog(_4("Card not found"), _4("The card does not exist"));
              }
            }
          );
        } else {
          if (cardStore.exists(id)) {
            return this.open(cardStore.get(id), { loadRelated: true, ...modalOptions });
          }
        }
      },
      loadByRef: function(project, ref, modalOptions, supressError) {
        if (isConnected()) {
          return $q.when(
            loadCardByRef(project, ref, { ignoreErrorHandlers: true }),
            (card2) => this.open(card2, { loadRelated: true, ...modalOptions }),
            () => {
              if (!supressError) {
                errorDialog(_4("Card not found"), _4("The card #{ref} does not exist in this workspace", { ref }));
              }
            }
          );
        } else {
          var card = cardStore.scopedByProject(project).query({ ref })?.[0];
          if (card) {
            return this.open(card, { loadRelated: true, ...modalOptions });
          }
        }
      },
      checkLocationHash: function(cb2, elseCb) {
        var hash = $location.hash();
        if (hash && (!this.current || hash != this.currentLocationHash)) {
          cb2.call(this, hash);
          return;
        } else if (!hash && this.current) {
          this.currentModalInstance.dismiss();
        }
        elseCb && elseCb(hash);
      }
    };
  }
]);

// public/app/modals/card-view/services/image-paste.js
angular_default.module("kantree").factory("imagePasteUtils", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    var acceptedFileTypes2 = ["image/gif", "image/png", "image/jpeg", "image/bmp"];
    function getImageFromPasteEvent2(event2, callback) {
      if (!event2.clipboardData || !event2.clipboardData.items || !event2.clipboardData.items.length) {
        return;
      }
      var imageBlob = getImage2(event2.clipboardData.items);
      if (imageBlob) {
        callback && callback(imageBlob);
        return imageBlob;
      }
    }
    function getImage2(items) {
      if (window.Clipboard || window.ClipboardEvent) {
        for (var i3 = 0; i3 < items.length; i3++) {
          if (acceptedFileTypes2.indexOf(items[i3].type) !== -1) {
            var blob = items[i3].getAsFile() || items[i3].webkitGetAsEntry();
            if (blob) {
              return blob;
            }
          }
        }
      }
    }
    function isFileData2(dataTransfer) {
      if (!dataTransfer) {
        return false;
      }
      return dataTransfer.types.length === 1 && dataTransfer.types[0] === "Files";
    }
    return {
      isFileData: isFileData2,
      getImageFromPasteEvent: getImageFromPasteEvent2,
      openModal: function(card, imageFile, callback) {
        var scope = $rootScope.$new();
        scope.card = card;
        scope.project = projectStore.getForCard(card);
        scope.imageFile = imageFile;
        var instance = $uibModal.open({
          templateUrl: "/static/app/modals/card-view/templates/image-paste-modal.html",
          windowClass: "image-paste-modal",
          controller: "imagePasteModalCtrl",
          scope
        });
        scope.$on("connectivityChanged", function(event2, connected) {
          if (!connected) {
            instance.dismiss();
          }
        });
        instance.result.then(function(result2) {
          callback && callback(result2);
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("imagePasteModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  "$document",
  function($scope2, $uibModalInstance, $q, $document) {
    injectI18nHelpersIntoScope($scope2);
    $scope2.uploading = false;
    function getSrcFromFile(file) {
      return (window.URL || window.webkitURL).createObjectURL(file);
    }
    function getDefaultPasteOptions(options2, defaultOpt) {
      if (defaultOpt) {
        var selected = options2.find(function(opt) {
          return opt.id === defaultOpt.id;
        });
        if (selected) {
          return selected;
        }
      }
      if (options2.length > 1 && canCreateComment($scope2.project)) {
        return options2[1];
      }
      return options2[0];
    }
    var commentOptions = {
      name: _4("In a new comment"),
      id: -1
    };
    function buildOptions() {
      var options2 = [];
      var model = getCardCompositeModel($scope2.card, false);
      var availableAttrs = model.attributes.filter(function(attr) {
        return attr.type === "files" && canEditAttribute($scope2.project, attr);
      });
      if (canCreateComment($scope2.project)) {
        options2.push(commentOptions);
      }
      return options2.concat(availableAttrs);
    }
    cardModelStore.$watchAll($scope2, function() {
      $scope2.pasteOptions = buildOptions();
      $scope2.pasteOptionSelected = getDefaultPasteOptions($scope2.pasteOptions, $scope2.pasteOptionSelected || null);
    });
    $scope2.$watch("imageFile", function() {
      $scope2.imageSrc = getSrcFromFile($scope2.imageFile);
    });
    function checkImageAvailability(image2) {
      let element2 = $document[0].createElement("img");
      element2.src = image2.url;
      return new Promise((resolve2, reject2) => {
        const retryInterval = 200;
        const retryDecay = 1.2;
        var retryAttempts = -1;
        function tryLoad() {
          retryAttempts++;
          if (retryAttempts > 15) {
            element2 = null;
            return reject2();
          }
          jquery_default(element2).attr("src", image2.url + "?" + (/* @__PURE__ */ new Date()).getTime()).each(function() {
            if (this.complete) jquery_default(this).trigger("load");
          });
        }
        jquery_default(element2).on("load", () => {
          element2 = null;
          resolve2();
        }).on("error", () => setTimeout(tryLoad, retryInterval * Math.pow(retryDecay, retryAttempts)));
        tryLoad();
      });
    }
    var errorHandler = function() {
      $scope2.uploading = false;
      errorDialog(_4("An error ocurred while uploading your file"));
    };
    var successHandler = async function(image2) {
      try {
        await checkImageAvailability(image2);
        $uibModalInstance.close({
          option: $scope2.pasteOptionSelected,
          image: image2
        });
        $scope2.uploading = false;
      } catch (r3) {
        errorHandler();
        throw r3;
      }
    };
    $scope2.paste = function() {
      $scope2.uploading = true;
      if ($scope2.pasteOptionSelected.id === -1) {
        upload({
          url: api_default.project_files.upload_file.url({ project_id: this.card.project_id }),
          data: { files: $scope2.imageFile },
          arrayKey: ""
        }).then((r3) => successHandler(r3.data[0]), errorHandler);
      } else {
        $q.when(appendFilesToCardAttribute(
          $scope2.card,
          $scope2.pasteOptionSelected.id,
          $scope2.imageFile,
          null,
          false
        ), (attr) => successHandler(attr.value[attr.value.length - 1]), errorHandler);
      }
    };
  }
]);

// public/app/modals/card-view/services/view-theme.js
angular_default.module("kantree").service("cardViewTheme", class extends AngularClass {
  static $inject = ["stylesheetManager"];
  createFromProjectColor(color) {
    color = tinycolor.mix(color, "#fff", 80);
    return this.create(color);
  }
  create(color) {
    const themeName2 = "card-view-theme-" + tinycolor(color).toHex();
    this.$stylesheetManager.createTheme(
      themeName2,
      tinycolor(color).toHexString(),
      "/static/app/modals/card-view/templates/view.css.html"
    );
    return themeName2;
  }
  remove(color) {
    const themeName2 = "card-view-theme-" + tinycolor(color).toHex();
    this.$stylesheetManager.remove(themeName2);
  }
});

// public/app/modals/demo-signup/demo-signup.js
angular_default.module("kantree").service("demoSignupModal", class extends AngularClass {
  static $inject = ["$uibModal", "$rootScope"];
  open(template3, demoName) {
    const scope = this.$rootScope.$new();
    scope.template = template3;
    scope.demoName = demoName;
    return this.$uibModal.open({
      template: `<demo-signup-modal template="template" demo-name="{{demoName}}" on-cancel="$dismiss()"></demo-signup-modal>`,
      windowClass: "demo-signup-modal",
      scope
    });
  }
});
angular_default.module("kantree").component("demoSignupModal", {
  templateUrl: "/static/app/modals/demo-signup/demo-signup-modal.html",
  bindings: {
    template: "<",
    demoName: "@",
    onCancel: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$http"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    signup() {
      const params = new URLSearchParams();
      params.set("email", this.email);
      params.set("create_project_from", this.template.id);
      params.set("utm_medium", this.demoName);
      let org2 = this.email.split("@")[1].split(".").slice(-2, -1)[0];
      if (["gmail", "hotmail"].includes(org2)) {
        org2 = _4("{name}'s team", { name: this.email.split("@")[0] });
      }
      params.set("create_org", org2);
      let invite = new URL(document.location).searchParams.get("demo_invite");
      if (invite) {
        params.set("demo_invite", invite);
      }
      this.loading = true;
      this.$http({
        url: "/signup/demo",
        method: "POST",
        data: params.toString(),
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        transformRequest: null
      }).then((r3) => {
        if (r3.data.success) {
          if (r3.data.redirect_url) {
            document.location.href = r3.data.redirect_url;
          } else {
            document.location.reload();
          }
        } else {
          errorDialog(r3.data.error);
        }
      });
    }
  }
});

// public/app/modals/file-select/file-select.js
angular_default.module("kantree").factory("fileSelectModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function() {
        const instance = $uibModal.open({
          templateUrl: "/static/app/modals/file-select/file-select-modal.html",
          windowClass: "file-select-modal"
        });
        return instance.result;
      }
    };
  }
]);

// public/app/modals/form-selector/modal.js
angular_default.module("kantree").service("requestFormSelectorModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(org2) {
    const instance = this.$uibModal.open({
      windowClass: "form-selector-modal",
      resolve: {
        org: () => org2
      },
      templateUrl: "/static/app/modals/form-selector/modal.html",
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $q.when(loadAllRequestFormsForOrg($scope2.$resolve.org), () => {
            let sections = {};
            requestFormStore.scopedByOrg($scope2.$resolve.org).query().forEach((form) => {
              const projectTitle = form.project_title || form.project?.title;
              if (!sections[projectTitle]) {
                sections[projectTitle] = [];
              }
              sections[projectTitle].push(form);
            });
            $scope2.sections = Object.keys(sections).sort().map((title) => {
              return {
                title,
                forms: sections[title].sort((a3, b3) => a3.name.localeCompare(b3.name.locale, { sensitivity: "base", ignorePunctuation: true, numeric: true }))
              };
            });
          });
        }
      ]
    });
    return instance.result;
  }
});

// public/app/modals/help/modal.js
angular_default.module("kantree").service("helpModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open() {
    const instance = this.$uibModal.open({
      windowClass: "help-modal",
      templateUrl: "/static/app/modals/help/modal.html",
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$scope", "hotkeys", "onboardingTour"];
        constructor(...args) {
          super(...args);
          injectI18nHelpersIntoScope(this.$scope);
          this.serverConfig = serverConfig;
          this.search = "";
          this.links = getLocalizedUrls();
          this.ticket_url = getTicketUrl();
          this.demo_url = getLocalizedUrl("demo");
          this.help_site_url = null;
          if (serverConfig.help_site_url) {
            this.help_site_url = getLocalizedConfigLink(serverConfig.help_site_url);
          }
        }
        doSearch() {
          if (this.search) {
            window.open(this.links.search + "?q=" + encodeURIComponent(this.search));
          }
        }
        showKeyboardShortcuts() {
          this.$hotkeys.toggleCheatSheet();
        }
        showWorkspaceTour() {
          this.$onboardingTour.start();
        }
      }
    });
    return instance.result;
  }
});

// public/app/modals/icalendar/icalendar.js
angular_default.module("kantree").factory("iCalendarModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(urlPromise) {
        var scope = $rootScope.$new();
        scope.urlPromise = urlPromise;
        var instance = $uibModal.open({
          templateUrl: "/static/app/modals/icalendar/icalendar-modal.html",
          windowClass: "icalendar-feed-modal",
          controller: "iCalendarModalCtrl",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("iCalendarModalCtrl", [
  "$scope",
  "$q",
  function($scope2, $q) {
    $q.resolve($scope2.urlPromise).then((url2) => {
      $scope2.url = url2;
    });
  }
]);

// public/app/modals/org-settings/change-plan-modal.js
angular_default.module("kantree").service("changeBillingPlanModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(account, newPlan, newPeriod) {
    const instance = this.$uibModal.open({
      windowClass: "change-billing-plan-modal",
      component: "changeBillingPlanModal",
      resolve: {
        account: () => account,
        newPlan: () => newPlan,
        newPeriod: () => newPeriod
      }
    });
    return instance.result;
  }
});
angular_default.module("kantree").component("changeBillingPlanModal", {
  templateUrl: "/static/app/modals/org-settings/templates/change-plan-modal.html",
  bindings: {
    "resolve": "<",
    "close": "&",
    "dismiss": "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.account = this.resolve.account;
      this.coupon = null;
      this.$q.when(api_default.pricing.get_pricing.get({ currency: this.account.currency }), (pricing) => {
        this.pricing = pricing;
        this.plan = pricing.plans.find((p4) => p4.name === this.resolve.newPlan);
        this.downgrading = (this.plan.flags || []).length < this.account.flags.length;
        let amount = this.account.next_period_seat_count * this.plan.amounts[this.resolve.newPeriod];
        if (this.resolve.newPeriod === "yearly") {
          amount = amount * 12;
        }
        this.amount = pricing.price_format.replace("%s", amount);
      });
    }
    confirm() {
      this.submitting = true;
      this.$q.when(api_default.billing.update_account.put({
        account_id: this.account.id,
        plan: this.resolve.newPlan,
        period: this.resolve.newPeriod,
        coupon: this.coupon || null
      }, { ignoreErrorHandlers: true }), () => {
        document.location.reload();
      }, (r3) => {
        this.submitting = false;
        if (r3.status === 400) {
          r3.json().then((data2) => errorDialog(data2.error));
        } else {
          errorDialog(_4("An error occured while changing your plan, please contact support"));
        }
      });
    }
  }
});

// public/app/services/stripe.js
var loadStripe = singleton(function() {
  return new Promise((resolve2, reject2) => {
    if (typeof window.Stripe === "undefined") {
      script_default(["https://js.stripe.com/v3/#.js"], () => {
        resolve2(window.Stripe);
      });
    } else {
      resolve2(window.Stripe);
    }
  });
});
var getStripeInstance = singleton(function() {
  return loadStripe().then((Stripe) => Stripe(serverConfig.stripe_publishable_key));
});

// public/app/modals/org-settings/components/billing-form.js
angular_default.module("kantree").component("billingForm", {
  templateUrl: "/static/app/modals/org-settings/templates/billing-form.html",
  bindings: {
    account: "<?",
    showPlanSelector: "<?",
    paymentMethodRequired: "<?",
    amount: "<?",
    onSubmit: "&",
    onCancel: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.paymentType = "card";
      this.plan = "team2024";
      this.period = "monthly";
      this.coupon = "";
      this.company = "";
      this.EUVATNumber = "";
      this.billingDetails = {
        // stripe format
        name: "",
        email: "",
        phone: "",
        address: {
          line1: "",
          line2: "",
          city: "",
          postal_code: "",
          state: "",
          country: "US"
        }
      };
      if (this.account) {
        this.plan = this.account.plan || "team2024";
        this.period = this.account.plan_period || "monthly";
        this.company = this.account.company;
        this.EUVATNumber = this.account.eu_vat_number;
        this.billingDetails = {
          name: this.account.billing_name,
          email: this.account.billing_email,
          phone: this.account.billing_phone,
          address: {
            line1: this.account.billing_address_line1,
            line2: this.account.billing_address_line2,
            city: this.account.billing_address_city,
            postal_code: this.account.billing_address_zip,
            state: this.account.billing_address_state,
            country: this.account.billing_address_country || "US"
          }
        };
      }
      const EUCountries = [
        "AT",
        "BE",
        "BG",
        "DE",
        "CY",
        "CZ",
        "DK",
        "EE",
        "ES",
        "FI",
        "FR",
        "GR",
        "HR",
        "HU",
        "IE",
        "IT",
        "LT",
        "LV",
        "LU",
        "MT",
        "NL",
        "PL",
        "PT",
        "RO",
        "SE",
        "SI",
        "SK"
      ];
      this.refreshVAT = debounce2(() => {
        this.isEUCountry = EUCountries.includes(this.billingDetails.address.country);
        if (this.isEUCountry) {
          this.EUVATInfo = null;
          this.$q.when(api_default.eu_vat.check.post({
            country_code: this.billingDetails.address.country,
            vat_number: this.EUVATNumber,
            amount: this.amount
          }), (info) => {
            this.EUVATInfo = info;
          });
        } else {
          this.paymentType = "card";
        }
      }, 200);
      this.refreshVAT.immediate();
    }
    selectPlan(plan, period, pricing) {
      this.plan = plan.name;
      this.period = period;
      this.amount = plan.amounts[period];
      this.currencySymbol = pricing.symbol;
      this.refreshVAT();
    }
    onFormSubmit() {
      this.submitting = true;
      let emptyPaymentMethod, paymentMethodData = {}, confirmMethod;
      if (this.paymentType === "card") {
        emptyPaymentMethod = this.emptyCardElement;
        paymentMethodData["card"] = this.cardElement;
        confirmMethod = "confirmCardSetup";
      } else if (this.paymentType === "sepa_debit") {
        emptyPaymentMethod = this.emptyIbanElement;
        paymentMethodData["sepa_debit"] = this.ibanElement;
        confirmMethod = "confirmSepaDebitSetup";
      }
      let q;
      if (emptyPaymentMethod) {
        if (!this.account || this.paymentMethodRequired) {
          errorDialog(_4("You must provide a payment method"));
          this.submitting = false;
          return;
        }
        q = Promise.resolve(null);
      } else {
        let billingDetails = angular_default.copy(this.billingDetails);
        if (!billingDetails.phone) {
          delete billingDetails.phone;
        }
        q = api_default.billing.create_setup_intent.post().then((intent2) => {
          return getStripeInstance().then((stripe) => {
            return stripe[confirmMethod](intent2.client_secret, {
              payment_method: Object.assign({ billing_details: billingDetails }, paymentMethodData)
            }).then((result2) => {
              if (result2.error) {
                return Promise.reject(result2.error.message);
              }
              return result2.setupIntent.payment_method;
            });
          });
        });
      }
      this.$q.when(q).then((paymentMethod) => {
        this.onSubmit({
          $plan: this.plan,
          $period: this.period,
          $billingDetails: {
            company: this.company,
            billing_name: this.billingDetails.name,
            billing_email: this.billingDetails.email,
            billing_phone: this.billingDetails.phone,
            billing_address_line1: this.billingDetails.address.line1,
            billing_address_line2: this.billingDetails.address.line2,
            billing_address_city: this.billingDetails.address.city,
            billing_address_zip: this.billingDetails.address.postal_code,
            billing_address_state: this.billingDetails.address.state,
            billing_address_country: this.billingDetails.address.country,
            eu_vat_number: this.EUVATNumber
          },
          $paymentMethod: paymentMethod,
          $coupon: this.coupon,
          $callback: () => {
            this.submitting = false;
          }
        });
      }).catch((r3) => {
        errorDialog(r3);
        this.submitting = false;
      });
    }
    $postLink() {
      this.stripeLoaded = false;
      getStripeInstance().then((stripe) => {
        this.stripeLoaded = true;
        const elements = stripe.elements();
        this.emptyCardElement = true;
        this.cardElement = elements.create("card");
        this.cardElement.mount(this.$element.find(".stripe-element-card .form-control")[0]);
        this.cardElement.addEventListener("change", (e3) => {
          this.emptyCardElement = e3.empty;
          this.$scope.$applyAsync(() => {
            this.cardElementError = e3.error ? e3.error.message : "";
          });
        });
        this.emptyIbanElement = true;
        this.ibanElement = elements.create("iban", { supportedCountries: ["SEPA"] });
        this.ibanElement.mount(this.$element.find(".stripe-element-iban .form-control")[0]);
        this.ibanElement.addEventListener("change", (e3) => {
          this.emptyIbanElement = e3.empty;
          this.$scope.$applyAsync(() => {
            this.ibanElementError = e3.error ? e3.error.message : "";
          });
        });
      });
    }
  }
});

// public/app/modals/org-settings/components/billing-panel.js
angular_default.module("kantree").component("billingPanel", {
  templateUrl: "/static/app/modals/org-settings/templates/billing-panel.html",
  bindings: {
    account: "<",
    org: "<",
    onDelete: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$element", "$timeout", "manageBillingSeatsModal", "changeBillingPlanModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.currentUser = currentUser2;
      this.paymentsEnabled = serverConfig.payments_enabled;
      this.remoteBilling = typeof KANTREE_MOBILE_REMOTE_BILLING !== "undefined" && KANTREE_MOBILE_REMOTE_BILLING;
      this.account.current_period_start_formatted = formatDate(this.account.current_period_start, "LL");
      this.account.current_period_end_formatted = formatDate(this.account.current_period_end, "LL");
      this.account.last_invoice_at_formatted = formatDate(this.account.last_invoice_at, "LL");
      this.adminAccount = angular_default.copy(this.account);
      this.showForm = false;
      this.canDisableAutoAdjust = this.account.seat_count >= this.org.nb_members + this.org.nb_invites;
      this.ngOrgUsers = this.account.auto_adjust_seat_count ? this.org.nb_members : this.org.nb_members + this.org.nb_invites;
      this.forceShowForm = this.account.payment_method === "stripe" && !this.account.has_stripe_payment_method && !this.remoteBilling;
      if (this.forceShowForm) {
        this.toggleForm(true);
      }
      if (this.account.payment_method === "stripe") {
        this.$q.when(api_default.billing.list_invoices.get({ account_id: this.account.id }, { ignoreErrorHandlers: true }), (invoices) => {
          this.invoices = invoices;
        });
        if (this.account.has_stripe_payment_method) {
          this.$q.when(api_default.billing.get_next_invoice_amount.get({ account_id: this.account.id }, { ignoreErrorHandlers: true }), (amount) => {
            this.nextInvoiceAmount = amount.currency === "EUR" ? amount.amount + "\u20AC" : "$" + amount.amount;
          });
        }
      }
      if (this.account.status === "trialing") {
        this.trialFormatParams = { date: moment_default(this.account.trial_ends_at).format("ll"), days: moment_default(this.account.trial_ends_at).diff(moment_default(), "days") };
      }
    }
    toggleAutoAdjustSeatCount() {
      this.$q.when(api_default.billing.update_account.put({
        account_id: this.account.id,
        auto_adjust_seat_count: this.account.auto_adjust_seat_count
      }), (account) => {
        Object.assign(this.account, account);
        this.ngOrgUsers = this.account.auto_adjust_seat_count ? this.org.nb_members : this.org.nb_members + this.org.nb_invites;
      });
    }
    openManageSeatCountModal() {
      this.$manageBillingSeatsModal.open(this.account);
    }
    switchPlan(plan, period) {
      if (this.account.has_stripe_payment_method) {
        this.$changeBillingPlanModal.open(this.account, plan.name, period);
      } else {
        this.$q.when(api_default.billing.update_account.put({
          account_id: this.account.id,
          plan: plan.name,
          period
        }), (account) => {
          Object.assign(this.account, account);
          document.location.reload();
        });
      }
    }
    cancelSubscription() {
      confirmDeleteDialog2(
        null,
        _4("Suspending your subscription will take effect at the end of the current billing period. You won't be charged anymore and your organization will become locked. Your workspaces will remain accessible in read-only mode for 30 days"),
        _4("Suspend")
      ).then(() => {
        this.$q.when(api_default.billing.cancel_account.post({ account_id: this.account.id }), (account) => {
          Object.assign(this.account, account);
        });
      });
    }
    continueSubscription() {
      this.$q.when(api_default.billing.revert_cancel_account.delete({ account_id: this.account.id }), (account) => {
        Object.assign(this.account, account);
      });
    }
    performStripePaymentMethodAction() {
      getStripeInstance().then((stripe) => {
        stripe.confirmCardPayment(this.account.stripe_payment_intent_secret).then((result2) => {
          if (result2.error) {
            errorDialog(result2.error);
          } else {
            document.location.reload();
          }
        });
      });
    }
    toggleForm(show) {
      this.showForm = typeof show !== "undefined" ? show : !this.showForm;
    }
    onFormSubmit(plan, period, billingDetails, paymentMethod, coupon, callback) {
      const onSuccess = (account) => {
        account.stripe_payment_method_requires_action = false;
        account.status = "active";
        Object.assign(this.account, account);
        this.toggleForm();
        document.location.reload();
      };
      this.$q.when(api_default.billing.update_account.put(Object.assign({
        account_id: this.account.id,
        plan,
        period,
        stripe_payment_method: paymentMethod ? paymentMethod : null,
        coupon
      }, billingDetails)), (account) => {
        if (account.stripe_payment_method_requires_action) {
          getStripeInstance().then((stripe) => {
            this.$q.when(stripe.confirmCardPayment(account.stripe_payment_intent_secret), (result2) => {
              if (result2.error) {
                errorDialog(result2.error);
              } else {
                onSuccess(account);
              }
            });
          });
        } else {
          onSuccess(account);
        }
      }, autoCatchAsRequestErrorDialog([400])).catch(callback);
    }
    updateFromAdmin() {
      let data2 = {
        account_id: this.account.id,
        payment_method: this.adminAccount.payment_method,
        status: this.adminAccount.status
      };
      if (data2.payment_method && data2.payment_method != "stripe") {
        Object.assign(data2, {
          seat_count: this.adminAccount.seat_count,
          expire_at: this.adminAccount.current_period_end
        });
      } else if (data2.status === "trialing") {
        data2["expire_at"] = this.adminAccount.current_period_end;
      }
      this.$q.when(api_default.admin.update_billing_account.post(data2), (account) => {
        Object.assign(this.account, account);
        successDialog(_4("Successfully updated"));
      });
    }
    createStripeCustomer() {
      this.$q.when(api_default.admin.create_stripe_customer.post({ account_id: this.account.id }), (account) => {
        Object.assign(this.account, account);
      });
    }
    forceUpdateStripe() {
      this.$q.when(api_default.admin.force_update_stripe.post({ account_id: this.account.id }), () => {
        infoDialog(_4("Stripe has been updated"));
      });
    }
    forceUpdateFromStripe() {
      this.$q.when(api_default.admin.force_update_from_stripe.post({ account_id: this.account.id }), () => {
        document.location.reload();
      });
    }
    async chargeStripeInvoiceItems() {
      await confirmDialog();
      await api_default.admin.charge_stripe_invoice_items.post({ account_id: this.account.id });
      document.location.reload();
    }
    deleteAccount() {
      confirmDialog().then(() => {
        this.$q.when(api_default.admin.delete_billing_account.delete({ account_id: this.account.id }), () => {
          this.onDelete();
        });
      });
    }
  }
});

// public/app/modals/org-settings/components/plan-selector.js
angular_default.module("kantree").component("billingPlanSelector", {
  templateUrl: "/static/app/modals/org-settings/templates/plan-selector.html",
  bindings: {
    selectedPlan: "<?plan",
    selectedPeriod: "<?period",
    currency: "<?",
    readonly: "<?",
    trialing: "<?",
    onLoad: "&",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$element", "$sce"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.plans = [];
      this.period = this.selectedPeriod || "monthly";
      this.$q.when(api_default.pricing.get_pricing.get({ currency: this.currency }), (pricing) => {
        this.pricing = pricing;
        this.plans = pricing.plans;
        if (this.selectedPlan) {
          let plan = this.plans.find((p4) => p4.name === this.selectedPlan);
          if (plan) {
            this.onLoad({ $plan: plan, $period: this.period, $pricing: this.pricing });
          }
        }
      });
      this.planFilter = (plan) => {
        return plan.periods.includes(this.period);
      };
      this.questionsLabel = this.$sce.trustAsHtml(_4(
        'Questions ? Contact us at <a href="mailto:sales@kantree.io">sales@kantree.io</a> or <a href="{0}" target="_blank">book a call</a>',
        getLocalizedUrl("sales")
      ));
    }
    selectPeriod(period) {
      this.period = period;
    }
    select(plan) {
      if (!this.readonly) {
        this.onChange({ $plan: plan, $period: this.period, $pricing: this.pricing });
      }
    }
    isCurrent(plan) {
      return this.selectedPlan === plan.name && this.selectedPeriod === this.period;
    }
  }
});

// public/app/modals/org-settings/manage-seats-modal.js
angular_default.module("kantree").service("manageBillingSeatsModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(account) {
    const instance = this.$uibModal.open({
      windowClass: "manage-billing-seats-modal",
      component: "manageBillingSeatsModal",
      resolve: {
        account: () => account
      }
    });
    return instance.result;
  }
});
angular_default.module("kantree").component("manageBillingSeatsModal", {
  templateUrl: "/static/app/modals/org-settings/templates/manage-seats-modal.html",
  bindings: {
    "resolve": "<",
    "close": "&",
    "dismiss": "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.account = this.resolve.account;
      this.currentScheduledRemoval = this.account.seat_count - this.account.next_period_seat_count;
      this.reset();
      this.$q.when(api_default.billing.get_seat_price.get({ account_id: this.account.id }), (pricing) => {
        this.pricing = pricing;
        this.computeDelta();
      });
    }
    computeDelta() {
      this.delta = this.seatCount - this.account.next_period_seat_count;
      this.scheduledRemoval = this.currentScheduledRemoval;
      if (this.delta > 0 && this.scheduledRemoval > 0) {
        this.scheduledRemoval -= this.delta;
        if (this.scheduledRemoval < 0) {
          this.delta = Math.abs(this.scheduledRemoval);
        } else {
          this.delta = 0;
        }
      }
      this.amount = this.pricing.format.replace("%s", this.pricing.prorated * this.delta);
      this.subscriptionTotal = this.pricing.format.replace("%s", this.pricing.full * this.seatCount);
    }
    reset() {
      if (this.submitting) return;
      this.seatCount = this.account.next_period_seat_count;
      this.scheduledRemoval = this.currentScheduledRemoval;
      this.delta = 0;
    }
    cancelRemoval() {
      if (this.submitting) return;
      this.seatCount += this.scheduledRemoval;
      this.computeDelta();
    }
    submit() {
      this.submitting = true;
      this.$q.when(api_default.billing.update_account.put({
        account_id: this.account.id,
        seat_count: this.seatCount
      }, { ignoreErrorHandlers: true }), (account) => {
        this.submitting = false;
        Object.assign(this.account, account);
        this.close();
      }, (r3) => {
        this.submitting = false;
        if (r3.status === 400) {
          r3.json().then((data2) => errorDialog(data2.error));
        } else {
          errorDialog(_4("An error occured while updating the seat count, please contact support"));
        }
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/ai.js
angular_default.module("kantree").component("orgSettingsAiPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/ai.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.aiProviders = [];
      this.aiAssistantServerEnabled = serverConfig.ai_assistant;
      this.$q.when(api_default.config.list_ai_providers.get(), (providers) => {
        this.aiProviders = providers;
        this.aiProvider = providers[0];
      });
      this.onAiProviderChange();
      this.$q.when(api_default.organizations.get_ai_config.get({ org_id: this.org.id }), (info) => this.refresh(info));
    }
    onAiEnabledChange() {
      if (this.aiEnabled === "$custom" && !this.data.ai_provider) {
        this.data.ai_provider = this.aiProviders[0];
      }
    }
    onAiProviderChange() {
      if (!this.aiProvider) {
        this.data = {
          ai_provider: this.aiProvider,
          ai_base_url: "",
          ai_model: "",
          ai_api_key: ""
        };
      } else {
        this.data = {
          ai_provider: this.aiProvider,
          ai_base_url: null,
          ai_model: null,
          ai_api_key: ""
        };
      }
    }
    submit() {
      if (!this.aiEnabled) {
        this.$q.when(api_default.organizations.update_ai_config.post({
          org_id: this.org.id,
          ai_enabled: false
        }), (info) => this.refresh(info, true));
      } else if (this.aiEnabled === "$global") {
        this.$q.when(api_default.organizations.update_ai_config.post({
          org_id: this.org.id,
          ai_enabled: null
        }), (info) => this.refresh(info, true));
      } else if (this.aiEnabled === "$custom") {
        this.$q.when(api_default.organizations.update_ai_config.post({
          org_id: this.org.id,
          ai_enabled: true,
          ...this.data,
          ai_assistant: this.aiAssistantEnabled
        }), (info) => this.refresh(info, true));
      }
    }
    refresh(info, refreshAppContext) {
      this.data = {
        ai_provider: info.ai_provider,
        ai_base_url: info.ai_base_url,
        ai_model: info.ai_model,
        ai_api_key: info.ai_api_key
      };
      this.hasGlobalConfig = serverConfig.has_global_ai_config;
      if (info.ai_enabled) {
        this.aiEnabled = "$custom";
        this.aiProvider = this.aiProviders.find((p4) => p4 === info.ai_provider);
      } else if (info.ai_enabled === null && this.hasGlobalConfig) {
        this.aiEnabled = "$global";
      } else {
        this.aiEnabled = null;
      }
      this.aiAssistantEnabled = info.ai_assistant;
      if (refreshAppContext) {
        fetchAppContextData();
      }
    }
    onAiAssistantEnabledChange() {
      this.$q.when(api_default.organizations.update_ai_config.post({
        org_id: this.org.id,
        ai_assistant: this.aiAssistantEnabled
      }), (info) => fetchAppContextData());
    }
  }
});

// public/app/modals/org-settings/panels/components/admin.js
angular_default.module("kantree").component("orgSettingsAdminPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/admin.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "orgExportModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.locked = this.org.locked;
      this.forceLock = this.org.billing && this.org.billing.locked;
      this.canCreateProjects = this.org.can_create_projects;
      this.canCreatePrivateProjects = this.org.can_create_private_projects;
      this.preventDeletion = this.org.prevent_deletion;
      this.maxAllowedUsers = this.org.max_allowed_users;
      this.featureFlags = this.org.feature_flags;
      if (this.org.billing) {
        this.featureFlags = this.featureFlags.filter((f3) => !this.org.billing.flags.include(f3));
      }
      this.savingStatus = "init";
    }
    update() {
      let data2 = {
        org_id: this.org.id,
        can_create_projects: this.canCreateProjects,
        can_create_private_projects: this.canCreatePrivateProjects,
        prevent_deletion: this.preventDeletion,
        max_allowed_users: this.maxAllowedUsers,
        feature_flags: this.featureFlags
      };
      if (!this.forceLock) {
        data2["locked"] = this.locked;
      }
      this.$q.when(api_default.admin.update_org.put(data2), (org2) => {
        this.savingStatus = "saved";
        orgStore.update(this.org, org2);
      });
    }
    export() {
      this.$orgExportModal.open(this.org);
    }
  }
});

// public/app/modals/org-settings/panels/components/appearance.js
angular_default.module("kantree").component("orgSettingsAppearancePanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/appearance.html",
  bindings: {
    org: "<",
    close: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.hasCustomColor = !!themeState.color;
      this.uploadBannerUrl = api_default.organizations.update_org.url({ org_id: this.org.id });
    }
    setColor(color) {
      this.$q.when(updateOrg(this.org, { color }), () => {
        this.org.color = color;
        setPageColor(color);
        onAppContextUpdate();
      });
    }
    setBanner(data2) {
      if (data2) {
        orgStore.update(this.org, data2);
      } else {
        this.$q.when(updateOrg(this.org, { image_cover: null }), () => {
          this.org.image_cover_url = null;
        });
      }
    }
    setBannerColor(color) {
      this.$q.when(updateOrg(this.org, { cover_color: color }), () => {
        this.org.cover_color = color;
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/billing.js
angular_default.module("kantree").component("orgSettingsBillingPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/billing.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.currentUser = currentUser2;
      this.isOwner = isOrgOwner(this.org);
      this.showOwnerAlert = isOrgAdmin(this.org) && !this.isOwner;
      if (this.org.billing && (this.isOwner || currentUser2.is_kantree_admin)) {
        this.loading = true;
        this.$q.when(api_default.billing.get_account.get({ account_id: this.org.billing.id }), (account) => {
          this.account = account;
          this.loading = false;
        });
      }
      this.availableCurrencies = ["EUR", "USD"];
      this.currency = "EUR";
    }
    createBillingAccount() {
      this.$q.when(api_default.admin.create_org_billing_account.post({ org_id: this.org.id, currency: this.currency }), (account) => {
        this.account = account;
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/group-types.js
angular_default.module("kantree").component("orgSettingsGroupTypesPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/group-types.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.groupTypes = [];
      this.locked = isOrgLocked(this.org);
      this.isOrgManager = isOrgManager(this.org);
      const store2 = cardGroupTypeStore.scoped({
        owner: query_exports.objMatch({
          id: this.org.id,
          type: "org"
        }),
        is_project_specific: false,
        attribute_id: query_exports.isUndefined()
      });
      store2.$watchAll(this.$scope, () => {
        this.groupTypes = store2.query({}, { sortBy: "name" });
      });
      ensureConnectivity(() => {
        this.$q.digest(loadAllGroupTypesForOrg(this.org));
      });
    }
    select(gt) {
      if (gt) {
        this.selected = angular_default.copy(gt);
      } else {
        this.selected = null;
      }
    }
    create() {
      this.select({
        scope: "project",
        one_group_per_card: true
      });
    }
    delete(gt) {
      confirmDeleteDialog2(
        _4("Are you sure?"),
        _4("All groups of this type will be removed.")
      ).then(() => this.$q.digest(deleteGroupType(gt)));
    }
    save() {
      this.$q.when(saveGroupType(this.selected, this.org), () => {
        this.selected = null;
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/integrations.js
angular_default.module("kantree").component("orgSettingsIntegrationsPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/integrations.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.locked = isOrgLocked(this.org);
      this.isOrgAdmin = isOrgAdmin(this.org);
      this.integrations = [];
      this.orgIntegrations = [];
      this.availableIntegrations = [];
      const store2 = integrationStore.scopedByOrg(this.org);
      store2.$watchAll(this.$scope, () => {
        this.orgIntegrations = store2.query();
        this.refresh();
      });
      this.$q.digest(loadAllIntegrations(this.org));
      this.$q.when(loadAllIntegrationType(), () => {
        this.availableIntegrations = integrationTypeStore.query({ activable: true }, { sortBy: "title" });
        this.refresh();
      });
    }
    refresh() {
      this.integrations = this.orgIntegrations.slice(0);
      this.availableIntegrations.forEach((inte) => {
        if (this.orgIntegrations.filter((i3) => i3.name === inte.name).length === 0) {
          this.integrations.push(inte);
        }
      });
    }
    activate(integration) {
      this.$q.digest(activateOrgIntegration(this.org, integration));
    }
    reauthorize(integration) {
      this.$q.digest(reauthorizeOrgIntegration(this.org, integration));
    }
    async remove(integration) {
      await confirmDeleteDialog2();
      this.$q.digest(removeOrgIntegration(integration));
    }
  }
});

// public/app/modals/org-settings/panels/components/models.js
angular_default.module("kantree").component("orgSettingsModelsPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/models.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.locked = isOrgLocked(this.org);
      this.isOrgManager = isOrgManager(this.org);
      this.editable = this.isOrgManager && !this.locked;
      this.selectedModel = null;
      this.selectedAttributes = null;
      this.models = [];
      const store2 = cardModelStore.scopedByOrg(this.org).scoped({ is_project_specific: false });
      store2.$watchAll(this.$scope, () => {
        this.models = store2.query({}, { sortBy: "id" });
      });
      ensureConnectivity(() => {
        this.$q.digest(loadAllModelsForOrg(this.org));
      });
    }
    modelsFilter(model) {
      return !model.base_model_type;
    }
    selectAttributes(attributes) {
      this.selectedModel = null;
      this.selectedAttributes = [];
      angular_default.copy(attributes, this.selectedAttributes);
    }
    selectModel(model) {
      this.selectedAttributes = null;
      this.selectedModel = {};
      angular_default.copy(model, this.selectedModel);
    }
    duplicate(model) {
      this.$q.digest(duplicateModel(model));
    }
    create() {
      this.selectModel({
        attributes: []
      });
    }
    delete(model) {
      confirmDeleteDialog2(
        _4("Are you sure?"),
        _4("The type will be removed from all cards using it and associated data will be lost.")
      ).then(() => this.$q.digest(deleteModel(model)));
    }
    saveModel() {
      this.selectedModel.attributes.forEach((attr) => {
        if (attr.opts && Object.keys(attr.opts).length) {
          attr.options = attr.opts;
        }
      });
      if (typeof this.selectedModel.id === "undefined") {
        this.$q.when(createModelInOrg(this.selectedModel, this.org), () => {
          this.selectedModel = null;
        });
      } else {
        this.$q.when(updateModel(this.selectedModel), () => {
          this.selectedModel = null;
        });
      }
    }
    saveAttributes() {
      this.selectedAttributes.forEach((attr) => {
        if (attr.opts && Object.keys(attr.opts).length) {
          attr.options = attr.opts;
        }
      });
      this.$q.when(api_default.organizations.update_attributes.put({
        org_id: this.org.id,
        attributes: this.selectedAttributes
      }), (attributes) => {
        this.org = orgStore.update(this.org, { attributes });
        this.selectedAttributes = null;
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/options.js
angular_default.module("kantree").component("orgSettingsOptionsPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/options.html",
  bindings: {
    org: "<",
    close: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$state", "Upload", "processingStatus"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.currentUser = currentUser2;
      this.name = this.org.name;
      this.description = this.org.description;
      this.uploadLogolUrl = api_default.organizations.update_org.url({ org_id: this.org.id });
      this.canCustomizeOrg = hasFeatureFlag(this.org, "org_hub");
    }
    update() {
      this.updateStatus = this.$processingStatus.saver(() => {
        const data2 = { name: this.name };
        if (this.canCustomizeOrg) {
          data2["description"] = this.description;
        }
        return this.$q.digest(updateOrg(this.org, data2));
      });
    }
    setLogo(data2) {
      if (data2) {
        orgStore.update(this.org, data2);
      } else {
        this.$q.when(updateOrg(this.org, { logo: null }), () => {
          this.org.logo_url = null;
        });
      }
    }
    exportOrg() {
      api_default.organizations.export.post({
        org_id: this.org.id,
        bundle_files: false,
        include_user_orgs: false
      }).then(() => {
        infoDialog(
          _4("You will receive an email with a link to download your exported file"),
          _4("Export in progress")
        );
      });
    }
    deleteOrg() {
      confirmDeleteDialog2(
        _4("Are you sure you want to delete this organization ?"),
        _4("This will permanently delete all workspaces belonging to it.")
      ).then(() => {
        this.$q.when(deleteOrg(this.org), () => {
          this.$state.go("/");
          this.close();
        });
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/pii.js
angular_default.module("kantree").component("orgSettingsPiiPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/pii.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.formats = exportFormats.filter((f3) => f3.tabular);
      this.format = this.formats[0];
      this.privacyURL = serverConfig.privacy_url;
      this.dataProcessingAgreementURL = serverConfig.data_processing_agreement_url;
    }
    generate(identifier) {
      api_default.organizations.export_pii_report.post({
        org_id: this.org.id,
        format: this.format.name,
        identifier: identifier || null
      }).then((id) => waitForAsyncDownload(id));
    }
    search() {
      this.$q.when(api_default.organizations.get_pii_data.get({ org_id: this.org.id, identifier: this.piiSearch || null }), (rows) => {
        this.rows = rows;
        this.cols = [];
        this.rows.forEach((row) => {
          Object.entries(row).forEach(([key2, value2]) => {
            if (key2 !== "#" && !this.cols.includes(key2)) {
              this.cols.push(key2);
            }
          });
        });
        this.cols.sort();
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/project-attrs.js
angular_default.module("kantree").component("orgSettingsProjectAttrsPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/project-attrs.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isConnected = isConnected;
      cardModelStore.$watch(this.$scope, cardModelStore.getTopLevelCardModel(this.org, null).id, (model) => {
        this.topLevelCardModel = {
          model,
          attributes: new ModelAttributeGroup(null, model, model.attributes)
        };
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/roles.js
angular_default.module("kantree").component("orgSettingsRolesPanel", {
  templateUrl: "/static/app/modals/org-settings/panels/templates/roles.html",
  bindings: {
    org: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.locked = isOrgLocked(this.org);
      this.isOrgAdmin = isOrgAdmin(this.org);
      this.editable = this.isOrgAdmin && !this.locked;
      this.selected = null;
      this.roles = [];
      this.defaultOrgMemberRole = null;
      roleStore.clear();
      const store2 = roleStore.scopedByOrg(this.org);
      store2.$watchAll(this.$scope, () => {
        this.roles = store2.query({}, { sortBy: "id" });
      });
      this.$q.digest(loadAllRolesForOrg(this.org));
    }
    selectRole(role) {
      this.selected = {};
      angular_default.copy(role, this.selected);
    }
    create() {
      this.selectRole({ permissions: [] });
    }
    async delete(role) {
      await confirmDeleteDialog2(
        _4("Are you sure?"),
        _4("All workspaces using this role will be affected.")
      );
      this.$q.digest(deleteRole(role));
    }
    duplicateRole(role) {
      this.$q.digest(duplicateRole(role));
    }
    saveRole() {
      if (typeof this.selected.id === "undefined") {
        this.$q.when(createRoleInOrg(this.selected, this.org), () => {
          this.selected = null;
        });
      } else {
        this.$q.when(updateRole(this.selected), () => {
          this.selected = null;
        });
      }
    }
    defineDefaultRole(role) {
      this.$q.when(api_default.organizations.update_org.put({
        org_id: this.org.id,
        default_org_member_role_id: role.id
      }), (org2) => {
        Object.assign(this.org, org2);
      });
    }
  }
});

// public/app/modals/org-settings/panels/components/templates.js
angular_default.module("kantree").component("orgSettingsTemplatesPanel", {
  template: `
    <div class="org-project-list">
      <form ng-if="::!$ctrl.locked">
        <button type="button" class="btn btn-default btn-ghost me-2 mb-2"
          ng-click="$ctrl.dismiss();$ctrl.createTemplate()">{{::$ctrl.createBtnLabel}}</button>
      </form>
      <div class="project-tile-list">
        <div class="empty" ng-if="$ctrl.templates.length === 0">{{::$ctrl.emptyMessage}}</div>
        <div ng-if="$ctrl.templates.length > 0" ng-repeat="template in $ctrl.templates">
          <solidjs-component component="$ctrl.ProjectTile" project="template"
            use-simple-anchor-tag="true"></solidjs-component>
        </div>
      </div>
    </div>
  `,
  bindings: {
    org: "<",
    dismiss: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "projectCreatorModal"];
    $onInit() {
      this.ProjectTile = ProjectTile;
      this.createBtnLabel = _4("New template");
      this.emptyMessage = _4("No templates have been created yet");
      this.locked = isOrgLocked(this.org);
      this.templates = [];
      ensureConnectivity(() => {
        this.$q.when(loadProjectTemplatesForOrg(this.org), () => {
          this.templates = projectStore.scopedByOrg(this.org).query({ is_template: true, is_archived: false }, { sortBy: "name" });
        });
      });
    }
    createTemplate() {
      this.$projectCreatorModal.open({ org: this.org, createTemplate: true });
    }
  }
});

// public/app/modals/org-settings/settings.js
angular_default.module("kantree").service("orgSettingsModal", class extends AngularClass {
  static $inject = ["$rootScope", "$uibModal", "$injector"];
  open(org2, panel) {
    if (this.current == org2) {
      return;
    }
    if (this.instance) {
      this.instance.close();
    }
    this.current = org2;
    this.instance = this.$uibModal.open({
      component: "orgSettingsModal",
      windowClass: "org-settings-modal",
      resolve: {
        org: () => org2,
        currentPanel: () => panel
      }
    });
    const closed = () => {
      this.instance = null;
      this.current = null;
    };
    this.instance.result.then(closed, closed);
    return this.instance.result;
  }
});
angular_default.module("kantree").component("orgSettingsModal", {
  templateUrl: "/static/app/modals/org-settings/templates/settings.html",
  bindings: {
    close: "&",
    dismiss: "&",
    resolve: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.org = this.resolve.org;
      this.panels = orgSettingsPanels.filter((panel) => {
        if (typeof panel.enabled !== "undefined" && !panel.enabled(this.org) || panel.featureFlag && !panel.upgradeForFeatureFlag && !hasFeatureFlag(this.org, panel.featureFlag)) {
          return false;
        }
        if (this.resolve.currentPanel === panel.name) {
          this.openPanel(panel);
        }
        return true;
      });
      if (!this.currentPanel && this.panels.length) {
        this.currentPanel = this.panels[0];
      }
    }
    openPanel(panel) {
      if (panel.featureFlag && !hasFeatureFlag(this.org, panel.featureFlag)) {
        return false;
      }
      this.currentPanel = panel;
      return true;
    }
  }
});

// public/app/modals/preview-pdf/pdf.js
angular_default.module("kantree").service("pdfModal", class extends AngularClass {
  static $inject = ["$uibModal", "$rootScope"];
  open(url2) {
    const scope = this.$rootScope.$new();
    scope.url = prependBaseUrl(`/static/pdfjs/viewer-v3.html?file=${encodeURIComponent(url2)}`);
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/modals/preview-pdf/pdf-modal.html",
      windowClass: "file-preview-modal pdf-preview-modal",
      scope
    });
    instance.result.finally(() => scope.$destroy());
    return instance.result;
  }
});

// public/app/modals/preview-video/video.js
angular_default.module("kantree").service("videoModal", class extends AngularClass {
  static $inject = ["$uibModal", "$rootScope", "$sce"];
  open(url2, mimetype) {
    const scope = this.$rootScope.$new();
    scope.sources = [{ src: this.$sce.trustAsResourceUrl(url2), type: mimetype }];
    scope.theme = null;
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/modals/preview-video/video-modal.html",
      windowClass: "file-preview-modal video-preview-modal",
      scope
    });
    instance.result.finally(() => scope.$destroy());
    return instance.result;
  }
});

// public/app/modals/project-creator/component.js
angular_default.module("kantree").component("projectCreator", {
  templateUrl: "/static/app/modals/project-creator/creator.html",
  bindings: {
    "org": "<?",
    "team": "<?",
    "template": "<?",
    "importer": "<?",
    "defaultViewMode": "<?",
    "createTemplate": "<?",
    "createPortfolio": "<?",
    "projectTitle": "<?",
    "asModal": "<?",
    "onCreated": "&",
    "onCancelled": "&",
    "includeCards": "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$timeout", "$state"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.color = null;
      this.onlyStructure = this.includeCards === void 0 ? false : !this.includeCards;
      this.import = false;
      this.creating = false;
      this.sharingSettings = null;
      this.showSharingSettings = true;
      this.portfolioProjects = [];
      if (!this.projectTitle) {
        if (this.createTemplate) {
          this.projectTitle = _4("New template");
        } else if (this.createPortfolio) {
          this.projectTitle = _4("New portfolio");
        } else {
          this.projectTitle = _4("New workspace");
        }
      }
      if (!this.org && appContext.org && !currentUser2.can_create_projects) {
        this.org = appContext.org;
        if (this.org.permission < 2) {
          const teamSpec = appContext.teams.find((t3) => t3.org.id === this.org.id && t3.team && t3.canCreate);
          if (!this.team) {
            this.org = null;
          } else {
            this.team = teamSpec.team;
          }
        }
      }
      if (this.org && !currentUser2.is_kantree_admin && !isCurrentUserMemberOf(this.org, this.team)) {
        this.org = null;
      }
      this.buildTeamList();
      if (this.org) {
        this.selectedTeam = this.teams.find((spec) => spec.org.id === this.org.id && (!this.team && !spec.team || this.team && spec.team?.id === this.team.id));
      }
      if (!this.selectedTeam) {
        this.selectedTeam = this.teams[0];
      }
      this.selectTeam(this.selectedTeam);
      if (this.importer) {
        this.showCreateFromImport(this.importer === "1" ? null : this.importer);
      }
    }
    get isUserOrg() {
      return !this.org || this.org.type == "user";
    }
    get nameFormLabel() {
      if (this.createTemplate) return _4("Template name:");
      if (this.createPortfolio) return _4("Portfolio name:");
      return _4("Workspace name:");
    }
    get sharingSettingsFormLabel() {
      if (this.createPortfolio) return _4("Who can see & access this portfolio:");
      return _4("Who can see & access this workspace:");
    }
    get colorFormLabel() {
      if (this.createTemplate) return _4("Customize the color of your template:");
      if (this.createPortfolio) return _4("Customize the color of your portfolio:");
      return _4("Customize the color of your workspace:");
    }
    get createBtnLabel() {
      if (this.creating) return _4("Creating...");
      if (this.createTemplate) return _4("Create template");
      if (this.createPortfolio) return _4("Create portfolio");
      if (this.importer) return _4("Import");
      return _4("Create");
    }
    get title() {
      if (this.createTemplate) return _4("New template");
      if (this.template && this.template.id && !this.template.fromScratch) return _4("New workspace from a template");
      if (this.createPortfolio) return _4("New portfolio");
      if (this.import) return _4("Import");
      return _4("New workspace");
    }
    get _projectTitle() {
      if (this.projectTitle) return this.projectTitle;
    }
    get portfolioProjectIds() {
      return this.portfolioProjects?.map((p4) => p4.id);
    }
    buildTeamList() {
      this.teams = [];
      if (currentUser2.can_create_projects && !this.createTemplate && !this.createPortfolio) {
        const myProjectsName = !currentUser2.can_create_private_projects ? _4("Personal public workspaces") : _4("Personal workspaces");
        this.teams.push({
          name: myProjectsName,
          org: {
            id: 0,
            name: myProjectsName,
            type: "user"
          }
        });
      }
      if (!this.isUserOrg && currentUser2.is_kantree_admin && !isCurrentUserMemberOf(this.org, this.team, false)) {
        this.teams = [{
          org: this.org,
          name: this.org.name,
          uuid: this.org.id
        }];
        if (this.team && !this.createTemplate) {
          this.teams.push({
            org: this.org,
            team: this.team,
            name: `${this.org.name} / ${this.team.name}`,
            uuid: `org${this.org.id}-team${this.team.id}`
          });
        }
      } else {
        this.teams.push(...appContext.teams.filter((t3) => t3.canCreate && (!this.createTemplate || !t3.team)));
      }
    }
    selectTeam(spec) {
      if (!spec) {
        infoDialog(this.createTemplate ? _4("Templates can only be created by organization managers") : _4("You do not have the rights to create workspaces"));
        this.onCancelled();
        return;
      }
      this.org = spec.org;
      this.team = spec.team || null;
      this.isOrgProject = !!this.org && !!this.org.id;
      if (this.isOrgProject && !currentUser2.is_kantree_admin && (!this.team && this.org.permission <= 1 || this.team && this.team.permission <= 1)) {
        this.$state.go("org.hub", { slug: this.org.slug });
      }
      if (!this.isOrgProject) {
        this.isForcedPublic = !currentUser2.can_create_private_projects;
      }
    }
    showCreateFromImport(forceImporter) {
      this.import = true;
      this.forceImporter = forceImporter;
      this.showSharingSettings = forceImporter === "spreadsheet";
    }
    selectTemplate(template3) {
      this.onlyStructure = false;
      this.template = template3;
    }
    onImportReady(data2) {
      if (!data2) {
        this.importData = null;
        return;
      }
      this.importData = Object.assign({}, this.sharingSettings, {
        title: data2.name === "spreadsheet" ? this.projectTitle : null,
        org_id: this.isOrgProject ? this.org.id : null,
        team_id: this.isOrgProject && this.team ? this.team.id : null,
        color: this.color
      }, data2);
    }
    create() {
      if (!this.org) {
        return;
      }
      this.creating = true;
      let req;
      const templateId = this.template && this.template.id ? this.template.id : null;
      if (this.import) {
        if (this.importData.file) {
          req = upload({
            url: api_default.importers.import_project.url(this.importData),
            data: this.importData,
            arrayKey: ""
          });
        } else {
          req = api_default.importers.import_project.post(this.importData);
        }
      } else if (this.isOrgProject) {
        if (this.createTemplate) {
          req = api_default.organizations.create_template.post({
            org_id: this.org.id,
            title: this.projectTitle,
            is_public: this.sharingSettings.is_public,
            template_id: templateId,
            include_cards: !this.onlyStructure,
            color: this.color
          });
        } else if (this.createPortfolio) {
          req = api_default.organizations.create_portfolio.post({
            org_id: this.org.id,
            team_id: this.team ? this.team.id : null,
            title: this.projectTitle,
            team_members_can_observe: this.sharingSettings.team_members_can_observe,
            team_members_can_autojoin: this.sharingSettings.team_members_can_autojoin,
            portfolio_project_ids: this.portfolioProjectIds,
            color: this.color
          });
        } else {
          req = api_default.organizations.create_project.post({
            org_id: this.org.id,
            team_id: this.team ? this.team.id : null,
            title: this.projectTitle,
            is_public: this.sharingSettings.is_public,
            public_role_id: this.sharingSettings.public_role_id,
            team_members_can_observe: this.sharingSettings.team_members_can_observe,
            team_members_can_autojoin: this.sharingSettings.team_members_can_autojoin,
            default_org_member_role_id: this.sharingSettings.default_org_member_role_id,
            template_id: templateId,
            default_view_mode: this.defaultViewMode,
            color: this.color,
            include_cards: !this.onlyStructure
          });
        }
      } else {
        const func = this.createTemplate ? api_default.user.create_template : api_default.user.create_project;
        req = func.post({
          title: this.projectTitle,
          is_public: this.sharingSettings.is_public,
          public_role_id: this.sharingSettings.public_role_id,
          template_id: templateId,
          default_view_mode: this.defaultViewMode,
          include_cards: !this.onlyStructure,
          color: this.color
        });
      }
      this.$q.when(req).then((project) => {
        this.$timeout(() => {
          projectStore.upsertAfterCreation(project);
          if (this.defaultViewMode) {
            setCurrentUser("preferred_default_view", this.defaultViewMode);
          }
          fetchAppContextData();
          this.onCreated({ $project: project });
          this.creating = false;
        }, this.template ? 1e3 : 0);
      }).catch(() => {
        this.creating = false;
        return this.$q.reject();
      });
    }
    cancel() {
      this.onCancelled({ $org: this.org, $wasTemplate: this.createTemplate });
    }
  }
});

// public/app/modals/project-creator/modal.js
angular_default.module("kantree").service("projectCreatorModal", class extends AngularClass {
  static $inject = ["$uibModal", "$rootScope"];
  open({ org: org2, team, template: template3, importer, defaultViewMode, createTemplate, createPortfolio } = {}) {
    const scope = this.$rootScope.$new();
    Object.assign(scope, arguments[0]);
    scope.projectTitle = template3 && !template3.is_template && template3.id ? template3.title : null;
    if (template3 && !org2 && isCurrentUserOwnerOf(template3)) {
      scope.org = template3.owner;
    }
    scope.asModal = true;
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/modals/project-creator/modal.html",
      windowClass: "create-project-from-tpl-modal",
      controller: "projectCreatorModalCtrl",
      scope
    });
    instance.result.finally(() => {
      scope.$destroy();
    });
    return instance.result;
  }
});
angular_default.module("kantree").controller("projectCreatorModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$state",
  function($scope2, $uibModalInstance, $state) {
    $scope2.projectCreated = function(project) {
      $state.go(project.is_portfolio ? "portfolio" : "project", { projectId: project.slug });
      $uibModalInstance.dismiss();
    };
  }
]);

// public/app/modals/project-selector/modal.js
angular_default.module("kantree").service("orgProjectSelectorModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(options2) {
    const instance = this.$uibModal.open({
      windowClass: "project-selector-modal",
      resolve: {
        options: () => options2
      },
      templateUrl: "/static/app/modals/project-selector/modal.html",
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.options = $scope2.$resolve.options || {};
          $scope2.projects = $scope2.options.selectedProjects || [];
          $scope2.directoryBreadcrumb = $scope2.options.team ? `${$scope2.options.org.name}/${$scope2.options.team.name}` : `${$scope2.options.org.name}`;
          $scope2.select = function(projects) {
            $scope2.projects = projects;
          };
          $scope2.add = function() {
            $scope2.$close($scope2.options.isMultiple ? $scope2.projects : $scope2.projects[0]);
          };
        }
      ]
    });
    return instance.result;
  }
});

// public/app/modals/project-settings/panels/ai.js
angular_default.module("kantree").directive("projectSettingsAiPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/ai.html",
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        $q.when(api_default.projects.get_ai_config.get({ project_id: $scope2.project.id }), (config3) => {
          $scope2.customContext = config3.ai_context;
        });
        $scope2.save = () => {
          $q.digest(api_default.projects.update_ai_config.post({
            project_id: $scope2.project.id,
            ai_context: $scope2.customContext
          }));
        };
      }
    ]
  };
});

// public/app/modals/project-settings/panels/appearance.js
angular_default.module("kantree").directive("projectSettingsAppearancePanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/appearance.html",
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        $scope2.bgcolor = $scope2.project.color;
        cardStore.$watch($scope2, $scope2.project.top_level_card, (card) => {
          $scope2.image_cover_url = card.image_cover_url;
        });
        $scope2.setBgColor = function(color) {
          $q.when(updateProject($scope2.project, { color: color || "" }), () => {
            $scope2.bgcolor = color;
          });
        };
        $scope2.resetImageCover = function() {
          $q.when(updateCard($scope2.project.top_level_card, { image_cover_url: null }), (card) => {
            card = cardStore.update(card);
          });
        };
        $scope2.uploadImageUrl = api_default.projects.update_project.url({ project_id: $scope2.project.id });
        $scope2.setImageBg = function(data2) {
          if (data2) {
            projectStore.update($scope2.project, data2);
            if ($scope2.project.top_level_card.image_cover_url) {
              cardStore.update($scope2.project.top_level_card, { image_cover_url: null });
            }
          } else {
            $q.digest(updateProject($scope2.project, { image_cover: null }));
          }
        };
      }
    ]
  };
});

// public/app/modals/project-settings/panels/group-types.js
angular_default.module("kantree").directive("projectSettingsGroupTypesPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/group-types.html",
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        $scope2.currentUser = currentUser2;
        $scope2.selected = null;
        $scope2.projGroupTypes = [];
        $scope2.orgGroupTypes = [];
        $scope2.hasOrgContexts = false;
        $scope2.isOwnerOfProjectOwner = isCurrentUserOwnerOf($scope2.project);
        if ($scope2.project.owner.type === "org") {
          var org2 = orgStore.query({ id: $scope2.project.owner.id })?.[0];
          $scope2.hasOrgContexts = typeof org2.no_org_context !== "undefined" && !org2.no_org_context;
        }
        if ($scope2.project?.owner?.type === "org" && $scope2.isOwnerOfProjectOwner) {
          $q.digest(loadAllGroupTypesForProjectOwner($scope2.project));
        }
        const scopedCardGroupTypeStore = cardGroupTypeStore.scopedByOrg($scope2.project.owner);
        scopedCardGroupTypeStore.$watchAll($scope2, function() {
          $scope2.projGroupTypes = [];
          $scope2.orgGroupTypes = [];
          scopedCardGroupTypeStore.query({}, { sortBy: "name" }).forEach((gt) => {
            if (gt.is_project_specific) {
              if (gt.used_by.indexOf($scope2.project.id) !== -1) {
                $scope2.projGroupTypes.push(gt);
              }
            } else {
              $scope2.orgGroupTypes.push(gt);
            }
          });
        });
        $scope2.canManageGrouptypes = function() {
          return isAllowedInProject($scope2.project, "card_group_type", ["CREATE", "EDIT", "DELETE"], $scope2.selected ? $scope2.selected.id : null) && !$scope2.project.is_archived;
        };
        $scope2.select = function(groupType) {
          if (groupType) {
            $scope2.selected = angular_default.copy(groupType);
          } else {
            $scope2.selected = null;
          }
        };
        $scope2.create = function() {
          $scope2.select({
            scope: "project",
            one_group_per_card: true,
            is_project_specific: true
          });
        };
        $scope2.toggleGrouptype = function(groupType, isChecked) {
          if (!isChecked) {
            groupType.used_by = groupType.used_by.filter((id) => id !== $scope2.project.id);
            $q.when(disableOrDeleteGroupType(groupType, $scope2.project)).catch(() => {
              groupType.used_by.push($scope2.project.id);
            });
          } else {
            $q.digest(enableGroupType(groupType, $scope2.project));
          }
        };
        $scope2.save = function() {
          $q.when(saveGroupType($scope2.selected, null, $scope2.project), () => {
            $scope2.selected = null;
          });
        };
      }
    ]
  };
});

// public/app/modals/project-settings/panels/members.js
angular_default.module("kantree").directive("projectSettingsMembersPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/members.html",
    controller: [
      "$scope",
      "orgAddMembersToModal",
      "$q",
      function($scope2, orgAddMembersToModal, $q) {
        $scope2.MemberList = MemberList;
        $scope2.sideLoaded = false;
        $scope2.isOrgProject = $scope2.project.owner.type === "org";
        $scope2.settingsSaveEnabled = false;
        $scope2.org = $scope2.isOrgProject ? orgStore.tryGet($scope2.project.owner.id) : null;
        $scope2.team = $scope2.project.team ? teamStore.tryGet($scope2.project.team.id) : null;
        $scope2.isUserOrgMember = isCurrentUserMemberOf($scope2.project.owner, $scope2.team);
        $scope2.typeLabel = getProjectTypeLabel($scope2.project);
        function updateDefaultRoles(settings) {
          $q.when(updateProjectAccess($scope2.project, settings));
        }
        function updateRoleMenu() {
          $scope2.defaultRoleMenu = { config: [
            { subheader: _4("Default role for organization members:") },
            ...$scope2.roles.org.map((r3) => ({
              label: r3.name,
              action: () => updateDefaultRoles({ default_org_member_role_id: r3.id }),
              selected: () => r3.id === $scope2.project.default_org_member_role_id
            }))
          ] };
          if ($scope2.project.is_public) {
            $scope2.defaultRoleMenu.config.push(
              { label: "--" },
              { subheader: _4("Default role for guests:") },
              ...$scope2.roles.guests.map((r3) => ({
                label: r3.name,
                action: () => updateDefaultRoles({ public_role_id: r3.id }),
                selected: () => r3.id === $scope2.project.public_role_id
              }))
            );
          }
        }
        if (!$scope2.project.is_template) {
          $q.digest(loadAllProjectMembers($scope2.project, true, { ignoreErrorHandlers: true }));
          projectMemberStore.scopedByProject($scope2.project).$watchAll($scope2, () => {
            $scope2.members = Object.assign({}, $scope2.members, projectMemberStore.getAll($scope2.project));
          });
          const scopedRoleStore = roleStore.scopedByOrg($scope2.project.owner);
          scopedRoleStore.$watchAll($scope2, () => {
            const roles = $scope2.project.is_portfolio ? roleStore.getAllForPortfolio($scope2.project) : roleStore.getAllForProject($scope2.project);
            $scope2.roles = Object.assign({}, roles);
            updateRoleMenu();
          });
          projectStore.$watch($scope2, $scope2.project, () => {
            $scope2.canManageMembers = canManageMembers($scope2.project) && !$scope2.project.is_archived && !$scope2.project.is_template;
            updateRoleMenu();
            if ($scope2.canManageMembers && !$scope2.sideLoaded) {
              $q.digest(loadAllRolesForProject($scope2.project));
              $q.when(listProjectInvites($scope2.project), (invites) => {
                $scope2.invites = invites;
              });
              $scope2.sideLoaded = true;
            }
          });
        }
        $scope2.openAddMemberModal = function() {
          orgAddMembersToModal.open(
            $scope2.org,
            $scope2.team,
            _4(
              "Add members to {projectType}",
              { projectType: $scope2.typeLabel }
            ),
            (member) => $scope2.members.org.find((m3) => m3.user.id === member.user.id),
            (member) => $scope2.addOrgMember(member.user),
            () => $scope2.isOrgProject && ($scope2.team ? isTeamAdmin($scope2.team) : $scope2.org && isOrgAdmin($scope2.org))
          ).catch((r3) => {
            if (r3 === "navigate") {
              $scope2.$uibModalInstance.dismiss();
            }
          });
        };
        $scope2.defaultRoleName = function() {
          return $scope2.roles?.org.find((r3) => r3.id === $scope2.project.default_org_member_role_id)?.name;
        };
        $scope2.addOrgMember = function(user) {
          $q.when(addProjectMember($scope2.project, user));
        };
        $scope2.invite = function(emailOrUsernames, message, callbacks2) {
          $q.when(addProjectInvites($scope2.project, emailOrUsernames, message), (invites) => {
            callbacks2?.success?.();
            for (const invite of invites) {
              if (invite.email) {
                $scope2.invites = $scope2.invites.concat(invite);
              }
            }
          }, (r3) => callbacks2?.error?.(r3));
        };
        $scope2.resendInvite = (invite) => {
          $q.digest(resendProjectInvite($scope2.project, invite));
        };
        $scope2.removeInvite = (invite) => {
          $q.when(removeProjectInvite($scope2.project, invite), () => {
            $scope2.invites = $scope2.invites.filter((i3) => i3.id !== invite.id);
          });
        };
        $scope2.removeMember = (member) => {
          $q.digest(removeProjectMember($scope2.project, member));
        };
        $scope2.updateMemberRole = (member, roleId) => {
          $q.digest(updateProjectMember($scope2.project, member, roleId));
        };
      }
    ]
  };
});

// public/app/modals/project-settings/panels/models.js
angular_default.module("kantree").directive("projectSettingsModelsPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/models.html",
    controller: [
      "$scope",
      "$timeout",
      "cardModal",
      "$q",
      function($scope2, $timeout2, cardModal, $q) {
        $scope2.currentUser = currentUser2;
        $scope2.models = [];
        $scope2.enabledModels = [];
        $scope2.projModels = [];
        $scope2.orgModels = [];
        $scope2.availableDefaultModels = [];
        $scope2.defaultChildCardModelId = $scope2.project.top_level_card.default_child_card_model_id;
        $scope2.isOwnerOfProjectOwner = isCurrentUserOwnerOf($scope2.project);
        $scope2.canCreateModel = function() {
          return canCreateCardModel($scope2.project) && !$scope2.project.is_archived;
        };
        $scope2.canManageProjectAttributes = function() {
          return canManageAttributes($scope2.project) && !$scope2.project.is_archived;
        };
        $scope2.canManageProjectOptions = function() {
          return canManageSettings($scope2.project) && !$scope2.project.is_archived;
        };
        $scope2.create = function() {
          inputDialog(_4("Card type name:")).then((name2) => {
            if (!name2) return;
            $q.digest(createModelInProject({ name: name2 }, $scope2.project));
          });
        };
        $scope2.toggleUseOrgAttributes = function() {
          var use3 = !$scope2.project.use_org_attributes;
          if (use3) {
            $q.all([
              loadAllGroupTypesForProject($scope2.project),
              loadAllAvailableGroupsForCard($scope2.project.top_level_card)
            ]);
            cardModelStore.upsertOrgModels($scope2.project.owner, $scope2.project);
          }
          $q.when(updateProject($scope2.project, { use_org_attributes: use3 }), () => {
            cardModelStore.upsertProjectModels($scope2.project);
          });
        };
        $scope2.editProjectAttributes = function() {
          cardModal.openEmpty($scope2.project.top_level_card, { title: _4("Example card") });
        };
        const scopedCardModelStore = cardModelStore.scopedByOrg($scope2.project.owner);
        scopedCardModelStore.$watchAll($scope2, function() {
          $scope2.models = scopedCardModelStore.query({}, { sortBy: "id" });
          $scope2.enabledModels = scopedCardModelStore.scopedByEnabled($scope2.project, true).scoped({ base_model_type: query_exports.isFalsy() }).query({}, { sortBy: "id" });
          $scope2.orgBaseAttributesFormatted = [];
          if ($scope2.project.owner.type === "org") {
            let orgBaseModel;
            try {
              orgBaseModel = cardModelStore.getOrgModel($scope2.project.owner, $scope2.project);
            } catch (e3) {
              if (e3 instanceof StoreNotFoundError) {
                orgBaseModel = null;
              } else {
                throw e3;
              }
            }
            if (orgBaseModel) {
              $scope2.orgBaseAttributesFormatted = (orgBaseModel.attributes || []).map(function(attr) {
                var attrType = attributeTypeRegistry.get(attr.type);
                return Object.assign({}, attr, {
                  typeIcon: attrType.icon,
                  typeTitle: attrType.title
                });
              });
            }
          }
          $scope2.projModels = [];
          $scope2.orgModels = [];
          $scope2.availableDefaultModels = [];
          $scope2.availableDefaultModels.push({
            id: null,
            name: _4("None")
          });
          $scope2.models.forEach(function(model) {
            if (model.is_project_specific) {
              if (model.used_by.indexOf($scope2.project.id) !== -1) {
                $scope2.projModels.push(model);
              }
            } else {
              $scope2.orgModels.push(model);
            }
            if (model.used_by.indexOf($scope2.project.id) !== -1) {
              $scope2.availableDefaultModels.push(model);
            }
            if ($scope2.panelArg && parseInt($scope2.panelArg, 10) === model.id) {
              $scope2.selectModel(model);
              $scope2.resetPanelArg();
            }
          });
        });
        $q.digest(loadAllEnabledModelsForProject($scope2.project));
        if ($scope2.project?.owner?.type === "org" && $scope2.isOwnerOfProjectOwner) {
          $q.digest(loadAllModelsForProjectOwner($scope2.project));
        }
        $scope2.defaultModelStatus = "init";
        $scope2.$watch("defaultChildCardModelId", (newValue, oldValue) => {
          if (typeof oldValue === "undefined" || oldValue === newValue) return;
          $scope2.defaultModelStatus = "updating";
          $timeout2(() => {
            $q.when(updateProject($scope2.project, { default_child_card_model_id: newValue }), () => {
              $scope2.defaultModelStatus = "saved";
            });
          }, 1e3, false);
        });
      }
    ]
  };
});
angular_default.module("kantree").directive("modelListItem", [
  function() {
    return {
      templateUrl: "/static/app/modals/project-settings/templates/model-list-item.html",
      restrict: "E",
      replace: true,
      scope: true,
      bindToController: {
        model: "<",
        project: "<",
        showDuplicate: "<?"
      },
      controllerAs: "$ctrl",
      controller: class extends AngularClass {
        static $inject = ["$scope", "$q", "cardModal"];
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.isOwnerOfProjectOwner = isCurrentUserOwnerOf(this.project);
        }
        $onChanges(changes) {
          if (changes.model || changes.project) {
            this.sharingMenu = this.getSharingModelMenu;
          }
        }
        get isOnlyUsedInThisProject() {
          return this.model.used_by && this.model.used_by.length === 1 && this.model.used_by.includes(this.project.id);
        }
        get canToggleModel() {
          return canCreateCardModel(this.project) && this.canDeleteModel;
        }
        get canCreateModel() {
          return canCreateCardModel(this.project);
        }
        get canEditModel() {
          return canEditCardModel(this.project, this.model ? this.model.id : null) && !this.project.is_archived;
        }
        get canDeleteModel() {
          return canDeleteCardModel(this.project, this.model ? this.model.id : null) && !this.project.is_archived;
        }
        get canShareModel() {
          return this.canEditModel && this.isOwnerOfProjectOwner && this.model.is_project_specific;
        }
        get isNotUsed() {
          return !this.model.used_by || this.model.used_by.length === 0;
        }
        get isUsedInOtherProjects() {
          return this.model.used_by && this.model.used_by.length === 1 && !this.model.used_by.includes(this.project.id) || this.model.used_by && this.model.used_by.length > 1;
        }
        get getSharingModelMenuItem() {
          const items = [];
          items.push({
            label: _4("Make it private for this workspace"),
            action: () => {
              this.makePrivate(this.model, this.project);
            }
          }, {
            desc: _4("It won't be available anymore for the other workspaces")
          });
          return items;
        }
        get getSharingModelMenu() {
          if (this.model.is_project_specific || this.isUsedInOtherProjects) {
            return null;
          }
          return {
            config: this.getSharingModelMenuItem
          };
        }
        edit() {
          this.$cardModal.openEmpty(this.project.top_level_card, { title: _4("Example card"), model_id: this.model.id }, { forceUndock: true });
        }
        share() {
          this.$q.digest(shareModel(this.model));
        }
        makePrivate() {
          this.$q.digest(makeModelPrivate(this.model, this.project));
        }
        duplicate() {
          this.$q.digest(duplicateModelInProject(this.model, this.project));
        }
        toggleModel(isChecked) {
          if (!isChecked) {
            this.model.used_by = this.model.used_by.filter((id) => id !== this.project.id);
            const buttonText = this.model.is_project_specific ? _4("Delete") : _4("Disable");
            confirmDeleteDialog2(
              _4("Are you sure?"),
              _4("This type will be removed from all cards using it and associated data will be lost"),
              buttonText
            ).then(() => {
              return this.$q.digest(disableOrDeleteModel(this.model, this.project));
            }).catch(() => {
              this.model.used_by.push(this.project.id);
            });
          } else {
            this.$q.digest(enableModelForProject(this.model, this.project));
          }
        }
      }
    };
  }
]);

// public/app/modals/project-settings/panels/options.js
angular_default.module("kantree").directive("projectSettingsOptionsPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/options.html",
    controller: [
      "$scope",
      "$state",
      "projectCreatorModal",
      "projectMoveModal",
      "cardSaveAsTplModal",
      "projectPage",
      "$q",
      function($scope2, $state, projectCreatorModal, projectMoveModal, cardSaveAsTplModal, projectPage, $q) {
        $scope2.title = $scope2.project.title;
        $scope2.bgcolor = $scope2.project.color;
        $scope2.send_emails = $scope2.project.send_emails;
        $scope2.locked_structure = $scope2.project.locked_structure;
        $scope2.canManageMembers = canManageMembers($scope2.project);
        $scope2.publishTemplate = $scope2.project.include_in_template_library;
        $scope2.templateDescription = $scope2.project.template_description;
        $scope2.templateLocale = $scope2.project.template_locale || "en";
        $scope2.templateTags = $scope2.project.template_tags || [];
        $scope2.isOrgProject = $scope2.project.owner.type === "org";
        $scope2.org = $scope2.project.owner.type === "user" ? $scope2.project.owner : orgStore.tryGet($scope2.project.owner.id) || $scope2.project.owner;
        $scope2.canEditOptions = !$scope2.project.is_archived && canManageSettings($scope2.project);
        $scope2.isManager = isCurrentUserManagerOf($scope2.org, $scope2.project.team);
        $scope2.canPublishTemplate = !$scope2.project.is_archived && !$scope2.project.is_portfolio && (currentUser2.is_kantree_admin || serverConfig.open_template_library);
        $scope2.availableLocales = availableLocales;
        $scope2.typeLabel = getProjectTypeLabel($scope2.project);
        $q.when(api_default.template_library.list_tags.get(), (tags2) => {
          $scope2.availableTags = tags2;
        });
        $scope2.rename = function(title) {
          $q.digest(updateProject($scope2.project, { title }));
          $scope2.titleChanged = false;
        };
        $scope2.setBgColor = function(color) {
          $q.when(updateProject($scope2.project, { color: color || "" }), () => {
            $scope2.bgcolor = color;
          });
        };
        $scope2.uploadImageUrl = api_default.projects.update_project.url({ project_id: $scope2.project.id });
        $scope2.setImageBg = function(data2) {
          if (data2) {
            projectStore.update($scope2.project, data2);
            if ($scope2.project.top_level_card.image_cover_url) {
              cardStore.update($scope2.project.top_level_card, { image_cover_url: null });
            }
          } else {
            $q.digest(updateProject($scope2.project, { image_cover: null }));
          }
        };
        $scope2.toggleNotificationEmails = function() {
          $q.digest(updateProject($scope2.project, { send_emails: $scope2.send_emails }));
        };
        $scope2.toggleLockedStructure = function() {
          $q.digest(updateProject($scope2.project, { locked_structure: $scope2.locked_structure }));
        };
        $scope2.gotoOrg = function() {
          $state.go("org.hub", { slug: $scope2.project.owner.slug });
          $scope2.$uibModalInstance.dismiss();
        };
        $scope2.archive = function() {
          confirmDeleteDialog2(_4("Are you sure you want to archive?"), null, _4("Archive")).then(() => {
            $q.digest(archiveProject($scope2.project));
          });
        };
        $scope2.restore = function() {
          $q.digest(restoreProject($scope2.project));
        };
        $scope2.delete = function() {
          confirmDeleteDialog2(
            _4("Are you sure you want to permanently delete this {projectType}?", { projectType: $scope2.typeLabel })
          ).then(() => {
            $q.when(deleteProject($scope2.project), () => {
              $scope2.$uibModalInstance?.dismiss();
              if (projectPage.isProjectActive($scope2.project)) {
                $state.go("/");
              }
            });
          });
        };
        $scope2.togglePublishTemplate = () => {
          if ($scope2.publishTemplate) {
            $q.when(confirmDialog({
              title: _4("Are you sure ?"),
              text: _4("Once published, it will become available to ALL users of Kantree")
            }), () => {
              $scope2.publishTemplate = true;
              $scope2.savePublishTemplate();
            }, () => {
              $scope2.publishTemplate = false;
            });
          } else {
            $scope2.savePublishTemplate();
          }
        };
        $scope2.savePublishTemplate = () => {
          $q.digest(updateProject($scope2.project, {
            include_in_template_library: $scope2.publishTemplate,
            template_description: $scope2.templateDescription,
            template_locale: $scope2.templateLocale,
            template_tags: $scope2.templateTags
          }));
        };
        $scope2.setTemplatePreviewMedia = function(data2) {
          if (data2) {
            projectStore.update($scope2.project, data2);
          } else {
            $q.digest(updateCard($scope2.project, { template_preview_media_url: null }));
          }
        };
        $scope2.uploadThumbnailUrl = api_default.cards.update.url({ card_id: $scope2.project.top_level_card_id });
        $scope2.setTemplateThumbnail = function(data2) {
          if (data2) {
            setTimeout(() => {
              cardStore.update($scope2.project.top_level_card, data2);
            }, 500);
          } else {
            $q.when(updateCard($scope2.project.top_level_card, { image_cover_url: null }), (card) => {
              card = cardStore.update(card);
            });
          }
        };
        cardStore.$watch($scope2, $scope2.project.top_level_card, (card) => {
          $scope2.image_cover_url = card.image_cover_url;
        });
        $scope2.savePublishTemplateDebounced = debounce2($scope2.savePublishTemplate, 1e3);
        $scope2.copyProject = () => {
          if (!isCurrentUserOwnerOf($scope2.project) || isCurrentUserPersonalOrg($scope2.project.owner)) {
            projectCreatorModal.open({ template: $scope2.project }).finally(() => $scope2.$uibModalInstance.dismiss());
          } else {
            $q.when(loadOrg($scope2.project.owner.id), (org2) => {
              projectCreatorModal.open({ org: org2, template: $scope2.project }).finally(() => $scope2.$uibModalInstance.dismiss());
            });
          }
        };
        $scope2.moveProject = () => {
          projectMoveModal.open($scope2.project).result.finally(() => $scope2.$uibModalInstance.dismiss());
        };
        $scope2.saveAsTemplate = () => {
          cardSaveAsTplModal.open($scope2.project.top_level_card);
        };
        $scope2.updateSharingSettings = function(settings, isFirst) {
          if (isFirst) return;
          if ($scope2.isOrgProject) {
            $q.digest(updateProjectAccess($scope2.project, settings));
          } else {
            $q.digest(updateProject($scope2.project, settings));
          }
        };
      }
    ]
  };
});

// public/app/modals/project-settings/panels/pii.js
angular_default.module("kantree").directive("projectSettingsPiiPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/pii.html",
    controller: [
      "$scope",
      "$q",
      "$timeout",
      function($scope2, $q, $timeout2) {
        $scope2.formats = exportFormats.filter(function(f3) {
          return f3.tabular;
        });
        $scope2.format = $scope2.formats[0];
        $scope2.attributes = cardModelStore.scopedByEnabled($scope2.project).getAttributesFromModels().filter(function(a3) {
          return a3.is_pii;
        });
        $scope2.canManageProjectOptions = canManageSettings($scope2.project);
        if ($scope2.project.pii_identifier_attribute_id) {
          $scope2.identifierAttributeId = $scope2.project.pii_identifier_attribute_id;
        }
        $scope2.identifierAttributeStatus = "init";
        $scope2.$watch("identifierAttributeId", (newValue, oldValue) => {
          if (typeof oldValue === "undefined" || oldValue === newValue) return;
          $scope2.identifierAttributeStatus = "updating";
          $timeout2(() => {
            $q.when(updateProject($scope2.project), { pii_identifier_attribute_id: newValue }, () => {
              $scope2.identifierAttributeStatus = "saved";
            });
          }, 1e3, false);
        });
        $scope2.generate = function() {
          api_default.projects.export_pii_report.post({ project_id: $scope2.project.id, format: $scope2.format.name }).then((id) => {
            waitForAsyncDownload(id);
          });
        };
      }
    ]
  };
});

// public/app/loaders/recurring-card.js
async function loadAllRecurringCardsForProject(project) {
  const preload = async (task) => {
    if (!cardStore.exists(task.template_id)) {
      await getOrLoadCard(task.template_id);
    }
    return task;
  };
  const tasks = await loadMany(recurringCardStore, api_default.project_recurring_cards.list_recurring_cards, { project_id: project.id }, {}, { preload });
  recurringCardStore.scopedByProject(project).removeAllNotMatching(tasks);
  return tasks;
}

// public/app/modals/project-settings/panels/recurring-cards.js
angular_default.module("kantree").directive("projectSettingsRecurringCardsPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/recurring-cards.html",
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.tasks = [];
        $scope2.loading = true;
        function buildImgName() {
          var locale = moment_default.locale();
          var baseName = "make-card-recurring";
          if (locale === "en") {
            return baseName;
          } else {
            return baseName + "_" + locale;
          }
        }
        $scope2.imgName = buildImgName();
        const scopedRecurringCardStore = recurringCardStore.scopedByProject($scope2.project);
        scopedRecurringCardStore.$watchAll($scope2, function() {
          $scope2.tasks = scopedRecurringCardStore.query();
        });
        $q.when(loadAllRecurringCardsForProject($scope2.project), () => {
          $scope2.loading = false;
        });
      }
    ]
  };
});

// public/app/modals/project-settings/panels/roles.js
angular_default.module("kantree").directive("projectSettingsRolesPanel", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/modals/project-settings/templates/roles.html",
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        $scope2.isOrgProject = $scope2.project.owner.type === "org";
        $scope2.isUserOrgMember = isCurrentUserMemberOf($scope2.project.owner, $scope2.project.team);
        $scope2.selectedRole = null;
        $scope2.canManageMembers = canManageMembers($scope2.project);
        $scope2.roles = [];
        const scopedRoleStore = roleStore.scopedByOrg($scope2.project.owner);
        scopedRoleStore.$watchAll($scope2, function() {
          $scope2.roles = scopedRoleStore.query();
        });
        $q.digest(loadAllRolesForProject($scope2.project));
        $scope2.selectRole = function(role) {
          $scope2.selectedRole = angular_default.copy(role);
        };
        $scope2.saveRole = function() {
          var permissions = $scope2.selectedRole.permissions.filter(function(p4) {
            return p4.project_id === $scope2.project.id;
          });
          $q.when(updateProjectRolePermissions($scope2.selectedRole, $scope2.project, permissions), () => {
            $scope2.selectedRole = null;
          });
        };
        $scope2.cancelEditRole = function() {
          $scope2.selectedRole = null;
        };
        $scope2.resetRole = function() {
          $q.when(resetRoleForProject($scope2.selectedRole, $scope2.project), () => {
            $scope2.selectedRole = null;
          });
        };
      }
    ]
  };
});

// public/app/modals/project-settings/settings.js
angular_default.module("kantree").factory("projectSettingsModal", [
  "$rootScope",
  "$uibModal",
  "$injector",
  function($rootScope, $uibModal, $injector) {
    var instance, current;
    return {
      open: async function(project, panel) {
        var $location = $injector.get("$location");
        if (current == project) {
          return;
        } else if (instance) {
          instance.close();
        }
        var panelArg = null;
        if (panel && panel.indexOf("/") !== -1) {
          panelArg = panel.split("/")[1];
          panel = panel.split("/")[0];
        }
        current = project;
        var scope = $rootScope.$new();
        scope.project = project;
        scope.currentPanel = panel;
        scope.panelArg = panelArg;
        scope.resetPanelArg = function() {
          scope.panelArg = null;
          delete scope.panelArg;
        };
        instance = $uibModal.open({
          templateUrl: "/static/app/modals/project-settings/templates/modal.html",
          controller: "ProjectSettingsModalCtrl",
          windowClass: "project-settings-modal",
          scope
        });
        var closed = function(preventLocationChange) {
          scope.$destroy();
          instance = null;
          current = null;
        };
        instance.result.then(closed, function() {
          closed();
        });
        return await instance.rendered;
      }
    };
  }
]);
angular_default.module("kantree").controller("ProjectSettingsModalCtrl", [
  "$scope",
  "$uibModalInstance",
  function($scope2, $uibModalInstance) {
    $scope2.$uibModalInstance = $uibModalInstance;
    $scope2.panels = projectSettingsPanels.filter(function(panel) {
      if (typeof panel.enabled === "undefined" || panel.enabled($scope2.project)) {
        if ($scope2.currentPanel && $scope2.currentPanel === panel.name) {
          $scope2.currentPanel = panel;
        }
        return true;
      }
      return false;
    });
    if (!$scope2.currentPanel && $scope2.panels.length) {
      $scope2.currentPanel = $scope2.panels[0];
    }
    $scope2.switchPanel = function(name2) {
      $scope2.currentPanel = $scope2.panels.find((p4) => p4.name === name2);
    };
  }
]);

// public/app/modals/search.js
angular_default.module("kantree").service("searchModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  async open(filter4) {
    if (this.instance) {
      this.instance.close();
      await this.instance.closed;
    }
    this.instance = this.$uibModal.open({
      component: "searchModal",
      windowClass: "search-modal",
      resolve: {
        filter: () => filter4
      }
    });
    const closed = () => {
      this.instance = null;
    };
    this.instance.result.then(closed, closed);
    return this.instance.result;
  }
});
angular_default.module("kantree").component("searchModal", {
  template: `
    <quick-global-search
      show-preview="true"
      initial-filter="$ctrl.resolve.filter"
      close-modal="$ctrl.dismiss()"
    ></quick-global-search>
  `,
  bindings: {
    "resolve": "<",
    "close": "&",
    "dismiss": "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.$scope.$parent.$uibModalInstance.rendered.then(() => {
        this.$scope.$broadcast("quickGlobalSearchModalOpen");
        if (this.resolve.filter) {
          this.$scope.$broadcast("doGlobalSearch", this.resolve.filter);
        }
      });
    }
  }
});

// public/app/modals/share-embed/share-embed.js
angular_default.module("kantree").service("shareEmbedModal", class extends AngularClass {
  static $inject = ["$uibModal"];
  open(url2) {
    const instance = this.$uibModal.open({
      windowClass: "share-embed-modal",
      component: "shareEmbedModal",
      resolve: {
        url: () => url2
      }
    });
    return instance.result;
  }
});
angular_default.module("kantree").component("shareEmbedModal", {
  templateUrl: "/static/app/modals/share-embed/share-embed-modal.html",
  bindings: {
    "resolve": "<",
    "close": "&",
    "dismiss": "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      const iframeUrl = this.resolve.url + (this.resolve.url.includes("?") ? "&" : "?") + "embed=1";
      this.html = `<iframe src="${iframeUrl}"></iframe>`;
    }
  }
});

// public/app/modals/terms/terms.js
angular_default.module("kantree").factory("termsValidationModal", [
  "$uibModal",
  function($uibModal) {
    var instance;
    return {
      open: function() {
        if (instance) {
          instance.close();
        }
        instance = $uibModal.open({
          templateUrl: "/static/app/modals/terms/terms-modal.html",
          controller: "TermsValidationModalCtrl",
          windowClass: "terms-validation-modal",
          backdrop: "static"
        });
      }
    };
  }
]);
angular_default.module("kantree").controller("TermsValidationModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $q.when(api_default.config.get_terms.get(), (terms) => {
      $scope2.terms = terms;
    });
    $scope2.accept = function() {
      $q.when(api_default.user.accept_terms.post(), (user) => {
        setCurrentUser(user);
        $uibModalInstance.close();
      });
    };
  }
]);

// public/app/modals/qrcode/qrcode.js
var import_qrious2 = __toESM(require_qrious());
angular_default.module("kantree").factory("qrcodeModal", [
  "$uibModal",
  function($uibModal) {
    return {
      open: function(value2, title) {
        const instance = $uibModal.open({
          component: "qrcodeModal",
          windowClass: "qrcode-modal",
          resolve: {
            value: () => value2,
            title: () => title
          }
        });
        return instance.result;
      }
    };
  }
]);
angular_default.module("kantree").component("qrcodeModal", {
  templateUrl: "/static/app/modals/qrcode/qrcode-modal.html",
  bindings: {
    "resolve": "<",
    "close": "&",
    "dismiss": "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $postLink() {
      const qr = new import_qrious2.default({
        element: this.$element.find("canvas")[0],
        value: this.resolve.value,
        size: 200
      });
    }
  }
});

// public/app/modals/file-preview/modal.js
angular_default.module("kantree").service("filePreviewer", class extends AngularClass {
  static $inject = ["$injector"];
  canPreview(file) {
    if (file.external) {
      return false;
    }
    for (var i3 = 0; i3 < filePreviewers.length; i3++) {
      if (filePreviewers[i3][0].test(file.mimetype)) {
        return filePreviewers[i3][1];
      }
    }
    return false;
  }
  open(file, store2) {
    let previewer = this.canPreview(file);
    if (previewer) {
      return this.$injector.get(previewer).open(file, store2);
    }
  }
});
angular_default.module("kantree").service("imageFilePreviewer", class extends AngularClass {
  static $inject = ["Lightbox"];
  open(file, store2) {
    let images = [], imageIdx = 0;
    if (store2) {
      images = store2.queryByMimetype(new RegExp("^image\\/", "i"));
      for (var i3 = 0; i3 < images.length; i3++) {
        images[i3].imageIdx = i3;
        if (images[i3].id === file.id) {
          imageIdx = i3;
        }
      }
    }
    this.$Lightbox.openModal(images, imageIdx);
  }
});
angular_default.module("kantree").service("pdfFilePreviewer", class extends AngularClass {
  static $inject = ["pdfModal"];
  open(file, store2) {
    this.$pdfModal.open(file.url);
  }
});
angular_default.module("kantree").service("videoFilePreviewer", class extends AngularClass {
  static $inject = ["videoModal"];
  open(file, store2) {
    this.$videoModal.open(file.url, file.mimetype);
  }
});

// public/app/ui/activities/ng-components/activities.js
angular_default.module("kantree").component("activities", {
  templateUrl: "/static/app/ui/activities/ng-components/templates/activities.html",
  bindings: {
    items: "<?",
    store: "<?",
    card: "<?",
    reversed: "<?",
    limit: "@?",
    groupedByDate: "@?",
    aggregate: "@?",
    forceAggregate: "<?",
    isStream: "<?",
    hoursOnly: "@?",
    emptyMessage: "@",
    actions: "<?",
    showRequestIndicatorInComment: "<?",
    onUpdate: "&?",
    unreadIds: "<?",
    onMarkAsRead: "&?",
    markAsReadOnScroll: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["cardModal", "$scope", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.showAll = false;
      this.loading = true;
      this.activities = [];
      this.displayedActivities = [];
      if (this.limit === void 0) {
        this.limit = 5;
      } else if (this.limit === "false") {
        this.showAll = true;
      }
      if (!this.store) {
        this.store = new ActivityStore({ autoLoad: false });
        this.refreshStoreWatcher();
        this.$scope.$watchCollection("$ctrl.items", (items) => {
          if (items) {
            this.store.replace(items);
          }
        });
      } else {
        this.refreshStoreWatcher();
      }
    }
    $onChanges(changes) {
      if (changes.store && !changes.store.isFirstChange()) {
        this.refreshStoreWatcher();
      }
    }
    $postLink() {
      const self2 = this;
      jquery_default(this.$element).on("click", "a.card-activity-subject[rel]", function(e3) {
        e3.preventDefault();
        self2.$cardModal.load(this.rel);
      });
    }
    refreshStoreWatcher() {
      if (this.deregisterStoreWatcher) this.deregisterStoreWatcher();
      if (this.store) {
        this.deregisterStoreWatcher = this.store.$watchAll(this.$scope, () => {
          this.updateView();
        });
      }
    }
    updateView() {
      this.activities = this.store.query({}, { sortBy: "date" });
      if (this.aggregate !== "false") {
        this.activities = aggregateActivities(this.activities, this.forceAggregate);
      }
      this.activitiesCount = this.activities.length;
      if (!this.showAll && this.activities.length > this.limit) {
        this.activities = this.activities.slice(-this.limit);
      }
      if (this.reversed) {
        this.activities = this.activities.reverse();
      }
      if (this.groupedByDate === "true") {
        this.activities = groupActivitiesByDate(this.activities);
      }
      this.displayedActivities = this.activities;
      this.loading = false;
      if (this.onUpdate) {
        this.onUpdate();
      }
    }
    toggleShowAll() {
      this.showAll = !this.showAll;
      this.updateView();
    }
  }
});
angular_default.module("kantree").directive("activitiesLine", [
  function() {
    return {
      restrict: "E",
      replace: true,
      scope: {
        item: "<",
        store: "<?",
        card: "<?",
        hoursOnly: "@?",
        emptyMessage: "<?",
        actions: "<?",
        showRequestIndicatorInComment: "<?",
        isUnread: "<?",
        onMarkAsRead: "&",
        markAsReadOnScroll: "<?",
        isStream: "<?"
      },
      templateUrl: "/static/app/ui/activities/ng-components/templates/activities-line.html",
      controller: [
        "$scope",
        function($scope2) {
          $scope2.$watch("actions", function(newVal, oldVal) {
            if (newVal === oldVal) {
              return;
            }
            $scope2.filteredActions = buildActions($scope2.item, newVal);
          });
          $scope2.$watch("item", function(newVal, oldVal) {
            $scope2.filteredActions = buildActions(newVal, $scope2.actions);
          });
          function buildActions(item, actions2) {
            if (!actions2 || !actions2.length) {
              return [];
            }
            if (item.stream_type === "comment") {
              return actions2.filter(function(action) {
                return action.indexOf("comments") !== -1;
              }).map(function(action) {
                return action.replace("comments:", "");
              }).filter(function(action) {
                if (["edit_temporarily", "delete_mine"].indexOf(action) !== -1) {
                  return item.user && item.user.id === currentUser2.id;
                }
                return true;
              }).map(function(action) {
                if (action === "delete_mine") {
                  return "delete";
                }
                return action;
              });
            }
            if (item.stream_type === "log") {
              return actions2.filter(function(action) {
                return action.indexOf("logs") !== -1;
              }).map(function(action) {
                return action.replace("logs:", "");
              }).filter(function(action) {
                if (action === "delete_mine") {
                  return item.user && item.user.id === currentUser2.id;
                }
                return true;
              }).map(function(action) {
                if (action === "delete_mine") {
                  return "delete";
                }
                return action;
              });
            }
            if (item.stream_type === "activity") {
              return actions2.filter(function(action) {
                return action.indexOf("activities") !== -1;
              }).map(function(action) {
                return action.replace("activities:", "");
              });
            }
            return [];
          }
        }
      ]
    };
  }
]);

// public/app/stores/utils/user.js
function formatUserDetails(user) {
  if (!user) {
    return {
      avatar: guestAvatarUrl(),
      display_name: _4("Unknown")
    };
  }
  let name2 = user.display_name;
  if (user.deleted) {
    name2 += " (" + _4("deleted") + ")";
  }
  return { id: user.id, avatar: user.avatar || guestAvatarUrl(), username: user.username, display_name: name2, special: !!user.special };
}

// public/app/ui/activities/ng-components/activity.js
angular_default.module("kantree").component("activity", {
  bindings: {
    activity: "<",
    card: "<?",
    hoursOnly: "@?",
    showMarkAsRead: "<?",
    onMarkAsRead: "&",
    markAsReadOnScroll: "<?",
    isStream: "<?"
  },
  templateUrl: "/static/app/ui/activities/ng-components/templates/activity.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "cardModal", "$sanitize", "$sce", "$element", "$sce"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isComment = this.activity.object.type === "CardComment";
      this.actor = formatUserDetails(this.activity.actor);
      const values2 = {
        actor: `<em title="${this.$sanitize(this.actor.username || this.actor.display_name)}">${this.$sanitize(this.actor.display_name)}</em>`
      };
      ["object", "sub_object", "origin", "target"].forEach((name2) => {
        if (this.activity[name2]) {
          values2[name2] = this.propToHtml(this.activity[name2]);
        }
      });
      if (this.activity.aggregated && this.activity.aggr_message.indexOf("{aggrObjects}") !== -1) {
        values2.aggrObjects = this.activityListToHtml(this.activity.aggregated, "object");
      }
      const isComment = this.activity.object && this.activity.object.type === "CardComment";
      if (isComment && this.isStream) {
        this.htmlMessage = this.$sce.trustAsHtml(this.activity.verb === "MENTION" ? _4(`${values2.actor} mentionned you`) : values2.actor);
      } else {
        this.htmlMessage = this.$sce.trustAsHtml(_4(this.activity.aggr_message || this.activity.message, values2));
      }
      if (isComment) {
        this.commentHtmlMessage = this.$sce.trustAsHtml(convertMarkdownToHTML(this.activity.object.value, true));
      }
    }
    $postLink() {
      if (this.markAsReadOnScroll) {
        this.checkReadOnScroll = function() {
          window.requestAnimationFrame(() => {
            if (this.isInViewport()) {
              this.markAsRead();
            }
          });
        }.bind(this);
        this.scrollViewport = this.$element.parents(".activity-scroll-viewport");
        this.scrollViewport.on("scroll", this.checkReadOnScroll);
      }
    }
    $onDestroy() {
      if (this.scrollViewport) {
        this.scrollViewport.off("scroll", this.checkReadOnScroll);
      }
    }
    propToHtml(prop2) {
      let value2 = "";
      if (typeof prop2 === "string") {
        value2 = prop2;
      } else if (prop2.type === "Card") {
        if (this.card && prop2.id === this.card.id) {
          value2 = _4("this card");
        } else {
          value2 = '<a class="card-activity-subject" rel="' + prop2.id + '">' + this.$sanitize(prop2.value) + "</a>";
        }
      } else if (prop2.type === "User") {
        if (prop2.id === currentUser2.id) {
          value2 = "<em>" + _4("you") + "</em>";
        } else {
          value2 = '<em title="' + this.$sanitize(prop2.value.username || prop2.value) + '">' + this.$sanitize(prop2.value.display_name || prop2.value) + "</em>";
        }
      } else if (prop2.type && prop2.type.toLowerCase() === "file") {
        value2 = '<a href="' + prop2.value.url + '" target="_blank">' + this.$sanitize(prop2.value.name) + "</a>";
      } else if (prop2.type === "commit" || prop2.type === "link") {
        value2 = '<a class="card-activity-subject" href="' + prop2.value.url + '">' + this.$sanitize(prop2.value.msg) + "</a>";
      } else {
        value2 = '<span class="card-activity-subject">' + this.$sanitize(prop2.value) + "</span>";
      }
      return value2;
    }
    activityListToHtml(activities, prop2) {
      let displayed, remaining, menuToggle;
      if (activities.length > 5) {
        displayed = activities.slice(0, 5);
        remaining = activities.slice(5);
      } else {
        displayed = activities;
      }
      let html5 = displayed.map((activity) => this.propToHtml(activity[prop2])).join(" , ");
      if (remaining) {
        this.aggrObjectsMenu = {
          config: remaining.map((activity) => {
            return {
              label: activity.object.type === "commit" ? activity.object.value.msg : activity.object.value,
              action: () => {
                if (activity.object.type === "commit") {
                  document.location = activity.object.value.url;
                } else if (activity.object.type === "Card") {
                  this.$cardModal.load(activity.object.id);
                }
              }
            };
          })
        };
        menuToggle = '<a class="card-activity-subject-more"  href drop-menu="this.aggrObjectsMenu">' + _4("and {number} more", { number: remaining.length }) + "</a>";
        html5 = html5 + " " + menuToggle;
      }
      return html5;
    }
    markAsRead() {
      if (this.showMarkAsRead) {
        this.onMarkAsRead();
        this.showMarkAsRead = false;
        if (this.scrollViewport) {
          this.scrollViewport.off("scroll", this.checkReadOnScroll);
        }
      }
    }
    isInViewport() {
      const rect = this.$element[0].getBoundingClientRect();
      const margin = 100;
      return rect.top >= margin && rect.left >= margin && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) - margin && rect.right <= (window.innerWidth || document.documentElement.clientWidth) - margin;
    }
  }
});
angular_default.module("kantree").directive("activityImage", [
  "Lightbox",
  function(Lightbox) {
    return {
      restrict: "E",
      template: '<img try-image-src="trySrc">',
      replace: true,
      scope: {
        trySrc: "<"
      },
      link: function(scope, element2, attrs2) {
        jquery_default(element2).on("click", function() {
          Lightbox.openModal([{ url: this.src }], 0);
        });
      }
    };
  }
]);

// public/app/ui/activities/ng-components/comment.js
angular_default.module("kantree").directive("cardComment", [
  "cardModal",
  "$q",
  function(cardModal, $q) {
    return {
      scope: {
        comment: "<",
        store: "<",
        card: "<?",
        showRequestIndicator: "<?",
        actions: "<"
      },
      templateUrl: "/static/app/ui/activities/ng-components/templates/comment.html",
      controller: [
        "$scope",
        "$q",
        "$sce",
        function($scope2, $q2, $sce) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.actions = $scope2.actions || [];
          $scope2.can = function() {
            var op = "or";
            var actions2 = Array.from(arguments).map(function(action) {
              if (action.charAt(0) === "&") {
                op = "and";
                return action.slice(1);
              }
              return action;
            });
            if (op === "and") {
              return !actions2.some(function(action) {
                return $scope2.actions.indexOf(action) === -1;
              });
            }
            return actions2.some(function(action) {
              return $scope2.actions.indexOf(action) !== -1;
            });
          };
          function fromNowInSeconds(dateInSeconds) {
            return (/* @__PURE__ */ new Date()).getTime() / 1e3 - dateInSeconds;
          }
          function commentedInTheLastTwoHours(commentDate) {
            return fromNowInSeconds(commentDate) < 3600 * 2;
          }
          $scope2.isEditingEnabled = function() {
            return $scope2.can("edit") || commentedInTheLastTwoHours($scope2.comment.date) && $scope2.can("edit_temporarily");
          };
          $scope2.getEditButtonTooltip = function() {
            if ($scope2.can("edit")) {
              return _4("Edit");
            }
            if ($scope2.can("edit_temporarily")) {
              if (commentedInTheLastTwoHours($scope2.comment.date)) {
                return _4("Can be edited for 2h");
              }
              return _4("Can't be edited (>2h)");
            }
          };
          $scope2.isEditButtonDisabled = function() {
            return $scope2.can("edit_temporarily") && !$scope2.can("edit") && !commentedInTheLastTwoHours($scope2.comment.date);
          };
          $scope2.togglePin = function() {
            if ($scope2.comment.is_pinned) {
              $q2.when(api_default.card_stream.unpin_comment.delete({ card_id: $scope2.card.id }), () => {
                $scope2.store.update($scope2.comment, { is_pinned: false });
              });
            } else {
              $q2.when(api_default.card_stream.pin_comment.post({ card_id: $scope2.card.id, comment_id: $scope2.comment.id }), () => {
                var oldPinnedComment = $scope2.store.query({ is_pinned: true })?.[0];
                if (oldPinnedComment) {
                  $scope2.store.update(oldPinnedComment, { is_pinned: false });
                }
                $scope2.store.update($scope2.comment, { is_pinned: true });
              });
            }
          };
          $scope2.toggleExpanded = function() {
            $scope2.isExpanded = !$scope2.isExpanded;
          };
          $scope2.isCommentEditing = false;
          $scope2.closeCommentEditor = function() {
            $scope2.isCommentEditing = false;
          };
          $scope2.openCommentEditor = function() {
            $scope2.isCommentEditing = true;
          };
          if ($scope2.isEditingEnabled()) {
            $scope2.commentEditorOptions = {
              data: {
                project_id: $scope2.card.project_id,
                card_id: $scope2.card.id,
                comment_id: $scope2.comment.id
              },
              type: "comment",
              buttons: [
                {
                  on: "submit",
                  label: _4("Comment")
                }
              ]
            };
          }
          $scope2.saveComment = async function(message) {
            if (!message || !message.length) {
              return $q2.reject();
            }
            if (message !== $scope2.comment.message) {
              return $q2.when(editCardComment($scope2.card, $scope2.comment, message), () => {
                $scope2.closeCommentEditor();
              });
            } else {
              $scope2.closeCommentEditor();
            }
          };
          $scope2.openDeletePopup = function() {
            $q2.digest(confirmDeleteDialog2().then(() => {
              return deleteCardComment($scope2.card, $scope2.comment);
            }));
          };
          $scope2.store.$watch($scope2, $scope2.comment, function() {
            $scope2.isExpanded = !$scope2.comment.is_pinned || !$scope2.can("collapse");
            $scope2.htmlMessage = $sce.trustAsHtml(convertMarkdownToHTML($scope2.comment.message, true));
          }, false);
          $scope2.$watch("actions", function(newVal, oldVal) {
            if (newVal === oldVal) {
              return;
            }
            $scope2.isExpanded = !$scope2.comment.is_pinned || !$scope2.can("collapse");
          });
          $scope2.$watch("comment", function(newVal, oldVal) {
            $scope2.user = formatUserDetails($scope2.comment.user);
            $scope2.isExpanded = !$scope2.comment.is_pinned || !$scope2.can("collapse");
            $scope2.htmlMessage = $sce.trustAsHtml(convertMarkdownToHTML($scope2.comment.message, true));
          });
        }
      ],
      link: function(scope, element2, attrs2) {
        jquery_default(element2).on("click", ".comment-message a", function(e3) {
          e3.preventDefault();
          e3.stopPropagation();
          if (jquery_default(this).hasClass("card-ref") && scope.card) {
            var project = projectStore.getForCard(scope.card);
            cardModal.loadByRef(project, this.rel);
          } else {
            window.open(this.href);
          }
        });
        scope.$watch("isCommentEditing", function(value2) {
          element2.toggleClass("editing", value2);
        });
      }
    };
  }
]);

// public/app/ui/activities/ng-components/log.js
angular_default.module("kantree").directive("cardLog", [
  function() {
    return {
      scope: {
        log: "<",
        card: "<?",
        actions: "<?"
      },
      templateUrl: "/static/app/ui/activities/ng-components/templates/log.html",
      controller: [
        "$scope",
        "$q",
        "$sanitize",
        "$sce",
        function($scope2, $q, $sanitize, $sce) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.user = formatUserDetails($scope2.log.user);
          $q.when(getOrLoadLogType($scope2.log.type_id), (logType) => {
            $scope2.logType = logType;
            projectLogTypeStore.$watch($scope2, logType, () => {
              $scope2.attributes = new AttributeGroup($scope2.logType.attributes);
            });
          });
          $scope2.actions = $scope2.actions || [];
          $scope2.can = function() {
            var op = "or";
            var actions2 = Array.from(arguments).map(function(action) {
              if (action.charAt(0) === "&") {
                op = "and";
                return action.slice(1);
              }
              return action;
            });
            if (op === "and") {
              return !actions2.some(function(action) {
                return $scope2.actions.indexOf(action) === -1;
              });
            }
            return actions2.some(function(action) {
              return $scope2.actions.indexOf(action) !== -1;
            });
          };
          $scope2.project = null;
          if ($scope2.card) {
            $q.when(getOrLoadProject($scope2.card.project_id), (project) => {
              $scope2.project = project;
            });
          }
          $scope2.showDeleteButton = function() {
            return canDeleteLog($scope2.project, $scope2.log.id);
          };
          $scope2.getLogMessage = function() {
            return $sce.trustAsHtml(_4("<em>{user}</em> logged something", { user: $sanitize($scope2.user.display_name) }));
          };
          $scope2.openDeletePopup = function() {
            $q.digest(confirmDeleteDialog2().then(() => {
              return deleteCardLog($scope2.card, $scope2.log);
            }));
          };
        }
      ]
    };
  }
]);

// public/app/ui/attributes/ng-components/attribute-editor.js
angular_default.module("kantree").directive("attributeEditorOpener", [
  "attributeEditor",
  function(attributeEditor) {
    return {
      restrict: "A",
      scope: {
        project: "<?",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        editable: "<?",
        attributeEditable: "<?",
        value: "<?",
        isolatedScope: "<?",
        onDone: "&",
        isTemplate: "<?"
      },
      link: function(scope, element2, attrs2, ctrl) {
        jquery_default(element2).on("click", function() {
          if (scope.editable) {
            attributeEditor.open(
              this,
              scope,
              scope.project,
              scope.attributeGroup,
              scope.attribute,
              scope.obj,
              scope.value,
              scope.attributeEditable,
              function() {
                scope.onDone();
              },
              null,
              !!scope.isolatedScope,
              scope.isTemplate
            );
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").directive("attributeEditor", [
  "$compile",
  "$q",
  function($compile, $q) {
    return {
      restrict: "E",
      replace: true,
      template: '<div class="attribute-editor"></div>',
      scope: {
        project: "<?",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<?",
        onDone: "&",
        onUpdate: "&",
        onInit: "&",
        directiveProperty: "@?",
        fetchValue: "<?",
        attributeEditable: "<?",
        embedded: "<?",
        isTemplate: "<?"
      },
      link: function(scope, el2) {
        var render3 = function() {
          const attrType = attributeTypeRegistry.get(scope.attribute.type);
          const editorDirective = attrType[scope.directiveProperty || "editorDirective"] || attrType.widgetDirective;
          const html5 = `<${editorDirective} project="project" attribute-group="attributeGroup" attribute="attribute"
              obj="obj" value="value" on-done="onDone()" on-update="onUpdate()" on-init="onInit()"
              editable="true" attribute-editable="attributeEditable"
              embedded="embedded" is-template="isTemplate" class="${attrType.name}-attribute-editor" />`;
          jquery_default(el2).html($compile(html5)(scope));
          if (!attrType.editorOptions || !attrType.editorOptions.is_async) {
            (scope.onInit || angular_default.noop)();
          }
        };
        scope.$watch("attribute", () => {
          if (typeof scope.value === "undefined" && (typeof scope.fetchValue === "undefined" || scope.fetchValue)) {
            $q.when(scope.attributeGroup.getObjAttributeValue(scope.obj, scope.attribute)[1], (value2) => {
              scope.value = value2;
              render3();
            });
          } else {
            if (typeof scope.value === "undefined") {
              scope.value = null;
            }
            render3();
          }
        });
      }
    };
  }
]);

// public/app/ui/attributes/ng-components/attribute-form.js
angular_default.module("kantree").directive("attributeForm", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-form">
          <attribute-group project="project" obj="obj" attribute-group="attributeGroup" attributes-editable="attributesEditable"
            editable="true" directive-property="formDirective" attribute-type-available-for="{{attributeTypeAvailableFor}}"
            show-add="showAdd" standalone-group="true" attributes-movable="attributesMovable" add-btn-position="bottom"
            show-empty-notice="showEmptyNotice" />
        </div>`,
      scope: {
        project: "<?",
        obj: "=?",
        data: "=?",
        files: "=?",
        attributeGroup: "<",
        attributesEditable: "<?",
        attributesMovable: "<?",
        showAdd: "<?",
        showEmptyNotice: "<?",
        attributeTypeAvailableFor: "@?"
      },
      controller: [
        "$scope",
        function($scope2) {
          $scope2.$watchCollection("attributeGroup", function(attributeGroup) {
            if (attributeGroup) {
              attributeGroup.$listen($scope2, function() {
                $scope2.data = attributeGroup.formatObjToServer($scope2.obj);
                if (typeof $scope2.files !== "undefined") {
                  var out = attributeGroup.extractFilesFromServerData($scope2.data);
                  $scope2.data = out[0];
                  $scope2.files = out[1];
                }
              });
            }
          });
          if (typeof $scope2.obj === "undefined") {
            $scope2.obj = { "attributes": [] };
          }
        }
      ]
    };
  }
]);

// public/app/ui/attributes/ng-components/attribute-group.js
angular_default.module("kantree").directive("attributeGroup", [
  "$timeout",
  "$document",
  "$q",
  function($timeout2, $document, $q) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/ui/attributes/ng-components/templates/attribute-group.html",
      scope: {
        obj: "<?",
        attributeGroup: "<",
        project: "<?",
        container: "@?",
        filterAttributesUsing: "<?",
        editable: "<?",
        isTemplate: "<?",
        attributesEditable: "<?",
        attributesMovable: "<?",
        showAdd: "<?",
        addBtnPosition: "@",
        directiveProperty: "@?",
        attributeTypeAvailableFor: "@?",
        attrShowOnlyModelOption: "<?",
        onAddAttribute: "&?",
        standaloneGroup: "<",
        showEmptyNotice: "<?"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.addAttrPosition = null;
          if ($scope2.attributesMovable === void 0) {
            $scope2.attributesMovable = true;
          }
          if ($scope2.showAdd === void 0 || $scope2.showAdd) {
            $scope2.showAdd = true;
            $scope2.attributeTypes = attributeTypeRegistry.getAll().filter(function(type) {
              return !type.hidden && (!$scope2.attributeTypeAvailableFor || !type.availableFor || type.availableFor.indexOf($scope2.attributeTypeAvailableFor) !== -1);
            });
          }
          $scope2.refreshAttributes = function() {
            $scope2.attributes = sortAttributes($scope2.attributeGroup, $scope2.container);
          };
          var watcherOff;
          $scope2.$watchCollection("attributeGroup", function(attributeGroup, prev) {
            if (watcherOff) {
              watcherOff();
            }
            if (attributeGroup && attributeGroup.$listen) {
              $scope2.refreshAttributes();
              if (prev.length > 0 && prev.length < attributeGroup.length && $scope2.addingAttribute) {
                let newAttr = null;
                for (const attr of attributeGroup) {
                  if (prev.indexOf(attr) === -1) newAttr = attr;
                }
                $timeout2(() => {
                  $scope2.$broadcast("newAttributeCreated", newAttr?.id);
                }, 500);
                $scope2.addingAttribute = false;
              }
            } else {
              $scope2.attributes = [];
            }
          });
          $scope2.$watch("filterAttributesUsing", (newVal, oldVal) => {
            const filters = [];
            if (!!$scope2.filterAttributesUsing) {
              for (const key2 of Object.keys($scope2.filterAttributesUsing)) {
                if (!$scope2.filterAttributesUsing[key2].disabled) {
                  filters.push($scope2.filterAttributesUsing[key2].filter);
                }
              }
            }
            if (filters.length === 0) {
              $scope2.isAttributeMatches = null;
            } else {
              $scope2.isAttributeMatches = (attr) => {
                for (const filter4 of filters) {
                  if (!filter4(attr)) {
                    return false;
                  }
                }
                return true;
              };
            }
          });
          $scope2.addAttr = function(type, onlyModel) {
            let promise;
            if ($scope2.onAddAttribute) {
              promise = $scope2.onAddAttribute({ $type: type, $position: $scope2.addAttrPosition, $onlyModel: onlyModel });
            } else {
              promise = $q.when($scope2.attributeGroup.create($scope2.obj, type.name, $scope2.container, $scope2.addAttrPosition));
            }
            promise?.then(() => {
              $scope2.addingAttribute = true;
            });
          };
        }
      ],
      link: function(scope, el2) {
        var dragScrollHelper;
        var $el = jquery_default(el2);
        var inner = $el.find(">.attribute-group-inner");
        let adder = $el.find(">.add-attribute"), adderBtn = adder.find(">.btn");
        const widgetBottomMargin = 24, widgetRightMargin = 24;
        let relativeWidget;
        function updateAdderPosition() {
          if (!scope.attributes.length) return;
          if (!relativeWidget?.length) {
            relativeWidget = null;
            adder.removeClass("vert").css({
              top: 0,
              left: 0,
              height: 0
            }).css("display", "flex");
          } else {
            if (scope.addBtnPosition === "bottom" || relativeWidget.hasClass("block")) {
              adder.removeClass("vert").css({
                left: 0,
                top: relativeWidget.position().top + relativeWidget.outerHeight() + widgetBottomMargin / 2,
                height: 0
              });
            } else {
              adder.addClass("vert").css({
                left: relativeWidget.position().left + relativeWidget.outerWidth() + widgetRightMargin / 2,
                top: relativeWidget.position().top,
                height: relativeWidget.outerHeight()
              });
            }
            adder.css("display", "flex");
            scope.addAttrPosition = relativeWidget.index() + 1;
          }
        }
        scope.onAddDropOpen = () => {
          scope.addAttributeDropOpen = true;
        };
        scope.onAddDropClosed = () => {
          scope.addAttributeDropOpen = false;
          if (scope.attributes.length) {
            adder.hide();
          }
        };
        if (scope.showAdd) {
          $el.on("mouseover", (e3) => {
            if (!scope.attributesEditable) return;
            if (!scope.attributes.length || inner.hasClass("ui-sortable-current-container") || e3.target === adder[0] || jquery_default(e3.target).parents(".add-attribute").length || adderBtn.hasClass("drop-enabled") || inner.children(".attribute-widget.drop-open").length) return;
            if (e3.target === inner[0]) {
              let offsetX = 0, offsetY = e3.clientY - widgetBottomMargin, minOffsetY = inner.offset().top + 10, maxOffsetY = minOffsetY - 10 + inner.height() - widgetBottomMargin;
              do {
                relativeWidget = jquery_default(document.elementFromPoint(e3.clientX - offsetX, Math.min(Math.max(minOffsetY, offsetY), maxOffsetY)));
                offsetX += 50;
              } while (relativeWidget[0] === inner[0]);
              adder.toggleClass("no-line", false);
            } else {
              relativeWidget = jquery_default(e3.target);
              adder.toggleClass("no-line", true);
            }
            if (!relativeWidget.hasClass("attribute-widget")) {
              relativeWidget = relativeWidget.parents(".attribute-widget");
            }
            updateAdderPosition();
          });
          let updateAdderPositionTimeout;
          adderBtn.on("click", () => updateAdderPositionTimeout = $timeout2(updateAdderPosition, 100, false));
          $el.on("mouseleave", () => {
            relativeWidget = null;
            $timeout2.cancel(updateAdderPositionTimeout);
          });
          const adderHider = () => {
            if (!relativeWidget && scope.attributes.length && adder.is(":visible") && !adderBtn.hasClass("drop-enabled")) {
              adder.hide();
            }
          };
          $document.on("mousemove", adderHider);
          scope.$on("$destroy", () => {
            $document.off("mousemove", adderHider);
            $timeout2.cancel(updateAdderPositionTimeout);
          });
        }
        scope.sortableOptions = {
          appendTo: "body",
          helper: "clone",
          items: ">.attribute-widget",
          connectWith: scope.standaloneGroup ? "" : ".attribute-group.sortable .attribute-group-inner",
          handle: ".move-handle",
          tolerance: "pointer",
          distance: 6,
          forcePlaceholderSize: true,
          scroll: false,
          zIndex: 0,
          placeholder: "ui-sortable-attributes-placeholder",
          start: function(e3, ui) {
            ui.item.sortable.targetScope = scope;
            ui.item.sortable.sourceScope = scope;
            dragScrollHelper = new DragScrollHelper({
              scrollable: $el.parents("project-overview-app").length ? $el.parents("project-overview-app") : $el.parents("#card-modal-host").length ? $el.parents(".card-view-body") : $el.parents(".card-modal"),
              threshold: {
                default: { top: 50, bottom: 50 },
                xs: { top: 30, bottom: 30 }
              },
              tolerance: "border"
            });
            ui.placeholder.height(ui.helperProportions.height - 6);
            if (ui.item.hasClass("block")) {
              setTimeout(() => {
                if (ui.placeholder) ui.placeholder.addClass("block");
              });
            }
            var rect = ui.placeholder[0].getBoundingClientRect();
            dragScrollHelper.update("draggable", {
              width: ui.helperProportions.width,
              height: ui.helperProportions.height > 300 ? 300 : ui.helperProportions.height,
              mousePosition: {
                x: e3.clientX - rect.left,
                y: e3.clientY - rect.top
              }
            });
          },
          over: (event2, ui) => {
            ui.item.sortable.targetScope = scope;
          },
          sort: function(e3, ui) {
            var $viewport = $el.parents("project-overview-app").length ? $el.parents("project-overview-app") : $el.parents("#card-modal-host").length ? $el.parents(".card-view-body") : $el.parents(".card-modal");
            if ($viewport[0].scrollHeight > $viewport[0].clientHeight) {
              dragScrollHelper.updateScroll(e3.pageX, e3.pageY, getScreensize());
            }
          },
          update: (event2, ui) => {
            const { sourceScope, targetScope, cancel, droptarget, index: index2, dropindex } = ui.item.sortable;
            if (sourceScope !== scope) return;
            if (event2.originalEvent.target === null) {
              cancel();
            }
            if (!droptarget || !droptarget.length) {
              cancel();
            }
            if (targetScope === scope && index2 === dropindex) {
              cancel();
            }
          },
          stop: function(e3, ui) {
            const {
              targetScope = scope,
              isCanceled,
              // the dragged card has already been added by ng-sortable.js in the droptargetModel
              // See : L246 for connected lists sort and L260 for normal sort
              droptargetModel: droptargetAttributes,
              model: attr,
              dropindex
            } = ui.item.sortable;
            dragScrollHelper.reset();
            dragScrollHelper = null;
            if (isCanceled()) return;
            if (!droptargetAttributes) return;
            const position = dropindex;
            $q.when(targetScope.attributeGroup.move(attr, position, targetScope.container), () => {
              scope.$applyAsync(() => {
                if (scope !== targetScope) {
                  ui.item.remove();
                }
                scope.refreshAttributes();
                if (!scope.attributes.length) {
                  adder.css({
                    top: 0,
                    left: 0,
                    height: 0
                  }).css("display", "");
                }
                if (scope != targetScope) {
                  targetScope.$applyAsync(() => {
                    targetScope.refreshAttributes();
                  });
                }
              });
            });
          }
        };
        $timeout2(function() {
          scope.$watch("attributesMovable", function(movable) {
            if (movable && scope.attributesEditable && !isScreensizeXS()) {
              inner.sortable("enable");
            } else {
              inner.sortable("disable");
            }
          });
          scope.$on("screensize:changed", () => {
            if (!isScreensizeXS() && scope.attributesEditable && scope.attributesMovable) {
              inner.sortable("enable");
            } else {
              inner.sortable("disable");
            }
          });
        }, 500, false);
      }
    };
  }
]);

// public/app/ui/attributes/ng-components/attribute-options.js
angular_default.module("kantree").directive("attributeOptions", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/attributes/ng-components/templates/attribute-options.html",
      replace: true,
      scope: {
        attribute: "<",
        onDelete: "&",
        editable: "<?",
        org: "<?",
        project: "<?",
        obj: "<?",
        showDelete: "<?",
        showContainer: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          if ($scope2.attribute.model_id) {
            $scope2.model = cardModelStore.tryGet($scope2.attribute.model_id);
          }
          $scope2.types = attributeTypeRegistry.getAll().filter(function(type) {
            return !type.hidden;
          });
          if (!$scope2.attribute.options) {
            $scope2.attribute.options = {};
          }
          $scope2.card = null;
          if ($scope2.obj && $scope2.obj.__type__ === "card") {
            $scope2.card = $scope2.obj;
          }
          $scope2.selectType = function(typeName2) {
            var resolvedType = attributeTypeRegistry.resolveAttrTypeAlias(typeName2);
            $scope2.currentType = resolvedType.type;
            $scope2.attribute.type = resolvedType.type.name;
            $q.when(getOrLoadAttrType(resolvedType.type.name), (type) => {
              $scope2.typeOptions = type.options;
              if (!$scope2.attribute.id) {
                $scope2.attribute.options = resolvedType.options;
              }
            });
          };
          if ($scope2.attribute.type) {
            $scope2.selectType($scope2.attribute.type);
          }
        }
      ]
    };
  }
]);

// public/app/ui/attributes/ng-components/attribute-repr.js
angular_default.module("kantree").component("attributeReprWidgets", {
  template: `<dynamic-directive directive="{{$ctrl.$attributeRepr.getWidgetComponent(widget)}}"
    ng-repeat="widget in $ctrl.widgets" widget="widget" attribute-group="$ctrl.attribute-group"
    attribute="$ctrl.attribute" obj="$ctrl.obj" editable="$ctrl.editable"><dynamic-directive/>`,
  bindings: {
    attributeGroup: "<",
    attribute: "<",
    obj: "<",
    editable: "<?",
    mode: "<?",
    options: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["attributeRepr", "$element", "$scope"];
    $onInit() {
      this.widgets = this.$attributeRepr.getAttributeWidgets(this.attribute, this.obj, this.options);
    }
    $postLink() {
      if (this.widgets.every((w3) => !w3.onDOMLoad)) {
        this.dispose = this.$attributeRepr.setDefaultReprEventListeners(
          this.$element,
          this.$scope,
          this.attributeGroup,
          this.attribute,
          this.obj,
          this.editable
        );
      }
    }
    $onDestroy() {
      this.dispose?.();
    }
  }
});

// public/app/ui/attributes/ng-components/attribute-table.js
angular_default.module("kantree").directive("attributeTable", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/ui/attributes/ng-components/templates/attribute-table.html",
      scope: {
        obj: "<",
        attributeGroup: "<",
        container: "@?"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.attrReprWidgetsOptions = { expanded: true, expandable: true };
          $scope2.$watchCollection("attributeGroup", function(attributeGroup) {
            if (attributeGroup) {
              $scope2.attributes = sortAttributes(attributeGroup, $scope2.container);
            } else {
              $scope2.attributes = [];
            }
          });
        }
      ]
    };
  }
]);

// public/app/services/debug.ts
var [isDebugModeEnabled, setDebugModeEnabled] = createSignal(false);
function toggleDebugMode() {
  setDebugModeEnabled(!isDebugModeEnabled());
}

// public/app/ui/attributes/ng-components/attribute-widget.js
function isCustomModel(attr) {
  return Number.isInteger(attr.model_id);
}
function isOrgModel(attr) {
  return isString_default(attr.model_id) && attr.model_id.indexOf("org") !== -1;
}
function isProjectModel(attr) {
  return isString_default(attr.model_id) && attr.model_id.indexOf("project") !== -1;
}
function isTopLevelCardModel(attr) {
  return isString_default(attr.model_id) && attr.model_id.indexOf("top_level_card") !== -1;
}
function isProjectScoped(attr) {
  if (isCustomModel(attr)) {
    const model = cardModelStore.tryGet(attr.model_id);
    return model && model.is_project_specific;
  }
  return isProjectModel(attr);
}
function countCardsUsingAttrInProject(attr, project) {
  const store2 = cardStore.scopedByProject(project);
  if (isCustomModel(attr)) {
    return store2.scoped({ model_id: attr.model_id }).count();
  }
  return store2.count();
}
function getOptionsMenuLabel(attr) {
  if (attr.is_from_integration) return _4("From integration");
  if (isTopLevelCardModel(attr)) {
    return _4("Options");
  }
  if (isProjectModel(attr)) {
    return _4("All cards");
  }
  if (isOrgModel(attr)) {
    return _4("All cards in org");
  }
  return attr.model_name;
}
angular_default.module("kantree").directive("attributeWidget", [
  "$compile",
  "$timeout",
  "$q",
  function($compile, $timeout2, $q) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/ui/attributes/ng-components/templates/attribute-widget.html",
      scope: {
        project: "<?",
        attributeGroup: "<",
        attribute: "<",
        obj: "<?",
        hideHeader: "<?",
        container: "@?",
        editable: "<?",
        attributeEditable: "<?",
        attributeMovable: "<?",
        directiveProperty: "@?",
        isTemplate: "<?"
      },
      controller: [
        "$scope",
        "attributeOptionsModal",
        "attributeRolesModal",
        "projectSettingsModal",
        "$q",
        "$sce",
        function($scope2, attributeOptionsModal, attributeRolesModal, projectSettingsModal, $q2, $sce) {
          injectI18nHelpersIntoScope($scope2);
          let attributeType;
          const isLimitedAttributeGroup = !($scope2.attributeGroup instanceof ModelAttributeGroup) || $scope2.attributeGroup.model?.base_model_type === "top_level_card";
          $scope2.nameEditing = false;
          $scope2.attrRenderDisabled = $scope2.obj && $scope2.obj.is_template && ["group_type", "members"].indexOf(attributeType) !== -1;
          if ($scope2.attrRenderDisabled) {
            $scope2.messageDisabled = $sce.trustAsHtml(_4("You can't edit this field on <span>card template</span>"));
          }
          $createEffect($scope2, () => {
            $scope2.isDebugModeEnabled = isDebugModeEnabled();
          });
          $scope2.getOptionsMenuLabel = getOptionsMenuLabel;
          function getOptionsMenuItems() {
            const items = [
              { subheader: _4("{type} field", { type: attributeType.title }) },
              {
                label: _4("Rename"),
                icon: "pencil",
                action: () => {
                  $scope2.toggleEditName(true);
                }
              },
              {
                label: _4("Options"),
                icon: "cog",
                action: () => {
                  attributeOptionsModal.open($scope2.project, $scope2.attributeGroup, $scope2.attribute, $scope2.obj);
                },
                enabled: () => $scope2._attributeEditable
              },
              {
                label: _4("Permissions"),
                icon: "bi-key-fill",
                action: () => {
                  attributeRolesModal.open($scope2.attributeGroup.project, $scope2.attributeGroup, $scope2.attribute);
                },
                enabled: () => $scope2.canManageRolePerms
              },
              {
                label: _n(
                  "Delete this field in {count} card",
                  "Delete this field in {count} cards",
                  countCardsUsingAttrInProject($scope2.attribute, $scope2.project)
                ),
                icon: "trash",
                action: () => {
                  $q2.when(confirmAttrDeletion(), () => $scope2.attributeGroup.remove($scope2.attribute));
                },
                enabled: () => $scope2._attributeEditable && !$scope2.attribute.is_from_integration && isProjectScoped($scope2.attribute)
              }
            ];
            if ($scope2.attribute.is_from_integration) {
              items.push({ label: "--" }, { desc: _4("This field is added via an integration") });
              return items;
            }
            if (isLimitedAttributeGroup) {
              return items;
            }
            if ($scope2.project) {
              if (isOrgModel($scope2.attribute)) {
                items.push(
                  { label: "--" },
                  {
                    desc: _4("This field is available for all cards in the organization"),
                    classes: "warning"
                  },
                  { desc: _4("Organization fields can be disabled from workspace settings") },
                  {
                    icon: "sliders",
                    label: _4("Open workspace settings"),
                    action: () => projectSettingsModal.open($scope2.project, "models")
                  }
                );
              } else {
                items.push({ label: "--" }, { desc: _4("The field is available for:") });
                items.push({
                  label: _4("All cards from the workspace"),
                  selected: () => isProjectModel($scope2.attribute),
                  action: () => {
                    $q2.digest($scope2.attributeGroup.changeOwner($scope2.attribute, $scope2.project));
                  }
                });
                items.push(...cardModelStore.scopedByEnabled($scope2.project).query({ base_model_type: query_exports.isNull() }).map((model) => ({
                  label: model.name,
                  icon: model.indicator || null,
                  color: model.card_color || "transparent",
                  selected: () => $scope2.attribute.model_id === model.id,
                  action: () => {
                    $q2.digest($scope2.attributeGroup.changeOwner($scope2.attribute, model));
                  }
                })));
              }
            }
            return items;
          }
          function refreshOptionsMenu() {
            if ($scope2._attributeEditable || $scope2.canManageRolePerms) {
              $scope2.optionsMenuSpec = {
                config: () => () => getOptionsMenuItems()
              };
              if ($scope2.project) {
                $scope2.optionsMenuSpec.options = {
                  watch: (cb2, scope) => cardModelStore.scopedByEnabled($scope2.project).$watchAll(scope, cb2)
                };
              }
            } else {
              $scope2.optionsMenuSpec = null;
            }
          }
          function $watchValue(listener) {
            const off = $scope2[attributeType.arrayValue ? "$watchCollection" : "$watch"](
              () => {
                let objAttr = $scope2.attributeGroup.getObjAttribute($scope2.obj, $scope2.attribute);
                if (objAttr) {
                  return objAttr.value;
                }
              },
              () => $q2.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], listener)
            );
            $q2.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], listener);
            return off;
          }
          function attributeEditable() {
            return $scope2.attributeEditable && (isLimitedAttributeGroup || !isCustomModel($scope2.attribute) || canEditCardModel($scope2.project, $scope2.attribute.model_id));
          }
          function canEditAttrValue() {
            return $scope2.editable && (!attributeType.requireValidOptions || $scope2.attribute.valid_options) && (isLimitedAttributeGroup || canEditAttribute($scope2.project, $scope2.attribute));
          }
          function canManageRolePerms() {
            return $scope2.editable && !isLimitedAttributeGroup && !attributeType.decorative && $scope2.project && $scope2.project.owner && $scope2.project.owner.type !== "user" && isAllowedInProject($scope2.project, "project", "ACCESS") && !structureIsLocked($scope2.project);
          }
          let attributeWatcherOff;
          function refreshAttribute() {
            attributeType = $scope2.attributeType = attributeTypeRegistry.get($scope2.attribute.type);
            if (attributeWatcherOff) attributeWatcherOff();
            if (!$scope2.attributeType.noAttributeValue && !!$scope2.obj) {
              attributeWatcherOff = $watchValue((value2) => {
                $scope2.value = value2;
              });
            }
            refreshOptionsMenu();
          }
          refreshAttribute();
          $scope2.$watch("attribute", (newVal, oldVal) => {
            if (newVal === oldVal) return;
            refreshAttribute();
            $scope2.renderWidget();
          });
          $scope2.$watch("editable", () => {
            $scope2.canEditAttrValue = canEditAttrValue();
            $scope2.canManageRolePerms = canManageRolePerms();
            $scope2._attributeEditable = attributeEditable();
            $scope2.canMoveAttr = $scope2._attributeEditable && $scope2.attributeMovable && !structureIsLocked($scope2.project);
            refreshOptionsMenu();
          });
          $scope2.$watch("attribute.valid_options", (newVal, oldVal) => {
            if (newVal === oldVal) return;
            $scope2.canEditAttrValue = canEditAttrValue();
          });
          $scope2.$watch("attribute.model_id", (newVal, oldVal) => {
            if (newVal === oldVal) return;
            $scope2._attributeEditable = attributeEditable();
            $scope2.canMoveAttr = $scope2._attributeEditable && $scope2.attributeMovable && !structureIsLocked($scope2.project);
            refreshOptionsMenu();
          });
          $scope2.$watch("attributeEditable", (newVal, oldVal) => {
            if (newVal === oldVal) return;
            $scope2._attributeEditable = attributeEditable();
            $scope2.canMoveAttr = $scope2._attributeEditable && $scope2.attributeMovable && !structureIsLocked($scope2.project);
            refreshOptionsMenu();
          });
          $scope2.getPosition = function(attribute2) {
            if (attribute2.model_is_base) return `${attribute2.model_is_base}-${attribute2.position}`;
            const position = $scope2.attributeGroup.getPosition(attribute2);
            if (!isNumber_default(position[1])) {
              return `model-${attribute2.position}`;
            }
            return `project-${position[1]} model-(-${position[2]})`;
          };
        }
      ],
      link: function(scope, el2) {
        var $el = jquery_default(el2);
        let childScope, widgetNode, html5;
        scope.renderWidget = function() {
          const isConfigured = isAttributeConfigured(scope.attribute);
          if (childScope) {
            childScope.$destroy();
            widgetNode.remove();
          }
          if (!scope.attrRenderDisabled && isConfigured) {
            let directiveProperty = "widgetDirective";
            if (scope.directiveProperty && typeof scope.attributeType[scope.directiveProperty] !== "undefined") {
              directiveProperty = scope.directiveProperty;
            }
            html5 = `<${scope.attributeType[directiveProperty]} project="project" attribute-group="attributeGroup"
            attribute="attribute" obj="obj" value="value" editable="canEditAttrValue"
            container="{{container}}" attribute-editable="_attributeEditable" is-template="isTemplate"/>`;
          } else {
            html5 = `<attribute-required-options project="project" attribute="attribute" obj="obj" />`;
          }
          childScope = scope.$new(false);
          widgetNode = $compile(html5)(childScope);
          $el.append(widgetNode);
        };
        scope.renderWidget($el);
        scope.toggleEditName = function(edit2) {
          scope.nameEditing = edit2;
          if (edit2 && !scope.hideHeader && !scope.attributeType.widgetHideAttributeName) {
            scope.attributeName = scope.attribute.name;
            $timeout2(function() {
              $el.find(">label>input")[0].focus();
              $el.find(">label>input")[0].select();
            });
          } else {
            $el.find('[ng-dblclick="edit()"]').trigger("dblclick");
          }
        };
        scope.handleNameDoubleClick = function() {
          if (scope._attributeEditable) {
            scope.toggleEditName(true);
          }
        };
        $el.on("mouseover", "label>.fa-arrows,.attribute-widget-settings-btn", function() {
          $el.addClass("hover");
        }).on("mouseout", "label>.fa-arrows,.attribute-widget-settings-btn", function() {
          if (!$el.hasClass("drop-open")) {
            $el.removeClass("hover");
          }
        });
        scope.onDropMenuOpen = function() {
          $el.addClass("hover drop-open");
        };
        scope.onDropMenuClose = function() {
          $el.removeClass("hover drop-open");
        };
        $el.on("keydown", ">label>input", (event2) => {
          if (["Enter", "NumpadEnter"].includes(event2.code)) {
            const newName = event2.target.value.trim();
            if (newName !== "") {
              scope.$evalAsync(() => {
                if (scope.attribute.name !== newName) {
                  $q.digest(scope.attributeGroup.update(scope.attribute, { name: newName }));
                }
                scope.toggleEditName(false);
              });
            }
          }
          if (event2.code === "Escape") {
            event2.stopPropagation();
            scope.$evalAsync(() => scope.toggleEditName(false));
          }
        });
        $el.on("focusout", ">label>input", (event2) => {
          scope.$evalAsync(() => {
            scope.toggleEditName(false);
          });
        });
        scope.$on("attrConfiguredSuccessfully", (event2, attrId) => {
          if (scope.attribute.id === attrId) scope.renderWidget($el);
        });
        scope.$on("newAttributeCreated", (event2, attrId) => {
          if (scope.attribute.id === attrId) {
            $el.addClass("highlight");
            const isConfigured = isAttributeConfigured(scope.attribute);
            if (isConfigured) scope.toggleEditName(true);
          }
        });
      }
    };
  }
]);

// public/app/ui/attributes/ng-components/attribute-required-options.js
angular_default.module("kantree").directive("attributeRequiredOptions", [
  function() {
    return {
      template: `<div>
          <span ng-show="attributeEditable" class="attribute-required-options">Configure this field</span>
          <span ng-show="!attributeEditable">Field not configured yet</span>
        </div>`,
      restrict: "E",
      scope: {
        project: "<",
        attribute: "<",
        obj: "<?"
      },
      controllerAs: "$ctrl",
      bindToController: {
        project: "<",
        attribute: "<",
        obj: "<?"
      },
      controller: [
        "$scope",
        "$element",
        "dropdown",
        function($scope2, $element2, $dropdown) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.attributeEditable = canEditCardModel($scope2.project, $scope2.attribute.model_id);
          const dropHtml = `
            <attribute-required-options-content project="$ctrl.project" attribute="$ctrl.attribute" obj="$ctrl.obj"
              on-close="closeDrop()" on-save="closeDrop()"></attribute-required-options-content>
          `;
          const target = $element2[0].getElementsByClassName("attribute-required-options")[0];
          const drop = $dropdown.openCompile(target, dropHtml, $scope2, {
            classes: "attribute-required-options-drop drop-theme-menu drop-theme-arrow",
            _autoOpen: false,
            _destroyOnClose: false,
            tetherOptions: {
              constraints: [{
                to: "window",
                pin: true,
                attachment: "together none"
              }]
            }
          });
          $scope2.closeDrop = function() {
            drop.close();
          };
          $scope2.$on("newAttributeCreated", (event2, attrId) => {
            if ($scope2.attribute.id === attrId) drop.open();
          });
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("attributeRequiredOptionsContent", [
  function() {
    return {
      templateUrl: "/static/app/ui/attributes/ng-components/templates/attribute-required-options-content.html",
      scope: {
        project: "<",
        attribute: "<",
        obj: "<?",
        onClose: "&",
        onSave: "&"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          const resolvedType = attributeTypeRegistry.resolveAttrTypeAlias($scope2.attribute.type);
          $q.when(getOrLoadAttrType(resolvedType.type.name), (type) => {
            $scope2.typeOptions = type.options.filter((opt) => opt.required);
          });
          $scope2.attrOptions = JSON.parse(JSON.stringify(unwrap($scope2.attribute.options)));
          $scope2.attributeName = $scope2.attribute.name;
          $scope2.card = null;
          if ($scope2.obj && $scope2.obj.__type__ === "card") {
            $scope2.card = $scope2.obj;
          }
          $scope2.canSave = false;
          $scope2.$watchGroup(["attributeName", "attrOptions"], (newVal, oldVal) => {
            const flattenedRequirements = [newVal[0], ...Object.values(newVal[1])];
            for (const opt of flattenedRequirements) {
              if (isNull(opt) || isUndefined(opt) || isString_default(opt) && opt.length === 0) {
                $scope2.canSave = false;
                break;
              } else {
                $scope2.canSave = true;
              }
            }
          });
          $scope2.close = function() {
            $scope2.onClose();
          };
          $scope2.save = function() {
            const model = cardModelStore.getAttributeOwner($scope2.attribute);
            const attrGroup = new ModelAttributeGroup($scope2.project, model, cardModelStore.getExtendedModelAttributes(model, $scope2.project));
            $q.when(attrGroup.update($scope2.attribute, { name: $scope2.attributeName, options: $scope2.attrOptions }), () => {
              toastNotify(_4("Field configured successfully"), "success");
              $broadcast("attrConfiguredSuccessfully", $scope2.attribute.id);
              $scope2.onSave();
            });
          };
        }
      ]
    };
  }
]);

// public/app/ui/attributes/ng-components/input.js
angular_default.module("kantree").directive("attributeTypeInput", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/ui/attributes/ng-components/templates/input.html",
    scope: {
      project: "<",
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<",
      attributeEditable: "<"
    },
    controller: [
      "$scope",
      "$element",
      "attributeEditor",
      "$q",
      "$injector",
      function($scope2, $element2, attributeEditor, $q, $injector) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.label = null;
        $scope2.edit = false;
        $scope2.loading = false;
        $scope2.hasError = false;
        $scope2.errorMessage = _4("An error ocurred");
        $scope2.isEmptyValue = function() {
          return isEmptyValue($scope2.label) && (!$scope2.options.valueIsOption || !$scope2.attribute.options || !$scope2.attribute.options[$scope2.options.valueIsOption]);
        };
        $scope2.isEditableValue = function() {
          return !$scope2.options.readonly && ($scope2.editable && !$scope2.options.valueIsOption || $scope2.options.valueIsOption && $scope2.attributeEditable);
        };
        $scope2.options = Object.assign({
          readonly: false,
          overflow: false,
          color: false,
          init: null,
          showActionIcon: null,
          action: null,
          actionIcon: "fa-external-link",
          actionTooltip: "Open link",
          clearable: true,
          valueIsOption: false,
          formatValue: null,
          editBtn: false,
          editorOpener: false
        }, attributeTypeRegistry.get($scope2.attribute.type).widgetOptions || {});
        if ($scope2.options.showActionIcon === null) {
          $scope2.options.showActionIcon = () => !!$scope2.options.action;
        } else if (typeof $scope2.options.showActionIcon !== "boolean") {
          const fn = $scope2.options.showActionIcon;
          $scope2.options.showActionIcon = () => $injector.invoke(fn, this, { "$scope": $scope2 });
        }
        if ($scope2.options.init) {
          $scope2.options.init($scope2);
        }
        $scope2.$watch("value", function(value2) {
          $scope2.isEmpty = false;
          if (angular_default.isArray(value2)) {
            $scope2.label = value2[0];
            $scope2.data = value2.join(" ");
          } else {
            $scope2.data = $scope2.label = value2;
          }
          $scope2.bgColor = null;
          $scope2.fgColor = null;
          if ($scope2.options.color) {
            const e3 = extractColorFromText2($scope2.label);
            if (e3) {
              $scope2.label = e3[0];
              $scope2.bgColor = e3[1];
              $scope2.fgColor = e3[2];
            }
          }
          $scope2.label = isEmptyValue($scope2.label) ? null : $scope2.label;
          if ($scope2.label && $scope2.options.formatValue) {
            $scope2.label = $injector.invoke($scope2.options.formatValue, this, { "$scope": $scope2, "$value": $scope2.label });
          }
          if ($scope2.label === null) {
            $scope2.isEmpty = true;
            $scope2.bgColor = null;
            $scope2.fgColor = null;
            if ($scope2.options.editBtn && $scope2.isEditableValue()) {
              $scope2.label = $scope2.options.editBtn === true ? translation._("Edit") : $scope2.options.editBtn;
            }
          }
          if (!$scope2.options.editorOpener) {
            $scope2.toggleEdit();
          }
        });
        $scope2.toggleEdit = function(edit2) {
          edit2 = $scope2.isEditableValue() && (edit2 || $scope2.label === null && !$scope2.hasError && !$scope2.loading);
          if (edit2 && $scope2.options.editorOpener) {
            const value2 = $scope2.options.valueIsOption ? ($scope2.attribute.options || {})[$scope2.options.valueIsOption] : $scope2.data;
            attributeEditor.open(
              $element2.find(">.value")[0],
              $scope2,
              $scope2.project,
              $scope2.attributeGroup,
              $scope2.attribute,
              $scope2.obj,
              value2,
              true,
              null,
              null,
              true
            );
          } else {
            $scope2.edit = edit2;
          }
        };
        $scope2.clearValue = function() {
          $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), () => {
            $scope2.value = "";
          });
        };
        $scope2.callAction = function() {
          $scope2.options.action($scope2);
        };
        $scope2.$watch("editable", function(newVal, oldVal) {
          if (newVal === oldVal) return;
          $scope2.toggleEdit();
        });
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeInputEditor", [
  "$timeout",
  function($timeout2) {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/ui/attributes/ng-components/templates/input-editor.html",
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        onDone: "&",
        noAutoFocus: "@?",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.dirty = false;
          $scope2.hasError = false;
          $scope2.options = Object.assign({
            inputType: "text",
            inputPlaceholder: _4("Empty"),
            color: false,
            allowEmpty: true,
            valueIsOption: false
          }, attributeTypeRegistry.get($scope2.attribute.type).widgetOptions || {});
          if ($scope2.options.valueIsOption) {
            $scope2.inputValue = ($scope2.attribute.options || {})[$scope2.options.valueIsOption];
          } else {
            $scope2.inputValue = $scope2.value;
          }
          if ($scope2.options.color) {
            const e3 = extractColorFromText2($scope2.inputValue);
            if (e3) {
              $scope2.inputValue = e3[0];
              $scope2.color = e3[1];
            }
          }
          $scope2.colorPickerMenu = { config: [
            { subheader: _4("Background color") },
            {
              colorpicker: true,
              getValue: () => $scope2.color,
              action: function(event2, color) {
                $scope2.$applyAsync(() => {
                  $scope2.color = color;
                  $scope2.dirty = true;
                  $scope2.focus();
                });
              },
              hasColorPalette: true
            }
          ] };
          $scope2.save = function() {
            if (isEmptyValue($scope2.inputValue)) {
              if (!$scope2.options.allowEmpty) {
                return;
              }
              if ($scope2.value) {
                $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), $scope2.onDone);
              }
              return;
            }
            var value2 = $scope2.inputValue;
            if ($scope2.options.color && $scope2.color) {
              value2 += " [" + $scope2.color + "]";
            }
            if ($scope2.options.save) {
              $scope2.options.save($scope2, value2);
            } else {
              $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, value2), $scope2.onDone, () => {
                $scope2.hasError = true;
              });
            }
          };
        }
      ],
      link: function(scope, element2, attrs2) {
        var $el = jquery_default(element2);
        var $input = $el.find("input");
        angular_default.forEach(scope.options.inputAttrs || {}, function(v3, k2) {
          $input.attr(k2, v3);
        });
        if (scope.noAutoFocus !== "true") {
          $timeout2(function() {
            $timeout2(function() {
              $el.find("input")[0].focus();
              $el.find("input")[0].select();
            }, 0, false);
          }, 0, false);
        }
        var cancel = function() {
          if (isEmptyValue(scope.inputValue) && !scope.options.allowEmpty) return;
          scope.$evalAsync(function() {
            scope.onDone();
          });
        };
        scope.focus = function() {
          $input.focus();
        };
        $input.on("keydown", function(e3) {
          if (e3.keyCode === 13) {
            if (scope.dirty) {
              scope.save();
            } else {
              cancel();
            }
          } else if (e3.keyCode === 27) {
            e3.stopPropagation();
            e3.preventDefault();
            cancel();
          } else {
            scope.dirty = true;
          }
        });
        if (!scope.embedded) {
          $input.on("blur", function(e3) {
            setTimeout(function() {
              if ($el.find(">a").hasClass("drop-enabled")) return;
              if (scope.dirty) {
                scope.save();
              } else {
                cancel();
              }
            }, 500);
          });
        }
        if (!isIE()) {
          $input.on("input", function() {
            scope.dirty = true;
          });
          if ($input.prop("type") === "number") {
            $input.on("click", function() {
              jquery_default(this).focus();
            });
          }
        }
      }
    };
  }
]);
angular_default.module("kantree").directive("attributeTypeInputForm", [
  "$q",
  function($q) {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-input-form">
          <input type="{{options.inputType}}" placeholder="{{options.inputPlaceholder}}" class="form-control"
            ng-model="inputValue">
        </div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<"
      },
      controller: [
        "$scope",
        function($scope2) {
          $scope2.inputValue = $scope2.value;
          $scope2.options = Object.assign({
            inputType: "text"
          }, attributeTypeRegistry.get($scope2.attribute.type).widgetOptions || {});
          $scope2.$watch("value", (newVal, oldVal) => {
            if (newVal === oldVal) return;
            if (newVal === $scope2.inputValue) return;
            $scope2.inputValue = newVal;
          });
        }
      ],
      link: function(scope, el2) {
        jquery_default(el2).on("input", "input", function(e3) {
          if (this.value) {
            let value2 = this.value;
            if (scope.options.inputType === "number") {
              value2 = this.valueAsNumber;
            }
            $q.digest(scope.attributeGroup.setObjAttribute(scope.obj, scope.attribute, value2));
          } else {
            $q.digest(scope.attributeGroup.clearObjAttribute(scope.obj, scope.attribute));
          }
        });
      }
    };
  }
]);

// public/app/ui/attributes/ng-components/repr-template.js
var { iconClass: iconClass4 } = (init_icons(), __toCommonJS(icons_exports));
(function() {
  var template3 = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
  templates["attributeReprWidgets"] = template3({ "1": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, alias3 = depth0 != null ? depth0 : container.nullContext || {};
    return '  <div class="attribute-repr-widget attribute-repr-widget-' + alias2(alias1((stack1 = blockParams[0][0]) != null ? stack1.type : stack1, depth0)) + " attribute-repr-type-" + alias2(alias1((stack1 = (stack1 = blockParams[0][0]) != null ? stack1.attribute : stack1) != null ? stack1.type : stack1, depth0)) + " " + alias2(alias1((stack1 = blockParams[0][0]) != null ? stack1.cssclass : stack1, depth0)) + '"\n    style="' + ((stack1 = helpers2["if"].call(alias3, (stack1 = blockParams[0][0]) != null ? stack1.color : stack1, { "name": "if", "hash": {}, "fn": container.program(2, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams })) != null ? stack1 : "") + " " + ((stack1 = helpers2["if"].call(alias3, (stack1 = blockParams[0][0]) != null ? stack1.bgcolor : stack1, { "name": "if", "hash": {}, "fn": container.program(4, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams })) != null ? stack1 : "") + '">\n    ' + ((stack1 = helpers2["if"].call(alias3, (stack1 = blockParams[0][0]) != null ? stack1.showIcon : stack1, { "name": "if", "hash": {}, "fn": container.program(6, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams })) != null ? stack1 : "") + "\n    " + ((stack1 = helpers2["if"].call(alias3, (stack1 = blockParams[0][0]) != null ? stack1.isText : stack1, { "name": "if", "hash": {}, "fn": container.program(8, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams })) != null ? stack1 : "") + "\n    " + ((stack1 = helpers2["if"].call(alias3, (stack1 = blockParams[0][0]) != null ? stack1.isImage : stack1, { "name": "if", "hash": {}, "fn": container.program(10, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams })) != null ? stack1 : "") + "\n  </div>\n";
  }, "2": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1;
    return "color: " + container.escapeExpression(container.lambda((stack1 = blockParams[1][0]) != null ? stack1.color : stack1, depth0)) + ";";
  }, "4": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1;
    return "background-color: " + container.escapeExpression(container.lambda((stack1 = blockParams[1][0]) != null ? stack1.bgcolor : stack1, depth0)) + ";";
  }, "6": function(container, depth0, helpers2, partials, data2) {
    var helper;
    return '<i class="' + iconClass4(container.escapeExpression((helper = (helper = helpers2.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : helpers2.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "icon", "hash": {}, "data": data2 }) : helper))) + '"></i>';
  }, "8": function(container, depth0, helpers2, partials, data2) {
    var helper;
    return "<span>" + container.escapeExpression((helper = (helper = helpers2.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : helpers2.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "value", "hash": {}, "data": data2 }) : helper)) + "</span>";
  }, "10": function(container, depth0, helpers2, partials, data2) {
    var helper;
    return '<img src="' + container.escapeExpression((helper = (helper = helpers2.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : helpers2.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "value", "hash": {}, "data": data2 }) : helper)) + '">';
  }, "compiler": [7, ">= 4.0.0"], "main": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1;
    return (stack1 = helpers2.each.call(depth0 != null ? depth0 : container.nullContext || {}, depth0 != null ? depth0.widgets : depth0, { "name": "each", "hash": {}, "fn": container.program(1, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams })) != null ? stack1 : "";
  }, "useData": true, "useBlockParams": true });
})();

// public/app/ui/attributes/ng-components/select.js
angular_default.module("kantree").directive("attributeTypeSelect", function() {
  return {
    restrict: "E",
    replace: true,
    templateUrl: "/static/app/ui/attributes/ng-components/templates/select.html",
    scope: {
      attributeGroup: "<",
      attribute: "<",
      obj: "<",
      value: "<",
      editable: "<",
      attributeEditable: "<?"
    },
    controller: [
      "$scope",
      "$q",
      function($scope2, $q) {
        injectI18nHelpersIntoScope($scope2);
        $scope2.options = getSelectOptions($scope2.attribute);
        $scope2.loading = false;
        $scope2.$watch("value", (value2) => {
          if ($scope2.options.useItemsAsValue) {
            $scope2.loading = true;
            $q.when(getSelectChoices($scope2.attributeGroup, $scope2.attribute, $scope2.obj), (choices) => {
              $scope2.loading = false;
              $scope2.selected = formatAttributeValueAsSelectChoice($scope2.options, value2, choices);
            });
          } else {
            $scope2.selected = formatAttributeValueAsSelectChoice($scope2.options, value2);
          }
        });
        $scope2.callAction = function() {
          $scope2.options.action($scope2);
        };
      }
    ]
  };
});
angular_default.module("kantree").directive("attributeTypeSelectEditor", [
  function() {
    return {
      restrict: "E",
      replace: true,
      template: `
        <div class="attribute-type-select-editor">
          <pretty-menu class="pretty-menu" config="menuSpec.config" options="menuSpec.options"
          on-close="onDone()" on-update="onMenuUpdate($menuEvent)"></pretty-menu>
        </div>`,
      scope: {
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        value: "<",
        onDone: "&",
        onUpdate: "&",
        onInit: "&",
        attributeEditable: "<?",
        embedded: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.options = getSelectOptions($scope2.attribute);
          $scope2.menuSpec = { config: [{ label: _4("Loading"), icon: "spin fa-spinner" }] };
          const refreshValue = () => {
            $q.when($scope2.attributeGroup.getObjAttributeValue($scope2.obj, $scope2.attribute)[1], (value2) => {
              $scope2.value = value2;
            });
          };
          $q.when(getSelectChoices($scope2.attributeGroup, $scope2.attribute, $scope2.obj), (choices) => {
            $scope2.menuSpec = {
              config: () => {
                return [
                  {
                    label: _4("[No value]"),
                    action: () => $q.when($scope2.attributeGroup.clearObjAttribute($scope2.obj, $scope2.attribute), $scope2.onDone)
                  }
                ].concat(choices.map((choice) => {
                  return {
                    label: choice[1],
                    color: choice[2],
                    icon: choice[3],
                    action: () => {
                      if ($scope2.options.onSelect) {
                        $q.when($scope2.options.onSelect($scope2.attributeGroup, $scope2.attribute, $scope2.obj, $scope2.value, choice), refreshValue, $scope2.onDone);
                      } else if ($scope2.options.multi) {
                        if (isSelected($scope2.options, $scope2.value, choice[0])) {
                          $q.when($scope2.attributeGroup.popObjAttribute($scope2.obj, $scope2.attribute, choice), refreshValue);
                        } else {
                          $q.when($scope2.attributeGroup.appendObjAttribute($scope2.obj, $scope2.attribute, choice), refreshValue);
                        }
                      } else {
                        $q.when($scope2.attributeGroup.setObjAttribute($scope2.obj, $scope2.attribute, choice), $scope2.onDone);
                      }
                    },
                    noCloseAfterAction: !!$scope2.options.multi,
                    enableActionOnselected: !!$scope2.options.multi,
                    selected: () => isSelected($scope2.options, $scope2.value, choice[0])
                  };
                }));
              },
              options: { filterable: true }
            };
          });
          var isInit = false;
          var debouncedUpdate = debounce2(() => {
            if (isFunction_default($scope2.onUpdate)) {
              $scope2.onUpdate();
            }
          }, 100);
          $scope2.onMenuUpdate = (menuEvent) => {
            if (!isInit && menuEvent === "panelInit") {
              $scope2.onInit();
              isInit = true;
            } else {
              debouncedUpdate();
            }
          };
        }
      ]
    };
  }
]);

// public/app/ui/attributes/repr-widgets/button/component.js
angular_default.module("kantree").directive("attributeReprButton", [
  function() {
    return {
      template: `
        <button type="button" class="attribute-repr attribute-repr-button btn btn-action" ng-disabled="$ctrl.widget.options.disabled"
          uib-tooltip="$ctrl.widget.options.disabledTooltip" tooltip-enable="!!$ctrl.widget.options.disabledTooltip">
          <i class="bi-exclamation-triangle-fill" ng-show="$ctrl.widget.options.disabled"></i>
          {{$ctrl.widget.options.label}}
        </button>
      `,
      restrict: "E",
      replace: true,
      scope: {
        widget: "<?",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        editable: "<?"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$element", "$scope"];
        $postLink() {
          this.dispose = this.widget.onDOMLoad?.(this.$element, {
            editable: this.editable,
            openEditor: () => this.attributeGroup.openEditor(this.obj, this.attribute, this.$element, this.$scope),
            scope: this.$scope
          });
        }
        $onDestroy() {
          this.dispose?.();
        }
      }
    };
  }
]);

// public/app/ui/attributes/repr-widgets/content/component.js
angular_default.module("kantree").directive("attributeReprContent", [
  function() {
    return {
      template: `
        <span class="attribute-repr attribute-repr-content">
          <p>{{$ctrl.widget.value|markdownToPlainText}}</p>
          <button type="button" class="btn btn-icon btn-sm expand" ng-show="$ctrl.widget.value"><i class="fa fa-expand"></i></button>
        </span>
      `,
      restrict: "E",
      replace: true,
      scope: {
        widget: "<",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        editable: "<?"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$element", "$scope"];
        $postLink() {
          this.dispose = this.widget.onDOMLoad?.(this.$element, {
            editable: this.editable,
            openEditor: () => this.attributeGroup.openEditor(this.obj, this.attribute, this.$element, this.$scope),
            scope: this.$scope
          });
        }
        $onDestroy() {
          this.dispose?.();
        }
      }
    };
  }
]);

// public/app/ui/attributes/repr-widgets/progress/component.js
angular_default.module("kantree").directive("attributeReprProgress", [
  function() {
    return {
      template: `
        <span class="attribute-repr attribute-repr-progress"
          uib-tooltip="{{::$ctrl.widget.tooltip}}">
          <solidjs-component
            component="$ctrl.Slider"
            value="$ctrl.widget.value"
            readonly="true"
            classes="slider-progress-bar"
          ></solidjs-component>
        </span>
      `,
      restrict: "E",
      replace: true,
      scope: {
        widget: "<",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        editable: "<?"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$element", "$scope"];
        Slider = slider_default;
        $postLink() {
          this.dispose = this.widget.onDOMLoad?.(this.$element, {
            editable: this.editable,
            openEditor: () => this.attributeGroup.openEditor(this.obj, this.attribute, this.$element, this.$scope),
            scope: this.$scope
          });
        }
        $onDestroy() {
          this.dispose?.();
        }
      }
    };
  }
]);

// public/app/ui/attributes/repr-widgets/widget/component.js
angular_default.module("kantree").directive("attributeReprWidget", [
  function() {
    return {
      template: `
        <span class="attribute-repr attribute-repr-widget"
          ng-class="::['attribute-repr-widget-' + $ctrl.widget.type,
            $ctrl.widget.attribute ? ('attribute-repr-type-' + $ctrl.widget.attribute.type) : '',
            $ctrl.widget.options.clickable ? 'clickable' : '',
            $ctrl.widget.options.cssclass]"
          uib-tooltip="{{::$ctrl.widget.tooltip}}" ng-attr-data-attr-id="{{$ctrl.widget.attribute.id}}">
          <i ng-if="::$ctrl.widget.options.showIcon" ng-class="::$ctrl.widget.options.icon|iconClass"></i>
          <span ng-if="::$ctrl.widget.options.isText">{{::$ctrl.widget.value}}</span>
          <img ng-if="::$ctrl.widget.options.isImage" ng-src="{{::$ctrl.widget.value}}">
        </span>
      `,
      restrict: "E",
      replace: true,
      scope: {
        widget: "<",
        attributeGroup: "<",
        attribute: "<",
        obj: "<",
        editable: "<?"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$element", "$scope"];
        $postLink() {
          if (this.widget.bgcolor) {
            $element.css({
              "background-color": this.widget.bgcolor,
              "color": this.widget.color || tinycolor.mostReadable(this.widget.bgcolor, ["#FFFFFF", "#000000"]).toHexString()
            });
          } else if (this.widget.color) {
            $element.css({
              "color": this.widget.color
            });
          }
          this.dispose = this.widget.onDOMLoad?.(this.$element, {
            editable: this.editable,
            openEditor: () => this.attributeGroup.openEditor(this.obj, this.attribute, this.$element, this.$scope),
            scope: this.$scope
          });
        }
        $onDestroy() {
          this.dispose?.();
        }
      }
    };
  }
]);

// public/app/ui/attributes/repr-widgets/repr-widgets-templates.js
var { iconClass: iconClass5 } = (init_icons(), __toCommonJS(icons_exports));
(function() {
  var template3 = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
  templates["attribute-repr-widget"] = template3({ "1": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return " attribute-repr-type-" + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "attribute") : depth0) != null ? lookupProperty(stack1, "type") : stack1, depth0));
  }, "3": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return " " + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "cssclass") : stack1, depth0));
  }, "5": function(container, depth0, helpers2, partials, data2) {
    return " clickable";
  }, "7": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return "color: " + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "color") : stack1, depth0)) + ";";
  }, "9": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return "background-color: " + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "bgcolor") : stack1, depth0)) + ";";
  }, "11": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="' + ((stack1 = lookupProperty(helpers2, "if").call(depth0 != null ? depth0 : container.nullContext || {}, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "iconClass") : stack1, { "name": "if", "hash": {}, "fn": container.program(12, data2, 0), "inverse": container.program(14, data2, 0), "data": data2, "loc": { "start": { "line": 5, "column": 36 }, "end": { "line": 5, "column": 119 } } })) != null ? stack1 : "") + '"></i>';
  }, "12": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "iconClass") : stack1, depth0));
  }, "14": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return iconClass5(container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "icon") : stack1, depth0)));
  }, "16": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return "<span>" + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "value") || (depth0 != null ? lookupProperty(depth0, "value") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "value", "hash": {}, "data": data2, "loc": { "start": { "line": 6, "column": 30 }, "end": { "line": 6, "column": 39 } } }) : helper)) + "</span>";
  }, "18": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<img src="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "value") || (depth0 != null ? lookupProperty(depth0, "value") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "value", "hash": {}, "data": data2, "loc": { "start": { "line": 7, "column": 35 }, "end": { "line": 7, "column": 44 } } }) : helper)) + '">';
  }, "20": function(container, depth0, helpers2, partials, data2) {
    return '  <span class="attribute-repr-widget-drop-icon">\n    <i class="bi-caret-down-fill"></i>\n    <i class="bi-caret-up-fill"></i>\n  </span>\n';
  }, "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, alias2 = container.hooks.helperMissing, alias3 = "function", alias4 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '\n<span class="attribute-repr attribute-repr-widget attribute-repr-widget-' + alias4((helper = (helper = lookupProperty(helpers2, "type") || (depth0 != null ? lookupProperty(depth0, "type") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "type", "hash": {}, "data": data2, "loc": { "start": { "line": 2, "column": 72 }, "end": { "line": 2, "column": 80 } } }) : helper)) + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "attribute") : depth0, { "name": "if", "hash": {}, "fn": container.program(1, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 2, "column": 80 }, "end": { "line": 2, "column": 143 } } })) != null ? stack1 : "") + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "cssclass") : stack1, { "name": "if", "hash": {}, "fn": container.program(3, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 2, "column": 143 }, "end": { "line": 2, "column": 195 } } })) != null ? stack1 : "") + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "clickable") : stack1, { "name": "if", "hash": {}, "fn": container.program(5, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 2, "column": 195 }, "end": { "line": 2, "column": 237 } } })) != null ? stack1 : "") + '"\n  title="' + alias4((helper = (helper = lookupProperty(helpers2, "tooltip") || (depth0 != null ? lookupProperty(depth0, "tooltip") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "tooltip", "hash": {}, "data": data2, "loc": { "start": { "line": 3, "column": 9 }, "end": { "line": 3, "column": 20 } } }) : helper)) + '" data-attribute-repr-id="' + alias4((helper = (helper = lookupProperty(helpers2, "id") || (depth0 != null ? lookupProperty(depth0, "id") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "id", "hash": {}, "data": data2, "loc": { "start": { "line": 3, "column": 46 }, "end": { "line": 3, "column": 52 } } }) : helper)) + '"\n  style="' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "color") : stack1, { "name": "if", "hash": {}, "fn": container.program(7, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 4, "column": 9 }, "end": { "line": 4, "column": 62 } } })) != null ? stack1 : "") + " " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "bgcolor") : stack1, { "name": "if", "hash": {}, "fn": container.program(9, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 4, "column": 63 }, "end": { "line": 4, "column": 131 } } })) != null ? stack1 : "") + '">\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "showIcon") : stack1, { "name": "if", "hash": {}, "fn": container.program(11, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 5, "column": 2 }, "end": { "line": 5, "column": 132 } } })) != null ? stack1 : "") + "\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "isText") : stack1, { "name": "if", "hash": {}, "fn": container.program(16, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 6, "column": 2 }, "end": { "line": 6, "column": 53 } } })) != null ? stack1 : "") + "\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "isImage") : stack1, { "name": "if", "hash": {}, "fn": container.program(18, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 7, "column": 2 }, "end": { "line": 7, "column": 53 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "hasDropdown") : stack1, { "name": "if", "hash": {}, "fn": container.program(20, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 8, "column": 2 }, "end": { "line": 13, "column": 9 } } })) != null ? stack1 : "") + "</span>\n";
  }, "useData": true });
  templates["attribute-repr-button"] = template3({ "1": function(container, depth0, helpers2, partials, data2) {
    return ' disabled="disabled"';
  }, "3": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return ' title="' + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "disabledTooltip") : stack1, depth0)) + '"';
  }, "5": function(container, depth0, helpers2, partials, data2) {
    return '<i class="bi-exclamation-triangle-fill"></i>';
  }, "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<button type="button" class="attribute-repr attribute-repr-button btn btn-action"\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "disabled") : stack1, { "name": "if", "hash": {}, "fn": container.program(1, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 2, "column": 2 }, "end": { "line": 2, "column": 53 } } })) != null ? stack1 : "") + "\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "disabledTooltip") : stack1, { "name": "if", "hash": {}, "fn": container.program(3, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 3, "column": 2 }, "end": { "line": 3, "column": 76 } } })) != null ? stack1 : "") + '\n  data-attribute-repr-id="' + alias2((helper = (helper = lookupProperty(helpers2, "id") || (depth0 != null ? lookupProperty(depth0, "id") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(alias1, { "name": "id", "hash": {}, "data": data2, "loc": { "start": { "line": 4, "column": 26 }, "end": { "line": 4, "column": 32 } } }) : helper)) + '">\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "disabled") : stack1, { "name": "if", "hash": {}, "fn": container.program(5, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 5, "column": 2 }, "end": { "line": 5, "column": 77 } } })) != null ? stack1 : "") + "\n  " + alias2(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "options") : depth0) != null ? lookupProperty(stack1, "label") : stack1, depth0)) + "\n</button>\n";
  }, "useData": true });
  templates["attribute-repr-content"] = template3({ "1": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return container.escapeExpression((helper = (helper = lookupProperty(helpers2, "value") || (depth0 != null ? lookupProperty(depth0, "value") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "value", "hash": {}, "data": data2, "loc": { "start": { "line": 2, "column": 29 }, "end": { "line": 2, "column": 38 } } }) : helper));
  }, "3": function(container, depth0, helpers2, partials, data2) {
    return '<button class="btn btn-icon btn-sm expand" type="button"><i class="fa fa-expand"></i></button>';
  }, "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, options2, alias1 = depth0 != null ? depth0 : container.nullContext || {}, alias2 = container.hooks.helperMissing, alias3 = "function", lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    }, buffer = '<span class="attribute-repr attribute-repr-content" data-attribute-repr-id="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "id") || (depth0 != null ? lookupProperty(depth0, "id") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "id", "hash": {}, "data": data2, "loc": { "start": { "line": 1, "column": 76 }, "end": { "line": 1, "column": 82 } } }) : helper)) + '">\n  <p>';
    stack1 = (helper = (helper = lookupProperty(helpers2, "markdownToPlainText") || (depth0 != null ? lookupProperty(depth0, "markdownToPlainText") : depth0)) != null ? helper : alias2, options2 = { "name": "markdownToPlainText", "hash": {}, "fn": container.program(1, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 2, "column": 5 }, "end": { "line": 2, "column": 62 } } }, typeof helper === alias3 ? helper.call(alias1, options2) : helper);
    if (!lookupProperty(helpers2, "markdownToPlainText")) {
      stack1 = container.hooks.blockHelperMissing.call(depth0, stack1, options2);
    }
    if (stack1 != null) {
      buffer += stack1;
    }
    return buffer + "</p>\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "value") : depth0, { "name": "if", "hash": {}, "fn": container.program(3, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 3, "column": 2 }, "end": { "line": 3, "column": 116 } } })) != null ? stack1 : "") + "\n</span>\n";
  }, "useData": true });
  templates["attribute-repr-progress"] = template3({ "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2) {
    var helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, alias2 = container.hooks.helperMissing, alias3 = "function", alias4 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<span class="attribute-repr attribute-repr-progress" data-attribute-repr-id="' + alias4((helper = (helper = lookupProperty(helpers2, "id") || (depth0 != null ? lookupProperty(depth0, "id") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "id", "hash": {}, "data": data2, "loc": { "start": { "line": 1, "column": 77 }, "end": { "line": 1, "column": 83 } } }) : helper)) + '" title="' + alias4((helper = (helper = lookupProperty(helpers2, "tooltip") || (depth0 != null ? lookupProperty(depth0, "tooltip") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "tooltip", "hash": {}, "data": data2, "loc": { "start": { "line": 1, "column": 92 }, "end": { "line": 1, "column": 103 } } }) : helper)) + '">\n  <div class="slider-root">\n    <span class="slider-rail"></span>\n    <span class="slider-track" style="width:' + alias4((helper = (helper = lookupProperty(helpers2, "value") || (depth0 != null ? lookupProperty(depth0, "value") : depth0)) != null ? helper : alias2, typeof helper === alias3 ? helper.call(alias1, { "name": "value", "hash": {}, "data": data2, "loc": { "start": { "line": 4, "column": 44 }, "end": { "line": 4, "column": 53 } } }) : helper)) + '%;"></span>\n  </div>\n</span>\n';
  }, "useData": true });
})();

// public/app/config/attr-type-categories.js
var attributeTypeCategories = [
  //{label: 'relationships', title: _lazy('Relationships'), submenu: true, important: true, icon: 'link'},
  { label: "remote", title: _lazy("External data source"), submenu: true, icon: "plug" },
  { label: "decoration" }
];

// public/app/ui/attributes/menus/add-attribute.js
angular_default.module("kantree").factory("addAttributeMenuFactory", [
  function() {
    var getItems = function(availableFor, onCreateAttribute, showOnlyModelOption) {
      var onlyModelOptionEnabled = true;
      var items = [];
      var attrTypes = attributeTypeRegistry.getAll().filter(function(type) {
        return !type.hidden && (!availableFor || !type.availableFor || type.availableFor.indexOf(availableFor) !== -1);
      });
      var importants, notImportants = [];
      importants = attrTypes.filter(function(type) {
        return type.important;
      });
      notImportants = attrTypes.filter(function(type) {
        return !type.important;
      });
      if (importants.length < 5 && notImportants.length > 0) {
        importants = attrTypes;
        notImportants = [];
      }
      var typeToMenuItem = function(type) {
        return {
          icon: type.icon,
          label: type.title,
          help: type.description,
          action: function() {
            onCreateAttribute(type, onlyModelOptionEnabled);
          }
        };
      };
      importants.forEach(function(type) {
        items.push(typeToMenuItem(type));
      });
      var notImportantCategoryItems = [];
      angular_default.forEach(attributeTypeCategories, function(cat) {
        var submenuItems = notImportants.filter(function(type) {
          return type.category === cat.label;
        }).map(typeToMenuItem);
        var menuItems = cat.important ? items : notImportantCategoryItems;
        if (cat.submenu) {
          if (submenuItems.length > 0) {
            menuItems.push({ label: cat.title, submenu: submenuItems, icon: cat.icon });
          }
        } else {
          menuItems.push({ label: "--" });
          if (cat.title) {
            menuItems.push({ subheader: cat.title });
          }
          menuItems.push(...submenuItems);
        }
      });
      var onlyModelOption = {
        checkbox: true,
        value: function() {
          return onlyModelOptionEnabled;
        },
        label: _4("Only add to current type"),
        toggle: function(isChecked) {
          onlyModelOptionEnabled = isChecked;
        }
      };
      if (notImportants.length || notImportantCategoryItems.length) {
        items.push({ label: "--" }, {
          label: _4("More types"),
          submenu: notImportants.filter(function(type) {
            return !type.category;
          }).map(typeToMenuItem).concat(notImportantCategoryItems).concat(showOnlyModelOption ? [onlyModelOption] : [])
        });
      }
      if (showOnlyModelOption) {
        items.push(onlyModelOption);
      }
      return items;
    };
    return {
      getItems,
      get: function(availableFor, onCreateAttribute, showOnlyModelOption) {
        return {
          options: {
            title: _4("Add a field of type...")
          },
          config: getItems(availableFor, onCreateAttribute, showOnlyModelOption)
        };
      }
    };
  }
]);
angular_default.module("kantree").directive("addAttributeMenuToggle", [
  "addAttributeMenuFactory",
  "menuDropdown",
  function(addAttributeMenuFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        onCreate: "&addAttributeMenuToggle",
        attrAvailableFor: "@",
        showOnlyModelOption: "<?",
        onDropOpened: "&?",
        onDropClosed: "&?"
      },
      link: function(scope, element2, attr) {
        var menu, drop;
        scope.$watch("showOnlyModelOption", function() {
          menu = addAttributeMenuFactory.get(scope.attrAvailableFor, function(attrType, onlyModel) {
            scope.onCreate({ attrType, onlyModel });
          }, scope.showOnlyModelOption);
        });
        element2.on("click touchstart", function() {
          if (!drop) {
            drop = menuDropdown.open(element2[0], menu, scope);
            if (scope.onDropOpened) {
              drop.on("open", () => scope.onDropOpened({ $drop: drop }));
            }
            drop.on("close", () => {
              if (scope.onDropClosed) {
                scope.onDropClosed();
              }
              drop = null;
            });
          }
        });
      }
    };
  }
]);

// public/app/ui/attributes/menus/group-menu.js
angular_default.module("kantree").factory("attributeGroupMenuFactory", [
  "groupsMenuFactory",
  "$rootScope",
  "$q",
  function(groupsMenuFactory, $rootScope, $q) {
    function isAttrEditable(attributeGroup, attr, project) {
      return !(attributeGroup instanceof ModelAttributeGroup || attributeGroup instanceof BatchAttributeGroup) || project && !project.is_archived && isConnected() && isAllowedInProject(project, "attribute", "EDIT", attr.id);
    }
    function isGroupTypeAttrEditable(attributeGroup, attr, project) {
      return isAttrEditable(attributeGroup, attr, project) && canMoveCardsInThisGroupType(project, attr.group_type_id);
    }
    var getItem = function(attr, options2) {
      let panelSpecs;
      const attrType = attributeTypeRegistry.get(attr.type);
      const obj = options2.obj;
      if (attrType.decorative || !isAttrEditable(options2.attributeGroup, attr, options2.project)) {
        return;
      }
      if (attrType.name === "group_type") {
        if (!isGroupTypeAttrEditable(options2.attributeGroup, attr, options2.project)) {
          return;
        }
        const groupType = cardGroupTypeStore.get(attr.group_type_id);
        const groupsOpts = Object.assign({
          groupType,
          backAfterToggle: groupType.one_group_per_card,
          noCloseAfterToggle: !groupType.one_group_per_card,
          parent: obj.parent_id ? cardStore.get(obj.parent_id) : obj,
          // il faut que je passe la carte
          // uniquement si c'est attributeGroup instanceOf CardModelAttributeGroup
          // Dans ce cas pas besoin de "parent:"
          card: obj,
          dataPrefetched: options2.dataPrefetched
        }, options2.groupsMenuOptions || {});
        if (options2.attributeGroup instanceof ModelAttributeGroup) {
          groupsOpts.card = obj;
        }
        const groupsMenu = groupsMenuFactory.get(groupsOpts);
        panelSpecs = {
          label: attr.name,
          submenu: groupsMenu.config,
          options: groupsMenu.options
        };
      } else if (typeof attrType.editorOpener === "function") {
        panelSpecs = {
          label: attr.name,
          action: () => {
            $q.when(options2.attributeGroup.getObjAttributeValue(obj, attr)[1], (value2) => {
              var editorScope = $rootScope.$new();
              editorScope.project = options2.project;
              editorScope.attributeGroup = options2.attributeGroup;
              editorScope.attribute = attr;
              editorScope.obj = obj;
              editorScope.value = value2;
              editorScope.attributeEditable = true;
              editorScope.onDone = angular_default.noop;
              attrType.editorOpener(null, editorScope);
            });
          }
        };
      } else {
        panelSpecs = {
          label: attr.name,
          submenu: [
            {
              component: "attribute-editor-menu-component",
              backAfterAction: true,
              params: {
                data: function() {
                  return {
                    project: options2.project,
                    attributeGroup: options2.attributeGroup,
                    attribute: attr,
                    obj,
                    isTemplate: !!options2.isTemplate
                  };
                }
              }
            }
          ]
        };
        if (!options2.noClear) {
          panelSpecs.submenu.push(
            { label: "--" },
            {
              label: _4("Clear"),
              backAfterAction: true,
              action: () => {
                $q.digest(options2.attributeGroup.clearObjAttribute(obj, attr));
              }
            }
          );
        }
        if (options2.resetAfterAction) {
          panelSpecs.submenu.forEach((item) => {
            if (item.label !== "--") {
              item.resetAfterAction = true;
              delete item.backAfterAction;
            }
          });
        }
      }
      return panelSpecs;
    };
    var getItems = function(options2) {
      return options2.attributeGroup.sort().map((attr) => getItem(attr, options2)).filter(Boolean);
    };
    return {
      getItems,
      getItem,
      get: (options2) => {
        return { config: () => getItems(options2) };
      }
    };
  }
]);
angular_default.module("kantree").component("attributeEditorMenuComponent", {
  bindings: {
    params: "<",
    onClose: "&",
    onUpdate: "&"
  },
  template: `
    <attribute-editor project="$ctrl.data.project" attribute-group="$ctrl.data.attributeGroup"
      attribute="$ctrl.data.attribute" obj="$ctrl.data.obj" on-done="$ctrl.onClose()"
      on-update="$ctrl.onUpdate()" embedded="true" is-template="$ctrl.data.isTemplate"/>`,
  controller: function() {
    this.$onInit = function() {
      this.data = this.params.data();
    };
  }
});

// public/app/ui/attributes/modals/attribute-options.js
angular_default.module("kantree").service("attributeOptionsModal", class extends AngularClass {
  static $inject = ["$uibModal", "$rootScope"];
  open(project, attributeGroup, attribute2, obj) {
    var scope = this.$rootScope.$new();
    scope.project = project;
    scope.attributeGroup = attributeGroup;
    scope.attribute = Object.assign({}, attribute2);
    scope.obj = obj;
    var instance = this.$uibModal.open({
      templateUrl: "/static/app/ui/attributes/modals/templates/attribute-options-modal.html",
      windowClass: "attribute-options-modal",
      controller: "AttributeOptionsModalCtrl",
      scope
    });
    instance.result.finally(() => {
      scope.$destroy();
    });
    return instance;
  }
});
angular_default.module("kantree").controller("AttributeOptionsModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.save = function() {
      let { default_value, description } = $scope2.attribute;
      if (typeof default_value === "string" && !default_value.length) {
        default_value = null;
      }
      if (typeof description === "string" && !description.length) {
        description = null;
      }
      $q.when($scope2.attributeGroup.update($scope2.attribute, { default_value, description }), () => {
        $uibModalInstance.close();
      });
    };
  }
]);

// public/app/ui/attributes/modals/attribute-roles.js
angular_default.module("kantree").factory("attributeRolesModal", [
  "roleObjExceptionsModal",
  function(roleObjExceptionsModal) {
    return {
      open: function(project, attributeGroup, focusAttribute) {
        return roleObjExceptionsModal.open({
          title: _4("Edit which roles can edit fields"),
          project,
          objectType: "attribute",
          objects: attributeGroup,
          focusObject: focusAttribute,
          actions: [
            {
              label: _4("Edit"),
              map: [{ object_type: "attribute", actions: ["EDIT"] }]
            }
          ]
        });
      }
    };
  }
]);

// public/app/ui/attributes/attribute-editor.js
angular_default.module("kantree").factory("attributeEditor", [
  "attributeDropdown",
  "$rootScope",
  "$q",
  function(attributeDropdown, $rootScope, $q) {
    return {
      open: function(target, scope, project, attributeGroup, attribute2, obj, value2, attributeEditable, onDone, dropConfig, isolatedScope, isTemplate) {
        const attrType = attributeTypeRegistry.get(attribute2.type);
        var render3 = function(value3) {
          var editorScope = isolatedScope ? $rootScope.$new() : scope.$new();
          editorScope.project = project;
          editorScope.attributeGroup = attributeGroup;
          editorScope.attribute = attribute2;
          editorScope.obj = obj;
          editorScope.value = value3;
          editorScope.attributeEditable = attributeEditable;
          editorScope.onDone = onDone || angular_default.noop;
          editorScope.isTemplate = isTemplate;
          if (typeof attrType.editorOpener === "function") {
            attrType.editorOpener(target, editorScope, attribute2, scope, dropConfig, onDone);
            if (!isolatedScope) {
              scope.$on("$destroy", function() {
                editorScope.$destroy();
              });
            }
          } else {
            var html5 = `<attribute-editor project="project" attribute-group="attributeGroup"
              attribute="attribute" obj="obj" value="value" on-done="onDone()"
              on-update="onUpdate()" on-init="onInit()" is-template="isTemplate" />`;
            attributeDropdown.open(target, scope, editorScope, html5, dropConfig, onDone);
          }
        };
        if (attrType.widgetOptions?.valueIsOption) {
          value2 = attribute2?.options?.[attrType.widgetOptions.valueIsOption] || null;
        }
        if (value2 === void 0) {
          $q.when(attributeGroup.getObjAttributeValue(obj, attribute2)[1], render3);
        } else {
          render3(value2);
        }
      }
    };
  }
]);
angular_default.module("kantree").factory("attributeDropdown", [
  "dropdown",
  "$timeout",
  "$compile",
  function(dropdown, $timeout2, $compile) {
    return {
      open: function(target, scope, dropScope, html5, dropConfig, onDone, onUpdate, onInit) {
        var drop;
        if (!dropScope) {
          dropScope = scope.$new();
        } else {
        }
        dropScope.onDone = function() {
          (onDone || angular_default.noop)();
          dropdown.close(drop);
        };
        dropScope.onUpdate = function() {
          (onUpdate || angular_default.noop)();
          dropdown.updateOnNextFrame(drop);
        };
        dropScope.onInit = function() {
          (onInit || angular_default.noop)();
          $timeout2(function() {
            dropdown.updateOnNextFrame(drop, true);
          }, 0, false);
        };
        if (dropScope.attribute && (dropScope.attribute.type === "state" || dropScope.attribute.type === "group_type")) {
          dropConfig = Object.assign(
            dropConfig || {},
            {
              classes: "drop-theme-menu"
            }
          );
        }
        var compiledHtml = $compile(html5)(dropScope)[0];
        drop = dropdown.open(target, scope, Object.assign({
          content: compiledHtml,
          _autoOpen: false
        }, dropConfig || {}, {
          classes: (dropConfig ? dropConfig.classes || "" : "") + " drop-theme-arrow attribute-editor-dropdown"
        }));
        if (drop.options._destroyOnClose) {
          drop.on("close", function() {
            if (dropScope) {
              dropScope.$destroy();
              dropScope = null;
            }
            if (compiledHtml) {
              compiledHtml.remove();
              compiledHtml = null;
            }
          });
        }
        return drop;
      }
    };
  }
]);

// public/app/ui/attributes/attribute-repr.js
init_icons();
var widgetTypes = {
  "avatar": "attribute-repr-widget",
  "icon": "attribute-repr-widget",
  "label": "attribute-repr-widget",
  "counter": "attribute-repr-widget",
  "progress": "attribute-repr-progress",
  "content": "attribute-repr-content",
  "button": "attribute-repr-button"
};
angular_default.module("kantree").run([function() {
  Object.values(widgetTypes).filter((component, i3, a3) => a3.indexOf(component) == i3).forEach((component) => {
    Handlebars.registerPartial({
      [component]: Handlebars.templates[component]
    });
  });
}]);
angular_default.module("kantree").factory("attributeRepr", [
  "attributeEditor",
  "dropdown",
  "$q",
  function(attributeEditor, $dropdown, $q) {
    return {
      getWidgets: function(attributeGroup, obj, options2) {
        return attributeGroup.map((attr) => {
          const objAttr = obj.attributes !== void 0 ? attributeGroup.getObjAttribute(obj, attr) : null;
          return this._getAttrWidgets(attr, objAttr, obj, options2);
        }).filter((widgets) => widgets?.length).reduce((accu, widgets) => accu.concat(widgets), []);
      },
      _getObjAttr: function(attribute2, obj) {
        if (typeof obj.attributes !== "undefined" && obj.attributes) {
          for (var i3 = 0; i3 < obj.attributes.length; i3++) {
            if (obj.attributes[i3].id === attribute2.id) {
              return obj.attributes[i3];
            }
          }
        }
      },
      getAttributeWidgets: function(attribute2, obj, options2) {
        var attrType = attributeTypeRegistry.get(attribute2.type);
        if (attrType && typeof attrType.getReprWidgets !== "undefined") {
          return this._getAttrWidgets(attribute2, this._getObjAttr(attribute2, obj), obj, options2, true);
        }
        return [];
      },
      _getAttrWidgets(attr, objAttr, obj, options2, formatting) {
        var attrType = attributeTypeRegistry.get(attr.type);
        if (!attrType.noAttributeValue && (!objAttr || isEmptyValue(objAttr.value))) {
          return [];
        }
        if (attrType && typeof attrType.getReprWidgets !== "undefined") {
          const widgets = attrType.getReprWidgets(obj, objAttr, attr, options2 || {});
          if (!widgets) return [];
          return (Array.isArray(widgets) ? widgets : [widgets]).map((widget) => {
            return { ...formatting ? this.formatWidget(widget) : widget, attribute: attr };
          });
        }
        return [];
      },
      formatWidget(widget) {
        widget.id = uuid4();
        widget.component = this.getWidgetComponent(widget);
        widget.partial = () => widget.component;
        widget.options = {
          ...widget.options,
          showIcon: widget.type !== "avatar" && (widget.options?.icon || widget.options?.iconClass),
          isText: widget.type !== "avatar" && widget.type !== "icon" && (widget.value && widget.value !== true || widget.value === 0),
          isImage: widget.type === "avatar"
        };
        if (widget.options?.bgcolor) {
          widget.options.color = widget.options.color || tinycolor.mostReadable(widget.options.bgcolor, ["#FFFFFF", "#000000"]).toHexString();
        }
        if (widget.options?.iconClass) {
          widget.options.iconClass = iconClass(widget.options.iconClass);
        }
        return widget;
      },
      getWidgetComponent(widget) {
        return widgetTypes[widget.type] || "attribute-repr-widget";
      },
      widgetsAggregators: {
        // sum all counters
        counter: function(widgets) {
          return [Object.assign({}, widgets[0], {
            value: widgets.reduce(function(accu, widget) {
              return accu + widget.value;
            }, 0)
          })];
        },
        // get nearest date in the future
        date: function(widgets) {
          var active;
          var now = /* @__PURE__ */ new Date();
          now.setHours(0, 0, 0, 0);
          angular_default.forEach(widgets, function(widget) {
            var set4 = true;
            if (active) {
              set4 = widget.date > active.date;
              if (widget.date - now >= 0) {
                set4 = widget.date <= active.date || active.date - now <= 0;
              }
            }
            if (set4) {
              active = widget;
            }
          });
          return [active];
        },
        // delete duplicated avatar
        avatar: function(widgets) {
          var out = [], avatars = [];
          angular_default.forEach(widgets, function(widget) {
            if (avatars.indexOf(widget.value) === -1) {
              out.push(widget);
              avatars.push(widget.value);
            }
          });
          return out;
        }
      },
      aggregateWidgets: function(widgets) {
        var aggregates = {};
        var remainingWidgets = [];
        angular_default.forEach(widgets, function(widget) {
          if (typeof widget.aggregate !== "undefined" && widget.aggregate) {
            var aggregator = typeof widget.aggregator !== "undefined" ? widget.aggregator : widget.type;
            if (typeof aggregates[aggregator] === "undefined") {
              aggregates[aggregator] = {};
            }
            if (typeof aggregates[aggregator][widget.aggregate] === "undefined") {
              aggregates[aggregator][widget.aggregate] = [];
            }
            aggregates[aggregator][widget.aggregate].push(widget);
          } else {
            remainingWidgets.push(widget);
          }
        });
        var out = [];
        angular_default.forEach(aggregates, function(aggs, aggregator) {
          angular_default.forEach(aggs, function(widgets2) {
            out = out.concat(this.widgetsAggregators[aggregator](widgets2));
          }, this);
        }, this);
        return out.concat(remainingWidgets);
      },
      filterWidgets: function(widgets) {
        return widgets.filter((widget) => angular_default.isArray(widget.value) ? widget.value.length : widget.value);
      },
      setReprEventListeners: function(element2, scope, attributeGroup, attribute2, obj, widgets, editable2) {
        let off;
        const isConfigured = isAttributeConfigured(attribute2 || {});
        if (!isConfigured) {
          this.setConfigAttrReprEventListener(element2, scope, attribute2, editable2);
          return;
        }
        if (widgets.some((w3) => w3.onDOMLoad)) {
          off = offMany(widgets.map((widget) => {
            const widgetElement = jquery_default(element2).find(`[data-attribute-repr-id="${widget.id}"]`);
            if (widgetElement.length && widget.onDOMLoad) {
              return widget.onDOMLoad(widgetElement, {
                editable: editable2,
                openEditor: () => attributeGroup.openEditor(obj, attribute2, widgetElement, scope),
                scope
              });
            }
          }).filter(Boolean));
          if (!widgets.filter((w3) => w3.onDOMLoad).every((w3) => w3.keepDefaultReprListeners)) {
            return off;
          }
        }
        const defaultOff = this.setDefaultReprEventListeners(element2, scope, attributeGroup, attribute2, obj, editable2);
        if (off) {
          return () => {
            off();
            defaultOff();
          };
        }
        return defaultOff;
      },
      setDefaultReprEventListeners: function(element2, scope, attributeGroup, attribute2, obj, editable2) {
        const onClickRepr = (event2) => {
          attributeGroup.openEditor(obj, attribute2, element2, scope);
        };
        if (editable2 && attributeGroup?.openEditor) {
          jquery_default(element2).on("click", onClickRepr);
        }
        return () => {
          if (editable2 && attributeGroup?.openEditor) {
            jquery_default(element2).off("click", onClickRepr);
          }
        };
      },
      setConfigAttrReprEventListener: function(element2, scope, attribute2, editable2) {
        let drop;
        function closeDrop() {
          if (drop?.drop) {
            drop.destroy();
            drop.contentScope = null;
            drop = null;
            return true;
          }
          return false;
        }
        const onClickRepr = (event2) => {
          const hasBeenClosed = closeDrop();
          if (hasBeenClosed) return;
          const newScope = scope.$new();
          newScope.attribute = attribute2;
          newScope.closeDrop = closeDrop;
          const dropHtml = `
            <attribute-required-options-content project="$ctrl.project" attribute="attribute"
              on-close="closeDrop()" on-save="closeDrop()"></attribute-required-options-content>
          `;
          if (element2[0]) {
            drop = $dropdown.openCompile(element2[0], dropHtml, newScope, {
              classes: "attribute-required-options-drop drop-theme-menu drop-theme-arrow",
              _autoOpen: true,
              _destroyOnClose: false,
              tetherOptions: {
                constraints: [{
                  to: "window",
                  pin: true,
                  attachment: "together none"
                }]
              }
            });
            drop.on("close", () => {
              drop.contentScope?.$destroy();
            });
          }
        };
        if (editable2) {
          jquery_default(element2).on("click", onClickRepr);
        }
        return () => {
          if (editable2) {
            jquery_default(element2).off("click", onClickRepr);
            drop = null;
          }
        };
      }
    };
  }
]);

// public/app/ui/base/ng-components/color-picker.js
var import_tinycolor29 = __toESM(require_tinycolor());
var allTinyColors = [];
for (i3 in import_tinycolor29.default.names) {
  allTinyColors.push(i3);
}
var i3;
angular_default.module("kantree").component("colorPickerPalette", {
  bindings: {
    color: "<?",
    colors: "<?",
    onChange: "&",
    emptyColor: "<?",
    hideCustomColor: "<?",
    ngDisabled: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      if (this.emptyColor === true) {
        this.emptyColor = null;
      }
      if (this.emptyColor !== void 0 && !this.color) {
        this.color = this.emptyColor;
      }
      this.refreshPalette();
      this.customColorMenu = { config: [{
        component: "menu-item-color-palette",
        onUpdate: (data2) => this.$scope.$applyAsync(() => this.select(data2.color)),
        params: {
          defaultColor: this.color
        }
      }] };
    }
    refreshPalette() {
      this.palette = this.colors || Array.from(defaultColorPalette());
      if (this.emptyColor !== void 0 && !this.isInDisplayedColors(this.emptyColor)) {
        this.palette.unshift(this.emptyColor);
      }
      if (this.hideCustomColor && !this.isInDisplayedColors(this.color)) {
        this.palette.push(this.color);
      }
    }
    select(color) {
      this.onChange({ $color: color === this.emptyColor ? null : color });
    }
    isSelected(color) {
      return this.colorsMatch(this.color, color);
    }
    isInDisplayedColors(color) {
      return this.palette.find((c3) => this.colorsMatch(c3, color)) !== void 0;
    }
    colorsMatch(a3, b3) {
      return !a3 && !b3 || a3 && b3 && a3.toUpperCase() === b3.toUpperCase();
    }
  },
  template: `
    <button type="button" ng-repeat="color in $ctrl.palette" ng-click="$ctrl.select(color)"
        ng-class="{'is-selected': $ctrl.isSelected(color), 'no-color': !color}"
        ng-style="{'background-color': color}"
        ng-disabled="$ctrl.ngDisabled">
    </button>
    <button type="button" ng-if="!$ctrl.hideCustomColor" class="picker" drop-menu="$ctrl.customColorMenu"
        custom-bgcolor="{{!$ctrl.isInDisplayedColors($ctrl.color) ? $ctrl.color : null}}" ng-disabled="$ctrl.ngDisabled">
      <i class="bi-palette-fill"></i>
    </button>
  `
});

// public/app/ui/base/ng-components/date-navigator.js
function findSpecialDateRange(dateRange) {
  return specialDateRanges.find((date) => dateRange.start.isSame(date.startDate, "day") && dateRange.end.isSame(date.endDate, "day"));
}
angular_default.module("kantree").component("dateNavigator", {
  bindings: {
    range: "<?",
    minDate: "<?",
    maxDate: "<?",
    minRange: "<?",
    maxRange: "<?",
    showArrows: "<?",
    showDatepicker: "<?",
    showSpecialLabels: "<?",
    onChange: "&"
  },
  templateUrl: "/static/app/ui/base/ng-components/templates/date-navigator.html",
  controller: [
    function() {
      var $ctrl = this;
      var picker;
      var formatDateRange2 = function(dateRange) {
        if (dateRange.start.isSame(dateRange.end, "day")) {
          return dateRange.start.format("LL");
        }
        return dateRange.start.format("LL") + " - " + dateRange.end.format("LL");
      };
      $ctrl.$onInit = function() {
        $ctrl.showArrows = typeof $ctrl.showArrows !== "undefined" ? $ctrl.showArrows : true;
        $ctrl.showSpecialLabels = typeof $ctrl.showSpecialLabels !== "undefined" ? $ctrl.showSpecialLabels : true;
        $ctrl.showDatepicker = typeof $ctrl.showDatepicker !== "undefined" ? $ctrl.showDatepicker : true;
        $ctrl.maxDate = typeof $ctrl.maxDate !== "undefined" ? $ctrl.maxDate : "today";
        $ctrl.activeRange = { start: moment_default(), end: moment_default() };
        $ctrl.updateMaxDate();
        $ctrl.updateRange($ctrl.range, true);
      };
      $ctrl.updateMaxDate = function() {
        if ($ctrl.maxDate === false) {
          $ctrl.maxDate = null;
        } else if ($ctrl.maxDate === "today") {
          $ctrl.maxDate = moment_default().endOf("day");
        } else if (!moment_default.isMoment($ctrl.maxDate)) {
          $ctrl.maxDate = null;
        }
      };
      $ctrl.updateRange = function(range2, preventNotify) {
        var activeStart = $ctrl.activeRange.start;
        var activeEnd = $ctrl.activeRange.end;
        var activeRangeDelta = Math.round(activeEnd.clone().endOf("day").diff(activeStart.clone().startOf("day"), "days", true));
        if (range2 === "prev") {
          $ctrl.range = {
            start: activeStart.clone().subtract(activeRangeDelta, "day"),
            end: activeEnd.clone().subtract(activeRangeDelta, "day")
          };
        } else if (range2 === "next") {
          $ctrl.range = {
            start: activeStart.clone().add(activeRangeDelta, "day"),
            end: activeEnd.clone().add(activeRangeDelta, "day")
          };
        } else if (range2) {
          $ctrl.range = { start: range2.start, end: range2.end };
        } else {
          $ctrl.range = { start: moment_default(), end: moment_default() };
        }
        var specialDateRange = findSpecialDateRange($ctrl.range);
        if (specialDateRange) {
          $ctrl.range = specialDateRange.name;
          $ctrl.activeRange = {
            start: specialDateRange.startDate,
            end: specialDateRange.endDate
          };
        } else {
          $ctrl.activeRange = { start: $ctrl.range.start, end: $ctrl.range.end };
          $ctrl.range.start = $ctrl.range.start.unix();
          $ctrl.range.end = $ctrl.range.end.unix();
        }
        $ctrl.formattedActiveRange = formatDateRange2($ctrl.activeRange);
        $ctrl.activeRangeLabel = specialDateRange ? specialDateRange.displayedName : null;
        $ctrl.activeRangeIsBeforeMinDate = $ctrl.minDate && moment_default.isMoment($ctrl.minDate) && ($ctrl.activeRange.start.isSameOrBefore($ctrl.minDate, "day") || $ctrl.activeRange.end.isSameOrBefore($ctrl.minDate, "day"));
        $ctrl.activeRangeIsAfterToday = $ctrl.maxDate && moment_default.isMoment($ctrl.maxDate) && ($ctrl.activeRange.start.isSameOrAfter(moment_default(), "day") || $ctrl.activeRange.end.isSameOrAfter(moment_default(), "day"));
        updateDateRangePicker();
        if (!preventNotify) {
          $ctrl.onChange({ $range: $ctrl.range, $formattedRange: $ctrl.activeRange });
        }
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.range && !changes.range.isFirstChange()) {
          $ctrl.updateRange($ctrl.range, true);
        }
        if (changes.minRange && !changes.minRange.isFirstChange()) {
          updateDateRangePicker();
        }
        if (changes.maxRange && !changes.maxRange.isFirstChange()) {
          updateDateRangePicker();
        }
      };
      var getPickerRanges = function() {
        var ranges = {};
        for (let date of specialDateRanges) {
          ranges[date.displayedName] = [date.startDate, date.endDate];
        }
        return ranges;
      };
      var updateDateRangePicker = function() {
        $ctrl.pickerOptions = Object.assign({}, {
          startDate: $ctrl.activeRange.start,
          endDate: $ctrl.activeRange.end,
          dateLimitMin: $ctrl.minRange,
          dateLimit: $ctrl.maxRange,
          isInvalidDate: function(date) {
            var minDate = moment_default.isMoment($ctrl.minDate) ? $ctrl.minDate.clone().startOf("day") : null;
            var maxDate = moment_default.isMoment($ctrl.maxDate) ? $ctrl.maxDate.clone().endOf("day") : null;
            if (maxDate && minDate) {
              return !date.isBetween(minDate, maxDate, "day", "[]");
            } else if (maxDate) {
              return date.isAfter(maxDate, "day");
            } else if (minDate) {
              return date.isBefore(maxDate, "day");
            }
            return false;
          },
          opens: "center",
          showCustomRangeLabel: false,
          alwaysShowCalendars: true,
          autoApply: true,
          autoUpdateInput: false,
          ranges: getPickerRanges()
        });
      };
      $ctrl.$postLink = function() {
        updateDateRangePicker();
      };
    }
  ]
});

// public/app/ui/base/ng-components/file-gallery.js
angular_default.module("kantree").directive("fileGallery", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/base/ng-components/templates/files.html",
      replace: true,
      scope: {
        card: "<?",
        store: "<?",
        files: "<?",
        showDelete: "@",
        showCover: "@",
        deleted: "&"
      },
      controller: [
        "$scope",
        function($scope2) {
          if (!$scope2.store) {
            $scope2.store = new FileStore();
            $scope2.$watchCollection("files", function(files) {
              if (files) {
                $scope2.store.replace(files);
              } else {
                $scope2.store.clear();
              }
            });
          }
          $scope2.displayFiles = [];
          $scope2.store.$watchAll($scope2, function() {
            $scope2.displayFiles = $scope2.store.query({}, { sortBy: "name" });
          });
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("fileThumb", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/base/ng-components/templates/file-thumb.html",
      replace: true,
      scope: {
        file: "=",
        card: "<?",
        store: "=?",
        showDelete: "@",
        showCover: "@",
        deleted: "&"
      },
      controller: [
        "$scope",
        "$q",
        "filePreviewer",
        function($scope2, $q, filePreviewer) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.isImage = $scope2.file.mimetype && $scope2.file.mimetype.match(/^image\//i);
          $scope2.canPreview = !$scope2.file.file && filePreviewer.canPreview($scope2.file) !== false;
          const onUrl = (url2) => {
            $scope2.url = url2;
            if ($scope2.isImage) {
              let img = new Image();
              img.src = url2;
              img.onload = () => {
                $scope2.imageUrl = url2;
              };
            }
          };
          if ($scope2.file.file) {
            var reader = new FileReader();
            reader.onload = (e3) => onUrl(e3.target.result);
            reader.readAsDataURL($scope2.file.file);
          } else {
            onUrl($scope2.file.url);
          }
          if ($scope2.card && $scope2.showCover === "true") {
            var project = projectStore.getForCard($scope2.card);
            $scope2.showToggleCoverButton = canEditCard(project, $scope2.card_id);
          } else {
            $scope2.showToggleCoverButton = false;
          }
          $scope2.menuConfig = { config: [
            {
              label: _4("Use as card cover"),
              icon: "bi-card-image",
              action: () => $q.digest(updateCard($scope2.card, { image_cover_url: $scope2.file.url })),
              enabled: () => $scope2.showToggleCoverButton && $scope2.card.image_cover_url !== $scope2.file.url
            },
            {
              label: _4("Remove as card cover"),
              icon: "bi-card-image",
              action: () => $q.digest(updateCard($scope2.card, { image_cover_url: null })),
              enabled: () => $scope2.showToggleCoverButton && $scope2.card.image_cover_url === $scope2.file.url
            },
            {
              label: _4("Download"),
              icon: "download",
              action: () => window.open($scope2.file.url)
            },
            {
              label: _4("Delete"),
              icon: "trash",
              action: () => {
                $q.when(confirmDeleteDialog2(), () => {
                  $scope2.deleted();
                });
              },
              enabled: () => $scope2.showDelete
            }
          ] };
          $scope2.open = function(e3) {
            e3.preventDefault();
            e3.stopPropagation();
            if ($scope2.canPreview) {
              filePreviewer.open($scope2.file, $scope2.store);
            } else if ($scope2.file.url) {
              window.open($scope2.file.url);
            }
          };
        }
      ]
    };
  }
]);
angular_default.module("kantree").directive("tryImageSrc", [
  function() {
    return {
      restrict: "A",
      scope: {
        tryImageSrc: "<",
        maxAttempts: "@"
      },
      link: function(scope, element2, attrs2) {
        var retryInterval = 1e3;
        var retryDecay = 1.5;
        var retryAttempts = -1;
        var maxAttempts = scope.maxAttempts || 5;
        var load2 = function() {
          if (++retryAttempts >= maxAttempts) {
            return;
          }
          jquery_default(element2).attr("src", scope.tryImageSrc).each(function() {
            if (this.complete) jquery_default(this).trigger("load");
          });
        };
        jquery_default(element2).on("load", function() {
          jquery_default(this).fadeIn();
        }).on("error", function() {
          jquery_default(this).hide();
          setTimeout(load2, retryInterval * Math.pow(retryDecay, retryAttempts));
        });
        scope.$watch("tryImageSrc", function() {
          retryAttempts = -1;
          if (scope.tryImageSrc) {
            load2();
          } else {
            jquery_default(element2).attr("src", "");
          }
        });
      }
    };
  }
]);

// public/app/ui/base/ng-components/full-calendar.js
init_icons();
angular_default.module("kantree").component("fullCalendar", {
  template: "<div></div>",
  bindings: {
    cards: "<?",
    groups: "<?",
    cardActiveDateAttributesNames: "<?",
    strikeDoneCards: "<?",
    editable: "<?",
    cardsEditable: "<?",
    groupsEditable: "<?",
    droppable: "<?",
    selectableDates: "<?",
    icalendarFeed: "<?",
    weekNumbers: "<?",
    eventSource: "&?",
    onSelect: "&",
    onChange: "&",
    onEventSourceUpdate: "&",
    onDayClick: "&",
    onDateSelected: "&"
  },
  controller: [
    "$element",
    "$scope",
    "fullCalendar",
    "iCalendarModal",
    function($element2, $scope2, fullCalendar, iCalendarModal) {
      var $ctrl = this;
      var $calendar;
      var calendarInstance;
      $ctrl.$postLink = function() {
        $calendar = jquery_default($element2.children()[0]);
        $calendar.fullCalendar({
          editable: !!$ctrl.editable || !!$ctrl.cardsEditable || $ctrl.groupsEditable,
          droppable: !!$ctrl.droppable && (!!$ctrl.editable || !!$ctrl.cardsEditable || $ctrl.groupsEditable),
          selectable: !!$ctrl.selectableDates,
          weekNumbers: $ctrl.weekNumbers,
          weekNumbersWithinDays: true,
          customButtons: {
            icalendar: {
              text: "iCalendar feed",
              click: function() {
                iCalendarModal.open($ctrl.icalendarFeed);
              }
            }
          },
          header: {
            left: "today prev,next",
            center: "title",
            right: "basicWeek,month" + ($ctrl.icalendarFeed ? ",icalendar" : "")
          },
          events: function(start, stop, tz, callback) {
            if ($ctrl.eventSource) {
              $ctrl.eventSource({
                start,
                stop,
                tz,
                callback
              });
            } else {
              eventSource(start, stop, tz, callback);
            }
          },
          eventClick: function(event2) {
            $ctrl.onSelect({ event: event2 });
          },
          dayClick: function(date) {
            $ctrl.onDayClick({ date: moment_default(date) });
          },
          select: function(start, stop, event2) {
            $ctrl.onDateSelected({ start, stop, event: event2 });
          },
          eventRender: (event2, $element3) => {
            const $titleElement = $element3.find(".fc-content .fc-title");
            if (event2.contentSmall) {
              $titleElement.after(`<span class="fc-content-small">${event2.contentSmall}</span>`);
            }
            if (event2.icon) {
              $titleElement.before(`<i class="fc-content-icon ${iconClass(event2.icon)}"></i>`);
            }
            return $element3;
          },
          eventDrop: updateFromEvent,
          eventResize: updateFromEvent,
          eventReceive: updateFromEvent,
          nextDayThreshold: "00:00:00",
          // 12am
          locale: getCurrentLocale(),
          timezone: "local"
          // firstDay: getFirstDayOfWeek(),
          // timeFormat: isLocaleDisplayAmPm() ? 'h(:mm)t' : 'H(:mm)'
        });
        calendarInstance = $calendar.fullCalendar("getCalendar");
        computeAspectRatio();
        $scope2.$on("calendarComputeAspectRatio", computeAspectRatio);
        $scope2.$on("calendarUpdateEvents", updateEvents);
        jquery_default(window).on("resize", computeAspectRatio);
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.cards && !changes.cards.isFirstChange() || changes.groups && !changes.groups.isFirstChange() || changes.eventSource && !changes.eventSource.isFirstChange() || changes.editable && !changes.editable.isFirstChange() || changes.strikeDoneCards && !changes.strikeDoneCards.isFirstChange() || changes.cardActiveDateAttributesNames && !changes.cardActiveDateAttributesNames.isFirstChange()) {
          updateEvents();
        }
        if (changes.editable && !changes.editable.isFirstChange()) {
          $calendar.fullCalendar("option", "editable", !!changes.editable.currentValue);
          $calendar.fullCalendar("option", "droppable", !!changes.editable.currentValue && !!$ctrl.droppable);
        }
        if (changes.weekNumbers && !changes.weekNumbers.isFirstChange()) {
          $calendar.fullCalendar("option", "weekNumbers", changes.weekNumbers.currentValue);
        }
      };
      $ctrl.$onDestroy = function() {
        jquery_default(window).off("resize", computeAspectRatio);
      };
      function updateEvents() {
        if ($calendar) {
          $calendar.fullCalendar("refetchEvents");
        }
      }
      function isRangesOverlapping(firstRange, secondRange) {
        return firstRange.end.isSameOrAfter(secondRange.start, "day") && firstRange.start.isBefore(secondRange.end, "day");
      }
      function eventSource(start, stop, tz, callback) {
        var events2 = [], scheduledCards = [], unscheduledCards = [];
        ($ctrl.cards || []).forEach(function(card) {
          var hasDate = false;
          var activeAttrsNames = $ctrl.cardActiveDateAttributesNames;
          if (!activeAttrsNames || activeAttrsNames.length === 0) {
            activeAttrsNames = card.attributes.filter(function(attr) {
              return attr.type === "date" || attributeTypeRegistry.get(attr.type)?.computed;
            }).map(function(attr) {
              return attr.name;
            });
          }
          (card.attributes || []).filter(function(attr) {
            return activeAttrsNames.includes(attr.name);
          }).forEach(function(attr) {
            var modelAttr = cardModelStore.getAttribute(attr.id);
            const { start: startDate, end: endDate } = parseDateFromComputedAttribute(modelAttr, attr) || {};
            if (!startDate && !endDate) return;
            hasDate = true;
            if (isRangesOverlapping({ start: startDate, end: endDate }, { start, end: stop })) {
              var event3 = fullCalendar.cardToEvent(card, modelAttr, { strikeDoneCards: $ctrl.strikeDoneCards });
              event3.editable = event3.editable && (!!$ctrl.editable || !!$ctrl.cardsEditable);
              events2.push(event3);
              scheduledCards.push({ card, event: event3 });
            }
          });
          if (!hasDate && activeAttrsNames.length) {
            var event2 = fullCalendar.cardToEvent(card, null, { strikeDoneCards: $ctrl.strikeDoneCards });
            event2.editable = event2.editable && (!!$ctrl.editable || !!$ctrl.cardsEditable);
            unscheduledCards.push({ card, event: event2 });
          }
        });
        $ctrl.onEventSourceUpdate({
          scheduled: scheduledCards,
          unscheduled: unscheduledCards
        });
        ($ctrl.groups || []).forEach(function(group2) {
          var event2 = fullCalendar.groupToEvent(group2);
          event2.editable = event2.editable && (!!$ctrl.editable || !!$ctrl.groupsEditable);
          events2.push(event2);
        });
        callback(events2);
      }
      function updateFromEvent(event2) {
        var startDate, endDate;
        if (event2.end) {
          startDate = event2.start;
          endDate = event2.end;
        } else {
          startDate = null;
          endDate = event2.start;
        }
        $ctrl.onChange({
          startDate,
          endDate,
          event: event2
        });
      }
      function computeAspectRatio() {
        var container = jquery_default($element2).parent();
        var ratio = container.innerWidth() / (container.innerHeight() - 60);
        $calendar.fullCalendar("option", "aspectRatio", ratio);
      }
    }
  ]
});
angular_default.module("kantree").factory("fullCalendar", [
  function() {
    return {
      cardToEvent: function(card, modelAttr, options2) {
        let title = card.title;
        if (card.path && card.path.length > 1) {
          title = "";
          for (let i3 = 1; i3 < card.path.length; i3++) {
            title += card.path[i3].title + " / ";
          }
          title += card.title;
        }
        var o3 = {
          id: card.id,
          cardId: card.id,
          title,
          allDay: true,
          contentSmall: `#${card.ref}`,
          className: "card-event"
        };
        if (card.is_archived || card.is_parent_archived) {
          o3["editable"] = false;
          o3["className"] += " readonly";
        }
        if (card.finished) {
          o3["className"] += " finished";
          if (card.state == "completed") {
            o3["className"] += " completed";
          }
          if (!!options2?.strikeDoneCards || options2?.strikeDoneCards === void 0) {
            o3["className"] += " struck-title";
          }
        }
        if (!modelAttr) {
          return o3;
        } else if (!!modelAttr.type) {
          o3["icon"] = attributeTypeRegistry.get(modelAttr.type)?.icon;
        }
        const model = getCardCompositeModel(card);
        if (model.model && model.model.style_class_name) {
          o3["className"] += " " + model.model.style_class_name;
        }
        var project = projectStore.getForCard(card);
        o3["editable"] = isAllowedInProject(project, "attribute", "EDIT", modelAttr.id) && !modelAttr.is_computed;
        if (!o3["editable"] && !o3["className"].includes("readonly")) {
          o3["className"] += " readonly";
        }
        Object.assign(o3, {
          id: card.id + "-" + modelAttr.id,
          attr: modelAttr
        });
        var attrs2 = (card.attributes || []).filter(function(attr2) {
          if (attr2.id === modelAttr.id) {
            return true;
          }
        });
        if (!attrs2.length) {
          return o3;
        }
        var attr = attrs2[0];
        const { start, end, allDay } = parseDateFromComputedAttribute(
          modelAttr,
          attr,
          { momentInstance: jquery_default.fullCalendar.moment }
        ) || {};
        if (start) {
          angular_default.extend(o3, { start, end, allDay });
          o3["end"].add(1, "days").startOf("day");
        } else if (end) {
          o3["start"] = end;
          o3["allDay"] = allDay;
        }
        return o3;
      },
      cardToEvents: function(card) {
        return (card.attributes || []).filter(function(attr) {
          return attr.type === "date" || attributeTypeRegistry.get(attr.type)?.computed;
        }).map(function(attr) {
          return this.cardToEvent(card, { id: attr.id });
        }, this);
      },
      groupToEvent: function(group2) {
        var o3 = {
          id: group2.id,
          groupId: group2.id,
          groupTypeId: group2.type_id,
          className: ["fc-group-event", "fa", "fa-flag-checkered"],
          title: group2.title,
          allDay: true,
          editable: false,
          startEditable: false,
          borderColor: group2.color || "#bbb"
        };
        var end;
        if (group2.end_date) {
          end = moment_default(group2.end_date).add(1, "d");
        }
        if (group2.start_date) {
          o3["start"] = moment_default(group2.start_date);
          if (end) {
            o3["end"] = end;
          }
        } else if (end && end.isAfter(moment_default())) {
          o3["start"] = moment_default();
          o3["end"] = end;
        } else if (end) {
          o3["start"] = end;
        }
        return o3;
      }
    };
  }
]);

// public/app/ui/base/ng-components/helplink.js
angular_default.module("kantree").directive("helpLink", () => ({
  //---act as component
  scope: {},
  controllerAs: "$ctrl",
  restrict: "E",
  //---
  bindToController: {
    guide: "@",
    anchor: "@?"
  },
  replace: true,
  transclude: true,
  template: `<a ng-href="{{::$ctrl.href}}" target="_blank" aria-label="Help" class="help-link" ng-transclude></a>`,
  controller: class extends AngularClass {
    $onInit() {
      const baseGuideUrl = getLocalizedUrl("guides");
      this.href = baseGuideUrl + "/" + this.guide;
      if (this.anchor) {
        this.href += "#" + this.anchor;
      }
    }
  }
}));
angular_default.module("kantree").directive("helpBtn", () => ({
  //---act as component
  scope: {},
  controllerAs: "$ctrl",
  restrict: "E",
  //---
  bindToController: {
    guide: "@",
    anchor: "@?"
  },
  replace: true,
  template: `<a ng-href="{{::$ctrl.href}}" target="_blank" aria-label="Help" class="help-link btn btn-icon"
    uib-tooltip="{{::_('Learn more in our guides')}}" tooltip-popup-delay="0" tooltip-placement="bottom"><i class="bi-question-circle-fill"></i></a>`,
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      const baseGuideUrl = getLocalizedUrl("guides");
      this.href = baseGuideUrl + "/" + this.guide;
      if (this.anchor) {
        this.href += "#" + this.anchor;
      }
    }
  }
}));

// public/app/ui/base/ng-components/invite-form.js
angular_default.module("kantree").directive("inviteForm", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/base/ng-components/templates/invite-form.html",
      replace: true,
      scope: {
        autoFocusInput: "<?",
        onSubmit: "&"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.showMessage = false;
          $scope2.submitting = false;
          $scope2.placeholder = _4("One or more emails or usernames separated by comma");
          if ($scope2.autoFocusInput === void 0) {
            $scope2.autoFocusInput = true;
          }
          if (serverConfig.max_invites_at_once) {
            $scope2.placeholder += " " + _4(
              "(up to {max_invites} at once)",
              { max_invites: serverConfig.max_invites_at_once }
            );
          }
          var callbacks2 = {
            success: function() {
              $scope2.emailOrUsernames = "";
              $scope2.message = "";
              $scope2.showMessage = false;
              $scope2.submitting = false;
            },
            error: function() {
              $scope2.submitting = false;
            }
          };
          $scope2.submit = function() {
            $scope2.submitting = true;
            $scope2.onSubmit({
              emailOrUsernames: $scope2.emailOrUsernames,
              message: $scope2.message,
              callbacks: callbacks2
            });
          };
          $scope2.autocomplete = function(query2) {
            if (!currentUser2.can_autocomplete_invites) {
              return [];
            }
            return $q.digest(api_default.user.autocomplete_invites.get({ q: query2 }));
          };
        }
      ]
    };
  }
]);

// public/app/ui/base/ng-components/loader.js
angular_default.module("kantree").component("loadingIndicator", {
  template: `
    <i class="fa fa-spin fa-spinner"></i>
  `
});

// public/app/ui/base/ng-components/topbar.js
angular_default.module("kantree").component("topbar", {
  template: `
    <button type="button" class="btn btn-topbar btn-icon btn-sidebar-toggle visible-xs-block" ng-click="$ctrl.toggleSidebar()"><i class="fa fa-bars"></i></button>
    <a class="navbar-brand hidden-xs hidden-with-sidebar" href="/" ng-attr-target="{{$ctrl.isAuthenticated() ? '' : '_self'}}"
      ng-if="$ctrl.withLogo" ng-style="$ctrl.logoStyle">Kantree</a>
    <ng-transclude></ng-transclude>
    <ul class="navbar-actions hidden-xs" ng-if="$ctrl.withAuth && !$ctrl.isAuthenticated()">
      <li>
        <a href class="btn btn-topbar" ng-click="$ctrl.authentication.login()" embed-blank-target>{{::$ctrl.loginBtnLabel}}</a>
      </li>
      <li>
        <a href class="btn btn-topbar" ng-click="$ctrl.authentication.signup()" embed-blank-target>{{::$ctrl.signupBtnLabel}}</a>
      </li>
    </ul>`,
  bindings: {
    withAuth: "<",
    withLogo: "<"
  },
  transclude: true,
  controller: class extends AngularClass {
    static $inject = ["navSidebar"];
    $onInit() {
      this.isAuthenticated = isAuthenticated;
      this.authentication = authSession;
      this.loginBtnLabel = _4("Login");
      this.signupBtnLabel = _4("Signup");
    }
    get logoStyle() {
      if (serverConfig.navbar_logo_url) {
        return { "background-image": "url(" + serverConfig.navbar_logo_url + ")" };
      }
      return {};
    }
    toggleSidebar() {
      if (isScreensizeXS()) {
        this.$navSidebar.toggle();
      }
    }
  }
});

// public/app/ui/base/ng-components/user-avatar.js
angular_default.module("kantree").component("userAvatar", {
  bindings: {
    user: "<",
    labels: "<?",
    showPresence: "<?",
    showPopover: "<?",
    connected: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "userAvatarPopover"];
    $onInit() {
      this.$element.addClass("user-avatar");
    }
    $onChanges(changes) {
      if (this.showPresence) {
        if (this.connected) {
          this.$element.html('<span class="user-online-dot"><span></span></span>');
        } else {
          this.$element.html("");
        }
      }
    }
    $postLink() {
      this.$element.css({
        "background-image": `url(${userAvatarUrl(this.user)})`
      });
      if (this.showPopover) {
        this.$userAvatarPopover.attach(this.$element, () => this.user, this.labels);
      }
    }
  },
  template: ""
});
angular_default.module("kantree").component("userInfoCard", {
  bindings: {
    user: "<",
    labels: "<",
    onRender: "&"
  },
  template: `
    <img ng-src="{{$ctrl.user|userAvatarUrl}}" alt="">
    <div>
      <span class="display-name">{{$ctrl.user.display_name}}</span>
      <span class="username">@{{$ctrl.user.username}}</span>
      <span class="badge" ng-repeat="lbl in $ctrl.labels">{{lbl}}</span>
    </div>
  `,
  controller: class extends AngularClass {
    static $inject = ["$timeout"];
    $postLink() {
      this.$timeout(() => {
        this.onRender();
      }, 0, false);
    }
  }
});
angular_default.module("kantree").directive("userAvatarPopover", [
  "userAvatarPopover",
  function(userAvatarPopover) {
    return {
      restrict: "A",
      scope: {
        "user": "<userAvatarPopover",
        "popoverLabels": "<?"
      },
      link: (scope, el2) => {
        userAvatarPopover.attach(el2, () => scope.user, scope.popoverLabels);
      }
    };
  }
]);
angular_default.module("kantree").service("userAvatarPopover", class extends AngularClass {
  static $inject = ["dropdown", "$rootScope"];
  attach(anchorElement, user, labels) {
    let drop, scope;
    anchorElement.on("mouseenter", () => {
      if (drop) return;
      scope = this.$rootScope.$new(true);
      scope.user = isFunction_default(user) ? user() : user;
      scope.labels = Array.isArray(labels) ? labels : labels ? [labels] : [];
      scope.openDrop = () => {
        if (drop) {
          this.$dropdown.updateOnNextFrame(drop, true);
        }
      };
      drop = this.$dropdown.openCompile(
        anchorElement[0],
        '<user-info-card user="user" labels="labels" on-render="openDrop()"></user-info-card>',
        scope,
        { classes: "drop-theme-arrow user-avatar-popover", _autoOpen: false, _closeOtherDrops: false, tetherOptions: { resizable: false } }
      );
    }).on("mouseleave", (event2) => {
      this.$dropdown.close(drop, event2);
      scope.$destroy();
      drop = null;
    });
  }
});

// public/app/ui/base/ng-components/dropdown/drop-position-manager.js
var DropPositionManager = class {
  constructor(options2) {
    this.options = Object.assign({
      container: "document",
      hook: {
        x: "left",
        y: "top"
      },
      anchor: {
        hook: {
          x: "left",
          y: "top"
        }
      },
      containerMargin: 4
    }, options2);
    this.drop = {
      $element: jquery_default(this.options.element)
    };
    this.offsetParent = {};
    this.anchor = {};
    if (typeof this.options.anchor.element !== "undefined") {
      this.anchor = {
        $element: jquery_default(this.options.anchor.element)
      };
    }
    this.container = {};
    if (this.options.container !== "document") {
      this.container.$element = jquery_default(this.options.container);
    } else {
      this.container.$element = jquery_default(document).offsetParent();
    }
  }
  _getRelativeOffset(absoluteOffset, margin) {
    margin = margin || 0;
    return {
      top: absoluteOffset.top - this.offsetParent.rect.top + margin,
      bottom: absoluteOffset.bottom - this.offsetParent.rect.top - margin,
      left: absoluteOffset.left - this.offsetParent.rect.left + margin,
      right: absoluteOffset.right - this.offsetParent.rect.left - margin
    };
  }
  _refreshAllOffsets(coord) {
    this.offsetParent.$element = this.drop.$element.offsetParent();
    this.offsetParent.rect = this.offsetParent.$element[0].getBoundingClientRect();
    this.container.rect = this.container.$element[0].getBoundingClientRect();
    this.container.offset = this._getRelativeOffset(this.container.rect, this.options.containerMargin);
    this.drop.rect = this.drop.$element[0].getBoundingClientRect();
    if (this.anchor.$element) {
      this.anchor.rect = this.anchor.$element[0].getBoundingClientRect();
      this.anchor.offset = this._getRelativeOffset(this.anchor.rect);
    } else if (coord) {
      this.anchor.offset = this._getRelativeOffset({
        top: coord.y,
        bottom: coord.y,
        left: coord.x,
        right: coord.x
      });
    }
  }
  _getComputedPosition(axis) {
    var ort, antiOrt, dim, anchorHookPoint, anchorSecondHookPoint;
    if (axis === "x") {
      ort = "left";
      antiOrt = "right";
      dim = "width";
    } else if (axis === "y") {
      ort = "top";
      antiOrt = "bottom";
      dim = "height";
    }
    anchorHookPoint = this.options.anchor.hook[axis] === antiOrt ? this.anchor.offset[antiOrt] : this.anchor.offset[ort];
    anchorSecondHookPoint = this.options.anchor.hook[axis] === antiOrt ? this.anchor.offset[ort] : this.anchor.offset[antiOrt];
    if (this.options.hook[axis] === ort) {
      if (this.container.offset[antiOrt] - anchorHookPoint > this.drop.rect[dim]) {
        return anchorHookPoint;
      } else if (this.container.offset[antiOrt] - anchorHookPoint > anchorSecondHookPoint - this.container.offset[ort]) {
        return Math.max(
          this.container.offset[ort],
          this.container.offset[antiOrt] - this.drop.rect[dim]
        );
      } else {
        return Math.max(
          this.container.offset[ort],
          anchorSecondHookPoint - this.drop.rect[dim]
        );
      }
    } else if (this.options.hook[axis] === antiOrt) {
      if (anchorHookPoint - this.container.offset[ort] > this.drop.rect[dim]) {
        return anchorHookPoint - this.drop.rect[dim];
      } else if (anchorHookPoint - this.container.offset[ort] > this.container.offset[antiOrt] - anchorSecondHookPoint) {
        return this.container.offset[ort];
      } else {
        return Math.max(
          this.container.offset[ort],
          anchorSecondHookPoint + Math.max(0, this.drop.rect[dim] - (this.container.offset[antiOrt] - anchorSecondHookPoint))
        );
      }
    }
  }
  _doPosition() {
    var el2 = this.drop.$element[0];
    var newCss = {
      top: this._getComputedPosition("y"),
      left: this._getComputedPosition("x")
    };
    if (this.drop.rect.width > this.container.rect.width - 2 * this.options.containerMargin) {
      newCss.width = this.container.rect.width - 2 * this.options.containerMargin;
    }
    if (this.drop.rect.height > this.container.rect.height - 2 * this.options.containerMargin) {
      newCss.height = this.container.rect.height - 2 * this.options.containerMargin;
    }
    if (typeof newCss.top !== "undefined") {
      el2.style.top = newCss.top + "px";
    }
    if (typeof newCss.left !== "undefined") {
      el2.style.left = newCss.left + "px";
    }
    if (typeof newCss.height !== "undefined") {
      el2.style.height = newCss.height + "px";
    }
    if (typeof newCss.width !== "undefined") {
      el2.style.width = newCss.width + "px";
    }
  }
  refresh(coord) {
    var self2 = this;
    var el2 = this.drop.$element[0];
    if (el2.style.height !== "" || el2.style.width !== "") {
      el2.style.height = null;
      el2.style.width = null;
    }
    if (this.options.hook.x === "right") {
      el2.style.right = "auto";
    }
    self2._refreshAllOffsets(coord);
    self2._doPosition();
  }
};

// public/app/ui/base/ng-components/dropdown/auto-drop-position.js
angular_default.module("kantree").directive("autoDropPosition", [
  function() {
    return {
      restrict: "A",
      link: function(scope, $element2, attr) {
        var $parent = $element2.parent();
        var positionManagerOpts = {
          element: $element2[0]
        };
        if ($element2.parents(".board-viewport").length) {
          positionManagerOpts.container = ".board-viewport";
        } else if ($element2.parents(".board").length) {
          positionManagerOpts.container = ".board";
        }
        if ($element2.hasClass("dropdown-menu")) {
          if ($parent.hasClass("dropdown-submenu") || $parent.hasClass("dropdown")) {
            positionManagerOpts.anchor = {
              element: $element2.parent()[0]
            };
            positionManagerOpts.hook = {
              x: $element2.hasClass("dropdown-menu-right") ? "right" : "left",
              y: "top"
            };
          }
          if ($parent.hasClass("dropdown-submenu")) {
            positionManagerOpts.anchor.hook = {
              x: $element2.hasClass("dropdown-menu-right") ? "left" : "right",
              y: "top"
            };
          } else if ($parent.hasClass("dropdown")) {
            positionManagerOpts.anchor.hook = {
              x: $element2.hasClass("dropdown-menu-right") ? "right" : "left",
              y: "bottom"
            };
          }
        }
        var positionManager = new DropPositionManager(positionManagerOpts);
        var dropPositionSimpleRefresh = function() {
          positionManager.refresh();
        };
        $parent.on("show.kt.contextmenu", function(event2, originalEvent) {
          positionManager.refresh({
            x: originalEvent.pageX,
            y: originalEvent.pageY
          });
        });
        if ($element2.hasClass("dropdown-menu")) {
          if ($parent.hasClass("dropdown-submenu")) {
            $parent.on("shown.bs.submenu", function(event2, data2) {
              positionManager.refresh();
              optimizedWindowResize.addHandler(dropPositionSimpleRefresh);
            });
            $parent.on("hide.bs.submenu", function() {
              optimizedWindowResize.removeHandler(dropPositionSimpleRefresh);
            });
          } else if ($parent.hasClass("dropdown")) {
            $parent.on("shown.bs.dropdown", function(event2, data2) {
              positionManager.refresh();
              optimizedWindowResize.addHandler(dropPositionSimpleRefresh);
            });
            $parent.on("hidden.bs.dropdown", function() {
              optimizedWindowResize.removeHandler(dropPositionSimpleRefresh);
            });
          }
        }
        $element2.on("refresh.autoDropPosition", dropPositionSimpleRefresh);
        scope.$on("$destroy", function() {
          $parent.off("show.kt.contextmenu");
          $parent.off("hide.kt.contextmenu");
          $parent.off("shown.bs.dropdown");
          $parent.off("hidden.bs.dropdown");
          $parent.off("show.bs.submenu");
          $parent.off("hide.bs.submenu");
        });
      }
    };
  }
]);

// public/app/ui/base/ng-components/dropdown/drop-toggle.js
angular_default.module("kantree").directive("dropToggle", [
  "dropdown",
  function(dropdown) {
    return {
      restrict: "A",
      scope: {
        config: "<dropToggle",
        html: "<dropHtml",
        template: "<dropTemplate",
        watchers: "<dropWatchers",
        params: "<dropParams"
      },
      link: function(scope, element2, attr) {
        var drop;
        var dropScope;
        scope.$watch("config", (newVal, oldVal) => {
          if (newVal === oldVal) return;
          if (drop && drop.drop && drop.isOpened()) {
            dropdown.close(drop);
            open();
          }
        });
        var open = function() {
          if (!dropScope) {
            dropScope = scope.$new();
            dropScope.updateDrop = function() {
              dropdown.updateOnNextFrame(drop);
            };
            dropScope.closeDrop = function() {
              dropdown.close(drop);
            };
            if (scope.params) {
              angular_default.forEach(scope.params, function(value2, key2) {
                dropScope[key2] = value2;
              });
            }
          }
          if (scope.html) {
            return dropdown.openCompile(element2[0], scope.html, dropScope, scope.config);
          } else if (scope.template) {
            return dropdown.openTemplate(element2[0], scope.template, dropScope, scope.config);
          } else {
            return dropdown.open(element2[0], scope, scope.config);
          }
        };
        var off;
        var toggleDrop = function(event2) {
          event2.preventDefault();
          event2.stopPropagation();
          if (!drop || !drop.drop) {
            drop = open();
            if (scope.watchers) {
              drop.on("open", function() {
                off = scope.watchers(function() {
                  dropdown.updateOnNextFrame(drop);
                });
              });
              drop.on("close", function() {
                if (off) {
                  off();
                }
                off = null;
              });
            }
            if (!drop.options._destroyOnClose) {
              element2.off("click", toggleDrop);
            }
          } else {
            if (drop.isOpened()) {
              dropdown.close(drop, event2);
            } else {
              dropdown.updateOnNextFrame(drop, true);
            }
          }
          return drop;
        };
        if (scope.config && scope.config.openOn === "hover") {
          var handleMouseEnter = function(event2) {
            toggleDrop(event2);
          };
          if (!isScreensizeXS()) {
            element2.on("mouseenter", handleMouseEnter);
          }
          scope.$on("screensize:changed", function() {
            element2.off("mouseenter", handleMouseEnter);
            if (!isScreensizeXS()) {
              element2.on("mouseenter", handleMouseEnter);
            }
          });
        }
        element2.on("click", function(event2) {
          toggleDrop(event2);
        });
        scope.$on("$destroy", function() {
          if (off) {
            off();
          }
        });
      }
    };
  }
]);

// virtual-ns:tether
var tether_default = Tether;

// virtual-ns:tether-custom-constraint
var tether_custom_constraint_default = TetherCustomConstraintModule;

// virtual-ns:drop
var drop_default = Drop;

// public/app/ui/base/ng-components/dropdown/dropdown.js
var defaultDropConfig = {
  position: "bottom left",
  openOn: "click"
};
tether_default.defaultModules = tether_default.modules.slice();
tether_default.modules.shift();
tether_default.modules.unshift(tether_custom_constraint_default);
(function(destroy) {
  tether_default.prototype.destroy = function() {
    if (this.options.resizable && this.mirror) {
      document.body.removeChild(this.mirror);
      this.mirror = null;
    }
    destroy.apply(this, arguments);
  };
})(tether_default.prototype.destroy);
angular_default.module("kantree").factory("dropdown", [
  "$compile",
  "$templateCache",
  function($compile, $templateCache) {
    var allDrops = [];
    var _closeAll = function() {
      allDrops.forEach(function(drop) {
        if (drop.openOn !== "always") {
          drop.close();
        }
      });
    };
    return {
      create: function(config3) {
        config3 = Object.assign({
          _closeOtherDrops: true
        }, config3 || {});
        const drop = new drop_default(config3);
        drop.on("open", (event2) => {
          for (const d3 of allDrops) {
            if (jquery_default(drop.target).closest(d3.drop).length) {
              if (!d3.childDrops) {
                d3.childDrops = /* @__PURE__ */ new Set();
              }
              if (d3.childDrops.size === 0) {
                d3.oldBeforeClose = d3.options.beforeClose;
                d3.options.beforeClose = (event3) => {
                  if (!event3 || event3.type === "programmatic") {
                    d3.options.beforeClose = d3.oldBeforeClose;
                    return;
                  }
                  return false;
                };
              }
              d3.childDrops.add(drop);
              drop.on("close", (event3) => {
                if (d3.childDrops.has(drop)) {
                  d3.childDrops.delete(drop);
                  requestAnimationFrame(() => {
                    if (d3.childDrops.size === 0) {
                      d3.options.beforeClose = d3.oldBeforeClose;
                    }
                  });
                }
              });
            } else if (config3._closeOtherDrops) {
              if (d3.openOn !== "always") {
                d3.close();
              }
            }
          }
          allDrops.push(drop);
        });
        drop.on("close", () => {
          allDrops = allDrops.filter((d3) => d3 !== drop);
        });
        return drop;
      },
      open: function(target, scope, customConfig) {
        var destroyScopeEventListenerOff;
        var config3 = Object.assign({
          target,
          classes: "drop-theme-arrow",
          constrainToWindow: false,
          constrainToScrollParent: false,
          _destroyOnClose: true,
          // Take care of race conditions when asynchronously opening the drop while using options.openOn: 'hover',
          // See menuDropdown factory for a good example
          _autoOpen: true,
          _closeOnResize: false,
          _withBackground: true,
          _closeOnBackgroundClick: true,
          beforeClose: (event2) => {
            const shouldClose = !drop.preventCloseOnNextClick;
            drop.preventCloseOnNextClick = false;
            return shouldClose;
          }
        }, customConfig, {
          tetherOptions: Object.assign({
            attachment: "top center",
            targetAttachment: "bottom center",
            // this is the default constraints config, it will erase
            // constrainToWindow and constrainToScrollParent anyway
            constraints: [
              {
                to: "scrollParent",
                pin: "top, bottom",
                attachment: "together none"
              },
              {
                to: "window",
                attachment: "together",
                pin: true
              }
            ],
            // custom options from the tether custom constraint module
            // it will expose a resizedHeight if the drop element needs to be resized
            resizable: true
          }, customConfig ? customConfig.tetherOptions || {} : {})
        });
        var openOnHover;
        var screensizeChangedEventListenerOff;
        if (config3.openOn === "hover") {
          if (isScreensizeXS()) {
            config3.openOn = "click";
          } else {
            openOnHover = true;
            config3.openOn = "null";
          }
          screensizeChangedEventListenerOff = scope.$on("screensize:changed", () => {
            if (drop && drop.drop && !openOnHover && !isScreensizeXS()) {
              drop.options._destroyOnClose = false;
              drop.destroy();
              this.open(target, scope, customConfig);
            } else if (drop && drop.drop && openOnHover && isScreensizeXS()) {
              drop.options._destroyOnClose = false;
              drop.destroy();
              this.open(target, scope, customConfig);
            }
          });
        }
        var drop = this.create(Object.assign({}, defaultDropConfig, config3, {
          tetherOptions: Object.assign({}, defaultDropConfig.tetherOptions, config3.tetherOptions)
        }));
        destroyScopeEventListenerOff = scope.$on("$destroy", function() {
          try {
            if (drop.options._closeOnResize) {
              optimizedWindowResize.removeHandler(drop.close);
            }
            if (destroyScopeEventListenerOff) {
              destroyScopeEventListenerOff();
            }
            requestAnimationFrame(() => {
              if (!drop.drop) return;
              drop.destroy();
            });
          } catch (e3) {
          }
        });
        drop._on(document, "mousedown", (event2) => {
          drop.preventCloseOnNextClick = false;
          if (jquery_default(event2.target).closest(drop.drop).length && (event2.target.tagName === "INPUT" || event2.target.tagName === "TEXTAREA" || jquery_default(event2.target).closest('[contenteditable="true"]').length)) {
            drop.preventCloseOnNextClick = true;
          }
        });
        var inTimeout = null;
        var outTimeout = null;
        if (openOnHover) {
          var inHandler = function inHandler2(event2) {
            if (outTimeout !== null) {
              clearTimeout(outTimeout);
            } else {
              inTimeout = setTimeout(function() {
                drop.trigger("hoverin");
                drop.open(event2);
                inTimeout = null;
              }, drop.options.hoverOpenDelay || drop.options.openDelay);
            }
          };
          var outHandler = function outHandler2(event2) {
            if (inTimeout !== null) {
              clearTimeout(inTimeout);
            } else {
              outTimeout = setTimeout(function() {
                drop.trigger("hoverout");
                drop.close(event2);
                outTimeout = null;
              }, drop.options.hoverCloseDelay || drop.options.closeDelay);
            }
          };
          drop._on(drop.target, "mouseover", inHandler);
          drop._on(drop.drop, "mouseover", inHandler);
          drop._on(drop.target, "mouseout", outHandler);
          drop._on(drop.drop, "mouseout", outHandler);
        }
        var background;
        if (drop.options._withBackground) {
          background = document.createElement("div");
          background.className = "drop-background";
          document.body.appendChild(background);
          angular_default.element(background).on("click", function(event2) {
            event2.stopPropagation();
            event2.stopImmediatePropagation();
            event2.preventDefault();
            if (drop.options._closeOnBackgroundClick) {
              drop.close(event2);
            }
          });
        }
        drop.on("open", function() {
          if (background) {
            background.className = "drop-background drop-open " + drop.options.classes;
          }
          if (drop.options._closeOnResize) {
            optimizedWindowResize.addHandler(drop.close);
          }
        });
        (function(destroy) {
          drop.destroy = function() {
            if (outTimeout !== null) {
              clearTimeout(outTimeout);
            }
            if (inTimeout !== null) {
              clearTimeout(inTimeout);
            }
            if (background) {
              angular_default.element(background).off();
              document.body.removeChild(background);
              background = null;
            }
            if (drop.options.content) {
              jquery_default(drop.options.content).remove();
              drop.options.content = null;
            }
            if (destroyScopeEventListenerOff) {
              destroyScopeEventListenerOff();
            }
            if (screensizeChangedEventListenerOff) {
              screensizeChangedEventListenerOff();
            }
            destroy.apply(this, arguments);
          };
        })(drop.destroy);
        drop.on("close", function() {
          if (background) {
            background.className = "drop-background";
          }
          if (drop.options._closeOnResize) {
            optimizedWindowResize.removeHandler(drop.close);
          }
          if (drop.options._destroyOnClose) {
            requestAnimationFrame(() => {
              if (!drop.drop) return;
              drop.destroy();
              drop.tether = void 0;
            });
          }
        });
        if (drop.tether.options.resizable) {
          drop.tether.on("repositioned", function() {
            if (this.resizedHeight) {
              let height = this.resizedHeight;
              if (this.element.classList.contains("drop-theme-arrow") && (this.element.classList.contains("drop-element-attached-top") || this.element.classList.contains("drop-element-attached-bottom"))) {
                height -= 16;
              }
              this.element.style.height = height + "px";
            } else {
              if (this.element.style.height) {
                this.element.style.height = null;
              }
            }
          });
        }
        if (drop.options._fixDropAfterMenuInit) {
          let fixed = false;
          const debouncedFixDropPos = debounce2((attachments) => {
            drop.tether.attachment = attachments.attachment;
            drop.tether.targetAttachment = attachments.targetAttachment;
            const newConstraints = drop.tether.options.constraints.map((constraint) => {
              constraint.attachment = "none";
              return constraint;
            });
            drop.tether.options.constraints = newConstraints;
            fixed = true;
            if (drop && drop.tether) {
              drop.tether.off("update", onTetherUpdate);
            }
          }, 300);
          const onTetherUpdate = (attachments) => {
            if (!fixed) {
              debouncedFixDropPos(attachments);
            }
          };
          drop.tether.on("update", onTetherUpdate);
        }
        if (drop.options._autoOpen) {
          drop.open();
        }
        return drop;
      },
      openCompile: function(target, html5, scope, config3) {
        config3 = Object.assign({
          _useChildScope: false,
          _destroyOnClose: true
        }, config3);
        var contentScope = config3._useChildScope ? scope.$new() : scope;
        var contentDomElement = $compile(html5)(contentScope);
        config3.content = contentDomElement[0];
        var drop = this.open(target, scope, config3);
        var scopeDestroyEventListenerOff = scope.$on("$destroy", () => this.close(drop));
        drop.contentScope = contentScope;
        drop.on("close", function() {
          if (drop.options._destroyOnClose) {
            if (scopeDestroyEventListenerOff) scopeDestroyEventListenerOff();
            if (drop.options._useChildScope && contentScope) contentScope.$destroy();
          }
        });
        contentScope.$on("$destroy", function() {
          if (contentDomElement) {
            contentDomElement.remove();
            contentDomElement = null;
          }
        });
        return drop;
      },
      openTemplate: function(target, template3, scope, config3) {
        return this.openCompile(target, $templateCache.get(template3), scope, config3);
      },
      update: function(drop, forceOpen) {
        if (drop && drop.drop) {
          if (drop.options._preUpdate) {
            drop.options._preUpdate(drop);
          }
          if (!drop.isOpened() && forceOpen) {
            drop.open();
          } else {
            drop.position();
          }
          if (drop.options._postUpdate) {
            drop.options._postUpdate(drop);
          }
        }
      },
      updateOnNextFrame: function(drop, forceOpen) {
        return requestAnimationFrame(() => this.update(drop, forceOpen));
      },
      toggle: function(drop, target, scope, config3, event2) {
        if (!drop || !drop.drop) {
          drop = this.open(target, scope, config3);
        } else {
          if (drop.isOpened()) {
            this.close(drop, event2);
          } else {
            this.updateOnNextFrame(drop, true);
          }
        }
        return drop;
      },
      close: function(drop, event2 = { type: "programmatic" }) {
        if (drop && drop.drop) {
          drop.close(event2);
        }
      },
      isOpened: function(drop) {
        return drop && drop.isOpened();
      }
    };
  }
]);

// public/app/ui/base/ng-components/dropdown/resize-dropdown.js
angular_default.module("kantree").directive("resizeDropdown", [
  "$window",
  function($window) {
    return {
      restrict: "A",
      scope: {
        "opt": "@resizeDropdown"
      },
      link: function(scope, $element2, attr) {
        function getMaxHeight() {
          return scope.opt === "halfWindow" ? ($window.innerHeight - 115) / 2 : $window.innerHeight - 115;
        }
        function dropdownResizer() {
          $element2.css("max-height", getMaxHeight() + "px");
        }
        dropdownResizer();
        jquery_default($window).resize(dropdownResizer);
        scope.$on("$destroy", () => jquery_default($window).off("resize", dropdownResizer));
      }
    };
  }
]);

// public/app/ui/base/ng-components/forms/auto-focus.js
angular_default.module("kantree").directive("autoFocus", [
  "$timeout",
  function($timeout2) {
    return {
      scope: {
        enabled: "<autoFocus"
      },
      link: function(scope, element2, attrs2) {
        scope.$watch("enabled", function(newVal, oldVal) {
          if (newVal === true || typeof newVal === "undefined") {
            $timeout2(function() {
              if (typeof attrs2.autoFocusSelect !== "undefined") {
                element2[0].setSelectionRange(0, element2[0].value.length);
              }
              element2[0].focus();
              if (typeof attrs2.selectOnFocus !== "undefined") {
                element2[0].select();
              }
            }, 200, false);
          }
        });
      }
    };
  }
]);

// public/app/ui/base/ng-components/forms/auto-grow.js
angular_default.module("kantree").directive("autoGrow", function() {
  return function(scope, element2, attr) {
    var opts = {
      maxWidth: parseInt(attr.maxWidth) || 1e3,
      minWidth: parseInt(attr.minWidth) || element2.width(),
      comfortZone: parseInt(attr.comfortZone) || 20
    };
    var minWidth = opts.minWidth;
    var val = "";
    var input = element2;
    var $shadow = angular_default.element("<div></div>").css({
      position: "absolute",
      top: -1e4,
      left: -1e4,
      width: "auto",
      fontSize: element2.css("fontSize"),
      fontFamily: element2.css("fontFamily"),
      fontWeight: element2.css("fontWeight"),
      letterSpacing: input.css("letterSpacing"),
      whitespace: "nowrap"
    });
    $shadow.insertAfter(element2);
    if (attr.ngModel) {
      scope.$watch(attr.ngModel, update2);
    } else {
      element2.bind("keyup keydown keypress change", update2);
    }
    scope.$on("autoGrowForceUpdate", update2);
    update2();
    function update2() {
      if (val === (val = input.val())) {
        return;
      }
      var escaped = val.replace(/&/g, "&amp;").replace(/\s/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
      $shadow.html(escaped);
      var testerWidth = $shadow.width(), newWidth = testerWidth + opts.comfortZone >= minWidth ? testerWidth + opts.comfortZone : minWidth, currentWidth = input.width(), isValidWidthChange = newWidth < currentWidth && newWidth >= minWidth || newWidth > minWidth && newWidth < opts.maxWidth;
      if (isValidWidthChange) {
        input.width(newWidth);
      }
      if (newWidth >= opts.maxWidth) {
        input.width(opts.maxWidth);
      }
    }
  };
});

// public/app/ui/base/ng-components/forms/checkbox-list.js
angular_default.module("kantree").directive("checkboxList", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/base/ng-components/forms/templates/checkbox-list.html",
      replace: true,
      scope: {
        values: "<",
        selected: "<?",
        sortable: "<?",
        onSelectionChanged: "&",
        idProperty: "@",
        labelProperty: "@"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.idProperty = $scope2.idProperty || "id";
          $scope2.labelProperty = $scope2.labelProperty || "label";
          $scope2.items = [];
          $scope2.update = function() {
            const values2 = $scope2.items.filter((i3) => !!i3.selected).map((i3) => i3.value);
            $scope2.onSelectionChanged({ "$values": values2 });
          };
          function resetItems() {
            $scope2.items = ($scope2.values || []).map((value2) => {
              return {
                id: value2[$scope2.idProperty],
                label: value2[$scope2.labelProperty],
                value: value2,
                selected: ($scope2.selected || []).includes(value2[$scope2.idProperty])
              };
            });
            return $scope2.items;
          }
          ;
          $scope2.$watch("values", resetItems);
          $scope2.$watch("selected", () => {
            var items = resetItems();
            $scope2.items = [];
            ($scope2.selected || []).forEach((id) => {
              const idx = items.findIndex((i3) => i3.id === id);
              if (idx !== -1) {
                $scope2.items.push(items[idx]);
                items.splice(idx, 1);
              }
            });
            $scope2.items = $scope2.items.concat(items);
            $scope2.update();
          });
          $scope2.sortableOptions = {
            axis: "y",
            "ui-floating": false,
            disabled: !$scope2.sortable,
            stop: $scope2.update
          };
          $scope2.toggleAll = function() {
            if ($scope2.items.some((i3) => !i3.selected)) {
              $scope2.items.forEach((i3) => i3.selected = true);
            } else {
              $scope2.items.forEach((i3) => i3.selected = false);
            }
            $scope2.update();
          };
        }
      ]
    };
  }
]);

// public/app/ui/base/ng-components/forms/checkbox-toggle.js
angular_default.module("kantree").component("checkboxToggle", {
  template: `
    <input type="checkbox" data-toggle="toggle" data-size="small" ng-disabled="$ctrl.disabled">
  `,
  bindings: {
    checked: "<",
    onLabel: "@",
    offLabel: "@",
    onChange: "&",
    disabled: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$rootScope"];
    $onChanges(changes) {
      if (changes.checked && this.checkbox) {
        this.checkbox[0].checked = changes.checked.currentValue;
      }
    }
    $postLink() {
      this.checkbox = this.$element.find("input");
      this.checkbox[0].checked = this.checked;
      this.checkbox.bootstrapToggle({
        on: this.onLabel,
        off: this.offLabel
      }).change(() => {
        this.$rootScope.$applyAsync(() => this.onChange({ $checked: this.checkbox[0].checked }));
      });
    }
  }
});

// public/app/ui/base/ng-components/forms/copyable-readonly-input.js
angular_default.module("kantree").directive("copyableReadonlyInput", function() {
  return {
    replace: true,
    template: `
      <div class="input-group">
        <input class="form-control" type="text" ng-attr-value="{{value}}" readonly auto-focus select-on-focus>
        <button class="btn btn-icon btn-default btn-ghost" type="button"><i class="fa fa-files-o"></i></button>
        <button class="btn btn-icon btn-default btn-ghost" type="button" ng-click="onQrcode({$modal: qrcodeModal.open(value, qrcodeModalTitle)})" ng-show="showQrcode"><i class="bi-qr-code"></i></button>
      </div>
    `,
    scope: {
      value: "<",
      showQrcode: "<?",
      qrcodeModalTitle: "@",
      onQrcode: "&"
    },
    controller: [
      "$scope",
      "qrcodeModal",
      function($scope2, qrcodeModal) {
        $scope2.qrcodeModal = qrcodeModal;
      }
    ],
    link: function(scope, el2) {
      const clip2 = new clipboard_default(el2.find("button").first()[0], { text: () => scope.value });
      scope.$on("$destroy", () => clip2.destroy());
    }
  };
});

// public/app/ui/base/ng-components/forms/datepicker.js
angular_default.module("kantree").component("datePicker", {
  bindings: {
    options: "<",
    range: "<?",
    onChange: "&"
  },
  controller: [
    "$element",
    "$scope",
    function($element2, $scope2) {
      var $ctrl = this;
      var updateDateRangePicker = function() {
        $element2.daterangepicker(Object.assign({
          inline: true,
          singleDatePicker: !$ctrl.range,
          locale: {
            firstDay: getFirstDayOfWeek()
          }
        }, $ctrl.options), function(start, end) {
          $scope2.$applyAsync(function() {
            $ctrl.onChange({ $start: start, $end: end });
          });
        });
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.options && !changes.options.isFirstChange()) {
          updateDateRangePicker();
        }
      };
      $ctrl.$postLink = function() {
        updateDateRangePicker();
        $element2.on("click", function(e3) {
          e3.stopPropagation();
        });
      };
    }
  ]
});
angular_default.module("kantree").directive("datepickerDropdown", [
  "dropdown",
  function(dropdown) {
    return {
      restrict: "A",
      scope: {
        "date": "<datepickerDropdown",
        "datepickerOptions": "<",
        "onDateChange": "&"
      },
      link: function(scope, el2, attrs2) {
        var drop;
        var isRange = !!attrs2.datepickerRange;
        var html5 = '<date-picker options="options" ' + (isRange ? ' range="true" ' : "") + 'on-change="updateDate($start, $end)" />';
        scope.updateDate = function(start, end) {
          if (isRange) {
            scope.onDateChange({ $start: start, $end: end });
          } else {
            scope.onDateChange({ $start: start });
          }
          if (scope.options.timePicker || scope.options.autoApply) {
            dropdown.close(drop);
          }
        };
        var updatePickerOptions = function() {
          var opts = {};
          if (scope.date) {
            if (isRange) {
              opts = { startDate: scope.date.start, endDate: scope.date.end };
            } else {
              opts = { startDate: scope.date };
            }
          }
          scope.options = Object.assign({}, opts, scope.datepickerOptions);
        };
        scope.$watch("datepickerOptions", function(newVal, oldVal) {
          if (newVal === oldVal) {
            return;
          }
          updatePickerOptions();
        });
        scope.$watch("date", function(newVal, oldVal) {
          if (newVal === oldVal) {
            return;
          }
          updatePickerOptions();
        });
        updatePickerOptions();
        drop = dropdown.openCompile(el2[0], html5, scope, {
          _autoOpen: false,
          _destroyOnClose: false,
          classes: "drop-theme-arrow datepicker-dropdown"
        });
      }
    };
  }
]);
function formatPeriodToDisplay(dateRange, withTime) {
  if (!dateRange) return null;
  return {
    start: dateRange.start.isSame(dateRange.end, "day") && !withTime ? null : formatDate(dateRange.start, withTime ? "lll" : "ll"),
    end: formatDate(dateRange.end, withTime ? "lll" : "ll")
  };
}
angular_default.module("kantree").component("datepickerMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&?"
  },
  template: `
    <div
      class="input-group"
      datepicker-dropdown="$ctrl.params.date()"
      datepicker-options="$ctrl.params.options()" datepicker-range="$ctrl.params.isRange()"
      on-date-change="$ctrl.params.onDateChange($start, $end)"
    >
      <button
        type="button"
        class="btn btn-icon btn-default btn-ghost"
      >
        <i class="bi-calendar-range"></i>
      </button>
      <input
        type="text"
        class="form-control"
        ng-model="$ctrl.period"
        readonly="true"
      />
    </div>
  `,
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.$scope.$watch(this.params.date(), () => {
        const period = formatPeriodToDisplay(this.params.date(), !!this.params.options().timePicker);
        this.period = period.start ? `${period.start} - ${period.end}` : period.end;
      });
    }
  }
});

// public/app/ui/base/ng-components/forms/icon-picker.js
init_icons();
angular_default.module("kantree").component("iconPicker", {
  bindings: {
    icon: "<?",
    onChange: "&",
    emptyIcon: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      if (this.emptyIcon === void 0) {
        this.emptyIcon = true;
      }
      this.refreshPalette();
      this.allIconsMenu = { config: [{
        iconpicker: true,
        completeSet: true,
        action: (event2, icon) => this.select(icon)
      }] };
    }
    refreshPalette() {
      this.icons = availableIcons.slice(0, 10);
      if (this.emptyIcon) {
        this.icons.unshift(null);
      }
      if (!this.isInDisplayed(this.icon)) {
        this.icons.push(this.icon);
      }
    }
    select(icon) {
      this.icon = icon;
      this.refreshPalette();
      this.onChange({ $icon: icon });
    }
    isSelected(icon) {
      return this.iconsMatch(this.icon, icon);
    }
    isInDisplayed(icon) {
      return this.icons.find((i3) => this.iconsMatch(i3, icon)) !== void 0;
    }
    iconsMatch(a3, b3) {
      return !a3 && !b3 || a3 && b3 && a3.toUpperCase() === b3.toUpperCase();
    }
  },
  template: `
    <button type="button" ng-repeat="icon in $ctrl.icons" ng-click="$ctrl.select(icon)"
        ng-class="{'is-selected': $ctrl.isSelected(icon), 'no-icon': !icon}">
        <i ng-class="icon|iconClass"></i>
    </button>
    <button type="button" class="picker" drop-menu="$ctrl.allIconsMenu">
      <span class="bi-caret-down-fill"></span>
    </button>
  `
});

// public/app/ui/base/ng-components/forms/indeterminate.js
angular_default.module("kantree").directive("ngIndeterminate", [
  function() {
    return {
      compile: function(tElm, tAttrs) {
        if (!tAttrs.type || tAttrs.type.toLowerCase() !== "checkbox") {
          return angular_default.noop;
        }
        return function($scope2, elm, attrs2) {
          $scope2.$watch(attrs2.ngIndeterminate, (newVal) => {
            elm[0].indeterminate = !!newVal;
          });
        };
      }
    };
  }
]);

// public/app/ui/base/ng-components/forms/indicator-dropdown.js
angular_default.module("kantree").directive("indicatorDropdown", function() {
  return {
    replace: true,
    templateUrl: "/static/app/ui/base/ng-components/forms/templates/indicator-dropdown.html",
    restrict: "E",
    scope: {
      indicator: "=",
      availableIndicators: "=?",
      hideSelection: "@"
    },
    controller: [
      "$scope",
      function($scope2) {
        injectI18nHelpersIntoScope($scope2);
        if (!$scope2.availableIndicators) {
          $scope2.availableIndicators = [
            "anchor",
            "asterisk",
            "ban",
            "bell",
            "birthday-cake",
            "bolt",
            "bomb",
            "bug",
            "bullhorn",
            "check",
            "cloud",
            "cog",
            "exclamation-triangle",
            "flag",
            "flask",
            "gift",
            "globe",
            "heart",
            "info-circle",
            "leaf",
            "life-ring",
            "lock",
            "magic",
            "magnet",
            "paw",
            "phone",
            "plug",
            "recycle",
            "question-circle",
            "rocket",
            "rss",
            "retweet",
            "shield",
            "shopping-cart",
            "star",
            "suitcase",
            "trophy",
            "umbrella",
            "unlock",
            "wrench",
            "pie-chart",
            "line-chart",
            "euro",
            "dollar"
          ];
        }
        $scope2.setIndicator = function(i3) {
          $scope2.indicator = i3;
        };
      }
    ]
  };
});

// public/app/ui/base/ng-components/forms/kt-form-check.js
angular_default.module("kantree").directive("ktFormCheck", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        value: "<?",
        onChange: "&?",
        switch: "<?",
        tooltip: "@?",
        ngDisabled: "<?",
        ngIndeterminate: "<?"
      },
      transclude: true,
      replace: true,
      template: `
        <div class="form-check" ng-class="{'form-switch': !!$ctrl.switch}">
          <input class="form-check-input" type="checkbox" ng-attr-role="::(!!$ctrl.switch ? 'switch' : null)" ng-model="$ctrl._value"
            ng-change="$ctrl.updateValue($event)" id="{{::$ctrl.inputId}}" uib-tooltip="{{::$ctrl.tooltip}}"
            tooltip-enable="::($ctrl.tooltip && $ctrl.tooltip.length)" ng-indeterminate="!!$ctrl.ngIndeterminate"
            ng-disabled="!!$ctrl.ngDisabled">
          <label class="form-check-label" for="{{::$ctrl.inputId}}" ng-transclude></label>
        </div>
      `,
      require: {
        ngModel: "?ngModel"
        // Use it with ngChangeDirective
      },
      controller: class extends AngularClass {
        static $inject = ["$scope"];
        $onInit() {
          this.inputId = uuid4();
          this._value = this.value;
          if (this.ngModel) {
            this.ngModel.$render = () => {
              this._value = this.ngModel.$viewValue || null;
            };
            this.ngModel.$viewChangeListeners.push(() => {
              this._value = this.ngModel.$viewValue;
            });
          }
        }
        $onChanges(changes) {
          if (changes.value && !changes.value.isFirstChange()) {
            this._value = this.value;
          }
        }
        updateValue(event2) {
          if (this.ngIndeterminate && !this.value) {
            this._value = false;
          }
          if (this.ngModel) {
            this.ngModel.$setViewValue(this._value);
          } else {
            this.onChange({ $event: event2, $isChecked: this._value });
          }
        }
      }
    };
  }
]);

// public/app/ui/base/ng-components/forms/pretty-select.js
angular_default.module("kantree").component("prettySelect", {
  bindings: {
    options: "<?",
    menuBuilder: "<?",
    customDropConfig: "<?dropConfig",
    labelFormatter: "<?",
    labelProp: "@",
    valueProp: "@",
    menuItemProp: "@",
    menuItemOptionsProp: "@",
    emptyLabel: "@?",
    allowUnknownValue: "<",
    skipUnknownValues: "<",
    unknownValueInputPlaceholder: "@",
    groupBy: "@",
    multiple: "<?",
    filterable: "<?",
    isRequired: "<?",
    // if true, auto select first option at init if no value is provided
    placeholder: "@",
    disabled: "<?",
    onChange: "&",
    onDropOpened: "&",
    onDropClosed: "&"
  },
  require: { ngModel: "?ngModel" },
  template: `
    <div ng-class="{'disabled': $ctrl.disabled}" drop-menu="$ctrl.menu" is-disabled="$ctrl.disabled"
      drop-config="$ctrl.dropConfig" on-drop-opened="$ctrl.onDropOpened({$drop})" on-drop-closed="$ctrl.notifyDropClosed()">
      <span ng-repeat="value in $ctrl.values" ng-class="{'me-1': !$last}">{{value + ($last ? '' : ',')}}</span>
      <span class="empty" ng-if="!$ctrl.values.length && $ctrl.emptyLabel">{{$ctrl.emptyLabel}}</span>
      <span class="placeholder" ng-if="!$ctrl.values.length && (!$ctrl.emptyLabel || $ctrl.placeholder)">{{$ctrl.placeholder}}&nbsp;</span>
    </div>
  `,
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $onInit() {
      this.dropConfig = Object.assign({
        classes: "pretty-select-drop drop-theme-menu",
        _closeOtherDrops: false,
        tetherOptions: {
          attachment: "top center"
        }
      }, this.customDropConfig || {});
      this.notifyDropClosedAfterValueSet = false;
      this.ngModel.$render = () => {
        this.selectDefaultValue();
        this.renderValue();
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.selectDefaultValue();
        this.renderValue();
      });
    }
    $postLink() {
      if (this.multiple) {
        this.$element.addClass("multiple");
      }
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.selectDefaultValue();
      }
      if (changes.options || changes.menuBuilder) {
        this.buildMenu();
        this.renderValue();
      }
    }
    setViewValue(value2) {
      this.ngModel.$setViewValue(value2);
      this.onChange({ $value: value2 });
      this.notifyDropClosedAfterValueSet = true;
    }
    getViewValueAsArray() {
      let viewValue = this.ngModel.$viewValue;
      if (!this.multiple) {
        if (viewValue === null || viewValue === void 0 || Number.isNaN(viewValue)) {
          return [];
        } else {
          return [viewValue];
        }
      } else if (!viewValue) {
        return [];
      }
      return viewValue;
    }
    selectDefaultValue() {
      if (this.isRequired && this.options?.length && (this.ngModel.$viewValue === void 0 || Number.isNaN(this.ngModel.$viewValue))) {
        this.setViewValue(this.formatValue(this.options[0]));
      }
    }
    findOption(value2) {
      return this.options && this.options.find((o3) => this.formatValue(o3) === value2);
    }
    renderValue() {
      this.values = [];
      const viewValue = this.getViewValueAsArray();
      for (let v3 of viewValue) {
        if (this.menuBuilder) {
          this.values.push(this.formatLabel(v3));
          continue;
        }
        let opt = this.findOption(v3);
        if (opt === void 0) {
          if (this.skipUnknownValues) {
            continue;
          }
          this.values.push(this.valueProp && typeof v3 === "object" && v3.hasOwnProperty(this.valueProp) ? v3[this.valueProp] : v3);
        } else {
          this.values.push(this.formatLabel(opt));
        }
      }
    }
    formatLabel(value2) {
      if (this.labelFormatter) {
        return this.labelFormatter(value2);
      }
      if (!this.labelProp) {
        return this.formatValue(value2);
      }
      let label = value2[this.labelProp];
      if (typeof label === "function") {
        return label(value2, this);
      }
      return label;
    }
    formatValue(value2) {
      return this.valueProp ? value2[this.valueProp] : value2;
    }
    buildMenu() {
      if (this.menuBuilder) {
        this.menu = this.menuBuilder((value2) => this.setViewValue(this.formatValue(value2)));
        return;
      }
      this.menu = { config: [] };
      if (!this.isRequired) {
        this.menu.config.push({
          label: this.emptyLabel || (this.multiple ? _4("Clear") : _4("None")),
          filterable: false,
          action: () => this.setViewValue(null)
        }, { label: "--" });
      }
      if (!this.options) {
        return;
      }
      let opts = this.options;
      let orderedGroupNames = [];
      let groups = {};
      if (this.groupBy) {
        opts = [];
        for (let o3 of this.options) {
          if (o3[this.groupBy]) {
            if (!orderedGroupNames.includes(o3[this.groupBy])) {
              orderedGroupNames.push(o3[this.groupBy]);
              groups[o3[this.groupBy]] = [];
            }
            groups[o3[this.groupBy]].push(o3);
          } else {
            opts.push(o3);
          }
        }
      }
      this.menu.config.push(...opts.map((o3) => this.buildMenuItem(o3)));
      for (let group2 of orderedGroupNames) {
        this.menu.config.push({ subheader: group2 });
        this.menu.config.push(...groups[group2].map((o3) => this.buildMenuItem(o3)));
      }
      if (this.allowUnknownValue) {
        this.menu.config.push({
          input: true,
          resetOnSubmit: true,
          placeholder: this.unknownValueInputPlaceholder,
          submit: (value2) => this.setViewValue(value2)
        });
      }
    }
    buildMenuItem(option2) {
      if (option2 === "--") {
        return { label: "--" };
      }
      if (this.menuItemProp && option2[this.menuItemProp]) {
        return option2[this.menuItemProp](this);
      }
      let item;
      item = this.multiple ? this.buildMenuItemForMultipleValues(option2) : this.buildMenuItemForSingleValue(option2);
      if (this.menuItemOptionsProp && value[this.menuItemOptionsProp]) {
        Object.assign(item, value[this.menuItemOptionsProp]);
      }
      return item;
    }
    buildMenuItemForSingleValue(value2) {
      return {
        label: this.formatLabel(value2),
        filterable: this.filterable,
        action: () => this.setViewValue(this.formatValue(value2))
      };
    }
    buildMenuItemForMultipleValues(value2) {
      return {
        checkbox: true,
        label: this.formatLabel(value2),
        filterable: this.filterable,
        value: () => this.getViewValueAsArray().includes(this.formatValue(value2)),
        toggle: () => {
          let values2 = Array.from(this.getViewValueAsArray());
          let v3 = this.formatValue(value2);
          let idx = values2.indexOf(v3);
          if (idx === -1) {
            values2.push(v3);
          } else {
            values2.splice(idx, 1);
          }
          this.setViewValue(values2);
        }
      };
    }
    notifyDropClosed() {
      this.onDropClosed({ $afterSet: this.notifyDropClosedAfterValueSet });
      this.notifyDropClosedAfterValueSet = false;
    }
  }
});

// public/app/ui/base/ng-components/forms/upload-field.js
angular_default.module("kantree").component("uploadImageField", {
  templateUrl: "/static/app/ui/base/ng-components/forms/templates/upload-field.html",
  bindings: {
    value: "<?",
    editable: "<?",
    uploadUrl: "<?",
    uploadFieldName: "@",
    onUpload: "&",
    onReset: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      if (this.editable !== false) {
        this.editable = true;
      }
    }
    upload(file) {
      upload({
        url: this.uploadUrl,
        data: { [this.uploadFieldName]: file }
      }, (evt) => {
        this.uploadProgress = parseInt(100 * evt.loaded / evt.total);
      }).then((r3) => {
        this.uploadProgress = false;
        this.onUpload({ $data: r3.data });
      }, (resp) => {
        errorDialog(_4("An error occured while uploading your file"));
      });
    }
    reset() {
      this.value = null;
      this.file = null;
      this.onReset();
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/dropdown.js
angular_default.module("kantree").factory("menuDropdown", [
  "dropdown",
  "$compile",
  "$timeout",
  function(dropdown, $compile, $timeout2) {
    return {
      open: function(target, menu, scope, dropConfig) {
        var drop;
        var menuScope = scope.$new();
        let menuScopeDestroyWatcherOff;
        var menuHtml = '<pretty-menu class="pretty-menu" config="menu.config" options="menu.options" action-params="menu.params" default-path="menu.defaultPath" on-update="updateDrop($menuEvent, $currentPath)" on-close="closeDrop()"></pretty-menu>';
        var dropOpen = false;
        var cancelOpening = false;
        var debounceDropdownUpdate = debounce2(function() {
          if (cancelOpening) return;
          dropdown.update(drop, !dropOpen);
          dropOpen = drop.isOpened();
        }, 100);
        menuScope.updateDrop = function(menuEvent, currentPath) {
          menuScope.currentPath = currentPath;
          if (menuEvent === "panelInit" && dropOpen) {
            return;
          }
          debounceDropdownUpdate();
        };
        menuScope.closeDrop = function() {
          dropdown.close(drop);
        };
        menuScope.currentPath = null;
        menuScope.menu = menu;
        var menuDomElement = $compile(menuHtml)(menuScope);
        dropConfig = Object.assign(
          {
            content: menuDomElement[0],
            _autoOpen: false,
            // set to false, the first updateDrop() coming from the menu will open the drop
            classes: "drop-theme-menu drop-theme-arrow"
          },
          dropConfig || {},
          // extending tetherOptions
          {
            tetherOptions: Object.assign({
              constraints: [{
                to: "window",
                pin: true,
                attachment: "together none"
              }]
            }, dropConfig ? dropConfig.tetherOptions || {} : {})
          }
        );
        drop = dropdown.open(target, scope, dropConfig);
        var destroyScopeEventListenerOff = scope.$on("$destroy", function() {
          dropdown.close(drop);
        });
        drop.contentScope = menuScope;
        drop.on("close", function() {
          dropOpen = false;
          if (drop.options._destroyOnClose) {
            if (menuScope) {
              if (menuScopeDestroyWatcherOff) menuScopeDestroyWatcherOff();
              menuScope.$destroy();
              if (menuDomElement) {
                menuDomElement.remove();
                menuDomElement = null;
              }
            }
            if (destroyScopeEventListenerOff) {
              destroyScopeEventListenerOff();
            }
          }
        });
        function handleDropHoverOut() {
          if (!dropOpen) {
            cancelOpening = true;
            debounceDropdownUpdate.immediate();
            cancelOpening = false;
            if (drop.options._destroyOnClose) {
              drop.options._destroyOnClose = false;
              drop.destroy();
              if (menuScopeDestroyWatcherOff) menuScopeDestroyWatcherOff();
              menuScope.$destroy();
              if (menuDomElement) {
                menuDomElement.remove();
                menuDomElement = null;
              }
              drop.options._destroyOnClose = true;
            }
          }
        }
        drop.on("hoverout", handleDropHoverOut);
        menuScopeDestroyWatcherOff = menuScope.$on("$destroy", function() {
          if (menuDomElement) {
            menuDomElement.remove();
            menuDomElement = null;
          }
        });
        return drop;
      },
      toggle: function(drop, target, menu, scope, dropConfig, event2) {
        if ((!drop || !drop.drop) && !!menu) {
          return this.open(target, menu, scope, dropConfig);
        } else {
          if (drop.isOpened()) {
            dropdown.close(drop, event2);
          } else {
            dropdown.updateOnNextFrame(drop, true);
          }
        }
      },
      close: function(drop, event2) {
        dropdown.close(drop, event2);
      },
      isOpened: function(drop) {
        return dropdown.isOpened(drop);
      },
      refreshMenu: function(drop, menu) {
        if (!drop) return;
        drop.contentScope.menu = menu;
        if (drop.contentScope.currentPath) {
          drop.contentScope.menu.defaultPath = drop.contentScope.currentPath;
        }
        if (drop.isOpened() && !menu) {
          dropdown.close();
        }
      },
      openContextMenu: function(target, menu, scope, config3) {
        var contextMenuConfig = {
          _fixDropAfterMenuInit: true,
          classes: "drop-theme-contextmenu",
          constrainToScrollParent: false,
          tetherOptions: {
            targetAttachment: "top left",
            attachment: "top left",
            targetOffset: "0 0",
            constraints: [
              {
                to: "window",
                attachment: "element",
                pin: true
              }
            ]
          }
        };
        var drop;
        config3 = Object.assign({}, contextMenuConfig, config3, {
          tetherOptions: Object.assign(
            {},
            contextMenuConfig.tetherOptions,
            config3 ? config3.tetherOptions || {} : {}
          )
        });
        menu.options.animatedHeight = false;
        drop = this.open(target, menu, scope, config3);
        return drop;
      }
    };
  }
]);
angular_default.module("kantree").directive("dropMenu", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "A",
      //---
      bindToController: {
        menuSpec: "<dropMenu",
        dropConfig: "<?",
        forceOpen: "<?",
        // enable parent component/directive to trigger a drop open
        isDisabled: "<?",
        // manage drop disabled state
        dropWatchers: "<?",
        onDropOpened: "&?",
        onDropClosed: "&?"
      },
      controller: class extends AngularClass {
        static $inject = ["$scope", "$element", "menuDropdown", "dropdown"];
        $onInit() {
          if (this.forceOpen) {
            this.toggleDrop();
          }
        }
        $onChanges(changes) {
          if (changes.forceOpen && !changes.forceOpen.isFirstChange() || changes.menuSpec && !changes.menuSpec.isFirstChange()) {
            this.refreshDrop(!!this.forceOpen);
          }
          if (changes.isDisabled && !changes.isDisabled.isFirstChange() && this.drop) {
            this.drop.options.disabled = this.isDisabled;
          }
        }
        $postLink() {
          if (!!this.dropConfig && this.dropConfig.openOn === "hover") {
            let cancelOpen = false;
            const handleMouseEnter = (event2) => {
              cancelOpen = false;
              this.$element.off("mouseenter", handleMouseEnter);
              this.toggleDrop(event2);
              this.drop.on("hoverout", () => {
                cancelOpen = true;
                this.$element.on("mouseenter", handleMouseEnter);
              });
              this.drop.on("close", () => {
                if (cancelOpen) return;
                this.$element.on("mouseenter", handleMouseEnter);
              });
            };
            if (!isScreensizeXS()) {
              this.$element.on("mouseenter", handleMouseEnter);
            }
            this.$scope.$on("screensize:changed", () => {
              this.$element.off("mouseenter", handleMouseEnter);
              if (!isScreensizeXS()) {
                this.$element.on("mouseenter", handleMouseEnter);
              }
            });
          }
          const onClick = (event2) => {
            event2.preventDefault();
            event2.stopPropagation();
            event2.stopImmediatePropagation();
            this.toggleDrop(event2);
          };
          this.$element.on("click", onClick);
          this.$scope.$on("$destroy", () => {
            this.$element.off("click", onClick);
          });
        }
        refreshDrop(forceOpen = false) {
          if (!!this.drop && !!this.drop.drop && this.drop.isOpened()) {
            if (!this.menuSpec) {
              this.$dropdown.close(this.drop);
            } else {
              this.$menuDropdown.refreshMenu(this.drop, this.menuSpec);
            }
          } else if (forceOpen) {
            if (!!this.menuSpec) {
              this.toggleDrop();
            }
          }
        }
        toggleDrop(event2) {
          if (!this.drop || !this.drop.drop) {
            this.drop = this.$menuDropdown.open(
              this.$element[0],
              this.menuSpec,
              this.$scope,
              Object.assign({}, this.dropConfig, { disabled: this.isDisabled })
            );
            if (this.onDropOpened) {
              this.drop.on("open", () => {
                this.onDropOpened({ $drop: this.drop });
              });
            }
            if (this.onDropClosed) {
              this.drop.on("close", () => {
                this.onDropClosed();
              });
            }
            if (this.dropWatchers) {
              this.drop.on("open", () => {
                this.deregisterDropWatchers = this.dropWatchers(() => {
                  this.$dropdown.updateOnNextFrame(this.drop);
                });
              });
              this.drop.on("close", () => {
                if (this.deregisterDropWatchers) this.deregisterDropWatchers();
                this.deregisterDropWatchers = null;
              });
            }
          } else {
            if (this.drop.isOpened()) {
              this.$dropdown.close(this.drop, event2);
            } else {
              this.$dropdown.updateOnNextFrame(this.drop, true);
            }
          }
          return this.drop;
        }
        $onDestroy() {
          if (this.deregisterDropWatchers) this.deregisterDropWatchers();
        }
      }
    };
  }
]);

// public/app/ui/base/ng-components/pretty-menu/menu-panel-items.js
angular_default.module("kantree").component("menuPanelItems", {
  template: '<i class="fa fa-spinner fa-spin">',
  bindings: {
    items: "<",
    async: "<?"
  },
  require: { menuPanel: "^^?menuPanel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$compile", "$timeout", "prettyMenuRenderQueue"];
    constructor(...args) {
      super(...args);
      this.tpl = `
      <ul class="list-unstyled">
        <li ng-repeat="item in $ctrl.items" class="menu-item {{item.classes || ''}}" ng-if="!item.enabled || item.enabled()"
          ng-class="::{'is-input': item.input || item.selectbox || item.content,
                    'is-hr': item === '--' || item.label === '--',
                    'is-desc': item.desc,
                    'is-subheader': item.subheader}"
          ng-show="$ctrl.matchFilter(item)" ng-mouseenter="item.hoveredIn()" ng-mouseleave="item.hoveredOut()">
          <dynamic-directive directive="menu-item-{{item.type}}"
            item="::item" on-change="$ctrl.handleInputItemChange($item, $inputValue)"
            ng-class="::[{'is-big': item.big, 'is-disabled': item.isDisabled}, 'menu-item-' + item.type]"
            ng-disabled="item.disabled() || (!$ctrl.isConnected() && !item.offline)"></dynamic-directive>
        </li>
      </ul>
      `;
      this.debounceRender = debounce2((tplElement) => {
        if (this.deregisterRenderingListener) {
          this.deregisterRenderingListener();
        }
        this.render(tplElement);
      }, 300);
    }
    $onInit() {
      this.formatItems();
      this.isConnected = isConnected;
    }
    $onChanges(changes) {
      const itemsChanged = changes.items && !changes.items.isFirstChange();
      if (itemsChanged) {
        this.formatItems();
      }
    }
    $postLink() {
      if (this.async) {
        this.asyncCompile();
      } else {
        const tplElement = this.compile();
        this.render(tplElement);
      }
    }
    render(tplElement) {
      this.$element.html(tplElement);
      this.$scope.$applyAsync(() => {
        this.$scope.$emit("prettyMenu.panelItemsRendered");
      });
    }
    compile() {
      if (this.tplScope) {
        this.tplScope.$destroy();
      }
      this.tplScope = this.$scope.$new();
      return this.$compile(this.tpl)(this.tplScope);
    }
    asyncCompile() {
      let tplElement;
      if (this.deregisterRenderingListener) {
        this.deregisterRenderingListener();
      }
      this.deregisterRenderingListener = this.$scope.$on("prettyMenu.itemRendered", (event2) => {
        event2.stopPropagation();
        this.debounceRender(tplElement);
      });
      const { promise, remove: remove3 } = this.$prettyMenuRenderQueue.add(() => {
        tplElement = this.compile();
      });
      this.cancelRendering = () => remove3();
    }
    formatItems() {
      this.items = this.items || [];
      this.items = this.items.map((i3) => {
        let item;
        if (i3 == "--") {
          item = { label: "--" };
        } else {
          item = { ...i3 };
        }
        if (item.type) {
          return item;
        }
        if (item.header) {
          item.type = "header";
        }
        if (item.subheader) {
          item.type = "subheader";
        }
        if (item.label === "--") {
          item.type = "separator";
        }
        if (item.label && item.label !== "--" && !item.checkbox || !item.label && item.buttons) {
          item.type = "default";
        }
        if (item.component) {
          item.type = "component";
        }
        if (item.colorpicker) {
          item.type = "colorpicker";
        }
        if (item.iconpicker) {
          item.type = "iconpicker";
        }
        if (item.datepicker) {
          item.type = "datepicker";
        }
        if (item.filepicker) {
          item.type = "filepicker";
        }
        if (item.input || item.content) {
          item.type = "input";
        }
        if (item.checkbox) {
          item.type = "checkbox";
        }
        if (item.imagepicker) {
          item.type = "imagepicker";
        }
        if (item.selectbox) {
          item.type = "selectbox";
        }
        if (item.desc) {
          item.type = "desc";
        }
        return item;
      });
    }
    get hasFilter() {
      if (!this.menuPanel) {
        return false;
      }
      if (!this.menuPanel.filterable) {
        return false;
      }
      return (this.menuPanel.filter || "").trim().length > 0;
    }
    matchFilter(item) {
      if (!this.hasFilter) return true;
      if (!item.filterable) {
        return true;
      }
      const formattedFilter = (this.menuPanel.filter || "").trim();
      if (item.filterPredicate) {
        return item.filterPredicate(formattedFilter);
      }
      if (!item.label) {
        return false;
      }
      if (item.label === "--") {
        return false;
      }
      if (item.label.toLowerCase().indexOf(formattedFilter.toLowerCase()) > -1) {
        return true;
      }
      if (Array.isArray(item.items)) {
        return item.items.some((i3) => this.matchFilter(i3));
      }
      return false;
    }
    handleInputItemChange(item, inputValue) {
      if (this.menuPanel && this.menuPanel.filterable && item.useAsFilter) {
        this.menuPanel.filter = inputValue;
      }
    }
    $onDestroy() {
      if (this.tplScope) {
        this.tplScope.$destroy();
      }
      if (this.deregisterRenderingListener) {
        this.deregisterRenderingListener();
      }
      if (this.cancelRendering) {
        this.cancelRendering();
      }
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/menu-panel.js
angular_default.module("kantree").component("menuPanel", {
  bindings: {
    panelConfig: "<",
    selectedTabId: "@"
  },
  require: {
    menu: "^^prettyMenu"
  },
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/menu-panel.html",
  controller: [
    "$scope",
    "$timeout",
    "$element",
    function($scope2, $timeout2, $element2) {
      var self2 = this;
      this.isConnected = isConnected;
      var debouncedUpdate = debounce2(function(data2) {
        if (data2.panelInit) {
          self2.updatePanel();
          self2.updateTab();
        } else {
          $scope2.$evalAsync(function() {
            self2.updatePanel();
            self2.updateTab();
          });
        }
      }, 16);
      this.setFilterable = function() {
        this.filterable = this.selectedTab.items.filter((item) => item.filterable).length > 1;
      };
      this.setSortable = function() {
        this.sortable = this.selectedTab.items.filter((item) => item.sortable).length > 1;
        if (this.sortable) this.sortAsc = null;
      };
      this.setDefaultFilterEnabled = function() {
        this.defaultFilterEnabled = this.filterable && !this.selectedTab.items.some((item) => item.input && item.useAsFilter);
      };
      this.updatePanel = function() {
        if (!this.panel) return;
        if (this.titleFactory) {
          this.panel.title = this.titleFactory();
        }
        if (this.tabsFactory) {
          this.menu.cleanPanels(this.panel);
          var processed = this.menu.processTabs(this.tabsFactory(), this.panel);
          this.panel.tabs = processed.tabs;
          if (this.selectedTab) {
            this.selectedTab = this.panel.tabs.find((tab) => this.selectedTab.id === tab.id, this);
            if (this.sortable) {
              const items = index_default_default.groupBy(this.selectedTab.items, (item) => item.hasOwnProperty("options"));
              items.true = items.true.sort((a3, b3) => {
                if (this.sortAsc === true) {
                  return a3.label.toUpperCase() > b3.label.toUpperCase() ? 1 : -1;
                } else if (this.sortAsc === false) {
                  return a3.label.toUpperCase() < b3.label.toUpperCase() ? 1 : -1;
                }
                return 0;
              });
              this.selectedTab.items = [...items.true, ...items.false];
            }
          }
          this.menu.panels = this.menu.panels.concat(processed.panels);
        }
      };
      this.updateTab = function() {
        if (this.tabItemsFactory) {
          this.menu.cleanPanels(null, this.selectedTab);
          var p4 = this.menu.processTabItems(
            this.tabItemsFactory(),
            this.panel,
            this.menu.getHighestSublevel(this.panel.level)
          );
          this.selectedTab.items = p4.items;
          this.selectedTab.submenuLevels = p4.panels.map((panel) => panel.level);
          this.menu.panels = this.menu.panels.concat(p4.panels);
        }
        this.setFilterable();
        this.setDefaultFilterEnabled();
        this.setSortable();
      };
      this.selectTab = function(tab, event2, ignoreConnection) {
        if (event2) event2.stopPropagation();
        var isInit = !this.selectedTab;
        if (!ignoreConnection && !isConnected() && !tab.offline) {
          return;
        }
        if (isInit || tab.id !== this.selectedTab.id) {
          this.selectedTab = Object.assign({}, tab);
          if (this.selectedTab && angular_default.isFunction(this.selectedTab.items)) {
            this.tabItemsFactory = this.selectedTab.items;
          } else {
            this.tabItemsFactory = null;
          }
          this.updateTab();
          if (!isInit) {
            this.menu.updateCurrentPath(this.panel.level, tab.id);
          }
          if (this.selectedTab && this.selectedTab.fetchData && !this.menu.isDataFetched(this.panel.level, this.selectedTab.id)) {
            this.selectedTab.fetchData(function() {
              debouncedUpdate({ isInit: true });
            });
            this.menu.onDataFetched(this.panel.level, this.selectedTab.id);
          }
          this.enableTabWatchers();
          this.menu.update(isInit ? "panelInit" : "panelUpdate");
          if (this.defaultFilterEnabled) {
            $timeout2(function() {
              jquery_default($element2).find(".menu-panel-filter input").trigger("focus");
            }, 200, false);
          }
        }
      };
      this.onFilterChange = function() {
        this.menu.update("panelUpdate");
      };
      this.toggleSort = function() {
        this.sortAsc = this.sortAsc === null ? true : this.sortAsc === true ? false : null;
        this.updatePanel();
      };
      this.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        this.filterFocused = false;
        this.panel = Object.assign({}, this.panelConfig);
        if (angular_default.isFunction(this.panel.tabs)) {
          this.tabsFactory = this.panel.tabs;
        }
        if (angular_default.isFunction(this.panel.title)) {
          this.titleFactory = this.panel.title;
        }
        this.updatePanel();
        this.selectTab(this.panel.tabs.find((tab) => parseInt(this.selectedTabId, 10) === tab.id), null, true);
        if (this.panel.fetchData && !this.panel.dataPrefetched && !this.menu.isDataFetched(this.panel.level, -1)) {
          this.panel.fetchData(function() {
            debouncedUpdate({ isInit: true });
          });
          this.menu.onDataFetched(this.panel.level, -1);
        }
        this.enablePanelWatchers();
      };
      this.enablePanelWatchers = function() {
        if (this.panel.hasOwnProperty("watch")) {
          if (angular_default.isFunction(this.panelWatchersOff)) {
            this.panelWatchersOff();
          }
          this.panelWatchersOff = this.panel.watch(function() {
            debouncedUpdate({ isInit: false });
          }, $scope2);
        }
      };
      this.enableTabWatchers = function() {
        if (this.selectedTab && this.selectedTab.hasOwnProperty("watch")) {
          if (angular_default.isFunction(this.tabWatchersOff)) {
            this.tabWatchersOff();
          }
          this.tabWatchersOff = this.selectedTab.watch(function() {
            debouncedUpdate({ isInit: false });
          }, $scope2);
        }
      };
      this.disableWatchers = function() {
        if (angular_default.isFunction(this.panelWatchersOff)) {
          this.panelWatchersOff();
        }
        if (angular_default.isFunction(this.tabWatchersOff)) {
          this.tabWatchersOff();
        }
      };
      this.$onChanges = function(changes) {
        const configChanged2 = changes.panelConfig && !changes.panelConfig.isFirstChange();
        const selectedTabChanged = changes.selectedTabId && !changes.selectedTabId.isFirstChange();
        if (configChanged2) {
          this.panel = Object.assign({}, this.panelConfig);
          this.updatePanel();
          if (this.panel) {
            this.selectTab(this.panel.tabs.find((tab) => parseInt(this.selectedTabId, 10) === tab.id));
          }
        } else if (selectedTabChanged) {
          this.selectTab(this.panel.tabs.find((tab) => parseInt(this.selectedTabId, 10) === tab.id));
        }
      };
      this.$onDestroy = function() {
        this.disableWatchers();
      };
    }
  ]
});

// public/app/ui/base/ng-components/pretty-menu/menu.js
angular_default.module("kantree").component("prettyMenu", {
  bindings: {
    config: "<",
    options: "<?",
    defaultPath: "<?",
    actionParams: "<?",
    onUpdate: "&",
    onClose: "&"
  },
  controller: [
    "$element",
    "$timeout",
    "$compile",
    "$scope",
    function($element2, $timeout2, $compile, $scope2) {
      var self2 = this;
      var firstRender;
      var defaultOpts = {
        transition: 200
      };
      var incrementLevel = function(level) {
        return level.split(".").map(function(l3, idx, levels) {
          if (idx === levels.length - 1) {
            return parseInt(l3, 10) + 1;
          }
          return l3;
        }).join(".");
      };
      var preProcessItem = function(item) {
        var preProcessedItem = Object.assign({}, item);
        if (item.colorpicker) {
          if (item.hasColorPalette && !item.submenu) {
            preProcessedItem.submenuIcon = "bi-palette-fill";
            preProcessedItem.submenu = function() {
              return function() {
                return [{
                  component: "menu-item-color-palette",
                  onUpdate: function(data2) {
                    return item.action(null, data2.color);
                  },
                  params: {
                    defaultColor: item.getValue()
                  }
                }];
              };
            };
            preProcessedItem.options = Object.assign({
              title: _4("Choose a color")
            }, item.options || {});
          } else if (item.submenu && !item.submenuIcon) {
            preProcessedItem.submenuIcon = "caret-right";
          }
        }
        if (item.iconpicker) {
          if (item.extended) {
            preProcessedItem.submenu = function() {
              return function() {
                return [Object.assign({}, item, {
                  icons: null,
                  extended: false,
                  completeSet: true,
                  options: {}
                })];
              };
            };
            preProcessedItem.options = Object.assign({
              title: _4("Choose an icon")
            }, item.options || {});
          }
        }
        return preProcessedItem;
      };
      var processItem = function(item, previousSubmenuLevel) {
        var newSubmenuLevel = previousSubmenuLevel;
        var panels = [];
        var processedItem = Object.assign({}, item);
        if (typeof item.offline === "undefined") {
          processedItem.offline = true;
        }
        if (angular_default.isFunction(item.action)) {
          var actionFn = item.action;
          var executeAction = function(event2) {
            var aArgs = Array.from(arguments).slice(1);
            if (!item.enableActionOnselected && angular_default.isFunction(item.selected) && item.selected.apply(self2, aArgs)) {
              return;
            }
            if (angular_default.isFunction(item.disabled) && item.disabled.apply(self2, aArgs)) {
              return;
            }
            if (!isConnected() && !processedItem.offline) {
              return;
            }
            var actionArgs = [event2].concat(aArgs, [item, self2.actionParams]);
            var returnValue;
            returnValue = actionFn.apply(self2, actionArgs);
            if (item.backAfterAction) {
              self2.back();
            } else if (item.resetAfterAction) {
              if (self2.resetLevel) {
                self2.updateCurrentPath(self2.resetLevel);
              } else {
                self2.currentPath = [[1, 0]];
              }
              self2.switchPanel(self2.findPanelByLevel(self2.getLevelFromCurrentPath()), "left");
            } else if (!item.noCloseAfterAction) {
              self2.close();
            }
            event2.stopPropagation();
            return returnValue;
          };
          processedItem.action = executeAction;
        }
        if (item.input) {
          if (angular_default.isFunction(item.submit)) {
            var submitFn = item.submit;
            var executeSubmit = function(value2) {
              var returnValue = submitFn.apply(self2, [value2, item, self2.actionParams]);
              if (item.closeAfterSubmit) {
                self2.close();
              }
              return returnValue;
            };
            processedItem.submit = executeSubmit;
          }
        }
        if (item.checkbox) {
          if (angular_default.isFunction(item.toggle)) {
            var toggleFn = item.toggle;
            var executeToggle = function(value2) {
              if (item.isDisabled) {
                return;
              }
              if (value2 === void 0) {
                if (angular_default.isFunction(item.value)) {
                  value2 = !item.value();
                } else {
                  value2 = !item.value;
                }
              }
              var returnValue = toggleFn.apply(self2, [value2, item, self2.actionParams]);
              if (item.closeAfterToggle) {
                self2.close();
              }
              event.stopPropagation();
              return returnValue;
            };
            processedItem.toggle = executeToggle;
          }
        }
        if (item.datepicker) {
          if (angular_default.isFunction(item.select)) {
            var selectFn = item.select;
            var executeSelect = function(value2) {
              var returnValue = selectFn.apply(self2, [value2]);
              if (item.closeAfterSelect) {
                $timeout2(() => self2.close());
              } else if (item.backAfterSelect) {
                $timeout2(() => self2.back());
              }
              event.stopPropagation();
              return returnValue;
            };
            processedItem.select = executeSelect;
          }
        }
        if (item.component) {
          if (!item.params) {
            processedItem.params = self2.actionParams;
          }
          processedItem.onClose = function(forceClose) {
            if (forceClose) {
              self2.close();
            } else if (item.backAfterAction) {
              self2.back();
            } else if (item.resetAfterAction) {
              if (self2.resetLevel) {
                self2.updateCurrentPath(self2.resetLevel);
              } else {
                self2.currentPath = [[1, 0]];
              }
              self2.switchPanel(self2.findPanelByLevel(self2.getLevelFromCurrentPath()), "left");
            } else if (!item.noCloseAfterAction) {
              self2.close();
            }
          };
          var updateFn = item.onUpdate;
          var executeOnUpdate = function() {
            self2.update();
            return updateFn && updateFn.apply(self2, Array.from(arguments));
          };
          processedItem.onUpdate = executeOnUpdate;
        }
        if (item.submenu) {
          newSubmenuLevel = incrementLevel(newSubmenuLevel);
          var subPanelOptions = {
            level: newSubmenuLevel,
            title: item.title || item.label
          };
          if (item.options) {
            subPanelOptions = Object.assign({}, subPanelOptions, item.options);
          }
          if (subPanelOptions.resetLevel === "parent") {
            subPanelOptions.resetLevel = subPanelOptions.level.split(".").slice(0, -1).join(".");
          }
          panels.push.apply(panels, self2.convertConfigToPanels(item.submenu, subPanelOptions));
          var openSubmenu = function(event2) {
            self2.forward(newSubmenuLevel);
            event2.stopPropagation();
          };
          if (!item.action && !item.input && (!item.buttons || !item.buttons.find(function(btn) {
            return angular_default.isString(btn.action) && btn.action.indexOf("Submenu") !== -1;
          }))) {
            processedItem.action = openSubmenu;
            if (!item.disableSubmenuStyle)
              processedItem.classes = "is-submenu";
          }
          if (item.submenuKey) {
            var key2 = item.submenuKey.charAt(0).toUpperCase() + item.submenuKey.slice(1);
            processedItem["open" + key2 + "Submenu"] = openSubmenu;
          } else {
            processedItem.openSubmenu = openSubmenu;
          }
        }
        if (item.type === "expandable-items") {
          const processed = item.items.reduce(function(accuObj, i3) {
            var p4 = processItem(preProcessItem(i3), accuObj.lastSubmenuLevel);
            return {
              items: accuObj.items.concat([p4[0]]),
              panels: accuObj.panels.concat(p4[1]),
              lastSubmenuLevel: p4[2]
            };
          }, {
            items: [],
            panels: [],
            lastSubmenuLevel: newSubmenuLevel
          });
          processedItem.items = processed.items;
          panels = panels.concat(processed.panels);
          newSubmenuLevel = processed.lastSubmenuLevel;
        }
        if (item.buttons) {
          processedItem.buttons = item.buttons.map(function(button) {
            if (item.displayButtonOnHover)
              processedItem.classes = "display-button-on-hover";
            var processedButton = Object.assign({}, button);
            if (angular_default.isFunction(button.action)) {
              var actionFn2 = button.action;
              var executeAction2 = function(event2) {
                var aArgs = Array.from(arguments).slice(1);
                var actionArgs = [event2].concat(aArgs, [item, self2.actionParams]);
                var returnValue;
                returnValue = actionFn2.apply(self2, actionArgs);
                if (button.backAfterAction) {
                  self2.back();
                } else if (!button.noCloseAfterAction) {
                  self2.close();
                }
                event2.stopPropagation();
                return returnValue;
              };
              processedButton.action = executeAction2;
            } else if (angular_default.isFunction(processedItem[button.action])) {
              processedButton.action = function(event2) {
                processedItem[button.action].apply(self2, [event2, processedItem, self2.actionParams]);
                event2.stopPropagation();
              };
            }
            return processedButton;
          }, this);
        }
        if (angular_default.isFunction(item.enabled)) {
          var enabledFn = item.enabled;
          var executeEnabled = function() {
            return enabledFn.apply(this, [item, self2.actionParams]);
          };
          processedItem.enabled = executeEnabled;
        }
        if (item.bgColor) {
          processedItem.textColor = tinycolor.mostReadable(item.bgColor, ["#262626", "#fff"]);
        }
        return [processedItem, panels, newSubmenuLevel];
      };
      this.processTabItems = function(items, panel, previousSubmenuLevel) {
        if (angular_default.isFunction(items)) {
          return {
            items,
            panels: [],
            lastSubmenuLevel: previousSubmenuLevel || panel.level + ".0"
          };
        } else {
          var p4 = items.reduce(function(accuObj, item) {
            var p5 = processItem(preProcessItem(item), accuObj.lastSubmenuLevel);
            return {
              items: accuObj.items.concat([p5[0]]),
              panels: accuObj.panels.concat(p5[1]),
              lastSubmenuLevel: p5[2]
            };
          }, {
            items: [],
            panels: [],
            lastSubmenuLevel: previousSubmenuLevel || panel.level + ".0"
          });
          return p4;
        }
      };
      this.processTabs = function(tabs, panel) {
        var i3 = 0;
        var processed = tabs.reduce(function(accuObj, tab) {
          var processedTab = Object.assign({}, tab);
          var p4 = self2.processTabItems(processedTab.items, panel, accuObj.lastSubmenuLevel);
          processedTab.id = i3++;
          processedTab.submenuLevels = p4.panels.map(function(panel2) {
            return panel2.level;
          });
          processedTab.items = p4.items;
          if (typeof tab.offline === "undefined") {
            tab.offline = true;
          }
          return {
            tabs: accuObj.tabs.concat([processedTab]),
            panels: accuObj.panels.concat(p4.panels),
            lastSubmenuLevel: p4.lastSubmenuLevel
          };
        }, {
          tabs: [],
          panels: [],
          lastSubmenuLevel: panel.level + ".0"
        });
        return processed;
      };
      this.convertConfigToPanels = function(config3, panelOpts) {
        var level = panelOpts.level || "1";
        var panel = {
          level,
          _classId: "menu-panel-" + level.split(".").join("-")
        };
        if (panelOpts.title) {
          panel.title = panelOpts.title;
        }
        if (panelOpts.icon) {
          panel.icon = panelOpts.icon;
        }
        if (panelOpts.fetchData) {
          panel.fetchData = panelOpts.fetchData;
        }
        if (panelOpts.dataPrefetched) {
          panel.dataPrefetched = panelOpts.dataPrefetched;
        }
        if (panelOpts.classes) {
          panel.classes = panelOpts.classes;
        }
        if (panelOpts.resetLevel) {
          panel.resetLevel = panelOpts.resetLevel;
        }
        if (panelOpts.help) {
          panel.help = panelOpts.help;
        }
        if (panelOpts.hasOwnProperty("watch")) {
          panel.watch = panelOpts.watch;
        }
        if (angular_default.isFunction(panelOpts.settings)) {
          var settingsFn = panelOpts.settings;
          var executeSettings = function(event2) {
            var returnValue;
            returnValue = settingsFn.apply(this);
            if (!panelOpts.noCloseAfterSettings) {
              self2.close();
            }
            event2.stopPropagation();
            return returnValue;
          };
          panel.settings = executeSettings;
        }
        if (panelOpts.sort) {
          panel.sort = panelOpts.sort;
        }
        var panels = [panel];
        var processed;
        if (angular_default.isFunction(config3)) {
          var factoredConfig = config3.apply(this);
          if (angular_default.isFunction(factoredConfig)) {
            panel.tabs = panelOpts.withTabs ? factoredConfig : function() {
              return [{ items: factoredConfig.apply(self2) }];
            };
          } else {
            if (!panelOpts.withTabs) {
              factoredConfig = [{
                items: factoredConfig
              }];
            }
            processed = this.processTabs(factoredConfig, panel);
            panel.tabs = processed.tabs;
            panels = panels.concat(processed.panels);
          }
        } else if (angular_default.isArray(config3)) {
          if (!panelOpts.withTabs) {
            config3 = [{
              items: config3
            }];
          }
          processed = this.processTabs(config3, panel);
          panel.tabs = processed.tabs;
          panels = panels.concat(processed.panels);
        }
        return panels;
      };
      this.close = function() {
        if (angular_default.isFunction(this.onClose)) {
          this.onClose({});
        }
      };
      this.back = function() {
        this.updateCurrentPath();
        var nextLevel = this.currentPath.map(function(level) {
          return level[0];
        }).join(".");
        var nextPanel = this.panels.find(function(panel) {
          return panel.level === nextLevel;
        });
        this.switchPanel(nextPanel, "left");
      };
      this.forward = function(level) {
        this.updateCurrentPath(level);
        var nextPanel = this.panels.find(function(panel) {
          return panel.level === level;
        });
        this.switchPanel(nextPanel, "right");
      };
      this.renderPanel = function(panel) {
        var panelIndex = this.panels.findIndex(function(p4) {
          return p4.level === panel.level;
        });
        if (panelIndex === -1) {
          return false;
        }
        if (this.activePanelScope) {
          this.oldPanelScope = this.activePanelScope;
        }
        this.activePanelScope = $scope2.$new();
        return $compile(`<menu-panel class="menu-panel"
        ng-class="[$ctrl.panels[${panelIndex}]._classId, $ctrl.panels[${panelIndex}].classes]"
        panel-config="$ctrl.panels[${panelIndex}]"
        selected-tab-id="{{ $ctrl.currentPath[$ctrl.currentPath.length - 1][1] }}"
        ></menu-panel>`)(this.activePanelScope);
      };
      this.switchPanel = function(newPanel, direction) {
        const $newPanelElement = jquery_default(this.renderPanel(newPanel));
        if (newPanel.resetLevel) {
          this.resetLevel = newPanel.resetLevel;
        } else if (this.resetLevel && !newPanel.level.includes(this.resetLevel)) {
          this.resetLevel = null;
        }
        if (firstRender) {
          firstRender = false;
          $element2.html($newPanelElement[0]);
          this.applyTransition($newPanelElement);
          this.currentPanel = newPanel;
          if (this.oldPanelScope) {
            this.oldPanelScope.$destroy();
          }
          return;
        }
        var $oldPanelElement = jquery_default($element2).find("." + this.currentPanel._classId);
        if (direction === "left") {
          $newPanelElement.css("margin-left", "-100%");
        }
        this.applyTransition($newPanelElement);
        $element2[direction === "left" ? "prepend" : "append"]($newPanelElement);
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            if (direction === "left") {
              $newPanelElement.css("margin-left", "0");
            } else {
              $oldPanelElement.css("margin-left", "-100%");
            }
            $timeout2(() => {
              if (this.oldPanelScope) {
                this.oldPanelScope.$destroy();
              }
              $oldPanelElement.remove();
              $oldPanelElement = null;
              this.update("panelSwitchEnd");
            }, this.options.transition);
          });
        });
        this.currentPanel = newPanel;
      };
      this.setHeight = function($el, height) {
        if (typeof height !== "undefined") {
          $element2.css("max-height", height);
        } else {
          $element2.css("max-height", $el.outerHeight());
        }
      };
      this.applyTransition = function($el) {
        var property2 = "all";
        if (!this.options.animatedHeight) {
          property2 = "margin-left";
        }
        $el.css("transition", property2 + " " + this.options.transition + "ms ease-in-out");
      };
      this.updateCurrentPath = function(level, tab) {
        if (level) {
          this.currentPath = level.split(".").map(function(l3, idx, levelArray) {
            var tmpLevel = parseInt(l3, 10);
            if (idx >= this.currentPath.length) {
              if (idx < levelArray.length - 1) {
                return [tmpLevel, 0];
              } else {
                var lastTabValue = typeof tab !== "undefined" && tab !== null ? tab : 0;
                return [tmpLevel, lastTabValue];
              }
            }
            if (tmpLevel === this.currentPath[idx][0]) {
              if (typeof tab !== "undefined" && tab !== null && idx === levelArray.length - 1) {
                return [tmpLevel, tab];
              } else {
                return this.currentPath[idx];
              }
            }
          }, this);
        } else {
          this.currentPath = this.currentPath.reduce(function(newPath, level2, idx, path) {
            if (idx < path.length - 1) {
              return newPath.concat([level2]);
            } else return newPath;
          }, []);
        }
      };
      this.getLevelFromCurrentPath = function() {
        return this.currentPath.reduce(function(level, p4) {
          return level.length ? level + "." + p4[0] : p4[0].toString();
        }, "");
      };
      this.findPanelByLevel = function(level) {
        return this.panels.find(function(panel) {
          return panel.level === level;
        });
      };
      this.update = function(event2) {
        if (angular_default.isFunction(self2.onUpdate)) {
          self2.onUpdate({
            $menuEvent: event2,
            $currentPath: self2.currentPath
          });
        }
      };
      this.onDataFetched = function(level, tabId) {
        if (typeof this.fetchedTabs[level] === "undefined") {
          this.fetchedTabs[level] = [tabId];
        } else {
          this.fetchedTabs[level].push(tabId);
        }
      };
      this.isDataFetched = function(level, tabId) {
        return typeof this.fetchedTabs[level] !== "undefined" && this.fetchedTabs[level].indexOf(tabId) !== -1;
      };
      this.cleanPanels = function(panel, tab) {
        var cleanedPanels = this.panels;
        if (tab) {
          cleanedPanels = cleanedPanels.filter(function(p4) {
            return !tab.submenuLevels.find(function(l3) {
              return p4.level.indexOf(l3) !== -1;
            });
          });
        }
        if (panel) {
          cleanedPanels = cleanedPanels.filter(function(p4) {
            return p4.level.indexOf(panel.level + ".") === -1;
          });
        }
        if (cleanedPanels.length !== this.panels.length) {
          this.panels = cleanedPanels;
        }
      };
      this.getHighestSublevel = function(level) {
        var levelArray = level.split(".");
        var highestSublevel = 0;
        this.panels.forEach(function(panel) {
          var l3 = panel.level;
          var lArray = l3.split(".");
          if (lArray.length === levelArray.length + 1) {
            var sublevel = lArray[lArray.length - 1];
            if (highestSublevel < sublevel) {
              highestSublevel = sublevel;
            }
          }
        });
        return level + "." + highestSublevel;
      };
      this.$onInit = function() {
        this.applyTransition($element2);
      };
      this.$onChanges = function(changes) {
        if (changes.defaultPath && !changes.defaultPath.isFirstChange()) {
          if (!equals(this.defaultPath, this.currentPath)) {
            if (this.defaultPath && this.defaultPath.length === this.currentPath.length && equals(this.defaultPath.slice(0, -1), this.currentPath.slice(0, -1)) && this.defaultPath[this.defaultPath.length - 1][0] === this.currentPath[this.currentPath.length - 1][0]) {
              this.currentPath = this.defaultPath || [[1, 0]];
            } else {
              var direction = this.defaultPath && this.currentPath && this.defaultPath.length > this.currentPath.length ? "right" : "left";
              this.currentPath = this.defaultPath || [[1, 0]];
              this.switchPanel(this.findPanelByLevel(this.getLevelFromCurrentPath()), direction);
            }
          }
        }
        if (changes.config || changes.options) {
          firstRender = true;
          this.fetchedTabs = {};
          this.options = Object.assign({}, defaultOpts, this.options || {});
          this.panels = this.convertConfigToPanels(this.config, this.options);
          this.currentPath = this.defaultPath || [[1, 0]];
          this.switchPanel(this.findPanelByLevel(this.getLevelFromCurrentPath()));
        }
      };
      this.$onDestroy = function() {
        if (this.activePanelScope) {
          this.activePanelScope.$destroy();
        }
        if (angular_default.isFunction(this.onClose)) {
          this.onClose({});
        }
      };
    }
  ]
});

// public/app/ui/base/ng-components/pretty-menu/render-queue.js
angular_default.module("kantree").service("prettyMenuRenderQueue", class extends AngularClass {
  static $inject = ["$q"];
  constructor(...args) {
    super(...args);
    this.queue = [];
    this.queueInProgress = false;
  }
  add(fn) {
    const requestRenderingDefer = this.$q.defer();
    const renderingDefer = this.$q.defer();
    const requestRenderingFn = (cancelRendering, renderingPromise) => {
      requestRenderingDefer.resolve({ cancelRendering, renderingPromise });
      return fn;
    };
    this.queue.push(requestRenderingFn);
    if (!this.queueInProgress) {
      this.runQueue();
    }
    let remove3 = () => {
      requestRenderingDefer.reject();
      this.remove(requestRenderingFn);
    };
    requestRenderingDefer.promise.then((data2) => {
      remove3 = () => data2.cancelRendering();
      data2.renderingPromise.then(() => renderingDefer.resolve(), () => renderingDefer.reject()).finally(() => {
        remove3 = () => {
        };
      });
    });
    return {
      promise: renderingDefer.promise,
      remove: () => remove3()
    };
  }
  remove(fn) {
    const fnIndex = this.queue.findIndex((f3) => f3 === fn);
    if (fnIndex >= 0) {
      this.queue.splice(fnIndex, 1);
    }
  }
  runQueue() {
    if (this.queue.length > 0) {
      this.queueInProgress = true;
      const renderingDefer = this.$q.defer();
      const requestRenderingFn = this.queue.shift();
      const cancelId = requestAnimationFrame(() => {
        nextRenderingFn();
        renderingDefer.resolve();
        this.runQueue();
      });
      const cancelRendering = () => {
        cancelAnimationFrame(cancelId);
        renderingDefer.reject();
      };
      const nextRenderingFn = requestRenderingFn(cancelRendering, renderingDefer.promise);
    } else {
      this.queueInProgress = false;
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/checkbox.js
angular_default.module("kantree").component("menuItemCheckbox", {
  template: `
    <div class="menu-item-checkbox-container" ng-class="{'with-buttons': $ctrl.item.buttons && $ctrl.item.buttons.length}">
      <kt-form-check ng-model="$ctrl.value" ng-change="$ctrl.item.toggle($ctrl.value)"
        ng-disabled="$ctrl.item.disabled && $ctrl.item.disabled()" switch="$ctrl.switch">
        <span ng-if="!$ctrl.item.action">
          <i class="menu-icon"
            ng-class="::($ctrl.item.icon|iconClass)"
            ng-style="::{'color': $ctrl.item.color && $ctrl.item.color !== 'transparent' ? $ctrl.item.color : null}"
            ng-if="::!!$ctrl.item.icon"
          ></i>
          {{$ctrl.item.label}}
          <small class="menu-item-default-small" ng-if="$ctrl.item.small">{{$ctrl.item.small}}</small>
        </span>
      </kt-form-check>
      <button ng-if="$ctrl.item.action" ng-click="$ctrl.item.action($event)">
        <span>{{$ctrl.item.label}}</span>
        <small class="menu-item-default-small" ng-if="$ctrl.item.small">{{$ctrl.item.small}}</small>
      </button>
      <button ng-if="$ctrl.item.buttons && $ctrl.item.buttons.length"
        class="btn btn-sm btn-text menu-item-additional-button"
        ng-repeat="button in $ctrl.item.buttons"
        ng-class="button.classes || {'btn-icon': !button.label, 'btn-default btn-text': !button.classes}"
        ng-style="{'color': button.color || null}"
        ng-click="button.action($event)"
        ng-show="!button.enabled || button.enabled()"
        ng-disabled="button.disabled()"
        uib-tooltip="{{::button.tooltip}}"
        tooltip-enable="::!!button.tooltip">
          <i ng-class="button.icon|iconClass" ng-if="button.icon"></i>
          <span ng-if="button.label">{{button.label}}</span>
      </button>
      <i ng-if="$ctrl.item.help" class="fa fa-question-circle menu-item-help" uib-tooltip="{{$ctrl.item.help}}"
        tooltip-placement="auto top"></i>
    </div>
  `,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onChanges() {
      if (angular_default.isFunction(this.item?.value)) {
        this.value = this.item.value();
      } else {
        this.value = !!this.item?.value;
      }
    }
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
      if (this.item.action) {
        this.$element.addClass("is-clickable");
      }
    }
    get switch() {
      return this.item.switch !== false;
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/color-palette.js
angular_default.module("kantree").component("menuItemColorPalette", {
  bindings: {
    params: "<?",
    onClose: "&",
    onUpdate: "&"
  },
  template: `<solidjs-component
    component="$ctrl.ColorPicker"
    default-color="$ctrl.defaultColor"
    default-color-palette="$ctrl.defaultColorPalette"
    on-change="$ctrl.debounceUpdate" />`,
  controller: [
    "$scope",
    function($scope2) {
      const debounceUpdate = debounce2((color) => {
        this.onUpdate && this.onUpdate({ $data: { color } });
      }, 200);
      this.$onInit = () => {
        this.ColorPicker = ColorPicker;
        this.debounceUpdate = debounceUpdate;
        this.defaultColorPalette = defaultColorPalette;
        this.defaultColor = this.params.defaultColor || null;
      };
      this.$postLink = () => {
        $scope2.$emit("prettyMenu.itemRendered");
      };
    }
  ]
});

// public/app/ui/base/ng-components/pretty-menu/items/colorpicker.js
angular_default.module("kantree").component("menuItemColorpicker", {
  bindings: {
    item: "<"
  },
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/items/colorpicker.html",
  controller: [
    "$scope",
    function($scope2) {
      var basicColors = [null, ...prettyMenuColorPickerPalette()];
      this.isInDisplayedColors = function(color) {
        return this.displayedColors.findIndex(function(c3) {
          if (!c3) {
            return !color;
          } else if (!color) {
            return false;
          }
          return c3.toUpperCase() === color.toUpperCase();
        }) !== -1;
      };
      this.$onInit = function() {
        this.refresh();
        if (this.item.watcher) {
          this.watcherOff = this.item.watcher(() => {
            this.refresh();
          }, $scope2);
        }
      };
      this.refresh = function() {
        this.displayedColors = this.item.colors || basicColors;
        this.selectedColor = this.item.getValue();
        if (this.selectedColor && !this.isInDisplayedColors(this.selectedColor)) {
          this.displayedColors = this.displayedColors.map(function(color, idx, colors) {
            if (idx === colors.length - 1) {
              return this.selectedColor;
            }
            return color;
          }, this);
        }
      };
      this.$postLink = function() {
        $scope2.$emit("prettyMenu.itemRendered");
      };
      this.isSelected = function(color) {
        if (!color) {
          return !this.selectedColor;
        } else if (!this.selectedColor) {
          return false;
        }
        return color.toUpperCase() === this.selectedColor.toUpperCase();
      };
      this.$onDestroy = function() {
        if (this.watcherOff) {
          this.watcherOff();
        }
      };
    }
  ]
});

// public/app/ui/base/ng-components/pretty-menu/items/component.js
angular_default.module("kantree").component("menuItemComponent", {
  template: `
    <dynamic-directive
      directive="{{$ctrl.item.component}}"
      params="$ctrl.item.params"
      on-close="$ctrl.item.onClose($forceClose)"
      on-update="$ctrl.onComponentUpdate($data)"
      open-submenu="$ctrl.item.openSubmenu($event)"
    ></dynamic-directive>
  `,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.renderedOnce = false;
    }
    onComponentUpdate(data2) {
      if (!this.renderedOnce) {
        this.$scope.$emit("prettyMenu.itemRendered");
        this.renderedOnce = true;
      }
      if (this.item && this.item.onUpdate) {
        return this.item.onUpdate(data2);
      }
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/datepicker.js
angular_default.module("kantree").component("menuItemDatepicker", {
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$compile"];
    get hasDate() {
      return this.date === null;
    }
    set hasDate(date) {
      this.date = null;
    }
    $onInit() {
      const html5 = `
        <div uib-datepicker ng-model="$ctrl.date" datepicker-options="$ctrl.opts"></div>
        <div class="menu-item-checkbox" ng-class="{'no-date': $ctrl.date === null}" ng-hide="$ctrl.item.hideNoDate">
          <kt-form-check ng-model="$ctrl.hasDate">{{::$ctrl.noDateBtnLabel}}</kt-form-check>
        </div>`;
      this.date = this.item.defaultValue || null;
      this.noDateBtnLabel = _4("No date");
      this.opts = {
        showWeeks: false
      };
      this.dom = this.$compile(html5)(this.$scope);
      this.$scope.$watch(() => this.date, (newVal, oldVal) => {
        if (newVal === oldVal) {
          return;
        }
        this.item.select(newVal);
      });
      this.stopEventPropagation = (event2) => {
        event2.stopPropagation();
      };
    }
    $postLink() {
      this.$element.html(this.dom);
      this.$element[0].addEventListener("click", this.stopEventPropagation);
      this.$scope.$emit("prettyMenu.itemRendered");
    }
    $onDestroy() {
      this.$element[0].removeEventListener("click", this.stopEventPropagation);
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/default.js
angular_default.module("kantree").component("menuItemDefault", {
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/items/default.html",
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope"];
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
      this.$element.toggleClass("is-clickable", !!this.item.action);
      if (this.item.selected) {
        this.$scope.$watch(() => this.item.selected(), (newVal, oldVal) => {
          this.$element.toggleClass("is-selected", !!this.item.selected());
        });
      }
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/desc.js
angular_default.module("kantree").component("menuItemDesc", {
  template: `{{$ctrl.item.desc}}`,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/expandableItems.js
angular_default.module("kantree").component("menuItemExpandableItems", {
  template: `
    <div class="inner" ng-class="{'collapsed': $ctrl.collapsed}">
      <div class="items-toggle" ng-click="$ctrl.toggled = !$ctrl.toggled" ng-class="{'collapsed': $ctrl.collapsed}">
        <i class="fa fa-chevron-down"></i>
        <span>{{$ctrl.item.label}}</span>
        <i class="fa fa-check menu-item-selected" ng-if=$ctrl.item.selected()></i>
      </div>
      <div class="items-container" ng-hide="$ctrl.collapsed">
        <menu-panel-items items="$ctrl.item.items" async="true"></menu-panel-items>
      </div>
    </div>
  `,
  bindings: {
    item: "<"
  },
  require: { menuPanelItems: "^^?menuPanelItems" },
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope"];
    $onInit() {
      this.toggled = false;
      if (this.item.selected) {
        this.$scope.$watch(() => this.item.selected(), (newVal, oldVal) => {
          this.$element.toggleClass("is-selected", !!this.item.selected());
        });
      }
    }
    $postLink() {
      this.$scope.$on("prettyMenu.panelItemsRendered", (event2) => {
        event2.stopPropagation();
        this.$scope.$emit("prettyMenu.itemRendered");
      });
    }
    get collapsed() {
      return !this.toggled && (!this.menuPanelItems || !this.menuPanelItems.hasFilter || this.item.items.every((item) => !this.menuPanelItems.matchFilter(item)));
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/filepicker.js
angular_default.module("kantree").component("menuItemFilepicker", {
  bindings: {
    item: "<"
  },
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/items/filepicker.html",
  controller: [
    "$scope",
    "$element",
    function($scope2, $element2) {
      this.pickFile = function(event2, files) {
        if (!files || files.length === 0) return;
        if (this.item.action) this.item.action(event2, files[0]);
        this.pickedFile = files[0];
      };
      this.unpickFile = function(event2) {
        if (this.item.action) this.item.action(event2, null);
        this.pickedFile = null;
      };
      this.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        this.pickedFile = angular_default.isFunction(this.item.initialFile) ? this.item.initialFile() : this.item.initialFile || null;
        this.getProgress = this.item.getProgress || angular_default.noop;
        this.getIsLoading = this.item.getIsLoading || this.getProgress;
      };
      this.$postLink = function() {
        $scope2.$emit("prettyMenu.itemRendered");
        $element2.find(".menu-filepicker-input > label").on("click", function(e3) {
          e3.preventDefault();
          e3.stopPropagation();
          $element2.find(".menu-filepicker-input > input").trigger("click");
        });
      };
    }
  ]
});

// public/app/ui/base/ng-components/pretty-menu/items/header.js
angular_default.module("kantree").component("menuItemHeader", {
  template: `
    <span><i ng-class="::$ctrl.item.icon|iconClass" ng-if="::$ctrl.item.icon"></i> {{::$ctrl.item.header}}</span>
    <small ng-show="::$ctrl.item.small">{{::$ctrl.item.small}}</small>
  `,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/iconpicker.js
init_icons();
angular_default.module("kantree").component("menuItemIconpicker", {
  bindings: {
    item: "<"
  },
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/items/iconpicker.html",
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.displayedIcons = this.item.icons || (this.item.completeSet ? availableIcons : availableIcons.slice(0, this.item.maxIcons || 5));
      if (this.item.emptyIcon) {
        this.displayedIcons = [null].concat(this.item.completeSet ? this.displayedIcons : this.displayedIcons.slice(0, -1));
      }
      this.selectedIcon = this.item.getValue();
      if (this.selectedIcon && !this.displayedIcons.includes(this.selectedIcon)) {
        this.displayedIcons = this.displayedIcons.slice(0, -1).concat([this.selectedIcon]);
      }
      this.textColor = this.item.color ? tinycolor.mostReadable(this.item.color, ["#ffffff", "#333333"]).toString() : null;
    }
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
    select(event2, icon) {
      this.item.action(event2, icon);
      this.selectedIcon = icon;
    }
    isSelected(icon) {
      return icon === this.selectedIcon;
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/imagepicker.js
angular_default.module("kantree").component("menuItemImagepicker", {
  template: `
    <div ng-repeat="image in $ctrl.item.images track by image.url"
      class="menu-image-container" ng-click="$ctrl.item.action($event, image)"
      ng-style="{width: (100 / ($ctrl.item.numberByRow || 1)) + '%'}">
      <div class="menu-image">
        <img ng-src="{{image.url}}" ng-attr-alt="{{image.caption}}" ng-attr-title="{{image.caption}}">
      </div>
      <span class="menu-image-caption" ng-if="image.caption">{{image.caption}}</span>
    </div>
  `,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/input.js
angular_default.module("kantree").component("menuItemInput", {
  bindings: {
    item: "<",
    onChange: "&"
  },
  require: { menuPanel: "^^?menuPanel" },
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/items/input.html",
  controller: [
    "$scope",
    "$element",
    "$timeout",
    function($scope2, $element2, $timeout2) {
      var self2 = this;
      this.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        this.value = this.item.defaultValue || null;
        this.placeholder = this.createPlaceholder();
        this.onChange({
          $item: this.item,
          $inputValue: this.value
        });
      };
      this.disabled = function() {
        if (!isConnected() && !this.item.offline) return true;
        return this.item.disabled && this.item.disabled();
      };
      this.createPlaceholder = function() {
        var placeholder = this.item.placeholder;
        if (this.menuPanel && this.menuPanel.filterable) {
          placeholder = _4("Filter or {givenPlaceholder}", {
            givenPlaceholder: placeholder || _4("Add")
          });
        }
        return placeholder;
      };
      this.submitable = function() {
        if (!this.item.submit) return false;
        if (this.disabled()) return false;
        var value2 = this.value ? this.value.length || this.item.inputType === "number" ? this.value : null : null;
        return (this.item.allowUnchangedDefaultValue || this.item.defaultValue !== value2) && (this.item.allowEmptyValue || value2 && value2.length);
      };
      this.onSubmit = function(event2) {
        if (!this.submitable()) {
          event2.stopPropagation();
          return;
        }
        this.item.submit(this.value);
        if (this.item.resetOnSubmit) {
          this.value = null;
        }
        event2.stopPropagation();
      };
      this.handleInputChange = function() {
        this.onChange({
          $item: this.item,
          $inputValue: this.value
        });
        if (this.item.onChange) {
          this.item.onChange(this.value);
        }
      };
      this.reset = function() {
        this.value = null;
      };
      this.resetable = function() {
        return this.item.reset && this.value && this.value.length && !this.disabled();
      };
      this.onResetBtn = function(event2) {
        if (!this.resetable()) {
          event2.stopPropagation();
          return;
        }
        this.onResettingBtn = true;
        this.reset();
        this.item.reset();
        event2.stopPropagation();
        $timeout2(function() {
          jquery_default($element2).find("textarea, input").focus();
        }, 0, false);
      };
      this.onKeydown = function(event2) {
        var code2 = event2.keyCode ? event2.keyCode : event2.which;
        if (code2 === 13) {
          if (event2.shiftKey && this.item.content || this.item.input) {
            event2.preventDefault();
            this.onSubmit(event2);
          }
        }
      };
      this.onFocusBtn = function(event2) {
        jquery_default($element2).find("textarea, input").focus();
        jquery_default($element2).find("textarea, input").select();
      };
      this.onBlur = function(event2) {
        $scope2.$evalAsync(function() {
          self2.formFocused = false;
          if (self2.item.submitOnBlur) {
            if (self2.onResettingBtn) {
              self2.onResettingBtn = false;
              return;
            }
            self2.onSubmit(event2);
          }
        });
      }.bind(this);
      this.onFocus = function(event2) {
        $scope2.$evalAsync(function() {
          self2.formFocused = true;
        });
      }.bind(this);
      this.$postLink = function() {
        if (this.item.buttons) {
          $element2.addClass("with-buttons");
        }
        if (this.item.content) {
          $timeout2(function() {
            jquery_default($element2).find("textarea").autosize();
          }, 0, false);
        }
        if (this.item.focusOnLoad) {
          $timeout2(function() {
            jquery_default($element2).find("textarea, input").trigger("focus");
          }, 200, false);
        }
        if (this.item.selectOnLoad) {
          $timeout2(function() {
            jquery_default($element2).find("textarea, input").trigger("select");
          }, 200, false);
        }
        $timeout2(function() {
          jquery_default($element2).find("textarea, input").on("focus", self2.onFocus);
          jquery_default($element2).find("textarea, input").on("blur", self2.onBlur);
        }, 0, false);
        $scope2.$emit("prettyMenu.itemRendered");
      };
      this.$onDestroy = function() {
        jquery_default($element2).find("textarea, input").off("focus", this.onFocus);
        jquery_default($element2).find("textarea, input").off("blur", this.onBlur);
        if (this.item.content) {
          jquery_default($element2).find("textarea").trigger("autosize.destroy");
        }
      };
    }
  ]
});

// public/app/ui/base/ng-components/pretty-menu/items/selectbox.js
angular_default.module("kantree").component("menuItemSelectbox", {
  bindings: {
    item: "<"
  },
  templateUrl: "/static/app/ui/base/ng-components/pretty-menu/templates/items/selectbox.html",
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.value = this.item.defaultValue || null;
      this.$scope.$watch(() => this.value, (newVal, oldVal) => {
        if (newVal === oldVal) {
          return;
        }
        this.item.select(newVal);
      });
    }
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
    disabled() {
      if (!isConnected() && !this.item.offline) return true;
      return this.item.disabled && this.item.disabled();
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/separator.js
angular_default.module("kantree").component("menuItemSeparator", {
  template: `<hr>`,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
  }
});

// public/app/ui/base/ng-components/pretty-menu/items/subheader.js
angular_default.module("kantree").component("menuItemSubheader", {
  template: `
    <span>{{::$ctrl.item.subheader}}</span>
    <i class="fa fa-question-circle menu-item-help" ng-show="::$ctrl.item.help"
      uib-tooltip="{{::$ctrl.item.help}}" tooltip-placement="auto top"></i>
  `,
  bindings: {
    item: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $postLink() {
      this.$scope.$emit("prettyMenu.itemRendered");
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/board-list.js
angular_default.module("kantree").component("navSidebarBoardList", {
  template: `
    <nav-sidebar-drop-menu-button ng-if="$ctrl.mode === 'icon'" options="$ctrl.dropMenuComponentOptions"
      mode="icon" active="$ctrl.active"></nav-sidebar-drop-menu-button>
    <div class="list-header" ng-if="!$ctrl.mode">
      <button class="btn" type="button" ng-click="$ctrl.toggleContent()">
        <span>
          <i class="fa fa-chevron-down"></i>
          <span class="title">{{$ctrl.label}}</span>
          <span class="count">({{$ctrl.boards.length}})</span>
        </span>
      </button>
    </div>
    <div class="list-content" ng-if="!$ctrl.mode">
      <nav-sidebar-board class="nav-sidebar-item" board="board" activable="$ctrl.options.itemsActivable"
        ng-repeat="board in $ctrl.boards track by board.id"></nav-sidebar-board>
    </div>
  `,
  bindings: {
    options: "<",
    mode: "@",
    active: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "navSidebarBoardListMenuFactory", "navSidebar", "$element"];
    $onInit() {
      this.boards = [];
      this.refreshDropMenuComponentOptions();
      this.refreshBoards();
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const modeChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged || modeChanged) {
        this.refreshDropMenuComponentOptions();
        this.refreshBoards();
      }
      if (modeChanged) {
        this.$element.toggleClass("nav-sidebar-list", !this.mode);
      }
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-list", !this.mode);
    }
    refreshDropMenuComponentOptions() {
      this.dropMenuComponentOptions = {
        ...this.options || {},
        withTooltip: false,
        menu: this.$navSidebarBoardListMenuFactory.get(this.options),
        drop: { openOn: "hover" }
      };
    }
    refreshBoards() {
      if (this.deregisterBoardsWatcher) {
        this.deregisterBoardsWatcher();
        this.deregisterBoardsWatcher = null;
      }
      if (!this.options?.store) {
        this.boards = this.options?.items || [];
        this.$element.toggleClass("hidden", !!this.options?.hideWhenEmpty && this.boards.length < 1);
        return;
      }
      this.deregisterBoardsWatcher = this.options.store.subscribe(this.options.subscribeEvent || "changed", () => {
        const oldBoardCount = this.boards.length;
        this.boards = this.options.store.query({}, { sortBy: "title" });
        this.$element.toggleClass("hidden", !!this.options.hideWhenEmpty && this.boards.length < 1);
        if (oldBoardCount !== this.boards.length) {
          this.$scope.$applyAsync();
        }
      }, true);
    }
    toggleContent() {
      if (!this.options?.storageKey) return;
      if (this.$navSidebar.isListCollapsed(this.options.storageKey)) {
        this.$navSidebar.expandList(this.options.storageKey);
      } else {
        this.$navSidebar.collapseList(this.options.storageKey);
      }
      this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.options.storageKey));
    }
    get label() {
      return this.options?.label || _4("Boards");
    }
    $onDestroy() {
      if (this.deregisterBoardsWatcher) {
        this.deregisterBoardsWatcher();
        this.deregisterBoardsWatcher = null;
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/board.js
angular_default.module("kantree").component("navSidebarBoard", {
  template: `
    <a class="nav-sidebar-btn" ui-state="$ctrl.state" ui-state-params="$ctrl.stateParams"
      ng-click="$ctrl.onButtonTriggered($event)" ng-show="!!$ctrl.board">
      <span class="color" ng-style="{'background-color': $ctrl.color, 'border-color': $ctrl.borderColor}"><div></div></span>
      <span class="title">{{$ctrl.board.title}}</span>
      <i class="fa fa-globe indicator" ng-show="$ctrl.isPublic" uib-tooltip="{{::$ctrl.shareableTooltip}}"></i>
      <i class="fa fa-cloud-download indicator" ng-show="$ctrl.isAvailableOffline" uib-tooltip="{{::$ctrl.offlineTooltip}}"></i>
    </a>
  `,
  bindings: {
    board: "<",
    activable: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "cardModal", "$element"];
    $onInit() {
      this.shareableTooltip = _4("Has shareable link");
      this.offlineTooltip = _4("Available offline");
      this.refresh();
      this.$scope.$on("connectivityChanged", (e3, connected) => {
        this.$element.find("> a").toggleClass("disabled", !isProjectAccessible(this.project));
      });
    }
    $onChanges(changes) {
      if (changes.board && !changes.board.isFirstChange() && changes.board.previousValue?.id !== this.board?.id) {
        this.refresh();
      }
    }
    refresh() {
      if (this.deregisterBoardWatcher) {
        this.deregisterBoardWatcher();
        this.deregisterBoardWatcher = null;
      }
      if (this.deregisterProjectWatcher) {
        this.deregisterProjectWatcher();
        this.deregisterProjectWatcher = null;
      }
      if (!this.board) return;
      this.deregisterBoardWatcher = cardStore.$watch(this.$scope, this.board, "updated", (board) => {
        this.board = board;
        const lastProjectId = this.project?.id;
        if (this.board.is_link) {
          this.project = projectStore.tryGet(this.board.link.project_id);
        } else {
          this.project = projectStore.tryGetForCard(this.board);
        }
        if (!this.project) {
          this.color = themeColor() || "#148a73";
          this.borderColor = slightlyDifferentColor(this.color, 0.3);
          this.isPublic = false;
          this.isAvailableOffline = !this.board.parent_id;
          this.state = null;
          this.stateParams = null;
        } else {
          if (!!this.deregisterProjectWatcher) {
            if (lastProjectId === this.project.id) return;
            this.deregisterProjectWatcher();
          }
          this.deregisterProjectWatcher = projectStore.$watch(this.$scope, this.project, "updated", (project) => {
            this.project = project;
            this.color = this.project.color || themeColor() || "#148a73";
            this.borderColor = slightlyDifferentColor(this.color, 0.3);
            this.isPublic = this.project.is_public && !this.board.parent_id;
            this.isAvailableOffline = isProjectAvailableOffline(this.project) && !this.board.parent_id;
            if (!this.board.parent_id || !!this.board.is_link && !this.board.link.parent_id) {
              this.state = "project";
              this.stateParams = { projectId: this.project.slug, view: null };
            } else {
              const boardRef = this.board.is_link ? this.board.link.ref : this.board.ref;
              if (this.board.board_created) {
                this.state = "project_board";
                this.stateParams = { projectId: this.project.slug, cardRef: boardRef, view: null };
              } else {
                this.stateParams = { projectId: this.project.slug, "#": boardRef, view: null };
              }
            }
          });
        }
      });
    }
    onButtonTriggered(event2) {
      if (this.board.parent_id && !this.board.board_created) {
        event2.preventDefault();
        return this.$cardModal.load(this.board.id);
      }
      if (!isProjectAccessible(this.project)) {
        event2.preventDefault();
        return;
      }
    }
  }
});

// virtual-ns:tippy.js
var tippy_default = tippy;

// public/app/ui/base/ng-components/sidebar/items/button.js
angular_default.module("kantree").component("navSidebarButton", {
  template: `
    <button class="nav-sidebar-btn" ng-class="{'btn-icon': $ctrl.mode === 'icon', 'active': $ctrl.active}" type="button"
      ng-click="$ctrl.options.action($event)">
      <i ng-class="$ctrl.options.icon|iconClass" ng-if="::$ctrl.options.icon"></i>
      <div class="badge badge-red badge-dot badge-up" ng-class="{'badge-empty': !$ctrl.options.dotLabel()}" ng-if="$ctrl.mode === 'icon' && $ctrl.options.dot()" ng-style="{'background-color': $ctrl.options.dotColor(),
        'color': $ctrl.textColor($ctrl.options.dotColor())}">{{$ctrl.options.dotLabel()}}</div>
      <span>{{::$ctrl.options.label}}</span>
    </button>
  `,
  bindings: {
    options: "<",
    mode: "@",
    active: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$window"];
    $onInit() {
      this.refresh();
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged) {
        this.refresh();
      }
    }
    $postLink() {
      this.$element.addClass("nav-sidebar-item");
    }
    refreshTooltip() {
      if (this.options?.label && this.mode === "icon") {
        if (this.tooltip) {
          this.tooltip.setProps({ placement: this.options?.tooltipPlacement || "right" });
        } else {
          this.tooltip = tippy_default(this.$element.find("button")[0], {
            content: this.options?.label,
            hideOnClick: true,
            theme: "light-border-tooltip",
            appendTo: () => this.$window.document.body,
            placement: this.options?.tooltipPlacement || "right"
          });
        }
      }
    }
    refresh() {
      this.refreshTooltip();
    }
  }
});

// public/app/ui/base/ng-components/dropdown/popper-modifier.js
function getPopperMaxHeight() {
  return {
    name: "maxHeight",
    enabled: true,
    phase: "main",
    requiresIfExists: ["offset", "preventOverflow", "flip"],
    fn({ state, name: name2, options: options2 }) {
      state.modifiersData[name2] = {
        height: state.scrollParents.popper[state.scrollParents.popper.length - 1].getBoundingClientRect().height
      };
    }
  };
}
function applyPopperMaxHeight() {
  return {
    name: "applyMaxHeight",
    enabled: true,
    phase: "beforeWrite",
    requires: ["maxHeight"],
    fn({ state }) {
      const { height } = state.modifiersData.maxHeight;
      state.styles.popper = {
        ...state.styles.popper,
        maxHeight: `${Math.max(200, height)}px`
      };
    }
  };
}

// public/app/ui/base/ng-components/sidebar/items/drop-menu-button.js
angular_default.module("kantree").component("navSidebarDropMenuButton", {
  bindings: {
    options: "<",
    mode: "@",
    active: "<"
  },
  template: `
    <button class="nav-sidebar-btn" ng-class="{'btn-icon': $ctrl.mode === 'icon', 'active': $ctrl.active}"
      type="button" ng-click="$ctrl.onBtnClick()">
      <i ng-class="$ctrl.options.icon|iconClass" ng-if="::$ctrl.options.icon"></i>
      <img ng-src="{{$ctrl.options.image}}" ng-if="::$ctrl.options.image">
      <div class="badge badge-sm badge-dot badge-down" ng-if="$ctrl.mode === 'icon' && $ctrl.options.dot()" ng-style="{'background-color': $ctrl.options.dotColor(),
        'color': $ctrl.textColor($ctrl.options.dotColor())}" ng-class="$ctrl.options.dotClass">{{$ctrl.options.dotLabel()}}</div>
      <span>{{::$ctrl.options.label}}</span>
    </button>
  `,
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope", "$compile", "$window", "$timeout", "$state"];
    $onInit() {
      this.menuHtml = `<pretty-menu class="pretty-menu" ng-class="classes" config="menu.config"
        options="menu.options" action-params="menu.params" default-path="menu.defaultPath"
        on-update="update($menuEvent)" on-close="close()"></pretty-menu>`;
      this.menuScope = this.$scope.$new();
      this.menuScope.menu = this.options?.menu;
      this.menuScope.close = () => {
        if (this.dropdown.state.isVisible) {
          this.dropdown.hide();
        }
      };
      this.menuScope.classes = this.options?.drop?.classes;
      this.menuScope.update = (menuEvent) => {
        if (this.dropdown.state.isVisible && menuEvent !== "panelInit") {
          this.dropdown.popperInstance.update();
        }
      };
      this.dropContent = this.$compile(this.menuHtml)(this.menuScope);
      this.menuScope.$on("$destroy", () => {
        if (this.dropContent) {
          this.dropContent.remove();
          this.dropContent = null;
        }
      });
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged) {
        this.refresh();
      }
    }
    $postLink() {
      this.$element.addClass("nav-sidebar-item");
      this.refresh();
    }
    get color() {
      return this.options?.color || "#f2f2f2";
    }
    textColor(input) {
      return textColor(input, null, "#333");
    }
    refreshTooltip() {
      if (this.withTooltip && this.options?.label) {
        if (this.tooltip) {
          this.tooltip.setProps({ placement: this.options?.tooltipPlacement || "right" });
        } else {
          this.tooltip = tippy_default(this.$element.find("button")[0], {
            content: this.options?.label,
            hideOnClick: true,
            theme: "light-border-tooltip",
            appendTo: () => this.$window.document.body,
            placement: this.options?.tooltipPlacement || "right"
          });
        }
      }
    }
    refreshDropdown() {
      if (this.dropdown) {
        this.dropdown.setProps({
          hideOnClick: this.options.drop?.openOn === "hover" ? false : true,
          trigger: this.options.drop?.openOn === "hover" ? "mouseenter" : "click"
        });
      } else {
        this.dropdown = tippy_default(this.$element.find("button")[0], {
          content: this.dropContent[0],
          placement: "right",
          interactive: true,
          theme: "light-border-drop",
          animation: false,
          appendTo: () => this.$window.document.body,
          hideOnClick: this.options.drop?.openOn === "hover" ? false : true,
          trigger: this.options.drop?.openOn === "hover" ? "mouseenter" : "click",
          offset: ({ placement, reference: reference2, popper }) => {
            return [popper.height / 2 - reference2.height / 2, 6];
          },
          popperOptions: {
            modifiers: [
              {
                name: "arrow",
                options: {
                  padding: 5
                }
              },
              getPopperMaxHeight(),
              applyPopperMaxHeight()
            ]
          },
          onShow: () => {
            if (this.tooltip) {
              this.tooltip.disable();
            }
          },
          onHide: () => {
            if (this.tooltip) {
              this.tooltip.enable();
            }
            this.$scope.$applyAsync(() => {
              this.menuScope.menu.defaultPath = [[1, 0]];
            });
          }
        });
      }
    }
    refresh() {
      this.tooltipPlacement = this.options?.tooltipPlacement || "right";
      this.menuScope.menu = this.options?.menu;
      this.menuScope.classes = (this.options?.drop || {}).classes;
      this.refreshTooltip();
      this.refreshDropdown();
    }
    get withTooltip() {
      return (typeof this.options?.withTooltip === "undefined" || !!this.options?.withTooltip) && this.mode === "icon";
    }
    onBtnClick() {
      if (this.options?.gotoState) {
        this.$state.go(...this.options.gotoState);
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/link.js
angular_default.module("kantree").component("navSidebarLink", {
  template: `
    <a class="nav-sidebar-btn" ng-class="{'active': $ctrl.active}" navigate-to="{{$ctrl.options.href}}">
      <i ng-class="$ctrl.options.icon|iconClass"></i>
      <div class="badge badge-red badge-dot badge-up" ng-if="$ctrl.mode === 'icon' && $ctrl.options.dot()" ng-style="{'background-color': $ctrl.options.dotColor(),
        'color': $ctrl.textColor($ctrl.options.dotColor())}">{{$ctrl.options.dotLabel()}}</div>
      <span>{{::$ctrl.options.label}}</span>
    </a>
  `,
  bindings: {
    options: "<",
    mode: "@",
    active: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$window"];
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.refresh();
      }
    }
    $postLink() {
      this.$element.addClass("nav-sidebar-item");
      this.refresh();
    }
    refreshTooltip() {
      if (this.options?.label) {
        if (this.tooltip) {
          this.tooltip.setProps({ placement: this.options?.tooltipPlacement || "right" });
        } else {
          this.tooltip = tippy_default(this.$element.find("a")[0], {
            content: this.options?.label,
            hideOnClick: true,
            theme: "light-border-tooltip",
            appendTo: () => this.$window.document.body,
            placement: this.options?.tooltipPlacement || "right"
          });
        }
      }
    }
    refresh() {
      this.refreshTooltip();
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/logo.js
angular_default.module("kantree").component("navSidebarLogo", {
  template: `
    <a class="nav-sidebar-btn" navigate-to="{{$ctrl.options.href}}"><i ng-style="$ctrl.logoStyle"></i></a>
  `,
  bindings: {
    options: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $onInit() {
      this.refresh();
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.refresh();
      }
    }
    $postLink() {
      this.$element.addClass("nav-sidebar-item");
    }
    refresh() {
      if (this.options?.logo) {
        this.logoStyle = { "background-image": "url(" + this.options.logo + ")" };
      } else {
        this.logoStyle = {};
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/page-header.js
angular_default.module("kantree").component("navSidebarPageHeader", {
  template: `
    <a navigate-to="{{$ctrl.options.url}}" ng-if="$ctrl.options.url">{{$ctrl.options.title}}</a>
    <span ng-if="!$ctrl.options.url">{{$ctrl.options.title}}</span>
  `,
  bindings: {
    options: "<"
  }
});

// public/app/ui/base/ng-components/sidebar/items/project-list.js
angular_default.module("kantree").component("navSidebarProjectList", {
  template: `
    <nav-sidebar-drop-menu-button ng-if="$ctrl.mode" options="$ctrl.dropMenuComponentOptions"
      mode="icon" active="$ctrl.active"></nav-sidebar-drop-menu-button>
    <div class="list-header" ng-if="!$ctrl.mode">
      <button class="btn" type="button" ng-click="$ctrl.toggleContent()">
        <span>
          <i class="fa fa-chevron-down"></i>
          <span class="title">{{$ctrl.label}}</span>
          <span class="count">({{$ctrl.projects.length}})</span>
        </span>
      </button>
    </div>
    <div class="list-content" ng-if="!$ctrl.mode">
      <nav-sidebar-project class="nav-sidebar-item" project="project" activable="$ctrl.options.itemsActivable"
        ng-repeat="project in $ctrl.projects track by project.id"></nav-sidebar-project>
    </div>
  `,
  bindings: {
    options: "<",
    mode: "@",
    active: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "navSidebarProjectListMenuFactory", "navSidebar", "$element"];
    $onInit() {
      this.projects = [];
      this.refreshDropMenuComponentOptions();
      this.refreshProjects();
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const modeChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged || modeChanged) {
        this.refreshDropMenuComponentOptions();
        this.refreshProjects();
      }
      if (modeChanged) {
        this.$element.toggleClass("nav-sidebar-list", !this.mode);
      }
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-list", !this.mode);
    }
    refreshDropMenuComponentOptions() {
      this.dropMenuComponentOptions = {
        ...this.options || {},
        withTooltip: false,
        menu: this.$navSidebarProjectListMenuFactory.get(this.options),
        drop: { openOn: "hover" }
      };
    }
    refreshProjects() {
      if (this.deregisterProjectsWatcher) {
        this.deregisterProjectsWatcher();
        this.deregisterProjectsWatcher = null;
      }
      if (!this.options?.store) {
        this.$element.toggleClass("hidden", !!this.options?.hideWhenEmpty && this.projects.length < 1);
        return;
      }
      this.deregisterProjectsWatcher = this.options.store.$watchAll(this.$scope, () => {
        this.projects = this.options.store.query({}, { sortBy: "title" });
        this.$element.toggleClass("hidden", !!this.options.hideWhenEmpty && this.projects.length < 1);
      });
    }
    toggleContent() {
      if (!this.options?.storageKey) return;
      if (this.$navSidebar.isListCollapsed(this.options.storageKey)) {
        this.$navSidebar.expandList(this.options.storageKey);
      } else {
        this.$navSidebar.collapseList(this.options.storageKey);
      }
      this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.options.storageKey));
    }
    get label() {
      return this.options?.label || _4("Boards");
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/project-page-header.js
angular_default.module("kantree").component("navSidebarProjectPageHeader", {
  templateUrl: "/static/app/ui/base/ng-components/sidebar/templates/project-page-header.html",
  bindings: {
    options: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "projectActionsMenuFactory", "cardActionsMenuFactory", "$state"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.refreshBoard();
      this.refreshProject();
      this.settingsMenuDropConfig = {
        classes: "drop-theme-menu drop-theme-arrow drop-theme-project-settings",
        tetherOptions: {
          attachment: "top left",
          offset: "0 22px"
        }
      };
      this.pathMenuDropConfig = {
        classes: "drop-theme-menu drop-theme-arrow",
        tetherOptions: {
          attachment: "top left",
          offset: "0 22px"
        }
      };
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const projectChanged = optionsChanged && changes.options?.project?.id !== changes.previousValue.options?.project?.id;
      const boardChanged = optionsChanged && changes.options?.board?.id !== changes.previousValue.options?.board?.id;
      if (boardChanged) {
        this.refreshBoard();
      }
      if (projectChanged) {
        this.refreshProject();
      }
    }
    refreshProject() {
      if (this.deregisterProjectWatcher) {
        this.deregisterProjectWatcher();
        this.deregisterProjectWatcher = null;
      }
      if (this.deregisterProjectMemberWatcher) {
        this.deregisterProjectMemberWatcher();
        this.deregisterProjectMemberWatcher = null;
      }
      if (!!this.options?.project) {
        this.deregisterProjectWatcher = projectStore.$watch(this.$scope, this.options.project, (project) => {
          const lastProjectId = this.project?.id;
          this.project = project;
          if (lastProjectId !== this.project?.id && this.board && !this.board.parent_id) {
            this.settingsMenu = this.$projectActionsMenuFactory.get(this.project, { showTeam: true, showLeave: true });
          }
        });
        const notApprovedDomainMembersStore = projectMemberStore.scopedByProject(this.project).scoped({
          user: query_exports.objMatch({ is_from_approved_domain: false })
        });
        this.deregisterProjectMemberWatcher = notApprovedDomainMembersStore.$watchAll(this.$scope, () => {
          this.hasNotApprovedDomainMembers = notApprovedDomainMembersStore.count() > 0;
        });
      }
    }
    refreshBoard() {
      if (this.deregisterBoardWatcher) {
        this.deregisterBoardWatcher();
        this.deregisterBoardWatcher = null;
      }
      if (!!this.options?.board) {
        this.deregisterBoardWatcher = cardStore.$watch(this.$scope, this.options.board, "updated", (board) => {
          if (this.board && board.id !== this.board.id) return;
          this.board = board;
          this.path = this.board.path.slice(1);
          if (this.board.parent_id) {
            this.settingsMenu = this.$cardActionsMenuFactory.get(this.board);
          }
          this.pathMenu = {
            config: () => this.path.map((parent) => ({
              label: parent.title,
              action: () => this.$state.go("project_board", { projectId: this.project.slug, cardRef: parent.ref })
            }))
          };
        });
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/project.js
angular_default.module("kantree").component("navSidebarProject", {
  template: `
    <a class="nav-sidebar-btn" ui-state="$ctrl.state" ui-state-params="$ctrl.stateParams" ng-click="$ctrl.onButtonTriggered($event)">
      <span class="color" ng-style="{'background-color': $ctrl.color,
      'border-color': $ctrl.borderColor}"><div></div></span>
      <span class="title">{{::$ctrl.project.title}}</span>
      <i class="fa fa-globe indicator" ng-show="$ctrl.isPublic"
        uib-tooltip="{{::$ctrl.shareableTooltip}}"></i>
      <i class="fa fa-cloud-download indicator" ng-show="$ctrl.isAvailableOffline"
        uib-tooltip="{{::$ctrl.offlineTooltip}}"></i>
    </a>
  `,
  bindings: {
    project: "<",
    activable: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      this.shareableTooltip = _4("Has shareable link");
      this.offlineTooltip = _4("Available offline");
      this.refresh();
      this.$scope.$on("connectivityChanged", (e3, connected) => {
        this.$element.find("> a").toggleClass("disabled", !isProjectAccessible(this.project));
      });
    }
    $onChanges(changes) {
      if (changes.project && !changes.project.isFirstChange() && changes.project.previousValue?.id !== this.project?.id) {
        this.refresh();
      }
    }
    refresh() {
      if (this.deregisterProjectWatcher) {
        this.deregisterProjectWatcher();
        this.deregisterProjectWatcher = null;
      }
      if (!this.project) return;
      this.deregisterProjectWatcher = projectStore.$watch(this.$scope, this.project, "updated", (project) => {
        this.project = project;
        this.color = this.project.color || themeColor() || "#148a73";
        this.borderColor = slightlyDifferentColor(this.color, 0.3);
        this.isPublic = this.project.is_public;
        this.isAvailableOffline = isProjectAvailableOffline(this.project);
        this.state = "project";
        this.stateParams = { projectId: this.project.slug, view: null };
      });
    }
    onButtonTriggered(event2) {
      if (!isProjectAccessible(this.project)) {
        event2.preventDefault();
        return;
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/recently-opened-list.js
angular_default.module("kantree").component("navSidebarRecentlyOpenedList", {
  template: `
    <nav-sidebar-board-list options="$ctrl.boardListOptions" mode="{{$ctrl.mode}}"></nav-sidebar-board-list>
  `,
  bindings: {
    options: "<",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.debounceRefreshOptions = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.refreshOptions();
        });
      }, 60);
      this.debounceRefreshOptions();
      $onEvent(this.$scope, onAppContextUpdate, () => this.debounceRefreshOptions());
      $createEffect(this.$scope, () => on(
        () => recentlyOpenedBoards(),
        () => this.debounceRefreshOptions()
      ));
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const modeChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged || modeChanged) {
        this.debounceRefreshOptions();
      }
    }
    refreshOptions() {
      this.boardListOptions = {
        ...this.options || {},
        label: _4("Recently opened"),
        icon: "bi-clock-history",
        storageKey: "recently-opened",
        items: recentlyOpenedBoards(),
        sorted: false,
        hideWhenEmpty: true
      };
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/separator.js
angular_default.module("kantree").component("navSidebarSeparator", {});

// public/app/ui/base/ng-components/sidebar/items/team.js
angular_default.module("kantree").component("navSidebarTeam", {
  template: `
    <a class="nav-sidebar-btn" ng-class="{'btn-icon': $ctrl.mode === 'icon', 'active': $ctrl.active}"
      ui-state="$ctrl.state" ui-state-params="$ctrl.stateParams" ui-state-opts="$ctrl.stateOpts" ng-click="$ctrl.onLinkClick($event)">
      <i ng-class="$ctrl.icon|iconClass" ng-if="::$ctrl.icon"></i>
      <div class="badge badge-sm badge-down" ng-if="$ctrl.mode === 'icon' && $ctrl.tag" ng-style="{'background-color': $ctrl.tagColor,
        'color': $ctrl.textColor}">{{$ctrl.tag|limitTo:3}}</div>
      <span>{{::$ctrl.tag}}</span>
    </a>
  `,
  bindings: {
    options: "<",
    mode: "@",
    active: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["navSidebarTeamMenuFactory", "$scope", "$state", "$compile", "$element", "$window", "$timeout"];
    $onInit() {
      this.stateOpts = { "inherit": false };
      this.dropHtml = `<pretty-menu class="pretty-menu" config="menu.config"
        options="menu.options" action-params="menu.params" default-path="menu.defaultPath"
        on-update="update($menuEvent)" on-close="close()"></pretty-menu>`;
      this.dropScope = this.$scope.$new();
      this.dropScope.close = () => {
        if (this.dropdown.state.isVisible) {
          this.dropdown.hide();
        }
      };
      this.dropScope.update = (menuEvent) => {
        if (this.dropdown.state.isVisible && menuEvent !== "panelInit") {
          this.dropdown.popperInstance.update();
        }
      };
      this.refresh();
      this.dropContent = this.$compile(this.dropHtml)(this.dropScope);
      this.$scope.$on("appContextupdate", () => {
        this.refresh();
      });
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const modeChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged || modeChanged) {
        this.refresh();
      }
    }
    $postLink() {
      this.$element.addClass("nav-sidebar-item");
      this.dropdown = tippy_default(this.$element.find("a")[0], {
        content: this.dropContent[0],
        placement: "right",
        interactive: true,
        theme: "light-border-drop",
        animation: false,
        appendTo: () => this.$window.document.body,
        offset: ({ placement, reference: reference2, popper }) => {
          return [popper.height / 2 - reference2.height / 2, 6];
        },
        popperOptions: {
          modifiers: [
            {
              name: "arrow",
              options: {
                padding: 5
              }
            },
            getPopperMaxHeight(),
            applyPopperMaxHeight()
          ]
        },
        onHide: () => {
          this.$scope.$applyAsync(() => {
            this.dropScope.menu.defaultPath = [[1, 0]];
          });
        }
      });
      const enableDropdownBasedOnScreensize = () => this.dropdown[isScreensizeXS() ? "disable" : "enable"]();
      enableDropdownBasedOnScreensize();
      this.$scope.$on("screensize:changed", () => enableDropdownBasedOnScreensize());
    }
    refresh() {
      this.tag = this.options.team ? this.options.team.name : this.options.org.name;
      this.icon = this.options.team ? this.options.team.icon || "bi-people-fill" : "bi-building";
      this.tagColor = (this.options.team ? this.options.team.color : this.options.org.color || this.options.org.cover_color) || "#f2f2f2";
      this.textColor = textColor(this.tagColor, null, "#333");
      this.dropScope.menu = this.$navSidebarTeamMenuFactory.get(this.options);
      this.state = this.options.team ? "org.team.hub" : "org.hub";
      const stateParams = { "slug": this.options.org.slug };
      if (this.options.team) {
        stateParams.teamSlug = this.options.team.slug;
      }
      this.stateParams = stateParams;
    }
    onLinkClick(event2) {
      event2.stopPropagation();
      event2.stopImmediatePropagation();
      if (this.options?.org?.permission === 0) {
        event2.preventDefault();
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/view-categories.js
angular_default.module("kantree").component("navSidebarViewCategories", {
  template: `
    <nav-sidebar-view-list ng-repeat="category in $ctrl.categories track by category.id" options="category"
      data-category-id="{{category.id}}"></nav-sidebar-view-list>
  `,
  bindings: {
    options: "<",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$q"];
    $onInit() {
      this.categories = [];
      this.noCategoryName = this.options.noCategoryName || _4("Views");
      this.refreshCategories();
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged) {
        this.refreshCategories();
      }
    }
    refreshCategories() {
      if (this.deregisterStoreWatcher) {
        this.deregisterStoreWatcher();
        this.deregisterStoreWatcher = null;
      }
      if (this.options?.categoryStore) {
        this.deregisterStoreWatcher = this.options.categoryStore.$watchAll(this.$scope, () => {
          this.categories = this.options.categoryStore.query({}, { sortBy: "position" }).map((category) => {
            return {
              id: category.id,
              category,
              label: category.name,
              store: this.options.viewStore.scoped({ category_id: category.id }),
              storageKey: this.options.storageKey.replace("$CATID", category.id),
              project: this.options.project,
              board: this.options.board,
              filterScopes: this.options.filterScopes,
              showCreate: this.options.showCreateView,
              create: this.options.createView,
              createPublic: this.options.createPublicView,
              showCreateCategory: this.options.showCreateCategory
            };
          });
          if (this.options.showNoCategoryViews) {
            this.categories.unshift({
              id: 0,
              label: this.noCategoryName,
              store: this.options.viewStore.scoped({ category_id: null }),
              storageKey: this.options.storageKey.replace("$CATID", 0),
              project: this.options.project,
              board: this.options.board,
              filterScopes: this.options.filterScopes,
              showCreate: this.options.showCreateView,
              create: this.options.createView,
              createPublic: this.options.createPublicView,
              showCreateCategory: this.options.showCreateCategory,
              hideWhenEmpty: true
            });
          }
        });
      }
    }
    $postLink() {
      jquery_default(this.$element).sortable({
        appendTo: "body",
        helper: "original",
        items: ".nav-sidebar-list",
        handle: ".list-header > .btn > span",
        cancel: "input,textarea,select,option",
        tolerance: "pointer",
        distance: 12,
        scroll: false,
        zIndex: 0,
        axis: "y",
        stop: (e3, ui) => {
          const categoryId = ui.item.data("category-id");
          let nextCategoryId;
          if (!ui.item.is(":last-child")) {
            nextCategoryId = ui.item.next().data("category-id");
          }
          this.$q.digest((async () => {
            let category, nextCategory = null;
            if (categoryId == 0) {
              category = await createDefaultViewCategory(this.options.project, this.noCategoryName);
            } else {
              category = viewCategoryStore.get(categoryId);
            }
            if (nextCategoryId === 0) {
              nextCategory = await createDefaultViewCategory(this.options.project, this.noCategoryName);
            } else if (nextCategoryId) {
              nextCategory = viewCategoryStore.get(nextCategoryId);
            }
            await reorderViewCategory(category, nextCategory);
          })());
        }
      });
      this.toggleSortable();
      this.$scope.$on("screensize:changed", () => this.toggleSortable());
    }
    toggleSortable() {
      const needSortable = this.options.project && canManageViews(this.options.project) && !isScreensizeXS();
      if (this.$element.sortable("instance")) {
        this.$element.sortable(needSortable ? "enable" : "disable");
      }
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/view-list.js
angular_default.module("kantree").component("navSidebarViewList", {
  template: `
    <div class="list-header" ng-if="!$ctrl.mode">
      <button type="button" class="btn" ng-click="$ctrl.toggleContent()" ng-hide="$ctrl.editingName">
        <span>
          <i class="fa fa-chevron-down"></i>
          <span class="title">{{$ctrl.label}}</span>
          <span class="count">({{$ctrl.views.length}})</span>
          <i class="indicator" ng-class="$ctrl.options.indicator|iconClass" ng-show="!!$ctrl.options.indicator"></i>
        </span>
      </button>
      <form ng-submit="$ctrl.rename($ctrl.nameInput)" ng-if="$ctrl.editingName">
        <input type="text" ng-model="$ctrl.nameInput" ng-attr-placeholder="{{$ctrl.inputPlaceholderLabel}}" required auto-focus>
      </form>
      <button class="btn" type="button" drop-menu="$ctrl.headerMenu" ng-if="$ctrl.showCategoryMenu"><i class="bi-three-dots"></i></button>
    </div>
    <div class="list-content js-sortable" ui-sortable="$ctrl.sortableOptions" ng-model="$ctrl.views">
      <nav-sidebar-view class="js-sortable-item" ng-repeat="view in $ctrl.views track by view.id"
        view="view" mode="{{$ctrl.mode}}" project="$ctrl.options.project"></nav-sidebar-view>
    </div>
    <div class="nav-sidebar-item nav-sidebar-hide-collapsed" ng-show="$ctrl.options.showCreate" hide-offline>
      <button class="nav-sidebar-btn btn-adder" type="button" ng-click="$ctrl.openCreateModal()">
        <i class="bi-plus-lg"></i>
        <span>{{::$ctrl.addBtnLabel}}</span>
      </button>
    </div>
  `,
  bindings: {
    options: "<",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = [
      "$scope",
      "$element",
      "$q",
      "navSidebar",
      "$compile",
      "$window",
      "projectPage",
      "projectAddViewModal"
    ];
    $onInit() {
      this.inputPlaceholderLabel = _4("Category name");
      this.addBtnLabel = _4("Add view");
      this.views = [];
      this.editingName = this.options.category && !this.options.category.name;
      this.nameInput = "";
      this.refreshViews();
      this.showCategoryMenu = canManageViews(this.options.project) && (this.options.showCreateCategory || this.options.category);
      this.headerMenu = { config: [
        {
          label: _4("Rename"),
          icon: "bi-pencil-square",
          action: () => {
            this.editingName = true;
            this.nameInput = this.options.category ? this.options.category.name : this.label;
          }
        },
        {
          label: _4("Delete"),
          icon: "trash",
          action: () => {
            yesNoDialog({
              title: _4("Also delete views?")
            }).then(() => this.$q.digest(deleteViewCategory(this.options.category, true))).catch(() => this.$q.digest(deleteViewCategory(this.options.category, false)));
          },
          enabled: () => !!this.options.category
        },
        {
          label: "--",
          enabled: () => this.options.showCreateCategory
        },
        {
          subheader: _4("Organized views in categories shared by all members")
        },
        {
          label: _4("Add category"),
          icon: "bi-plus-lg",
          action: () => this.$q.digest(createViewCategory(this.options.project, "")),
          enabled: () => this.options.showCreateCategory
        }
      ] };
      this.sortableOptions = {
        appendTo: "body",
        helper: "original",
        items: ".js-sortable-item:not(.is-draft)",
        handle: ".js-sortable-item-handle",
        tolerance: "pointer",
        connectWith: this.options.category || this.options.showCreateCategory ? "nav-sidebar-view-list.is-droppable .js-sortable" : false,
        dropOnEmpty: true,
        distance: 12,
        scroll: false,
        zIndex: 0,
        axis: "y",
        start: (e3, ui) => {
          ui.item.sortable.targetCtrl = this;
          ui.item.sortable.sourceCtrl = this;
          ui.item.targetCategory = this.options.category;
        },
        over: (event2, ui) => {
          ui.item.sortable.targetCtrl = this;
        },
        update: (event2, ui) => {
          const { sourceCtrl, targetCtrl, cancel, droptarget, index: index2, dropindex } = ui.item.sortable;
          const droppedInSameList = targetCtrl === this;
          if (sourceCtrl !== this) return;
          if (event2.originalEvent.target === null) {
            cancel();
          }
          if (!droptarget || !droptarget.length) {
            cancel();
          }
          if (droppedInSameList && index2 === dropindex) {
            cancel();
          }
        },
        receive: (e3, ui) => {
          ui.item.targetCategory = this.options.category;
        },
        stop: (e3, ui) => {
          const {
            targetCtrl = this,
            isCanceled,
            // the dragged card has already been added by ng-sortable.js in the droptargetModel
            // See : L246 for connected lists sort and L260 for normal sort
            droptargetModel: droptargetViews,
            model: view,
            dropindex,
            index: index2
          } = ui.item.sortable;
          const droppedInSameList = targetCtrl === this;
          if (isCanceled()) return;
          if (!droptargetViews) return;
          let relativeToView = null;
          let positionStrategy = "replace";
          if (droptargetViews.length <= 1) {
            relativeToView = null;
          } else if (droppedInSameList) {
            if (dropindex < index2) {
              relativeToView = droptargetViews.slice(dropindex + 1).find((v3) => v3.id !== view.id);
            } else if (dropindex > index2) {
              relativeToView = droptargetViews.slice(0, dropindex).reverse().find((v3) => v3.id !== view.id);
            }
          } else {
            relativeToView = droptargetViews.slice(dropindex + 1).find((v3) => v3.id !== view.id);
            if (relativeToView && relativeToView.position > view.position) {
              positionStrategy = "before";
            }
          }
          this.$q.when(reorderView(view, relativeToView, positionStrategy, ui.item.targetCategory));
        }
      };
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.refreshViews();
        this.editingName = this.options.category && !this.options.category.name;
      }
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-list");
      if (this.options.category || this.options.showCreateCategory) {
        this.$element.toggleClass("is-droppable");
      }
      if (this.options.category) {
        this.$element.toggleClass("has-category");
      }
      if (this.storageKey) {
        this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.storageKey));
      }
      this.toggleSortable();
      this.$scope.$on("screensize:changed", () => this.toggleSortable());
    }
    get label() {
      return this.options?.label || _4("Views");
    }
    refreshViews() {
      if (this.deregisterStoreWatcher) {
        this.deregisterStoreWatcher();
        this.deregisterStoreWatcher = null;
      }
      if (this.options?.store) {
        this.deregisterStoreWatcher = this.options.store.root.$watchAll(this.$scope, () => {
          const userViewPerms = this.options.project.user_permissions?.filter((perm) => perm.object_type === "view");
          this.views = this.options.store.query(userViewPerms ? {
            id: query_exports.not(query_exports.any(userViewPerms.map((perm) => perm.object_id)))
          } : {}, { sortBy: "position" });
          if (this.options.hideWhenEmpty) {
            this.$element.toggleClass("hidden", !this.views.length);
          }
        });
      }
    }
    rename(name2) {
      if (!name2) {
        return;
      }
      if (this.options.category) {
        this.$q.when(renameViewCategory(this.options.category, name2), () => {
          this.editingName = false;
        });
      } else {
        this.$q.when(createDefaultViewCategory(this.options.project, name2), () => {
          this.editingName = false;
        });
      }
    }
    toggleSortable() {
      const needSortable = this.options.project && canManageViews(this.options.project) && !isScreensizeXS();
      const $sortableElement = jquery_default(this.$element).find(".js-sortable");
      if ($sortableElement && $sortableElement.sortable("instance")) {
        $sortableElement.sortable(needSortable ? "enable" : "disable");
      }
    }
    toggleContent() {
      if (!(this.options || {}).storageKey) return;
      if (this.$navSidebar.isListCollapsed(this.options.storageKey)) {
        this.$navSidebar.expandList(this.options.storageKey);
      } else {
        this.$navSidebar.collapseList(this.options.storageKey);
      }
      this.$element.toggleClass("collapsed", !!this.$navSidebar.isListCollapsed(this.options.storageKey));
    }
    activate(view) {
      $navigateToView(view);
    }
    openCreateModal() {
      const { project, board, category, filterScopes, createPublic: isPublic } = this.options;
      this.$projectAddViewModal.open({ project, board, category, filterScopes, isPublic }).then((view) => {
        this.activate(view);
      });
    }
  }
});

// public/app/ui/base/ng-components/sidebar/items/view.js
angular_default.module("kantree").component("navSidebarView", {
  templateUrl: "/static/app/ui/base/ng-components/sidebar/templates/view.html",
  bindings: {
    view: "<",
    project: "<?",
    mode: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$state", "projectPage", "$timeout"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isDraftView = viewStore.isDraftView(this.view);
      viewStore.$watchAll(this.$scope, () => {
        this.draftView = this.view._draft ? null : viewStore.tryGetDraftView(this.view);
      });
      this.$scope.$watch(() => this.view.name, () => {
        this.name = this.view.name || _4("Untitled view");
      });
      if (this.project) {
        const currentMember = getCurrentUserProjectMember(this.project);
        projectMemberStore.$watch(this.$scope, currentMember, (newVal) => {
          this.isMemberOfProject = isAuthenticated() && !!newVal;
        });
      }
      this.openMenuIfUntitled();
    }
    $postLink() {
      this.$element.toggleClass("nav-sidebar-item");
      this.$element.toggleClass("nav-sidebar-item-view");
      this.$element.toggleClass("active", !!this.active);
      this.$element.toggleClass("editable", !!this.editable);
      this.$element.toggleClass("draft", !!this.isDraftView);
      this.$scope.$watch(() => this.active, (newVal, oldVal) => {
        this.$element.toggleClass("active", !!newVal);
      });
      this.$scope.$watch(() => this.editable, (newVal, oldVal) => {
        this.$element.toggleClass("editable", !!newVal);
      });
    }
    openMenuIfUntitled() {
      if (!this.view.name) {
        let app = projectAppRegistry.get(this.view.mode);
        if (!app || !app.keepUntitled) {
          this.$timeout(() => {
            if (this.active) {
              this.$element.find("button[view-menu-toggle]").click();
            }
          }, 50);
        }
      }
    }
    get editable() {
      return isConnected() && (!this.project || !this.project.is_archived && (!this.view.is_public || canManageViews(this.project)));
    }
    get active() {
      let view;
      if (this.$state.includes("myWork")) {
        view = { id: parseInt(this.$state.params.viewId) };
        return this.view.id === parseInt(this.$state.params.viewId);
      }
      return this.$projectPage.isViewActive(this.view);
    }
    get showSharedIcon() {
      return this.view.share_token && (this.isMemberOfProject || canManageMembers(this.project));
    }
    activate() {
      if (!this.active) {
        $navigateToView(this.view);
      }
      this.openMenuIfUntitled();
    }
    delete() {
      viewStore.remove(this.view);
    }
  }
});

// public/app/ui/base/ng-components/sidebar/menus/utils.tsx
function getProjectColor(project) {
  return project?.color || project?.owner?.color || themeColor() || "#148a73";
}
function getProjectOrCardMenuItem(projectOrCard, showIcon = false) {
  const project = projectOrCard.project_id ? projectStore.getForCard(projectOrCard) : projectStore.tryGet(projectOrCard.id);
  return Object.assign({
    label: projectOrCard.title,
    classes: "menu-project-item",
    color: getProjectColor(project),
    action: () => {
      if (projectOrCard.parent_id && !projectOrCard.board_created) {
        return ngApp.$injector.get("cardModal").load(projectOrCard.id);
      }
      if (isProjectAccessible(project)) {
        $navigateToProject(project, projectOrCard);
        return;
      }
    },
    disabled: () => !isProjectAccessible(project)
  }, showIcon ? {
    icon: !projectOrCard.parent_id ? project.icon : void 0
  } : {});
}
function getProjectOrCardMenuItems(projectsOrCards = [], {
  grouped = false,
  showAddBtn = false,
  org: org2,
  team
}) {
  const items = [];
  if (grouped) {
    const portfolios = [];
    const projects = [];
    const boards = [];
    const cards = [];
    for (const projectOrCard of projectsOrCards) {
      if (projectOrCard.parent_id) {
        if (projectOrCard.board_created) {
          boards.push(projectOrCard);
        } else {
          cards.push(projectOrCard);
        }
        continue;
      }
      const project = projectOrCard.project_id ? projectStore.getForCard(projectOrCard) : projectStore.tryGet(projectOrCard.id);
      if (project.is_portfolio) {
        portfolios.push(projectOrCard);
        continue;
      }
      projects.push(projectOrCard);
    }
    const showSubheader = [portfolios, projects, boards, cards].filter((arr) => arr.length > 0).length > 1;
    if (projects.length) {
      if (showSubheader) {
        items.push({
          subheader: _4("Workspaces")
        });
      }
      items.push(...projects.map((projectOrCard) => {
        return getProjectOrCardMenuItem(projectOrCard, true);
      }));
      if (showAddBtn) {
        items.push({
          label: _4("New workspace"),
          icon: "plus",
          offline: false,
          action: () => {
            ngApp.$injector.get("$state").go("templates", {
              org: org2.id,
              team: team ? team.id : ""
            }, {
              inherit: false
            });
          }
        });
      }
      items.push({
        label: "--"
      });
    }
    if (portfolios.length) {
      if (showSubheader) {
        items.push({
          subheader: _4("Portfolios")
        });
      }
      items.push(...portfolios.map((projectOrCard) => {
        return getProjectOrCardMenuItem(projectOrCard, true);
      }));
      if (showAddBtn) {
        items.push({
          label: _4("New portfolio"),
          icon: "plus",
          offline: false,
          action: () => {
            ngApp.$injector.get("projectCreatorModal").open({
              org: org2,
              createPortfolio: true
            }).then((portfolio) => ngApp.$injector.get("$state").go("portfolio", {
              slug: portfolio.slug
            }));
          }
        });
      }
      items.push({
        label: "--"
      });
    }
    if (boards.length) {
      if (showSubheader) {
        items.push({
          subheader: _4("Sub-boards")
        });
      }
      items.push(...boards.map((projectOrCard) => {
        return getProjectOrCardMenuItem(projectOrCard, true);
      }), {
        label: "--"
      });
    }
    if (cards.length) {
      if (showSubheader) {
        items.push({
          subheader: _4("Cards")
        });
      }
      items.push(...cards.map((projectOrCard) => {
        return getProjectOrCardMenuItem(projectOrCard, true);
      }), {
        label: "--"
      });
    }
  } else {
    items.push(...projectsOrCards.map((projectOrCard) => {
      return getProjectOrCardMenuItem(projectOrCard, true);
    }));
  }
  return items;
}

// public/app/ui/base/ng-components/sidebar/menus/board-list.js
angular_default.module("kantree").service("navSidebarBoardListMenuFactory", class extends AngularClass {
  getItems(options2) {
    if (!options2) return [];
    const items = [];
    items.push({
      label: options2.label || _4("Boards"),
      icon: options2.icon
    }, { label: "--" });
    const allCards = options2.store ? options2.store.query({}, { sortBy: "title" }) : options2.items || [];
    items.push(...getProjectOrCardMenuItems(allCards, { grouped: options2.grouped }));
    if (items[items.length - 1].label === "--") {
      items.pop();
    }
    return items;
  }
  get(options2) {
    const menuOptions = {};
    if ((options2 || {}).store) {
      menuOptions.watch = (cb2, scope) => {
        let oldCount = options2.store.count();
        return offMany([
          options2.store.subscribe(options2.subscribeEvent || "changed", () => {
            const newCount = options2.store.count();
            if (newCount !== oldCount) {
              oldCount = newCount;
              cb2();
            }
          }, true),
          scope.$watch(() => themeColor() || "#148a73", cb2)
        ]);
      };
    }
    return {
      config: () => () => this.getItems(options2),
      options: menuOptions
    };
  }
});

// public/app/ui/base/ng-components/sidebar/menus/project-list.js
angular_default.module("kantree").service("navSidebarProjectListMenuFactory", class extends AngularClass {
  static $inject = ["$state"];
  getItems(options2) {
    const items = [];
    items.push({
      label: options2.label || _4("Workspaces"),
      icon: options2.icon
    }, { label: "--" });
    const allProjects = options2.store ? options2.store.query({}, { sortBy: "title" }) : options2.items || [];
    items.push(...getProjectOrCardMenuItems(allProjects, { grouped: options2.grouped, showSelected: options2.itemsActivable }));
    if (items[items.length - 1].label === "--") {
      items.pop();
    }
    if (options2.canCreateProjects) {
      items.push({
        label: _4("New workspace"),
        icon: "plus",
        action: () => this.$state.go("templates", {}, { inherit: false })
      });
    }
    return items;
  }
  getProjectColor(project) {
    return project?.color || themeColor() || "#148a73";
  }
  get(options2) {
    const menuOptions = {};
    if ((options2 || {}).store) {
      menuOptions.watch = (cb2, scope) => {
        return offMany([
          (options2 || {}).store.$watchAll(scope, cb2),
          scope.$watch(() => themeColor() || "#148a73", cb2)
        ]);
      };
    }
    return {
      config: () => () => this.getItems(options2),
      options: menuOptions
    };
  }
});

// public/app/ui/base/ng-components/sidebar/menus/project-views.js
angular_default.module("kantree").factory("projectViewsMenuFactory", [
  "navSidebar",
  function(navSidebar) {
    return {
      get: function(board, project) {
        var buildViewItem = function(view) {
          return {
            icon: view.icon || projectAppRegistry.get(view.mode)?.icon,
            label: view.name,
            action: function() {
              if (isScreensizeXS()) navSidebar.toggle(false);
              $navigateToProject(project, board, view);
            }
          };
        };
        var getItems = function() {
          var items = [];
          var store2 = viewStore.scopedByProject(project).scoped(() => (view) => {
            return !view.limit_to_ref || view.card_ref === null || view.card_ref === board.ref;
          });
          var sharedViews = store2.scoped({
            is_public: function(isPublic) {
              return isPublic;
            }
          }).query();
          if (sharedViews.length) {
            items.push({
              subheader: _4("Shared Views")
            });
            items.push.apply(items, sharedViews.map(function(view) {
              return buildViewItem(view);
            }));
          }
          var privateView = store2.scoped({
            is_public: function(isPublic) {
              return !isPublic;
            }
          }).query();
          if (privateView.length) {
            items.push({
              subheader: _4("Private Views")
            });
            items.push.apply(items, privateView.map(function(view) {
              return buildViewItem(view);
            }));
          }
          return items;
        };
        var watch = function(cb2, scope) {
          return viewStore.scopedByProject(project).scoped(() => (view) => {
            return !view.limit_to_ref || view.card_ref === null || view.card_ref === board.ref;
          }).$watchAll(scope, cb2);
        };
        return {
          config: function() {
            return function() {
              return getItems();
            };
          },
          options: {
            watch
          }
        };
      }
    };
  }
]);

// public/app/ui/base/ng-components/sidebar/menus/team.js
angular_default.module("kantree").service("navSidebarTeamMenuFactory", class extends AngularClass {
  static $inject = ["projectPage", "$state"];
  getItems({ org: org2, team, icon, store: store2, items }) {
    const menuItems = [];
    const permission = org2?.permission === 0 ? 0 : (
      // For now GUEST role on org prevent to have any permission on teams
      team && team.permission ? team.permission : org2?.permission || 0
    );
    menuItems.push({
      icon,
      label: org2.name + (team ? " / " + team.name : ""),
      small: team ? getRoleLabelForTeam(team) : getRoleLabelForOrg(org2),
      color: team?.color,
      action: permission > 0 ? () => {
        if (team) {
          this.$state.go("org.team.hub", { slug: org2.slug, teamSlug: team.slug });
        } else {
          this.$state.go("org.hub", { slug: org2.slug });
        }
      } : void 0
    }, { label: "--" });
    const allProjects = store2 ? store2.query({}, { sortBy: "title" }) : items || [];
    menuItems.push(...getProjectOrCardMenuItems(allProjects, {
      grouped: true,
      showSelected: true,
      showAddBtn: permission > 1 && !isOrgLocked(org2),
      org: org2,
      team
    }));
    if (org2 && !team && permission > 0) {
      menuItems.push({
        label: _4("Explore"),
        icon: "search",
        action: () => {
          this.$state.go("org.projects", { slug: org2.slug }, { inherit: false });
        }
      });
    }
    if (menuItems[menuItems.length - 1].label === "--") {
      menuItems.pop();
    }
    return menuItems;
  }
  get(options2) {
    const menuOptions = {};
    if (options2.store) {
      menuOptions.watch = (cb2, scope) => {
        return offMany([
          options2.store.$watchAll(scope, cb2),
          scope.$watch(() => themeColor() || "#148a73", cb2)
        ]);
      };
    }
    return {
      config: () => () => this.getItems(options2),
      options: menuOptions
    };
  }
});

// public/app/ui/base/ng-components/sidebar/nav-sidebar-service.js
angular_default.module("kantree").service("navSidebar", class extends angularClassMixin(AngularClass, EventedMixin) {
  static $inject = ["$compile", "$rootScope"];
  constructor(...args) {
    super(...args);
    this.initEventedMixin();
    this.collapsedLists = jsonLocalStorage.getItem("nav-sidebar:collapsed-lists") || [];
  }
  // COLLAPSING LISTS
  // prefix storageKey with '-' if you want to store expanded instead of collapsed
  hasListExpandedKey(listKey) {
    return listKey.charAt(0) === "-";
  }
  collapseList(listKey) {
    if (this.isListCollapsed(listKey)) return;
    if (this.hasListExpandedKey(listKey)) {
      this.collapsedLists = this.collapsedLists.filter((key2) => key2 !== listKey);
    } else {
      this.collapsedLists.push(listKey);
    }
    jsonLocalStorage.setItem("nav-sidebar:collapsed-lists", this.collapsedLists);
  }
  expandList(listKey) {
    if (!this.isListCollapsed(listKey)) return;
    if (this.hasListExpandedKey(listKey)) {
      this.collapsedLists.push(listKey);
    } else {
      this.collapsedLists = this.collapsedLists.filter((key2) => key2 !== listKey);
    }
    jsonLocalStorage.setItem("nav-sidebar:collapsed-lists", this.collapsedLists);
  }
  isListCollapsed(listKey) {
    if (this.hasListExpandedKey(listKey)) return this.collapsedLists.indexOf(listKey) === -1;
    return this.collapsedLists.indexOf(listKey) !== -1;
  }
  toggle(sidebarEl) {
    if ((sidebarEl || jquery_default("nav-sidebar")).hasClass("opened")) {
      this.close(sidebarEl);
    } else {
      this.open(sidebarEl);
    }
  }
  close(sidebarEl) {
    if (this.overlayElement) {
      this.overlayScope.$destroy();
      this.overlayElement.remove();
      this.overlayElement = null;
    }
    if (sidebarEl) {
      jquery_default(sidebarEl).removeClass("opened");
    } else {
      jquery_default("nav-sidebar").removeClass("opened");
    }
  }
  open(sidebarEl) {
    this.overlayScope = this.$rootScope.$new();
    this.overlayElement = this.$compile(`<nav-sidebar-overlay></nav-sidebar-overlay>`)(this.overlayScope);
    jquery_default(".page-container").prepend(this.overlayElement);
    if (sidebarEl) {
      jquery_default(sidebarEl).addClass("opened");
    } else {
      jquery_default("nav-sidebar").addClass("opened");
    }
  }
});
angular_default.module("kantree").run([
  "navSidebar",
  "$rootScope",
  function(navSidebar, $rootScope) {
    $rootScope.$on("$locationChangeSuccess", () => {
      if (isScreensizeXS()) {
        navSidebar.close();
      }
    });
  }
]);

// public/app/ui/base/ng-components/sidebar/nav-sidebar.js
angular_default.module("kantree").component("navSidebar", {
  template: `
    <button class="nav-sidebar-toggle-btn hidden-xs js-toggle-sidebar" type="button"
      ng-if="::$ctrl.withToggle" ng-click="$ctrl.toggleCollapse()"><i class="bi-chevron-left"></i></button>
    <div class="nav-sidebar-inner">
      <div class="nav-sidebar-header" ng-if="$ctrl.headerItems.length">
        <div ng-repeat="item in $ctrl.headerItems" ng-if="!item.enabled || item.enabled()">
          <dynamic-directive directive="{{item.component}}" options="item.options"
            mode="{{$ctrl.mode}}" active="item.active && !!item.active()" ng-attr-id="{{item.id || ''}}">
          </dynamic-directive>
        </div>
      </div>
      <fake-nav-sidebar show-header="!$ctrl.headerItems.length"></fake-nav-sidebar>
      <div class="nav-sidebar-fixed-content" ng-if="$ctrl.fixedContentItems.length">
        <div ng-repeat="item in $ctrl.fixedContentItems" ng-if="!item.enabled || item.enabled()">
          <dynamic-directive directive="{{item.component}}" options="item.options"
            mode="{{$ctrl.mode}}" active="item.active && !!item.active()" ng-attr-id="{{item.id || ''}}">
          </dynamic-directive>
        </div>
      </div>
      <div class="nav-sidebar-content" ng-if="$ctrl.contentItems.length || $ctrl.footerItems.length" data-simplebar>
        <div ng-repeat="item in $ctrl.contentItems" ng-if="!item.enabled || item.enabled()">
          <dynamic-directive directive="{{item.component}}" options="item.options"
            mode="{{$ctrl.mode}}" active="item.active && !!item.active()" ng-attr-id="{{item.id || ''}}">
          </dynamic-directive>
        </div>
      </div>
      <div class="nav-sidebar-footer" ng-if="$ctrl.footerItems.length">
        <div ng-repeat="item in $ctrl.footerItems" ng-if="!item.enabled || item.enabled()">
          <dynamic-directive directive="{{item.component}}" options="item.options"
            mode="{{$ctrl.mode}}" active="item.active && !!item.active()" ng-attr-id="{{item.id || ''}}">
          </dynamic-directive>
        </div>
      </div>
    </div>
  `,
  bindings: {
    config: "<",
    mode: "@?",
    withToggle: "<?",
    collapsable: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope", "hotkeys", "$interval", "$timeout"];
    $onChanges(changes) {
      const configChanged2 = changes.config && !changes.config.isFirstChange();
      if (configChanged2) {
        this.refresh();
      }
    }
    $postLink() {
      this.refresh();
      if (this.collapsable) {
        this.$element.find(".nav-sidebar-inner").on("mouseenter", (event2) => {
          if (this.$element.hasClass("collapsed") && !this.mouseOn) {
            this.mouseOn = true;
            this.$element.find(".nav-sidebar-inner").on("mouseleave", onSidebarMouseLeave);
            this.timeoutOpenPromise = this.$timeout(() => {
              this.$element.toggleClass("hovered", true);
            }, 200, false);
            this.timeoutOpenPromise.catch(() => {
            }).finally(() => {
              this.timeoutOpenPromise = null;
            });
          }
        });
        const onSidebarMouseLeave = (event2) => {
          if (jquery_default(event2.relatedTarget).closest(".nav-sidebar-inner").length) return;
          this.mouseOn = false;
          this.$element.find(".nav-sidebar-inner").off("mouseleave", onSidebarMouseLeave);
          if (jquery_default(event2.relatedTarget).closest(".js-toggle-sidebar").length) {
            this.$element.find(".js-toggle-sidebar").on("mouseleave", onSidebarToggleMouseLeave);
          } else {
            this.$element.toggleClass("hovered", false);
            if (this.timeoutOpenPromise) this.$timeout.cancel(this.timeoutOpenPromise);
          }
        };
        const onSidebarToggleMouseLeave = (event2) => {
          this.$element.find(".js-toggle-sidebar").off("mouseleave", onSidebarToggleMouseLeave);
          if (!jquery_default(event2.relatedTarget).closest(".nav-sidebar-inner").length) {
            this.$element.toggleClass("hovered", false);
            if (this.timeoutOpenPromise) this.$timeout.cancel(this.timeoutOpenPromise);
          }
        };
      }
      if (!isScreensizeXS()) {
        this.$element.addClass("opened");
        this.$element.removeClass("collapsed");
      }
      this.$scope.$on("screensize:changed", () => {
        if (isScreensizeXS()) {
          this.$element.removeClass("opened");
          this.$element.removeClass("collapsed");
        } else {
          this.$element.addClass("opened");
        }
      });
      if (typeof ResizeObserver === "undefined") return;
      let contentEl, innerScrollContentEl, outerScrollContentEl, innerHeight2, outerHeight;
      this.resizeObserver = new ResizeObserver((entries2) => {
        for (let entry of entries2) {
          if (entry.target === innerScrollContentEl) {
            innerHeight2 = entry.contentRect.height;
          }
          if (entry.target === outerScrollContentEl) {
            outerHeight = entry.contentRect.height;
          }
          if (outerHeight && innerHeight2) {
            jquery_default(contentEl).toggleClass("scrollable", innerHeight2 > outerHeight);
          }
        }
      });
      this.onScroll = () => jquery_default(contentEl).toggleClass("scrolled", !!outerScrollContentEl.scrollTop);
      this.initOuterInnerElPromise = this.$interval(() => {
        contentEl = this.$element.find(".nav-sidebar-content")[0];
        outerScrollContentEl = this.$element.find(".nav-sidebar-content .simplebar-content-wrapper")[0];
        innerScrollContentEl = this.$element.find(".nav-sidebar-content .simplebar-content")[0];
        if (contentEl && outerScrollContentEl && innerScrollContentEl) {
          this.resizeObserver.observe(innerScrollContentEl);
          this.resizeObserver.observe(outerScrollContentEl);
          jquery_default(outerScrollContentEl).on("scroll", this.onScroll);
          this.$interval.cancel(this.initOuterInnerElPromise);
        }
      }, 100, 40);
      this.initOuterInnerElPromise.then(() => {
        console.warn("nav-view resize can't be observed");
      }).catch(() => {
      }).finally(() => {
        this.initOuterInnerElPromise = null;
      });
      this.$scope.$on("$destroy", () => {
        jquery_default(outerScrollContentEl).off("scroll", this.onScroll);
      });
    }
    refresh() {
      this.headerItems = this.formatItems((this.config || {}).header || []);
      this.fixedContentItems = this.formatItems((this.config || {}).fixedContent || []);
      this.contentItems = this.formatItems((this.config || {}).content || []);
      this.footerItems = this.formatItems((this.config || {}).footer || []);
      (this.hotkeys || []).forEach((hotkey) => {
        this.$hotkeys.del(hotkey);
      });
      this.hotkeys = [];
      if (this.collapsable) {
        this.addHotkey({
          combo: ["shift+/", "mod+/"],
          description: _4("Toggle sidebar"),
          callback: () => {
            this.toggleCollapse();
          }
        });
      }
      [...this.headerItems, ...this.contentItems, ...this.footerItems].filter((item) => !!item.hotkey).forEach((item) => {
        if (Array.isArray(item.hotkey)) {
          item.hotkey.forEach((hotkey) => this.addHotkey(hotkey));
        } else {
          this.addHotkey(item.hotkey);
        }
      });
      if (this.config && (this.fixedContentItems.length || this.contentItems.length || this.footerItems.length)) {
        this.$element.find("fake-nav-sidebar").hide();
      }
    }
    formatItems(items) {
      return items.map((item) => {
        if (item.type) {
          item.component = `nav-sidebar-${item.type}`;
        }
        return item;
      }).filter((item) => !!item.component);
    }
    addHotkey(hotkey) {
      hotkey = this.$hotkeys.add(hotkey);
      this.hotkeys.push(hotkey);
    }
    toggleCollapse() {
      this.$element.toggleClass("hovered", false);
      this.$element.toggleClass("collapsed");
    }
    $onDestroy() {
      (this.hotkeys || []).forEach((hotkey) => {
        this.$hotkeys.del(hotkey);
      });
      if (this.initOuterInnerElPromise) {
        this.$interval.cancel(this.initOuterInnerElPromise);
        this.initOuterInnerElPromise = null;
      }
      if (this.resizeObserver) {
        this.resizeObserver.disconnect();
      }
      if (this.timeoutOpenPromise) this.$timeout.cancel(this.timeoutOpenPromise);
    }
  }
});
angular_default.module("kantree").component("fakeNavSidebar", {
  bindings: {
    showHeader: "<"
  },
  template: `
    <div class="nav-sidebar-header" ng-show="$ctrl.showHeader">
      <div class="fake-nav-sidebar-header"></div>
    </div>
    <div class="nav-sidebar-content">
      <div class="fake-nav-sidebar-list mod-shiny">
        <div class="fake-nav-sidebar-list-header"></div>
        <div class="fake-nav-sidebar-list-content">
          <div class="fake-nav-sidebar-item item-1">
            <div class="fake-nav-sidebar-item-color"></div>
            <div class="fake-nav-sidebar-item-title"></div>
          </div>
          <div class="fake-nav-sidebar-item item-2">
            <div class="fake-nav-sidebar-item-color"></div>
            <div class="fake-nav-sidebar-item-title"></div>
          </div>
        </div>
      </div>
      <div class="fake-nav-sidebar-list mod-shiny">
        <div class="fake-nav-sidebar-list-header"></div>
        <div class="fake-nav-sidebar-list-content">
          <div class="fake-nav-sidebar-item item-1">
            <div class="fake-nav-sidebar-item-color"></div>
            <div class="fake-nav-sidebar-item-title"></div>
          </div>
          <div class="fake-nav-sidebar-item item-2">
            <div class="fake-nav-sidebar-item-color"></div>
            <div class="fake-nav-sidebar-item-title"></div>
          </div>
        </div>
      </div>
    </div>
  `
});
angular_default.module("kantree").component("navSidebarOverlay", {
  controller: class extends AngularClass {
    static $inject = ["$element", "$injector"];
    $postLink() {
      this.$element.on("click touch", () => {
        this.$injector.get("navSidebar").toggle();
      });
    }
  }
});

// public/app/ui/base/ng-filters/avatarUrl.js
angular_default.module("kantree").filter("avatarUrl", [
  function() {
    return avatarUrl;
  }
]);
angular_default.module("kantree").filter("userAvatarUrl", [
  function() {
    return userAvatarUrl;
  }
]);

// public/app/ui/base/ng-filters/iconclass.js
init_icons();
angular_default.module("kantree").filter("iconClass", [
  function() {
    return iconClass;
  }
]);

// public/app/ui/card/ng-components/browser-tile.js
angular_default.module("kantree").component("cardBrowserTile", {
  templateUrl: "/static/app/ui/card/ng-components/templates/browser-tile.html",
  bindings: {
    card: "<",
    selectable: "<?",
    selectedCardsIds: "<?",
    onSelect: "&?",
    showSelectButton: "<?",
    selectButtonLabel: "<?",
    showProject: "<?",
    showChildren: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "stylesheetManager"];
    get fullDisplay() {
      return this.card.created_by;
    }
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.refreshSelected();
      if (!this.card.created_by) {
        return;
      }
      this.model = getCardCompositeModel(this.card);
      if (this.model && this.model.model.card_color) {
        const tinyCardColor = tinycolor(this.model.model.card_color);
        const themeName2 = "card-model-theme-" + tinyCardColor.toHex();
        this.$stylesheetManager.createTheme(
          themeName2,
          tinyCardColor.toHexString(),
          "/static/app/ui/card-models/ng-components/templates/card.css.html"
        );
        this.$element.addClass(themeName2);
      }
      this.project = projectStore.getForCard(this.card);
      this.state = cardStateStore.getForCard(this.card);
      this.refreshParents();
      this.linkTooltip = this.card.broken_link ? _4("Broken link") : this.card.link_has_own_attributes ? _4("This card points to another card") : _4("This card is a mirrored card");
    }
    $onChanges(changes) {
      if (changes.showProject && !changes.showProject.isFirstChange()) {
        this.refreshParents();
      }
      if (changes.selectedCardsIds && !changes.selectedCardsIds.isFirstChange()) {
        this.refreshSelected();
      }
    }
    refreshParents() {
      this.parents = (this.showProject ? [this.project.title] : []).concat(this.card.path.slice(1).map((p4) => p4.title)).join(" / ");
    }
    refreshSelected() {
      this.selected = this.selectedCardsIds && this.selectedCardsIds.includes(this.card.id);
    }
    select(card) {
      this.onSelect({ $card: card });
    }
    toggleChildrenList() {
      this.childrenToggleState = !this.childrenToggleState;
    }
  }
});

// public/app/ui/card/ng-components/browser.js
angular_default.module("kantree").component("cardBrowser", {
  templateUrl: "/static/app/ui/card/ng-components/templates/browser.html",
  bindings: {
    projects: "<",
    defaultSelectedCard: "<?",
    withLeaves: "@",
    withLinks: "@",
    withSaveOption: "@",
    defaultIcon: "@",
    disableSearch: "<",
    onChanged: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.searching = false;
      this.results = null;
      this.resultsCards = null;
      this.resultsOptionsVisible = false;
      this.selectedCardsIds = null;
      this.groupByItems = [
        { id: "nothing", label: _4("Nothing") },
        { id: "project", label: _4("Workspace"), active: true }
      ];
      this.sortByItems = [
        { id: "title", label: _4("A-Z"), active: true },
        { id: "ref", label: _4("Reference") }
      ];
      this.refreshGroupByMenuSpec();
      this.refreshSortByMenuSpec();
    }
    get resultsCountLabel() {
      if (this.activeGroupBy.id === "project") {
        return _4("{cardsCount} card(s) in {projectsCount} workspace(s)", {
          cardsCount: this.resultsCards.length,
          projectsCount: this.results.length
        });
      }
      return _4("{cardsCount} card(s)", {
        cardsCount: this.resultsCards.length
      });
    }
    get activeGroupBy() {
      return this.groupByItems.find((gb) => gb.active);
    }
    get activeSortBy() {
      return this.sortByItems.find((sb) => sb.active);
    }
    refreshGroupByMenuSpec() {
      this.groupByMenuSpec = {
        config: this.groupByItems.map((gb) => {
          return {
            label: gb.label,
            noCloseAfterAction: true,
            selected: () => gb.active === true,
            action: () => {
              if (gb.active) return;
              this.activeGroupBy.active = false;
              gb.active = true;
              this.refreshGroupByMenuSpec();
              this.refreshSearchResults(this.resultsCards);
            }
          };
        })
      };
    }
    refreshSortByMenuSpec() {
      this.sortByMenuSpec = {
        config: this.sortByItems.map((sb) => {
          return {
            label: sb.label,
            noCloseAfterAction: true,
            enableActionOnselected: true,
            selected: () => sb.active === true,
            action: () => {
              if (sb.active) {
                sb.reverse = !sb.reverse;
                this.refreshSortByMenuSpec();
                this.refreshSearchResults(this.resultsCards);
                return;
              }
              const activeSortBy = this.activeSortBy;
              activeSortBy.reverse = false;
              activeSortBy.active = false;
              sb.active = true;
              this.refreshSortByMenuSpec();
              this.refreshSearchResults(this.resultsCards);
            },
            icon: sb.active ? sb.reverse ? "long-arrow-up" : "long-arrow-down" : null
          };
        }),
        options: {
          classes: "menu-panel-card-browser-sort-by"
        }
      };
    }
    refreshSearchResults(cards) {
      const projectIndex = {};
      if (this.activeGroupBy.id === "project") {
        this.results = cards.reduce((accu, card) => {
          const project = projectStore.getForCard(card);
          if (projectIndex[project.id]) {
            projectIndex[project.id].cards.push(card);
          } else {
            const resultsGroup = {
              id: "project-" + project.id,
              title: project.title,
              cards: [card]
            };
            accu.push(resultsGroup);
            projectIndex[project.id] = resultsGroup;
          }
          return accu;
        }, []);
        this.results.sort((a3, b3) => a3.id - b3.id);
      } else {
        this.results = [{ cards }];
      }
      this.results.forEach((resultsGroup) => {
        resultsGroup.cards.sort((a3, b3) => {
          const direction = this.activeSortBy.reverse ? -1 : 1;
          if (this.activeSortBy.id === "title") {
            return direction * a3.title.localeCompare(b3.title);
          }
          return direction * (a3.ref - b3.ref);
        });
      });
      this.resultsCards = cards;
    }
    search() {
      this.searching = true;
      this.$q.when(searchCards(this.query.trim(), null, null, { ignoreErrorHandlers: true }), (cards) => {
        this.searching = false;
        this.refreshSearchResults(cards);
        if (cards.length) {
          this.select(this.results[0].cards[0]);
        } else {
          this.select(null);
        }
      }, () => {
        this.searching = false;
        this.results = null;
        this.resultsCards = null;
        this.resultsOptionsVisible = false;
        this.select(null);
      });
    }
    clearQuery() {
      this.query = null;
      this.$element.find(">form>input").focus();
    }
    clearResults() {
      this.select(null);
      this.results = null;
      this.resultsCards = null;
      this.resultsOptionsVisible = false;
      this.clearQuery();
    }
    select(card, project) {
      if (card && card.is_archived) return;
      this.selectedCardsIds = card ? [card.id] : null;
      if (!project && card && card.id !== "new") {
        project = projectStore.getForCard(card);
      }
      this.onChanged({ project: project || null, card });
    }
  }
});

// public/app/ui/editors/recurrence-editor/utils.js
function buildTimeInMinutesWithModifer(timeInMinutes) {
  if (timeInMinutes < 0) {
    return ["-", 1440 + timeInMinutes];
  } else if (timeInMinutes >= 1440) {
    return ["+", timeInMinutes - 1440];
  }
  return ["", timeInMinutes];
}
function formatTimeFromUTCToLocal(time3) {
  const utcOffsetInMinutes = moment_default().utcOffset();
  time3 = time3.split(":").map((t3) => parseInt(t3, 10));
  const utcTimeInMinutes = time3[0] * 60 + time3[1] + utcOffsetInMinutes;
  const [modifier, timeInMinutes] = buildTimeInMinutesWithModifer(utcTimeInMinutes);
  time3[0] = Math.trunc(timeInMinutes / 60);
  time3[1] = timeInMinutes % 60;
  return modifier + time3.map((t3) => convertTimeIntToString(t3)).join(":");
}
function formatTimeFromLocalToUTC(time3) {
  const utcOffsetInMinutes = moment_default().utcOffset();
  time3 = time3.split(":").map((t3) => parseInt(t3, 10));
  const utcTimeInMinutes = time3[0] * 60 + time3[1] - utcOffsetInMinutes;
  const [modifier, timeInMinutes] = buildTimeInMinutesWithModifer(utcTimeInMinutes);
  time3[0] = Math.trunc(timeInMinutes / 60);
  time3[1] = timeInMinutes % 60;
  return modifier + time3.map((t3) => convertTimeIntToString(t3)).join(":");
}
function getDayModifierFromConvertedTime(time3) {
  const firstChar = time3.charAt(0);
  if (firstChar === "+") {
    return 1;
  } else if (firstChar === "-") {
    return -1;
  } else {
    return 0;
  }
}
function buildWeekdaysWithModifier(weekdays, modifier) {
  return weekdays.map((weekdaysIdx) => {
    weekdaysIdx = parseInt(weekdaysIdx, 10) + modifier;
    if (weekdaysIdx < 0) {
      return 7 + weekdaysIdx;
    } else if (weekdaysIdx > 6) {
      return weekdaysIdx - 7;
    }
    return weekdaysIdx;
  });
}
function buildMonthdaysWithModifier(monthdays, modifier) {
  return monthdays.map((monthday) => {
    monthday = parseInt(monthday, 10) + modifier;
    if (monthday < 1) {
      return 31 + monthday;
    } else if (monthday > 31) {
      return monthday - 31;
    }
    return monthday;
  });
}
function formatWeekDayToClientLocale(weekdays) {
  const firstDayOfWeekClient = getFirstDayOfWeek();
  const firstDayOfWeekServer = 1;
  return weekdays.map((weekday) => ((weekday + firstDayOfWeekServer - firstDayOfWeekClient) % 7 + 7) % 7);
}
function formatWeekDayToServerLocale(weekdays) {
  const firstDayOfWeekClient = getFirstDayOfWeek();
  const firstDayOfWeekServer = 1;
  return weekdays.map((weekday) => ((weekday - firstDayOfWeekServer + firstDayOfWeekClient) % 7 + 7) % 7);
}
function convertTimeIntToString(time3) {
  if (time3 < 10) {
    return "0" + time3;
  } else {
    return time3.toString();
  }
}
function parseTime(time3) {
  const parsed = {};
  const isHours24Selector = isLocaleDisplayAmPm();
  time3 = time3.split(":");
  parsed.minutes = time3[1];
  if (parseInt(time3[0], 10) > 11) {
    if (isHours24Selector) {
      parsed.amPm = "PM";
      time3[0] = parseInt(time3[0], 10) - 12;
    }
    parsed.hour = convertTimeIntToString(time3[0]);
  } else {
    if (isHours24Selector) {
      parsed.amPm = "AM";
    }
    parsed.hour = time3[0];
  }
  return parsed;
}
function parseRecurrenceString(recurrence, time3) {
  let parsed = {
    frequency: "weekly",
    monthdays: [1],
    weekdays: [0],
    hour: "00",
    minutes: "00",
    amPm: "AM",
    customDays: 7,
    annualMonth: 1
  };
  let dayModifier = 0;
  if (time3 === null) {
    time3 = "00:00:00";
  }
  if (time3) {
    time3 = formatTimeFromUTCToLocal(time3);
    dayModifier = getDayModifierFromConvertedTime(time3);
    if (dayModifier) {
      time3 = time3.slice(1);
    }
    parsed = Object.assign(parsed, parseTime(time3));
  }
  if (!recurrence) {
    return parsed;
  }
  if (recurrence.indexOf("hourly") === 0) {
    parsed.frequency = "hourly";
  } else if (recurrence === "daily") {
    parsed.frequency = "daily";
    parsed.weekdays = [];
  } else if (recurrence.indexOf("weekly") === 0) {
    parsed.frequency = "weekly";
    parsed.weekdays = recurrence.replace(/weekly:/g, "").split(",");
    parsed.weekdays = buildWeekdaysWithModifier(parsed.weekdays, dayModifier);
    parsed.weekdays = formatWeekDayToClientLocale(parsed.weekdays);
  } else if (recurrence.indexOf("monthly") === 0) {
    parsed.frequency = "monthly";
    parsed.monthdays = recurrence.replace(/monthly:/g, "").split(",");
    parsed.monthdays = buildMonthdaysWithModifier(parsed.monthdays, dayModifier);
  } else if (recurrence === "quarterly") {
    parsed.frequency = "quarterly";
  } else if (recurrence.indexOf("annually:") === 0) {
    parsed.frequency = "annually";
    parsed.annualMonth = parseInt(recurrence.replace("annually:", ""), 10);
  } else if (recurrence.indexOf("every:") === 0) {
    parsed.frequency = "custom";
    parsed.customDays = parseInt(recurrence.replace("every:", ""), 10);
  }
  return parsed;
}
function compressRecurrence(recurrence) {
  let dayModifier = 0;
  let time3 = null;
  let schedule = recurrence.frequency;
  if (schedule !== "hourly") {
    let hour = recurrence.hour;
    if (recurrence.amPm === "PM") {
      hour = parseInt(hour, 10) + 12;
    }
    time3 = formatTimeFromLocalToUTC([hour, recurrence.minutes, "00"].join(":"));
    dayModifier = getDayModifierFromConvertedTime(time3);
    if (dayModifier) {
      time3 = time3.slice(1);
    }
  }
  if (recurrence.frequency === "hourly") {
    schedule = "hourly:00";
  } else if (recurrence.frequency === "weekly") {
    schedule = buildWeekdaysWithModifier(recurrence.weekdays, dayModifier);
    schedule = formatWeekDayToServerLocale(schedule);
    schedule = schedule.map((weekday) => "weekly:" + weekday).join(",");
  } else if (recurrence.frequency === "monthly") {
    schedule = buildMonthdaysWithModifier(recurrence.monthdays, dayModifier);
    schedule = schedule.map((monthday) => "monthly:" + monthday).join(",");
  } else if (recurrence.frequency === "quarterly") {
    schedule = "quarterly";
  } else if (recurrence.frequency === "annually") {
    schedule = "annually:" + (recurrence.annualMonth || 1);
  } else if (recurrence.frequency === "custom") {
    schedule = "every:" + (recurrence.customDays || 7);
  }
  return { schedule, time: time3 };
}
function buildRecapFrequency(recurrence) {
  if (recurrence.frequency === "daily") {
    return _4("day");
  } else if (recurrence.frequency === "weekly") {
    return _4("week");
  } else if (recurrence.frequency === "monthly") {
    return _4("month");
  } else if (recurrence.frequency === "quarterly") {
    return _4("quarter");
  } else if (recurrence.frequency === "annually") {
    return _4("year");
  } else if (recurrence.frequency === "custom") {
    return _n("{count} day", "{count} days", recurrence.customDays, { count: recurrence.customDays });
  }
}
function formatEnum(recapEnum) {
  if (recapEnum.length <= 1) {
    return recapEnum.join(", ");
  } else {
    return recapEnum.slice(0, -1).join(", ") + " " + _4("and") + " " + recapEnum[recapEnum.length - 1];
  }
}
function buildRecapMonthdays(recurrence) {
  const monthdays = recurrence.monthdays.sort((a3, b3) => a3 - b3).map((monthday) => "<span>" + monthday + "</span>");
  return formatEnum(monthdays);
}
function buildRecapWeekdays(recurrence) {
  const weekdays = moment_default.weekdays(true).filter((weekday, idx) => recurrence.weekdays.indexOf(idx) !== -1).map((weekday) => "<span>" + capitalize(weekday) + "</span>");
  return formatEnum(weekdays);
}
function buildRecapHour(recurrence) {
  if (isLocaleDisplayAmPm()) {
    return [recurrence.hour, recurrence.minutes].join(":") + " " + recurrence.amPm;
  } else {
    return [recurrence.hour, recurrence.minutes].join(":");
  }
}
function buildRecapAnnualMonth(recurrence) {
  const monthName = moment_default.months()[recurrence.annualMonth - 1];
  return "<span>" + capitalize(monthName) + "</span>";
}
function buildRecap(recurrence) {
  let recap = _4("every <span>{frequency}</span>", {
    frequency: buildRecapFrequency(recurrence)
  });
  if (recurrence.frequency === "monthly") {
    recap += _4(" on {monthdays}", {
      monthdays: buildRecapMonthdays(recurrence)
    });
  }
  if (recurrence.frequency === "weekly") {
    recap += _4(" on {weekdays}", {
      weekdays: buildRecapWeekdays(recurrence)
    });
  }
  if (recurrence.frequency === "annually") {
    recap += _4(" in {month}", {
      month: buildRecapAnnualMonth(recurrence)
    });
  }
  recap += _4(" at <span>{hour}</span>", {
    hour: buildRecapHour(recurrence)
  });
  return recap;
}

// public/app/actions/recurring-card.ts
function parseRecurringCardString(task) {
  return {
    ...parseRecurrenceString(task.recurrence, task.recurrence_time),
    groups: task.groups.reduce((accu, id) => {
      const group2 = cardGroupStore.tryGet(id);
      return group2 ? accu.concat(group2) : accu;
    }, [])
  };
}
function compressRecurringCard(task) {
  return {
    ...compressRecurrence(task),
    groups: (task.groups || []).map((g3) => g3.id)
  };
}
async function addRecurringCard(project, template3, data2) {
  let task = Object.assign({ project_id: project.id }, compressRecurringCard(data2));
  try {
    task = await api_default.project_recurring_cards.create_recurring_card.post({
      card_id: template3.id,
      project_id: task.project_id,
      group_id: task.groups || null,
      recurrence: task.schedule,
      recurring_time: task.time
    });
    await getOrLoadCard(task.template_id);
    return recurringCardStore.upsert(task);
  } catch (r3) {
    return autoCatchAsRequestErrorDialog([403, 409, 412])(r3);
  }
}
async function updateRecurringCard(project, task, data2) {
  task = Object.assign({ project_id: project.id }, task, compressRecurringCard(data2));
  try {
    task = await api_default.project_recurring_cards.update_recurring_card.put({
      recurring_id: task.id,
      project_id: task.project_id,
      group_id: task.groups || null,
      recurrence: task.schedule,
      recurring_time: task.time
    });
    return recurringCardStore.upsert(task);
  } catch (r3) {
    return autoCatchAsRequestErrorDialog([403, 409, 412])(r3);
  }
}
async function deleteRecurringCard(project, task) {
  await api_default.project_recurring_cards.remove_recurring_card.delete({ project_id: project.id, recurring_id: task.id });
  cardStore.removeById(task.template_id);
  recurringCardStore.remove(task);
}
function getRecurringCardEditorMenu(task, isEditing) {
  return {
    config: () => {
      return () => {
        return [{
          component: "recurring-card-editor-menu-component",
          params: { task }
        }];
      };
    },
    options: {
      title: isEditing ? _4("Edit recurring card") : _4("Make recurring card")
    }
  };
}

// public/app/ui/card/ng-components/recurring-card-editor.js
angular_default.module("kantree").component("recurringCardEditor", {
  bindings: {
    task: "<",
    onUpdate: "&",
    onSave: "&",
    onCancel: "&",
    onDelete: "&"
  },
  templateUrl: "/static/app/ui/card/ng-components/templates/recurring-card-editor.html",
  controller: [
    "$scope",
    "$sce",
    "$sanitize",
    "$q",
    function($scope2, $sce, $sanitize, $q) {
      var $ctrl = this;
      function buildRecapGroups(recurrence) {
        var groups = recurrence.groups.map((group2) => buildRecapGroup(group2));
        if (groups.length <= 1) {
          return groups.join(", ");
        } else {
          return groups.slice(0, -1).join(" ,  ") + " " + _4("and") + " " + groups[groups.length - 1];
        }
      }
      function buildRecapGroup(group2) {
        let bgColor = "#eee";
        let fgColor = "#333";
        if (group2.color) {
          bgColor = group2.color;
          fgColor = textColor(group2.color, null, null);
        }
        return `<span class="group"
          style="'background-color': ${bgColor};'color': ${fgColor};">
            ${$sanitize(group2.title)}</span>`;
      }
      function buildRecurringCardRecap(task) {
        let { schedule, time: time3 } = compressRecurrence(task);
        task = Object.assign({}, task, parseRecurringCardString({
          recurrence: schedule,
          groups: [],
          recurrence_time: time3
        }));
        let recap = buildRecap(task);
        if (task.groups && task.groups.length) {
          recap += _4(" in {groups}", {
            groups: buildRecapGroups(task)
          });
        }
        return $sce.trustAsHtml(recap);
      }
      $ctrl.updateEditor = function() {
        $ctrl.updateRecap();
        $ctrl.onUpdate();
      };
      $ctrl.updateRecap = function() {
        $ctrl.recap = $sce.trustAsHtml(_4("This creates a card {recap}", {
          recap: buildRecurringCardRecap($ctrl.selected)
        }));
      };
      $ctrl.isFrequencySelected = function(frequency) {
        return $ctrl.selected.frequency === frequency;
      };
      $ctrl.selectFrequency = function(frequency) {
        $ctrl.selected.frequency = frequency;
        if ($ctrl.selected.frequency === "daily") {
          $ctrl.selected.weekdays = [];
        } else if ($ctrl.selected.frequency === "weekly") {
          $ctrl.selected.weekdays = [0];
        } else if ($ctrl.selected.frequency === "custom") {
          if (!$ctrl.selected.customDays || $ctrl.selected.customDays < 1) {
            $ctrl.selected.customDays = 7;
          }
        }
        $ctrl.updateEditor();
      };
      $ctrl.handleCustomDaysChange = function() {
        if ($ctrl.selected.customDays < 1) {
          $ctrl.selected.customDays = 1;
        }
        $ctrl.updateEditor();
      };
      $ctrl.handleAnnualMonthChange = function() {
        $ctrl.updateEditor();
      };
      $ctrl.isMonthdaySelected = function(monthday) {
        return $ctrl.selected.monthdays.indexOf(monthday) !== -1;
      };
      $ctrl.isSelectedMonthdaysPotentiallyUnavailable = function() {
        return $ctrl.selected.monthdays.some(function(monthday) {
          return [29, 30, 31].indexOf(monthday) !== -1;
        });
      };
      $ctrl.toggleMonthdays = function(selectedMonthday) {
        if ($ctrl.selected.monthdays.indexOf(selectedMonthday) !== -1) {
          $ctrl.selected.monthdays = $ctrl.selected.monthdays.filter(function(monthday) {
            return monthday !== selectedMonthday;
          });
        } else {
          $ctrl.selected.monthdays.push(selectedMonthday);
        }
        $ctrl.updateEditor();
      };
      $ctrl.isWeekdaySelected = function(weekdayIdx) {
        return $ctrl.selected.weekdays.indexOf(weekdayIdx) !== -1;
      };
      $ctrl.toggleWeekdays = function(weekdayIdx) {
        if ($ctrl.selected.weekdays.indexOf(weekdayIdx) !== -1) {
          $ctrl.selected.weekdays = $ctrl.selected.weekdays.filter(function(weekday) {
            return weekday !== weekdayIdx;
          });
        } else {
          $ctrl.selected.weekdays.push(weekdayIdx);
        }
        $ctrl.updateEditor();
      };
      $ctrl.isAmPmSelected = function(amPm) {
        return $ctrl.selected.amPm === amPm;
      };
      $ctrl.selectAmPm = function(amPm) {
        $ctrl.selected.amPm = amPm;
        $ctrl.updateEditor();
      };
      $ctrl.handleTimeSelect = function() {
        $ctrl.updateEditor();
      };
      $ctrl.handleGroupSelect = function(groups) {
        $ctrl.selected.groups = groups;
        $ctrl.updateEditor();
      };
      $ctrl.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        $ctrl.frequencies = [{
          name: "daily",
          label: _4("Daily")
        }, {
          name: "weekly",
          label: _4("Weekly")
        }, {
          name: "monthly",
          label: _4("Monthly")
        }, {
          name: "quarterly",
          label: _4("Quarterly")
        }, {
          name: "annually",
          label: _4("Annually")
        }, {
          name: "custom",
          label: _4("Custom")
        }];
        $ctrl.monthdays = Array.apply(null, Array(31)).map(function(_5, i3) {
          return i3 + 1;
        });
        $ctrl.months = moment_default.months().map(function(name2, idx) {
          return { value: idx + 1, label: name2 };
        });
        $ctrl.weekdays = moment_default.weekdaysMin(true);
        var hours = [
          "00",
          "01",
          "02",
          "03",
          "04",
          "05",
          "06",
          "07",
          "08",
          "09",
          "10",
          "11"
        ];
        var hours24 = hours.concat([
          "12",
          "13",
          "14",
          "15",
          "16",
          "17",
          "18",
          "19",
          "20",
          "21",
          "22",
          "23"
        ]);
        $ctrl.isHours24Selector = !isLocaleDisplayAmPm();
        $ctrl.hours = $ctrl.isHours24Selector ? hours24 : hours;
        $ctrl.minutes = ["00", "15", "30", "45"];
        $ctrl.amPm = ["AM", "PM"];
        if (!$ctrl.task || !$ctrl.task.template_id) {
          throw new Error("Workspace Task Editor Error: You should pass a task obj with a template_id");
        }
        $ctrl.template = cardStore.tryGet($ctrl.task.template_id);
        $ctrl.project = projectStore.getForCard($ctrl.template);
        $ctrl.board = cardStore.tryGet($ctrl.template.parent_id);
        $ctrl.selected = parseRecurringCardString($ctrl.task);
        $ctrl.updateEditor();
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.task && !changes.task.isFirstChange()) {
          $ctrl.selected = parseRecurringCardString($ctrl.task);
          $ctrl.updateEditor();
        }
      };
      $ctrl.cancel = function() {
        $ctrl.onCancel({ $selected: $ctrl.selected });
      };
      $ctrl.isCreating = function() {
        return typeof $ctrl.task.id === "undefined";
      };
      $ctrl.save = function() {
        if ($ctrl.isCreating()) {
          $q.when(addRecurringCard($ctrl.project, $ctrl.template, $ctrl.selected), () => {
            $ctrl.onSave({ $selected: $ctrl.selected });
          });
        } else {
          $q.when(updateRecurringCard($ctrl.project, $ctrl.task, $ctrl.selected), () => {
            $ctrl.onSave({ $selected: $ctrl.selected });
          });
        }
      };
    }
  ]
});
angular_default.module("kantree").component("recurringCardEditorMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&",
    onUpdate: "&"
  },
  template: `
    <recurring-card-editor
      task="$ctrl.params.task"
      on-update="$ctrl.handleEditorUpdate()"
      on-save="$ctrl.handleEditorSave($selected)"
      on-cancel="$ctrl.handleEditorCancel($selected)"
    ></recurring-card-editor>`,
  controller: [
    function() {
      var $ctrl = this;
      $ctrl.handleEditorUpdate = function() {
        $ctrl.onUpdate();
      };
      $ctrl.handleEditorSave = function() {
        $ctrl.onClose();
      };
      $ctrl.handleEditorCancel = function() {
        $ctrl.onClose();
      };
    }
  ]
});

// public/app/ui/card/ng-components/recurring-card-tile.js
angular_default.module("kantree").component("recurringCardTile", {
  bindings: {
    task: "<"
  },
  templateUrl: "/static/app/ui/card/ng-components/templates/recurring-card-tile.html",
  controller: [
    "$scope",
    "$sce",
    "$sanitize",
    "$q",
    function($scope2, $sce, $sanitize, $q) {
      var $ctrl = this;
      function buildRecapGroups(recurrence) {
        var groups = recurrence.groups.map((group2) => buildRecapGroup(group2));
        if (groups.length <= 1) {
          return groups.join(", ");
        } else {
          return groups.slice(0, -1).join(" ,  ") + " " + _4("and") + " " + groups[groups.length - 1];
        }
      }
      function buildRecapGroup(group2) {
        let bgColor = "#eee";
        let fgColor = "#333";
        if (group2.color) {
          bgColor = group2.color;
          fgColor = textColor(group2.color, null, null);
        }
        return `<span class="group"
          style="'background-color': ${bgColor};'color': ${fgColor};">
            ${$sanitize(group2.title)}</span>`;
      }
      function buildRecurringCardRecap(task) {
        task = Object.assign({}, task, parseRecurringCardString(task));
        let recap = buildRecap(task);
        if (task.groups && task.groups.length) {
          recap += _4(" in {groups}", {
            groups: buildRecapGroups(task)
          });
        }
        return $sce.trustAsHtml(recap);
      }
      $ctrl.dropConfig = {
        tetherOptions: {
          attachment: "top left",
          offset: "0 22px",
          constraints: [{
            to: "window",
            attachment: "together",
            pin: true
          }]
        }
      };
      $ctrl.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        $scope2.isConnected = isConnected;
        $ctrl.recap = buildRecurringCardRecap($ctrl.task);
        $ctrl.projectTaskEditorMenuSpec = getRecurringCardEditorMenu($ctrl.task, true);
        cardStore.$watch($scope2, $ctrl.task.template_id, () => {
          const template3 = cardStore.tryGet($ctrl.task.template_id);
          if (template3) {
            $ctrl.template = template3;
            $ctrl.project = projectStore.getForCard(template3);
          }
        });
        recurringCardStore.$watch($scope2, $ctrl.task, "updated", function(task) {
          $ctrl.task = task;
          $ctrl.recap = buildRecurringCardRecap($ctrl.task);
          $ctrl.projectTaskEditorMenuSpec = getRecurringCardEditorMenu($ctrl.task, true);
        }, false);
      };
      $ctrl.delete = function() {
        confirmDeleteDialog2(
          null,
          _4("You will delete this recurring card permanently")
        ).then(() => {
          $q.digest(deleteRecurringCard($ctrl.project, $ctrl.task));
        });
      };
    }
  ]
});

// public/app/ui/card/ng-components/reminder-editor.js
var import_air_datepicker2 = __toESM(require_air_datepicker());
angular_default.module("kantree").component("reminderEditor", {
  bindings: {
    card: "<",
    onUpdate: "&",
    onSave: "&",
    onCancel: "&",
    onDelete: "&"
  },
  templateUrl: "/static/app/ui/card/ng-components/templates/reminder-editor.html",
  controller: [
    "$scope",
    "$q",
    function($scope2, $q) {
      var $ctrl = this;
      $ctrl.spanUnits = [{
        value: "minutes",
        label: _4("Minutes")
      }, {
        value: "hours",
        label: _4("Hours")
      }, {
        value: "days",
        label: _4("Days")
      }, {
        value: "weeks",
        label: _4("Weeks")
      }];
      $ctrl.targets = [{
        value: "creator",
        label: _4("Me")
      }, {
        value: "subscribers",
        label: _4("Card subscribers")
      }, {
        value: "members",
        label: _4("Selected members in fields")
      }, {
        value: "project_members",
        label: _4("All workspace members")
      }];
      $ctrl.updateEditor = function() {
        $ctrl.onUpdate();
      };
      $ctrl.handleSpanUnitSelect = function() {
        $ctrl.updateEditor();
      };
      $ctrl.isAmPmSelected = function(amPm) {
        return $ctrl.selected.amPm === amPm;
      };
      $ctrl.selectAmPm = function(amPm) {
        $ctrl.selected.amPm = amPm;
      };
      $ctrl.isTimeSelectorAvailable = function() {
        return ["days", "weeks"].indexOf($ctrl.selected.spanUnit) !== -1;
      };
      $ctrl.isRelativeMode = function() {
        return $ctrl.selected.mode === "relative";
      };
      $ctrl.isAbsoluteMode = function() {
        return $ctrl.selected.mode === "absolute";
      };
      $ctrl.setMode = function(mode) {
        $ctrl.selected.mode = mode;
        $ctrl.updateEditor();
        if (mode === "absolute") {
          $ctrl.initDatePicker();
        } else if ($ctrl.datePicker) {
          $ctrl.datePicker.destroy();
          $ctrl.datePicker = null;
        }
      };
      $ctrl.initDatePicker = function() {
        requestAnimationFrame(function() {
          var container = document.getElementById("reminder-datepicker-container");
          if (!container) return;
          if ($ctrl.datePicker) {
            $ctrl.datePicker.destroy();
          }
          var minDate = /* @__PURE__ */ new Date();
          var defaultDate = /* @__PURE__ */ new Date();
          defaultDate.setHours(defaultDate.getHours() + 1);
          defaultDate.setMinutes(Math.ceil(defaultDate.getMinutes() / 15) * 15);
          defaultDate.setSeconds(0);
          $ctrl.datePicker = new import_air_datepicker2.default(container, {
            inline: true,
            timepicker: true,
            minutesStep: 15,
            minDate,
            selectedDates: [defaultDate],
            locale: airdatepickerLocale(),
            classes: "daterangepicker",
            onSelect: function(opts) {
              $scope2.$applyAsync(function() {
                $ctrl.selected.absoluteDate = opts.date;
                $ctrl.updateEditor();
              });
            }
          });
          $ctrl.selected.absoluteDate = defaultDate;
          $ctrl.updateEditor();
        });
      };
      $ctrl.isAbsoluteDateValid = function() {
        if (!$ctrl.selected.absoluteDate) return false;
        return moment_default($ctrl.selected.absoluteDate).isAfter(moment_default());
      };
      $ctrl.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        $ctrl.selected = {
          mode: "relative",
          // 'relative' or 'absolute'
          absoluteDate: null,
          span: 1,
          spanUnit: "days",
          relative: "after",
          minutes: "00",
          hours: "00",
          amPm: "AM",
          creator: true,
          subscribers: true,
          members: false
        };
        $ctrl.datePicker = null;
        var hours = [
          "00",
          "01",
          "02",
          "03",
          "04",
          "05",
          "06",
          "07",
          "08",
          "09",
          "10",
          "11"
        ];
        var hours24 = hours.concat([
          "12",
          "13",
          "14",
          "15",
          "16",
          "17",
          "18",
          "19",
          "20",
          "21",
          "22",
          "23"
        ]);
        $ctrl.isHours24Selector = !isLocaleDisplayAmPm();
        $ctrl.hours = $ctrl.isHours24Selector ? hours24 : hours;
        $ctrl.minutes = ["00", "15", "30", "45"];
        $ctrl.amPm = ["AM", "PM"];
        $ctrl.updateEditor();
      };
      $ctrl.$onDestroy = function() {
        if ($ctrl.datePicker) {
          $ctrl.datePicker.destroy();
          $ctrl.datePicker = null;
        }
      };
      $ctrl.$onChanges = function(changes) {
        $ctrl.updateEditor();
      };
      $ctrl.cancel = function() {
        $ctrl.onCancel({ $selected: $ctrl.selected });
      };
      $ctrl.isTargetSelected = function() {
        return $ctrl.targets.map(function(t3) {
          return t3.value;
        }).some(function(t3) {
          return $ctrl.selected[t3];
        });
      };
      $ctrl.canSave = function() {
        if (!$ctrl.isTargetSelected()) return false;
        if ($ctrl.isAbsoluteMode()) {
          return $ctrl.isAbsoluteDateValid();
        }
        return $ctrl.selected.span > 0;
      };
      $ctrl.save = function() {
        if (!$ctrl.isTargetSelected()) {
          return;
        }
        var reminding_date;
        if ($ctrl.isAbsoluteMode()) {
          if (!$ctrl.isAbsoluteDateValid()) {
            return;
          }
          reminding_date = moment_default($ctrl.selected.absoluteDate);
          reminding_date.seconds(0);
        } else {
          var span = Math.abs(Math.round($ctrl.selected.span));
          reminding_date = moment_default().add(span, $ctrl.selected.spanUnit);
          reminding_date.seconds(0);
          if (["days", "weeks"].includes($ctrl.selected.spanUnit)) {
            var hours = $ctrl.selected.hours;
            if (!$ctrl.isHours24Selector) {
              if ($ctrl.selected.amPm === "PM") {
                hours = parseInt(hours, 10) + 12;
              }
            }
            reminding_date.hours(hours);
            reminding_date.minutes(parseInt($ctrl.selected.minutes, 10));
          }
        }
        const targets = [];
        if ($ctrl.selected.creator) {
          targets.push("creator");
        }
        if ($ctrl.selected.subscribers) {
          targets.push("subscribers");
        }
        if ($ctrl.selected.members) {
          targets.push("members");
        }
        if ($ctrl.selected.project_members) {
          targets.push("project_members");
        }
        $q.when(addCardReminder($ctrl.card, targets, reminding_date.utc().format("YYYY-MM-DD HH:mm:ss")), (reminder) => {
          $ctrl.onSave({ $selected: reminder });
        }, autoCatchAsRequestErrorDialog([403, 409, 412]));
      };
    }
  ]
});
angular_default.module("kantree").component("reminderEditorMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&",
    onUpdate: "&"
  },
  template: `
    <reminder-editor
      card="$ctrl.params.card"
      on-save="$ctrl.handleEditorSave($selected)"
      on-cancel="$ctrl.handleEditorCancel($selected)"
    ></reminder-editor>`,
  controller: [
    function() {
      var $ctrl = this;
      $ctrl.handleEditorSave = function() {
        $ctrl.onClose();
      };
      $ctrl.handleEditorCancel = function() {
        $ctrl.onClose();
      };
    }
  ]
});

// public/app/ui/card/ng-components/stream-box.js
angular_default.module("kantree").component("cardStreamBox", {
  bindings: {
    card: "<?",
    activities: "<?",
    unreadIds: "<?",
    onMarkAsRead: "&",
    markAsReadWhenComment: "<?",
    markAsReadOnScroll: "<?"
  },
  templateUrl: "/static/app/ui/card/ng-components/templates/stream-box.html",
  controller: class extends AngularClass {
    static $inject = ["$scope", "cardModal", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.commenting = false;
      this.commentEditorOptions = {
        data: {
          project_id: this.card.project_id
        },
        type: "comment",
        buttons: [
          {
            label: _4("Comment"),
            whenTextChange: {
              disabled: true
            }
          }
        ]
      };
      this.activities.$watchAll(this.$scope, () => {
        this.refreshHasUnread();
      });
    }
    $onChanges(changes) {
      if (changes.unreadIds && !changes.unreadIds.isFirstChange()) {
        this.refreshHasUnread();
      }
    }
    refreshHasUnread() {
      if (this.unreadIds?.length) {
        this.hasUnread = this.activities.query({ id: query_exports.any(this.unreadIds) }).length;
      } else {
        this.hasUnread = 0;
      }
    }
    openCardModal() {
      this.$cardModal.load(this.card.id);
    }
    toggleCommentEditor() {
      this.commenting = !this.commenting;
    }
    submitComment(text3) {
      this.$q.when(postCardComment(this.card, text3, false), (comment4) => {
        this.activities.upsert(this.transformCommentToActivity(comment4));
        this.toggleCommentEditor();
        if (this.markAsReadWhenComment) {
          this.markAllAsRead();
        }
      });
    }
    transformCommentToActivity(comment4) {
      return {
        id: "a" + comment4.id,
        stream_type: "activity",
        actor: comment4.user,
        verb: "CREATE",
        date: comment4.date,
        card_id: comment4.card_id,
        project_id: comment4.project_id,
        object: {
          type: "CardComment",
          id: comment4.id,
          value: comment4.message
        },
        target: {
          type: "Card",
          id: comment4.card_id
        }
      };
    }
    markAllAsRead() {
      this.onMarkAsRead({ "$activities": this.activities.query({ id: (id) => this.unreadIds.includes(id) }) });
    }
  }
});

// public/app/ui/card/ng-components/tile-list.js
var CARD_REF_PATTERN = /^#([0-9]+)/;
angular_default.module("kantree").component("cardTileList", {
  templateUrl: "/static/app/ui/card/ng-components/templates/tile-list.html",
  bindings: {
    card: "<",
    project: "<",
    attribute: "<",
    selectedCards: "<",
    filteredCardsIds: "<",
    widgetOptions: "<",
    onCardAdded: "&",
    onCardRemoved: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$timeout"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.abortController = null;
      this.cardTree = [];
      this.selectedCards = this.selectedCards || [];
      this.updateSelectedIds();
      this.newCardTitle = "";
      this.currentProject = this.project;
      this.canChangeProject = true;
      this.loading = false;
      this.showCardCreator = false;
      if (this.widgetOptions) {
        this.applyOptions(this.widgetOptions);
      }
      this.placeholder = _4("Add new card in {workspace}", { workspace: this.currentProject.title });
      this.loadCards(this.currentProject);
    }
    $onChanges(changes) {
      if (changes.selectedCards && !changes.selectedCards.isFirstChange()) {
        this.selectedCards = this.selectedCards || [];
        this.updateSelectedIds();
      }
    }
    $onDestroy() {
      this.abortController?.abort();
    }
    updateSelectedIds() {
      this.selectedCardsIds = this.selectedCards.map((card) => card.id);
    }
    applyOptions(options2) {
      if (!!options2.project) {
        this.canChangeProject = false;
        this.currentProject = projectStore.tryGet(options2.project);
      }
      if (options2.search) this.serverSideFilter = options2.search;
      if (options2.limit_to_one) this.isSingleSelect = true;
    }
    get isAttributeChoicesMode() {
      return !!(!this.canChangeProject && this.card && this.attribute);
    }
    onSearchChange() {
      this.buildClientFilter();
    }
    buildClientFilter() {
      if (!this.searchInput || this.searchInput === "#") {
        this.filterFn = void 0;
        return;
      }
      const refMatch = CARD_REF_PATTERN.exec(this.searchInput);
      const key2 = refMatch ? "ref" : "title";
      const term = refMatch ? `^${refMatch[1].trim()}` : this.searchInput;
      const regex = new RegExp(term, "i");
      this.filterFn = (card) => this.collectValuesRecursive(card, key2).some((v3) => v3.match(regex));
    }
    collectValuesRecursive(card, key2) {
      let values2 = [card[key2].toString()];
      if (card.children) {
        for (const child of card.children) {
          values2.push(child[key2].toString());
          if (child.children.length) values2.push(...this.collectValuesRecursive(child, key2));
        }
      }
      return values2;
    }
    toggleSort() {
      this.sortBy = !this.sortBy;
    }
    loadCards(project) {
      if (!project) return;
      this.cardTree = [];
      this.loading = true;
      this.loadError = false;
      const onSuccess = (cards) => {
        if (this.abortController?.signal.aborted) return;
        this.$scope.$applyAsync(() => {
          this.cardTree = this._buildCardTree(cards);
          this.loading = false;
        });
      };
      const onError = () => {
        if (this.abortController?.signal.aborted) return;
        this.$scope.$applyAsync(() => {
          this.loading = false;
          this.loadError = true;
        });
      };
      this.abortController?.abort();
      this.abortController = new AbortController();
      if (this.isAttributeChoicesMode) {
        this.$q.when(api_default.cards.list_attribute_choices.get({
          card_id: this.card.id,
          attr_id: this.attribute.id
        }, { signal: this.abortController.signal }), onSuccess, onError);
      } else {
        this.$q.when(fetchAllPaginated(api_default.projects.list_cards, {
          project_id: project.id,
          sort: "smart",
          filter: this.serverSideFilter || null,
          summary_only: true,
          per_page: 1e3
        }, {
          signal: this.abortController.signal
        }), onSuccess, onError);
      }
    }
    _buildCardTree(cards) {
      const nodeMap = /* @__PURE__ */ new Map();
      for (const card of cards) {
        if (this.filteredCardsIds.includes(card.id) || this.filteredCardsIds.includes(card.parent_id)) continue;
        const node = this.toCardNode(card);
        node.children = nodeMap.get(card.id)?.children ?? [];
        nodeMap.set(card.id, node);
        if (!nodeMap.has(card.parent_id)) {
          nodeMap.set(card.parent_id, { children: [] });
        }
        nodeMap.get(card.parent_id).children.push(node);
      }
      return nodeMap.get(this.currentProject.top_level_card_id)?.children ?? [];
    }
    toCardNode(card) {
      return {
        title: card.title,
        ref: card.ref,
        id: card.id,
        project_id: card.project_id,
        parent_id: card.parent_id,
        children: []
      };
    }
    onProjectChange(selectedProjectsArray) {
      this.showCardCreator = false;
      if (!selectedProjectsArray) return;
      const newProject = selectedProjectsArray[0];
      if (this.currentProject.id !== newProject.id) {
        this.currentProject = newProject;
        this.placeholder = _4("Add new card in {workspace}", { workspace: this.currentProject.title });
        this.loadCards(newProject);
      }
    }
    onCardToggled(selectedCard) {
      if (this.selectedCardsIds.includes(selectedCard.id)) {
        this.selectedCards = this.selectedCards.filter((card) => card.id !== selectedCard.id);
        this.updateSelectedIds();
        this.onCardRemoved({ $selectedCard: selectedCard });
        return;
      }
      if (this.isSingleSelect) {
        this.selectedCards = [selectedCard];
      } else {
        this.selectedCards = Array.from(this.selectedCards).concat([selectedCard]);
      }
      this.updateSelectedIds();
      this.onCardAdded({ $selectedCard: selectedCard });
    }
    get canCreate() {
      return canAddCard(this.currentProject);
    }
    create() {
      this.isCreatingCard = true;
      const [card, promise] = createCard(this.currentProject.top_level_card, this.newCardTitle, [], this.attribute.options?.model);
      this.$q.when(promise, (card2) => {
        this.newCardTitle = "";
        this.cardTree.unshift(this.toCardNode(card2));
        this.$timeout(() => {
          this.onCardCreated(card2);
        }, 100);
      });
    }
    openCardCreator() {
      this.showCardCreator = true;
      this.$timeout(() => {
        document.getElementById("new-card-input")?.focus();
      }, 10);
    }
    closeCardCreator() {
      this.newCardTitle = "";
      this.showCardCreator = false;
    }
    onCardCreated(card) {
      const el2 = document.querySelector(`[data-id="${card.id}"]`);
      if (el2) {
        el2.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
        angular_default.element(el2).addClass("new-element");
      }
      this.onCardToggled(card);
      this.$timeout(() => {
        this.isCreatingCard = false;
      }, 200);
    }
  }
});

// public/app/ui/card/ng-components/tile-templates.js
var { iconClass: iconClass6 } = (init_icons(), __toCommonJS(icons_exports));
(function() {
  var template3 = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
  templates["tile"] = template3({ "1": function(container, depth0, helpers2, partials, data2) {
    return '<i class="request-indicator fa fa-inbox"></i>';
  }, "3": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-parents">' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "parents") || (depth0 != null ? lookupProperty(depth0, "parents") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "parents", "hash": {}, "data": data2, "loc": { "start": { "line": 9, "column": 46 }, "end": { "line": 9, "column": 57 } } }) : helper)) + "</div>";
  }, "5": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<img class="card-tile-cover" src="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "imageCoverUrl") || (depth0 != null ? lookupProperty(depth0, "imageCoverUrl") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "imageCoverUrl", "hash": {}, "data": data2, "loc": { "start": { "line": 10, "column": 55 }, "end": { "line": 10, "column": 72 } } }) : helper)) + '">';
  }, "7": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<span class="ref">#' + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "ref") : stack1, depth0)) + "</span>";
  }, "9": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="model-indicator ' + iconClass6(container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "indicator") : stack1, depth0))) + '"></i>';
  }, "11": function(container, depth0, helpers2, partials, data2) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="state-indicator ' + iconClass6(alias2(alias1((stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "icon") : stack1, depth0))) + '" title="' + alias2(alias1((stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "label") : stack1, depth0)) + '"></i>';
  }, "13": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <span class="link" ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(14, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 19, "column": 21 }, "end": { "line": 19, "column": 68 } } })) != null ? stack1 : "") + ' title="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "linkTooltip") || (depth0 != null ? lookupProperty(depth0, "linkTooltip") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(alias1, { "name": "linkTooltip", "hash": {}, "data": data2, "loc": { "start": { "line": 19, "column": 76 }, "end": { "line": 19, "column": 91 } } }) : helper)) + '">\n    ' + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "unless", "hash": {}, "fn": container.program(16, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 20, "column": 4 }, "end": { "line": 20, "column": 70 } } })) != null ? stack1 : "") + "\n    " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(18, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 21, "column": 4 }, "end": { "line": 21, "column": 69 } } })) != null ? stack1 : "") + "\n  </span>\n";
  }, "14": function(container, depth0, helpers2, partials, data2) {
    return 'class="fa-stack"';
  }, "16": function(container, depth0, helpers2, partials, data2) {
    return '<i class="fa fa-chain"></i>';
  }, "18": function(container, depth0, helpers2, partials, data2) {
    return '<i class="fa fa-chain-broken"></i>';
  }, "20": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-widgets">\n' + ((stack1 = lookupProperty(helpers2, "each").call(alias1, depth0 != null ? lookupProperty(depth0, "widgets") : depth0, { "name": "each", "hash": {}, "fn": container.program(21, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 28, "column": 2 }, "end": { "line": 30, "column": 11 } } })) != null ? stack1 : "") + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "avatars") : depth0) != null ? lookupProperty(stack1, "length") : stack1, { "name": "if", "hash": {}, "fn": container.program(23, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 31, "column": 2 }, "end": { "line": 37, "column": 9 } } })) != null ? stack1 : "") + "</div>\n";
  }, "21": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return (stack1 = container.invokePartial((((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "partial") : stack1) || container.hooks.helperMissing).call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "widget.partial", "hash": {}, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 29, "column": 8 }, "end": { "line": 29, "column": 24 } } }), depth0, { "data": data2, "blockParams": blockParams, "indent": "    ", "helpers": helpers2, "partials": partials, "decorators": container.decorators })) != null ? stack1 : "";
  }, "23": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <div class="card-tile-avatars">\n' + ((stack1 = lookupProperty(helpers2, "each").call(depth0 != null ? depth0 : container.nullContext || {}, depth0 != null ? lookupProperty(depth0, "avatars") : depth0, { "name": "each", "hash": {}, "fn": container.program(24, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 33, "column": 2 }, "end": { "line": 35, "column": 11 } } })) != null ? stack1 : "") + "  </div>\n";
  }, "24": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '    <img class="card-tile-avatar" src="' + alias2(alias1((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "value") : stack1, depth0)) + '" title="' + alias2(alias1((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "tooltip") : stack1, depth0)) + '">\n';
  }, "26": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-model-warning alert alert-warning"><i class="fa fa-warning"></i>' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "modelAccessWarning") || (depth0 != null ? lookupProperty(depth0, "modelAccessWarning") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "modelAccessWarning", "hash": {}, "data": data2, "loc": { "start": { "line": 42, "column": 86 }, "end": { "line": 42, "column": 108 } } }) : helper)) + "</div>\n";
  }, "28": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<a class="card-tile-action" href="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "boardUrl") || (depth0 != null ? lookupProperty(depth0, "boardUrl") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(alias1, { "name": "boardUrl", "hash": {}, "data": data2, "loc": { "start": { "line": 46, "column": 34 }, "end": { "line": 46, "column": 46 } } }) : helper)) + '">\n  <span class="card-tile-action-label">' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showBoardBtnLabel") : depth0, { "name": "if", "hash": {}, "fn": container.program(29, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 47, "column": 39 }, "end": { "line": 47, "column": 77 } } })) != null ? stack1 : "") + '<i class="fa fa-sign-in"></i></span>\n</a>\n';
  }, "29": function(container, depth0, helpers2, partials, data2) {
    return "Board ";
  }, "31": function(container, depth0, helpers2, partials, data2) {
    return '<button class="btn card-tile-action js-go-to-card">\n  <span class="card-tile-action-label"><i class="fa fa-arrow-right"></i></span>\n</button>\n';
  }, "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-append">\n  <i class="bi-plus-lg"></i>\n</div>\n<div class="card-tile-append-disabled">\n  <i class="bi-dash-circle-fill"></i>\n</div>\n<div class="card-tile-inner">\n' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "from_request") : stack1, { "name": "if", "hash": {}, "fn": container.program(1, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 8, "column": 0 }, "end": { "line": 8, "column": 77 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "parents") : depth0, { "name": "if", "hash": {}, "fn": container.program(3, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 9, "column": 0 }, "end": { "line": 9, "column": 70 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "imageCoverUrl") : depth0, { "name": "if", "hash": {}, "fn": container.program(5, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 10, "column": 0 }, "end": { "line": 10, "column": 81 } } })) != null ? stack1 : "") + '\n<div class="card-tile-title">\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showRef") : depth0, { "name": "if", "hash": {}, "fn": container.program(7, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 12, "column": 2 }, "end": { "line": 12, "column": 62 } } })) != null ? stack1 : "") + '\n  <span class="loader"><i class="fa fa-spin fa-spinner"></i></span>\n  <span class="offline"><i class="fa fa-refresh"></i></span>\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "indicator") : stack1, { "name": "if", "hash": {}, "fn": container.program(9, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 15, "column": 2 }, "end": { "line": 15, "column": 89 } } })) != null ? stack1 : "") + '\n  <span class="title">' + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "title") : stack1, depth0)) + "</span>\n  " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showStateIcon") : depth0, { "name": "if", "hash": {}, "fn": container.program(11, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 17, "column": 2 }, "end": { "line": 17, "column": 106 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "is_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(13, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 18, "column": 2 }, "end": { "line": 23, "column": 9 } } })) != null ? stack1 : "") + "</div>\n\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showWidgets") : depth0, { "name": "if", "hash": {}, "fn": container.program(20, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 26, "column": 0 }, "end": { "line": 39, "column": 7 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "modelAccessWarning") : depth0, { "name": "if", "hash": {}, "fn": container.program(26, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 41, "column": 0 }, "end": { "line": 43, "column": 7 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showBoardBtn") : depth0, { "name": "if", "hash": {}, "fn": container.program(28, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 45, "column": 0 }, "end": { "line": 49, "column": 7 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showGoToBtn") : depth0, { "name": "if", "hash": {}, "fn": container.program(31, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 51, "column": 0 }, "end": { "line": 55, "column": 7 } } })) != null ? stack1 : "") + "</div>\n";
  }, "usePartial": true, "useData": true, "useBlockParams": true });
  templates["task"] = template3({ "1": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-parents">' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "parents") || (depth0 != null ? lookupProperty(depth0, "parents") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "parents", "hash": {}, "data": data2, "loc": { "start": { "line": 7, "column": 46 }, "end": { "line": 7, "column": 57 } } }) : helper)) + "</div>";
  }, "3": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-checkbox ' + ((stack1 = lookupProperty(helpers2, "if").call(depth0 != null ? depth0 : container.nullContext || {}, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "finished") : stack1, { "name": "if", "hash": {}, "fn": container.program(4, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 11, "column": 31 }, "end": { "line": 11, "column": 66 } } })) != null ? stack1 : "") + '"></div>\n';
  }, "4": function(container, depth0, helpers2, partials, data2) {
    return "checked";
  }, "6": function(container, depth0, helpers2, partials, data2) {
    var stack1, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '    <span class="model">\n    ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "indicator") : stack1, { "name": "if", "hash": {}, "fn": container.program(7, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 17, "column": 4 }, "end": { "line": 17, "column": 91 } } })) != null ? stack1 : "") + "\n    " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "model") : stack1, { "name": "if", "hash": {}, "fn": container.program(9, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 18, "column": 4 }, "end": { "line": 18, "column": 63 } } })) != null ? stack1 : "") + "\n    </span>\n";
  }, "7": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="model-indicator ' + iconClass6(container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "indicator") : stack1, depth0))) + '"></i>';
  }, "9": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return "<span>" + container.escapeExpression(container.lambda((stack1 = (stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "model") : stack1) != null ? lookupProperty(stack1, "name") : stack1, depth0)) + "</span>";
  }, "11": function(container, depth0, helpers2, partials, data2) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<i class="state-indicator ' + iconClass6(alias2(alias1((stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "icon") : stack1, depth0))) + '" title="' + alias2(alias1((stack1 = depth0 != null ? lookupProperty(depth0, "state") : depth0) != null ? lookupProperty(stack1, "label") : stack1, depth0)) + '"></i>';
  }, "13": function(container, depth0, helpers2, partials, data2) {
    return '<i class="request-indicator fa fa-inbox"></i>';
  }, "15": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <span class="link" ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(16, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 31, "column": 21 }, "end": { "line": 31, "column": 68 } } })) != null ? stack1 : "") + ' title="' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "linkTooltip") || (depth0 != null ? lookupProperty(depth0, "linkTooltip") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(alias1, { "name": "linkTooltip", "hash": {}, "data": data2, "loc": { "start": { "line": 31, "column": 76 }, "end": { "line": 31, "column": 91 } } }) : helper)) + '">\n    ' + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "unless", "hash": {}, "fn": container.program(18, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 32, "column": 4 }, "end": { "line": 32, "column": 70 } } })) != null ? stack1 : "") + "\n    " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "broken_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(20, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 33, "column": 4 }, "end": { "line": 33, "column": 69 } } })) != null ? stack1 : "") + "\n  </span>\n";
  }, "16": function(container, depth0, helpers2, partials, data2) {
    return 'class="fa-stack"';
  }, "18": function(container, depth0, helpers2, partials, data2) {
    return '<i class="fa fa-chain"></i>';
  }, "20": function(container, depth0, helpers2, partials, data2) {
    return '<i class="fa fa-chain-broken"></i>';
  }, "22": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return (stack1 = lookupProperty(helpers2, "each").call(depth0 != null ? depth0 : container.nullContext || {}, depth0 != null ? lookupProperty(depth0, "widgets") : depth0, { "name": "each", "hash": {}, "fn": container.program(23, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 38, "column": 2 }, "end": { "line": 40, "column": 11 } } })) != null ? stack1 : "";
  }, "23": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return (stack1 = container.invokePartial((((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "partial") : stack1) || container.hooks.helperMissing).call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "widget.partial", "hash": {}, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 39, "column": 8 }, "end": { "line": 39, "column": 24 } } }), depth0, { "data": data2, "blockParams": blockParams, "indent": "    ", "helpers": helpers2, "partials": partials, "decorators": container.decorators })) != null ? stack1 : "";
  }, "25": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <div class="card-tile-avatars">\n' + ((stack1 = lookupProperty(helpers2, "each").call(depth0 != null ? depth0 : container.nullContext || {}, depth0 != null ? lookupProperty(depth0, "avatars") : depth0, { "name": "each", "hash": {}, "fn": container.program(26, data2, 2, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 45, "column": 2 }, "end": { "line": 47, "column": 11 } } })) != null ? stack1 : "") + "  </div>\n";
  }, "26": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = container.lambda, alias2 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '    <img class="card-tile-avatar" src="' + alias2(alias1((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "value") : stack1, depth0)) + '" title="' + alias2(alias1((stack1 = blockParams[0][0]) != null ? lookupProperty(stack1, "tooltip") : stack1, depth0)) + '">\n';
  }, "28": function(container, depth0, helpers2, partials, data2) {
    var helper, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '  <div class="card-tile-model-warning alert alert-warning"><i class="fa fa-warning"></i>' + container.escapeExpression((helper = (helper = lookupProperty(helpers2, "modelAccessWarning") || (depth0 != null ? lookupProperty(depth0, "modelAccessWarning") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "modelAccessWarning", "hash": {}, "data": data2, "loc": { "start": { "line": 52, "column": 88 }, "end": { "line": 52, "column": 110 } } }) : helper)) + "</div>\n";
  }, "30": function(container, depth0, helpers2, partials, data2) {
    var stack1, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "cardUrl") : depth0, { "name": "if", "hash": {}, "fn": container.program(31, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 56, "column": 4 }, "end": { "line": 58, "column": 11 } } })) != null ? stack1 : "") + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, depth0 != null ? lookupProperty(depth0, "cardUrl") : depth0, { "name": "unless", "hash": {}, "fn": container.program(33, data2, 0), "inverse": container.noop, "data": data2, "loc": { "start": { "line": 59, "column": 4 }, "end": { "line": 61, "column": 15 } } })) != null ? stack1 : "");
  }, "31": function(container, depth0, helpers2, partials, data2) {
    var stack1, helper, alias1 = container.escapeExpression, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '    <a class="ref" href="' + alias1((helper = (helper = lookupProperty(helpers2, "cardUrl") || (depth0 != null ? lookupProperty(depth0, "cardUrl") : depth0)) != null ? helper : container.hooks.helperMissing, typeof helper === "function" ? helper.call(depth0 != null ? depth0 : container.nullContext || {}, { "name": "cardUrl", "hash": {}, "data": data2, "loc": { "start": { "line": 57, "column": 25 }, "end": { "line": 57, "column": 36 } } }) : helper)) + '">#' + alias1(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "ref") : stack1, depth0)) + "</a>\n";
  }, "33": function(container, depth0, helpers2, partials, data2) {
    var stack1, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '    <span class="ref">#' + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "ref") : stack1, depth0)) + "</span>\n";
  }, "35": function(container, depth0, helpers2, partials, data2) {
    return '<button class="btn card-tile-action js-go-to-card">\n  <span class="card-tile-action-label"><i class="fa fa-arrow-right"></i></span>\n</button>\n';
  }, "compiler": [8, ">= 4.3.0"], "main": function(container, depth0, helpers2, partials, data2, blockParams) {
    var stack1, alias1 = depth0 != null ? depth0 : container.nullContext || {}, lookupProperty = container.lookupProperty || function(parent, propertyName2) {
      if (Object.prototype.hasOwnProperty.call(parent, propertyName2)) {
        return parent[propertyName2];
      }
      return void 0;
    };
    return '<div class="card-tile-append">\n  <i class="bi-plus-lg"></i>\n</div>\n<div class="card-tile-append-disabled">\n  <i class="bi-dash-circle-fill"></i>\n</div>\n' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "parents") : depth0, { "name": "if", "hash": {}, "fn": container.program(1, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 7, "column": 0 }, "end": { "line": 7, "column": 70 } } })) != null ? stack1 : "") + '\n<div class="card-tile-inner">\n\n' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "canToggleState") : depth0, { "name": "if", "hash": {}, "fn": container.program(3, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 10, "column": 0 }, "end": { "line": 12, "column": 7 } } })) != null ? stack1 : "") + '\n<div class="card-tile-content">\n' + ((stack1 = lookupProperty(helpers2, "unless").call(alias1, (stack1 = (stack1 = depth0 != null ? lookupProperty(depth0, "model") : depth0) != null ? lookupProperty(stack1, "model") : stack1) != null ? lookupProperty(stack1, "base_model_id") : stack1, { "name": "unless", "hash": {}, "fn": container.program(6, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 15, "column": 2 }, "end": { "line": 20, "column": 13 } } })) != null ? stack1 : "") + '\n  <div class="card-tile-title">\n    <span class="title">' + container.escapeExpression(container.lambda((stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "title") : stack1, depth0)) + "</span>\n    " + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showStateIcon") : depth0, { "name": "if", "hash": {}, "fn": container.program(11, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 24, "column": 4 }, "end": { "line": 24, "column": 108 } } })) != null ? stack1 : "") + '\n    <span class="loader"><i class="fa fa-spin fa-spinner"></i></span>\n    <span class="offline"><i class="fa fa-refresh"></i></span>\n  </div>\n\n  ' + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "from_request") : stack1, { "name": "if", "hash": {}, "fn": container.program(13, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 29, "column": 2 }, "end": { "line": 29, "column": 79 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "card") : depth0) != null ? lookupProperty(stack1, "is_link") : stack1, { "name": "if", "hash": {}, "fn": container.program(15, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 30, "column": 2 }, "end": { "line": 35, "column": 9 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showWidgets") : depth0, { "name": "if", "hash": {}, "fn": container.program(22, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 37, "column": 2 }, "end": { "line": 41, "column": 9 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, (stack1 = depth0 != null ? lookupProperty(depth0, "avatars") : depth0) != null ? lookupProperty(stack1, "length") : stack1, { "name": "if", "hash": {}, "fn": container.program(25, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 43, "column": 2 }, "end": { "line": 49, "column": 9 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "modelAccessWarning") : depth0, { "name": "if", "hash": {}, "fn": container.program(28, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 51, "column": 2 }, "end": { "line": 53, "column": 9 } } })) != null ? stack1 : "") + "\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showRef") : depth0, { "name": "if", "hash": {}, "fn": container.program(30, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 55, "column": 2 }, "end": { "line": 62, "column": 9 } } })) != null ? stack1 : "") + "</div>\n\n" + ((stack1 = lookupProperty(helpers2, "if").call(alias1, depth0 != null ? lookupProperty(depth0, "showGoToBtn") : depth0, { "name": "if", "hash": {}, "fn": container.program(35, data2, 0, blockParams), "inverse": container.noop, "data": data2, "blockParams": blockParams, "loc": { "start": { "line": 65, "column": 0 }, "end": { "line": 69, "column": 7 } } })) != null ? stack1 : "") + "</div>\n";
  }, "usePartial": true, "useData": true, "useBlockParams": true });
})();

// public/app/ui/card/ng-components/tile.js
angular_default.module("kantree").directive("cardTile", [
  "attributeRepr",
  "$state",
  "$compile",
  "cardModal",
  "$q",
  "menuDropdown",
  "cardActionsMenuFactory",
  "$timeout",
  "statesMenuFactory",
  "projectPage",
  function(attributeRepr, $state, $compile, cardModal, $q, menuDropdown, cardActionsMenuFactory, $timeout2, statesMenuFactory, projectPage) {
    return {
      restrict: "A",
      scope: {
        card: "<cardTile",
        selector: "<?",
        hideState: "@",
        modalLoad: "@",
        showProject: "<?",
        showParents: "<?",
        showAttributes: "<?",
        showCheckbox: "<?",
        showArchived: "<?",
        showChildren: "<?",
        showChildrenAttributes: "<?",
        showBoardPattern: "<?",
        showBoardBtnLabel: "<?",
        showRef: "<?",
        strikeTitleWhenDone: "<?",
        templateType: "@",
        disableChildrenToggle: "<?",
        loadRelated: "<?",
        onToggleChildren: "&?",
        forceCompleteChildrenList: "<?",
        toggleChildrenKey: "@?",
        timelineSpec: "<?",
        scrollViewport: "@"
      },
      require: { cardsApp: "?^^cardsApp" },
      compile: function(el2, attrs2) {
        return function(scope, $el, attrs3, ctrl) {
          scope.project = projectStore.getForCard(scope.card);
          scope.isCardInActiveProject = function(card) {
            return $state.params.projectId === scope.project.slug;
          };
          function childrenCardsContainCard() {
            return cardStore.isValidLink(scope.card) && scope.project.id === scope.card.link.project_id && cardStore.isCardDescendantOf(scope.card, scope.card.link);
          }
          function showAttribute(attrName) {
            return !scope.showAttributes || scope.showAttributes.includes(attrName);
          }
          function canShowChildren() {
            return (typeof scope.showChildren === "undefined" || !!scope.showChildren) && showAttribute("__children__");
          }
          function showBoardPattern() {
            return typeof scope.showBoardPattern === "undefined" || !!scope.showBoardPattern;
          }
          function buildRenderParams() {
            const card = scope.card;
            const params = {
              card,
              model: scope.model,
              showProject: scope.showProject,
              widgets: [],
              showRef: (typeof scope.showRef === "undefined" || !!scope.showRef) && showAttribute("__ref__")
            };
            if (card.nb_children && canShowChildren()) {
              params.widgets.push({
                type: "label",
                value: (card.nb_finished_children > 0 ? card.nb_finished_children + "/" : "") + card.nb_children,
                tooltip: (card.board_created ? _4("Number of cards in board") : _4("Number of sub-cards")) + (card.nb_completed_pct > 0 ? _4(" ({pct}% completed)", { pct: card.nb_completed_pct }) : ""),
                options: {
                  iconClass: card.board_created ? "fa-columns" : "bi-list-check",
                  cssclass: "card-tile-children" + (scope.disableChildrenToggle || childrenCardsContainCard() ? "" : " is-togglable js-toggle-children") + (showChildren ? " is-opened" : ""),
                  hasDropdown: !scope.disableChildrenToggle && !childrenCardsContainCard()
                }
              });
            }
            if (card.nb_comments && showAttribute("__comments__")) {
              params.widgets.push({
                type: "counter",
                value: card.nb_comments,
                options: {
                  iconClass: "bi-chat-left"
                }
              });
            }
            var widgets = attributeRepr.getWidgets(params.model.attributes, card);
            params.widgets = attributeRepr.filterWidgets(params.widgets.concat(attributeRepr.aggregateWidgets(widgets)));
            var groupWidgets = card.groups.reduce(function(accu, group2) {
              if (!!ctrl.cardsApp && (ctrl.cardsApp.groupBy || []).some((gby) => gby.getGroupType() && gby.getGroupType().id === group2.type_id)) {
                return accu;
              }
              if (!cardGroupStore.exists(group2.id)) {
                return accu;
              }
              group2 = cardGroupStore.get(group2.id);
              if (!cardGroupTypeStore.exists(group2.type_id)) {
                return accu;
              }
              var groupType = cardGroupTypeStore.get(group2.type_id);
              if (groupType.attribute_id) {
                return accu;
              }
              if (group2.is_archived && !scope.showArchived) {
                return accu;
              }
              if (scope.showAttributes && !scope.showAttributes.includes(groupType.name)) {
                return accu;
              }
              return accu.concat({
                type: "label",
                value: group2.title,
                tooltip: group2.title + " (" + groupType.singular_name + ")",
                options: {
                  bgcolor: group2.color,
                  icon: group2.icon || groupType.icon,
                  cssclass: group2.is_archived ? "closed" : ""
                }
              });
            }, []);
            params.widgets = params.widgets.concat(groupWidgets).map((widget) => attributeRepr.formatWidget(widget));
            params.avatars = params.widgets.filter(function(widget) {
              return widget.type === "avatar";
            });
            params.widgets = params.widgets.filter(function(widget) {
              return widget.type !== "avatar";
            });
            params.showWidgets = params.avatars.length || params.widgets.length;
            params.state = cardStateStore.getForCard(card);
            if (scope.timelineSpec) {
              params.showGoToBtn = scope.timelineSpec.cardHasDateRange(card);
            } else {
              params.boardUrl = card.is_link ? card.link ? projectRouteHref({ slug: card.link.project_slug }, card.link) : null : projectRouteHref(scope.project, card);
              params.showBoardBtn = !card.is_archived && card.board_created && !!params.boardUrl;
              params.showBoardBtnLabel = scope.showBoardBtnLabel;
            }
            params.linkTooltip = card.broken_link ? _4("Broken link") : card.link_has_own_attributes ? _4("This card points to another card") : _4("This card is a mirrored card");
            params.showStateIcon = scope.hideState !== "true" && params.state.icon;
            params.canToggleState = (scope.showCheckbox === void 0 || scope.showCheckbox) && !card.is_archived && !card.is_parent_archived && isAuthenticated() && isConnected() && isAllowedInProject(scope.project, "card", "EDIT", card.id);
            if (card.model_id && !cardModelStore.exists(card.model_id) || cardStore.isValidMirror(card) && !projectStore.exists(card.link.project_id)) {
              params.modelAccessWarning = _4("You may not see some fields because you don't have access to the card type");
            }
            let parents = [];
            if (scope.showProject) {
              parents.push(scope.project.title);
            }
            if (scope.showParents) {
              parents = parents.concat(card.path.slice(1).map((p4) => p4.title));
            }
            params.parents = parents.length ? _4("in {parents}", { parents: parents.join(" / ") }) : null;
            params.cardUrl = document.location.pathname + document.location.search + "#" + card.ref;
            if ((card.image_cover_url || !card.parent_id && scope.project.image_cover_url) && showAttribute("__cover__")) {
              if (card.image_cover_url) {
                params.imageCoverUrl = prependBaseUrl(card.image_cover_url);
              } else if (!card.parent_id && scope.project.image_cover_url) {
                params.imageCoverUrl = prependBaseUrl(scope.project.image_cover_url);
              }
            }
            return params;
          }
          var i3 = 0;
          var hasModelTheme = false;
          var content2;
          var template3 = scope.templateType === "task" || scope.templateType === "timeline" ? handlebars_default.templates.task : handlebars_default.templates.tile;
          var children2 = [];
          var childrenElement = null;
          var childrenScope = null;
          scope.toggleChildrenKey = scope.toggleChildrenKey || "card-tile";
          var localStoragePrefixForChildrenDisplay = scope.toggleChildrenKey + "." + (cardStore.isValidLink(scope.card) ? scope.card.link.id : scope.card.id);
          var showChildren = jsonLocalStorage.getItem(localStoragePrefixForChildrenDisplay + ".show-children") || false;
          var showCompleteChildrenList = jsonLocalStorage.getItem(localStoragePrefixForChildrenDisplay + ".show-complete-children-list") || false;
          let attributeReprWatcherOff;
          function render3() {
            const params = buildRenderParams();
            const newContent = template3(params);
            if (content2 !== newContent) {
              if (childrenElement) {
                jquery_default($el).children(".card-tile-inner, .card-tile-append, .card-tile-append-disabled").remove();
                jquery_default($el).prepend(newContent);
              } else {
                jquery_default($el).html(newContent);
              }
              content2 = newContent;
            }
            $el.toggleClass("locked", !params.card.ref && params.card.ref !== 0 && !params.card.offline && cardStore.isLocked(scope.card));
            $el.toggleClass("offline", !!params.card.offline);
            $el.toggleClass("has-board", showBoardPattern() && params.card.board_created);
            if (params.hideState !== "true") {
              $el.toggleClass("finished", params.card.finished);
              $el.toggleClass("struck-title", params.card.finished && (!!scope.strikeTitleWhenDone || scope.strikeTitleWhenDone === void 0));
            }
            $el.toggleClass("archived", params.card.is_archived);
            if (hasModelTheme) {
              $el.removeClassRegex("card-model-theme-");
              hasModelTheme = false;
            }
            if (attrs3.editOnClick === "true") {
              $el.toggleClass("is-editable-on-click", !scope.card.is_archived && !scope.card.is_parent_archived && !scope.card.is_link && isAuthenticated() && isConnected() && isAllowedInProject(scope.project, "card", "EDIT", scope.card.id));
            }
            if (scope.model.model && scope.model.model.style_class_name) {
              $el.addClass(scope.model.model.style_class_name);
              hasModelTheme = true;
            } else if (!scope.card.parent_id && scope.project.card_model_theme) {
              $el.addClass(scope.project.card_model_theme);
              hasModelTheme = true;
            }
            if (scope.timelineSpec) {
              $el.toggleClass("has-daterange", !!scope.timelineSpec.cardHasDateRange(scope.card));
            }
            if (attributeReprWatcherOff) {
              attributeReprWatcherOff();
            }
            const watchersOff = params.widgets.map((widget) => {
              const attrElement = $el.find(`[data-attribute-repr-id="${widget.id}"]`);
              if (attrElement.length && widget.onDOMLoad) {
                return widget.onDOMLoad(attrElement, { editable: !!isConnected() });
              }
            }).filter(Boolean);
            attributeReprWatcherOff = offMany(watchersOff);
          }
          ;
          var editorScope, editorElement;
          var isEditing;
          var startTitleEditor = function() {
            var tpl = '<div class="text-composer" text-composer="cardEditorOptions" init-value="card.title"></div>';
            editorScope = scope.$new();
            editorElement = $compile(tpl)(editorScope);
            editorElement.insertAfter($el.find("> .card-tile-inner .title"));
            $el.addClass("editing");
            isEditing = true;
            $timeout2(function() {
              editorElement.find("textarea, input").focus();
            });
          };
          var stopTitleEditor = function() {
            $el.removeClass("editing");
            isEditing = false;
            editorScope.$destroy();
            editorElement.remove();
            editorScope = null;
            editorElement = null;
          };
          scope.cardEditorOptions = {
            saveChange: function(event2, title, cb2) {
              $q.when(updateCard(scope.card, { title }), cb2);
              stopTitleEditor();
            },
            cancelChange: function() {
              stopTitleEditor();
            },
            saveBtn: false,
            cancelBtn: false,
            saveOn: { tab: true },
            hideOn: { save: true },
            resetOn: { save: false }
          };
          if (scope.templateType === "timeline" || scope.templateType === "task") {
            scope.cardEditorOptions.inputType = "input";
          }
          var stateDrop;
          var toggleState = function() {
            var aliasStates = cardStateStore.getAvailableAliasesForCard(scope.card, scope.card.finished ? "waiting" : "completed");
            if (aliasStates.length > 1) {
              const target = $el.find(".card-tile-checkbox")[0];
              const statesMenuSpec = statesMenuFactory.get(scope.card, {
                withGroupStates: true,
                filters: scope.card.finished ? "waiting" : "completed"
              });
              statesMenuSpec.options.title = _4("Mark this card as...");
              stateDrop = menuDropdown.open(target, statesMenuSpec, scope);
            } else if (aliasStates.length === 1) {
              $q.digest(setCardState(scope.card, aliasStates[0]));
            } else {
              $q.digest(toggleCardAsCompleted(scope.card));
            }
          };
          $el.on("click", ".card-tile-checkbox", function(e3) {
            e3.stopPropagation();
            e3.preventDefault();
            if (stateDrop && stateDrop.drop) {
              menuDropdown.close(stateDrop, e3);
              return;
            }
            if (!isConnected()) {
              return;
            }
            if (scope.isCardInActiveProject(scope.card)) {
              toggleState();
            } else {
              $q.when(loadAvailableStatesForCard(scope.card), toggleState);
            }
          });
          var modelWatcherOff;
          var modelChanged = function() {
            modelWatcherOff && modelWatcherOff();
            scope.model = getCardCompositeModel(
              scope.card,
              getAttrVisibilityFilterObject(scope.showAttributes, true)
            );
            if (scope.showAttributes) {
              scope.model.attributes.sort((a3, b3) => scope.showAttributes.indexOf(a3.name) - scope.showAttributes.indexOf(b3.name));
            }
            var watchers = [];
            if (scope.model.model) {
              watchers.push(cardModelStore.watch(scope.model.model, "updated", modelChanged, false));
            }
            if (scope.card.model_id && !cardModelStore.tryGet(scope.card.model_id)) {
              watchers.push(cardModelStore.watch(scope.card.model_id, "inserted", modelChanged, false));
            }
            if (watchers.length) {
              modelWatcherOff = offMany(watchers);
            }
            render3();
          };
          var cardWatcherOff = cardStore.watch(scope.card, "updated", modelChanged);
          var lockOff = cardStore.watch(scope.card, ["locked", "unlocked"], function() {
            $el.toggleClass("locked", !scope.card.ref && scope.card.ref !== 0 && !scope.card.offline && cardStore.isLocked(scope.card));
          });
          scope.$on("connectivityChanged", render3);
          let wasChildrenShown = showChildren;
          scope.$watch("showAttributes", (newValue, oldValue) => {
            if (newValue !== oldValue) {
              modelChanged();
            }
            if (scope.card.nb_children) {
              if (wasChildrenShown && !showChildren && canShowChildren()) {
                toggleChildrenElement(true);
              } else if (showChildren && !canShowChildren()) {
                wasChildrenShown = true;
                toggleChildrenElement(false);
              } else if (!canShowChildren()) {
                wasChildrenShown = false;
              }
            }
          });
          scope.$watch("strikeTitleWhenDone", (newValue, oldValue) => {
            if (scope.card.finished && newValue !== oldValue) {
              modelChanged();
            }
          });
          scope.selected = false;
          scope.highlighted = false;
          function selectCard() {
            scope.selected = true;
            $el.toggleClass("selected", true);
            $el.removeClass("highlighted");
          }
          function unselectCard() {
            scope.selected = false;
            $el.toggleClass("selected", false);
            if (scope.highlighted) {
              $el.addClass("highlighted");
            }
          }
          scope.$on("selectCards", (e3, cardIds) => {
            if (cardIds.includes(scope.card.id)) {
              selectCard();
            }
          });
          scope.$on("unselectCard", (e3, cardId) => {
            if (cardId === scope.card.id) {
              unselectCard();
            }
          });
          scope.$on("selectAllCards", (e3, cardIds) => {
            if (!cardIds || cardIds.includes(scope.card.id)) {
              selectCard();
            }
          });
          scope.$on("clearSelectedCards", () => unselectCard());
          function highlightCard(cardIds) {
            scope.highlighted = cardIds.includes(scope.card.id);
            if (!scope.selected) {
              $el.toggleClass("highlighted", scope.highlighted);
            }
          }
          scope.$on("highlightCards", (e3, cardIds) => highlightCard(cardIds));
          scope.$on("refreshCardHighlight", () => projectPage.isActive && highlightCard(projectPage.highlightedCardIds));
          scope.$on("scrollToCard", (e3, cardId) => {
            if (scope.card.id === cardId) {
              $el.parents(scope.scrollViewport || ".ui-sortable-cards-items-container").scrollTo($el, 100, { offset: { top: -50 } });
            }
          });
          $el[0].scope = function() {
            return scope;
          };
          if (scope.selector) {
            $el.on("mouseenter", function(e3) {
              if (e3.button) return;
              if (scope.selector.selected) {
                scope.selector.unselect();
              }
            });
            scope.selector.$on(scope, scope.card, function() {
              $el.addClass("hover");
            });
            scope.selector.$off(scope, scope.card, function() {
              $el.removeClass("hover");
            });
          }
          $el.on("click", "textarea, input", function(e3) {
            e3.stopPropagation();
          });
          $el.addClass("card-tile");
          if (attrs3.disableDefaultModelTheme !== "true") {
            $el.addClass("card-tile-model-theme");
          }
          var cancelOpen = false;
          var touchedTimer;
          var touchedAction = false;
          $el.on("touchstart", function() {
            touchedAction = true;
            cancelOpen = false;
            touchedTimer = setTimeout(function() {
              cancelOpen = true;
            }, 200);
            $el.addClass("touched");
          });
          $el.on("touchend", function() {
            touchedAction = false;
            if (touchedTimer) {
              clearTimeout(touchedTimer);
              $el.removeClass("touched");
              $el.removeClass("pressed");
            }
          });
          var openModal2 = function() {
            if (scope.modalLoad === "true") {
              cardModal.load(scope.card.id, { parentSelector: scope.selector });
            } else {
              cardModal.open(scope.card, { parentSelector: scope.selector, showArchived: scope.showArchived });
            }
          };
          if (attrs3.editOnClick === "true" && isConnected() && !scope.card.is_link && isAllowedInProject(scope.project, "card", "EDIT", scope.card.id)) {
            $el.on("click", ".title", (e3) => {
              if (!!scope.card.is_archived || !!scope.card.is_parent_archived && !isAuthenticated()) return;
              e3.preventDefault();
              e3.stopPropagation();
              startTitleEditor();
            });
          }
          $el.addClass("clickable").on("click", function(e3) {
            const keyModifier = isMacOS() ? "metaKey" : "ctrlKey";
            if (e3[keyModifier] && projectPage.isProjectActive(scope.project)) {
              if (projectPage.isCardSelected(scope.card)) {
                projectPage.unselectCard(scope.card);
              } else {
                projectPage.selectCard(scope.card);
              }
              scope.$applyAsync();
              return;
            }
            if (jquery_default(e3.target).closest("a").is("a.card-tile-action") || $el.parents(".card-tile-children-list").length === 0 && jquery_default(e3.target).parents(".card-tile").length > 1) {
              return;
            }
            if (touchedTimer) {
              clearTimeout(touchedTimer);
              $el.removeClass("touched");
              $el.removeClass("pressed");
            }
            if (cancelOpen) {
              return;
            }
            if (scope.selector) {
              scope.selector.select(scope.card, true);
            }
            e3.preventDefault();
            e3.stopPropagation();
            openModal2();
          });
          if (typeof attrs3.noContextMenu === "undefined" || attrs3.noContextMenu !== "true") {
            $el.on("contextmenu", function(e3) {
              if (jquery_default(e3.target).closest("a").is("a.ref")) return;
              e3.preventDefault();
              e3.stopPropagation();
              if (cancelOpen) {
                return;
              }
              var elementOffset = jquery_default($el).offset();
              var dropTargetOffset = e3.clientY - elementOffset.top + "px " + (e3.clientX - elementOffset.left) + "px";
              var contextMenuDropConfig = {
                classes: "card-actions-menu",
                tetherOptions: {
                  targetOffset: dropTargetOffset
                }
              };
              var menu = cardActionsMenuFactory.get(scope.card, {
                rename: startTitleEditor,
                editable: true,
                hideShareableLink: true,
                hideMakeReccuring: true,
                hideRequest: true,
                dataPrefetched: !scope.loadRelated && !scope.card.is_link,
                showSelect: true
              });
              menuDropdown.openContextMenu($el[0], menu, scope, contextMenuDropConfig);
            });
          }
          var doesChildrenNeedSort = function() {
            return !scope.forceCompleteChildrenList && !showCompleteChildrenList && children2.length > 3;
          };
          var doesChildrenNeedLoad = function() {
            return scope.loadRelated || cardStore.isValidLink(scope.card) && !scope.isCardInActiveProject(scope.card.link);
          };
          var getChildCardHtml = function(idx) {
            return `<div
                class="sortable-disabled ${scope.templateType === "timeline" ? "mod-timeline" : "mod-task"}"
                card-tile="::children[${idx}]"
                selector="false"
                hide-state="{{ ::(hideState || null) }}"
                show-archived="showArchived"
                modal-load="{{ ::(modalLoad || null) }}"
                template-type="{{ ::(templateType === 'timeline' ? 'timeline' : 'task') }}"
                data-id="{{::children[${idx}].id}}"
                load-related="::(loadRelated || null)"
                show-attributes="showAttributes"
                show-children-attributes="showChildrenAttributes"
                on-toggle-children="onToggleChildren && onToggleChildren({$card: $card, $toggleState: $toggleState})"
                force-complete-children-list="forceCompleteChildrenList"
                toggle-children-key="{{ ::toggleChildrenKey }}"
                timeline-spec="timelineSpec"
                disable-default-model-theme="${attrs3.disableDefaultModelTheme || "false"}"
                no-context-menu="${attrs3.noContextMenu || "false"}"
              ></div>`;
          };
          var createChildrenHtml = function() {
            var html5 = '<div class="card-tile-children-list">';
            children2.slice(0, showCompleteChildrenList || scope.forceCompleteChildrenList ? children2.length : 3).forEach(function(card, idx) {
              html5 += getChildCardHtml(idx);
            });
            if (children2.length > 3 && !scope.forceCompleteChildrenList) {
              html5 += '<button type="button" class="card-tile-children-expand-button js-expand-children" ' + (showCompleteChildrenList ? 'style="display: none;"' : "") + ">" + _4("Display all cards ({nb} more)", { nb: children2.length - 3 }) + '<i class="bi-caret-down-fill"></i></button><button type="button" class="card-tile-children-expand-button js-collapse-children" ' + (showCompleteChildrenList ? "" : 'style="display: none;"') + ">" + _4("Collapse list") + '<i class="bi-caret-up-fill"></i></button>';
            }
            html5 += "</div>";
            return html5;
          };
          var createChildrenElement = function() {
            var cardlistHtml = createChildrenHtml();
            childrenScope = scope.$new();
            childrenScope.children = children2;
            switch (scope.showChildrenAttributes) {
              case "none":
                childrenScope.showAttributes = ["__ref__", "__comments__", "__children__", "__cover__"];
                break;
              case "selected":
                childrenScope.showAttributes = scope.showAttributes;
                break;
              default:
                childrenScope.showAttributes = null;
                break;
            }
            childrenElement = angular_default.element($compile(cardlistHtml)(childrenScope));
          };
          var cardlistExpandSelectors = [
            "> .card-tile-children-list > .js-expand-children",
            "> .card-tile-children-list > .js-collapse-children"
          ];
          var appendChildrenElement = function() {
            $el.append(childrenElement);
            jquery_default($el).find(cardlistExpandSelectors.join(", ")).on("click", toggleCompleteChildrenList);
          };
          var removeChildrenElement = function() {
            if (childrenScope) {
              childrenScope.$destroy();
              childrenScope = null;
            }
            if (childrenElement) {
              jquery_default($el).find(cardlistExpandSelectors.join(", ")).off("click", toggleCompleteChildrenList);
              childrenElement.remove();
              childrenElement = null;
            }
          };
          var updateChildren = function() {
            const card = cardStore.isValidLink(scope.card) ? scope.card.link : scope.card;
            children2 = cardStore.scopedByParent(card).scoped({
              is_archived: (v3) => scope.showArchived ? true : !v3
            }).query({}, { sortBy: "position", sortCastToInt: true });
            if (scope.timelineSpec) {
              children2 = children2.filter(scope.timelineSpec.filterChildrenPredicate);
            }
          };
          var toggleCompleteChildrenList = function(event2) {
            event2.stopPropagation();
            event2.preventDefault();
            toggleChildrenElement(true, true);
            if (scope.onToggleChildren) {
              scope.onToggleChildren({
                $card: cardStore.isValidLink(scope.card) ? scope.card.link : scope.card,
                $toggleState: true
              });
            }
          };
          function toggleChildrenElement(toggleState2, toggleCompleteList) {
            var updateLocalData = function(label, toggleState3) {
              var currentState = jsonLocalStorage.getItem(localStoragePrefixForChildrenDisplay + "." + label) || false;
              var newState = toggleState3 !== void 0 ? toggleState3 : !currentState;
              if (newState !== currentState) {
                jsonLocalStorage.setItem(localStoragePrefixForChildrenDisplay + "." + label, newState);
              }
              return newState;
            };
            var wasSorted = doesChildrenNeedSort();
            showChildren = updateLocalData("show-children", toggleState2);
            if (toggleCompleteList) {
              showCompleteChildrenList = updateLocalData("show-complete-children-list");
            }
            removeChildrenElement();
            if (showChildren) {
              updateChildren();
            }
            if (childrenListenersOff) {
              childrenListenersOff();
            }
            if (showChildren && scope.card.nb_children) {
              childrenListenersOff = attachChildrenListeners();
            }
            if (showChildren && children2 && children2.length) {
              if (doesChildrenNeedSort()) {
                children2.sort(function(a3, b3) {
                  if (a3.finished && !b3.finished) {
                    return 1;
                  }
                  if (!a3.finished && b3.finished) {
                    return -1;
                  }
                  return 0;
                });
              } else if (wasSorted) {
                children2.sort(function(a3, b3) {
                  return a3.ref - b3.ref;
                });
              }
              createChildrenElement();
              appendChildrenElement();
            }
            $el.toggleClass("children-shown", !!(showChildren && children2 && children2.length));
            jquery_default($el).find("> .card-tile-inner .js-toggle-children").toggleClass("is-opened", showChildren);
          }
          ;
          var toggleChildrenElementDebounced = debounce2(function() {
            scope.$applyAsync(function() {
              toggleChildrenElement(showChildren);
            });
          }, 200);
          var childrenListenersOff;
          var attachChildrenListeners = function() {
            var childrenWatcherOff;
            var tempCardWatcherOff;
            let showArchivedWatcherOff;
            let showChildrenAttributesWatcherOff;
            if (cardStore.isValidLink(scope.card)) {
              childrenWatcherOff = cardStore.scopedByParent(scope.card.link).subscribe(["inserted", "updated", "removed"], function() {
                toggleChildrenElementDebounced();
              });
            } else {
              tempCardWatcherOff = cardStore.watch(scope.card, "updated", function() {
                if (cardStore.isTemporaryCard(scope.card)) {
                  return;
                }
                if (tempCardWatcherOff) {
                  tempCardWatcherOff();
                }
                childrenWatcherOff = cardStore.scopedByParent(scope.card).subscribe(["inserted", "updated", "removed"], function() {
                  toggleChildrenElementDebounced();
                });
              });
            }
            showArchivedWatcherOff = scope.$watch("showArchived", (newVal, oldVal) => {
              if (newVal === oldVal) return;
              toggleChildrenElementDebounced();
            });
            showChildrenAttributesWatcherOff = scope.$watchGroup(["showChildrenAttributes", "showAttributes"], (newVal, oldVal) => {
              if (newVal === oldVal) return;
              toggleChildrenElementDebounced();
            });
            return offMany([
              childrenWatcherOff,
              tempCardWatcherOff,
              showArchivedWatcherOff,
              showChildrenAttributesWatcherOff
            ]);
          };
          const loadChildren = (cb2) => {
            if (!showChildren && doesChildrenNeedLoad()) {
              var card = cardStore.isValidLink(scope.card) ? scope.card.link : scope.card;
              const loaders = [loadChildCardsOf(card)];
              if (scope.showArchived) {
                loaders.push(loadArchivedChildCardsOf(card));
              }
              $q.all(loaders).then(cb2, () => {
                canLoadChildren = false;
              });
            } else {
              cb2();
            }
          };
          var canLoadChildren = true;
          if (!scope.disableChildrenToggle && !childrenCardsContainCard()) {
            if (scope.card.nb_children && canShowChildren()) {
              toggleChildrenElement(showChildren);
            }
            jquery_default($el).on("click", "> .card-tile-inner .js-toggle-children", function(e3) {
              if (!scope.card.nb_children || !canLoadChildren) {
                return;
              }
              e3.stopPropagation();
              e3.preventDefault();
              loadChildren(() => {
                toggleChildrenElement();
                if (scope.onToggleChildren) {
                  scope.onToggleChildren({
                    $card: cardStore.isValidLink(scope.card) ? scope.card.link : scope.card,
                    $toggleState: showChildren
                  });
                }
              });
            });
            scope.$on(scope.toggleChildrenKey + ":toggleChildren", function(event2, cardId, toggleState2) {
              if (cardId !== (cardStore.isValidLink(scope.card) ? scope.card.link.id : scope.card.id)) return;
              if (toggleState2 === showChildren) return;
              if (!canLoadChildren) return;
              loadChildren(() => {
                toggleChildrenElement(toggleState2);
              });
            });
          }
          var projectGlobalEventsOff = offMany([
            scope.$on("showAllChildren", function() {
              toggleChildrenElement(true);
            }),
            scope.$on("hideAllChildren", function() {
              toggleChildrenElement(false);
            })
          ]);
          if (scope.timelineSpec) {
            $el.on("click", ".js-go-to-card", function(event2) {
              event2.stopPropagation();
              scope.$evalAsync(function() {
                scope.timelineSpec.goToCard(scope.card);
              });
            });
            var timelineWatchOff = scope.timelineSpec.watch(scope, function() {
              toggleChildrenElement(showChildren);
              render3();
            });
            scope.$on("$destroy", timelineWatchOff);
          }
          scope.$on("$destroy", function() {
            toggleChildrenElementDebounced.clear();
            if (editorScope) {
              stopTitleEditor();
            }
            cardWatcherOff();
            lockOff();
            if (modelWatcherOff) {
              modelWatcherOff();
            }
            if (childrenListenersOff) {
              childrenListenersOff();
            }
            if (projectGlobalEventsOff) {
              projectGlobalEventsOff();
            }
            if (attributeReprWatcherOff) {
              attributeReprWatcherOff();
            }
          });
        };
      }
    };
  }
]);

// public/app/ui/card/ng-components/tree-view.js
angular_default.module("kantree").component("cardTreeView", {
  bindings: {
    projects: "<",
    defaultSelectedCard: "<?",
    withLeaves: "@",
    withLinks: "@",
    withSaveOption: "@",
    defaultIcon: "@",
    onChanged: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope", "$q"];
    createProjectsTree(callback) {
      const treeData = [];
      if (this.withSaveOption) {
        treeData.push({
          id: "new",
          card_id: "new",
          project_id: "new",
          text: _4("Save as new workspace"),
          type: "new"
        });
      }
      (this.projects || []).sort((a3, b3) => {
        return a3.title.localeCompare(b3.title, currentUser2.locale, { sensitivity: "base", ignorePunctuation: true, numeric: true });
      }).forEach((project) => {
        treeData.push({
          id: project.top_level_card.id.toString(),
          ref: project.top_level_card.ref,
          card_id: project.top_level_card.id,
          project_id: project.id,
          children: true,
          owner: project.owner,
          slug: project.slug,
          text: project.title,
          type: "project"
        });
      });
      callback(treeData);
    }
    formatChildren(path, children2 = []) {
      children2.forEach((child) => {
        const newPath = path ? path.slice() : [];
        newPath.push(child.id.toString());
        child.card_id = child.id;
        child.id = newPath.join("-");
        if (child.children) {
          if (child.type === "link") {
            child.children = [1];
          } else {
            this.formatChildren(newPath, child.children);
          }
        } else {
          child.type = "leave";
        }
      });
    }
    getHierarchy(node, callback) {
      if (node.original && node.original.id === "new") {
        return callback([]);
      }
      this.$q.when(api_default.cards.get_hierarchy.get({
        card_id: node.original ? node.original.card_id : node.id,
        with_leaves: this.withLeaves === "true",
        with_links: this.withLinks === "true",
        from_current: true
      }), (data2) => {
        const path = this.tree.get_path(node, null, true);
        this.formatChildren(path, data2.children);
        callback(data2.children || []);
      });
    }
    onCardSelected(card) {
      this.$scope.$evalAsync(() => {
        this.onChanged({
          project: card ? projectStore.getForCard(card) : null,
          card: card ? card : { id: "new" }
        });
      });
    }
    selectDefaultCard(data2) {
      if (!this.defaultSelectedCard) return;
      const node = data2.instance.get_node(this.defaultSelectedCard.id.toString());
      if (node && !node.state.disabled) {
        data2.instance.select_node(this.defaultSelectedCard.id.toString());
      }
    }
    initTree(treeElement) {
      treeElement.jstree({
        core: {
          themes: {
            dots: false,
            responsive: true
          },
          check_callback: true,
          data: (node, callback) => {
            if (node.id === "#") {
              this.createProjectsTree(callback);
            } else {
              this.getHierarchy(node, callback);
            }
          }
        },
        state: {
          events: ""
        },
        types: {
          new: {
            icon: "bi-plus-lg"
          },
          link: {
            icon: "bi-link"
          },
          leave: {
            icon: this.defaultIcon || "fa fa-square-o"
          },
          default: {
            icon: this.defaultIcon || "fa fa-columns"
          }
        },
        plugins: ["state", "wholerow", "types"]
      });
      this.tree = treeElement.jstree(true);
      treeElement.on("ready.jstree", (e3, data2) => {
        this.tree.deselect_all();
        this.selectDefaultCard(data2);
      });
      treeElement.on("refresh.jstree", (e3, data2) => {
        if (!data2.instance.get_selected(true).length) {
          this.selectDefaultCard(data2);
        }
      });
      treeElement.on("changed.jstree", (e3, data2) => {
        var node = data2.instance.get_selected(true)[0];
        if (node) {
          if (node.original.id === "new") {
            this.onCardSelected(null);
          } else {
            this.$q.when(getOrLoadCard(node.original.card_id || node.original.id), (card) => this.onCardSelected(card));
          }
        }
      });
    }
    $onChanges(changes) {
      if (["projects", "withLeaves", "withLinks", "withSaveOption"].some((binding) => changes[binding] && !changes[binding].isFirstChange())) {
        if (this.tree) {
          this.tree.destroy();
          this.tree = null;
        }
        this.initTree(jquery_default(this.$element));
      }
    }
    $onInit() {
      this.initTree(jquery_default(this.$element));
    }
  }
});

// public/app/ui/card/ng-components/utils.js
angular_default.module("kantree").component("cardTitleFromId", {
  template: `{{$ctrl.title}}`,
  bindings: {
    cardId: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.refresh();
    }
    $onChanges(changes) {
      if (changes.cardId && !changes.cardId.isFirstChange()) {
        this.refresh();
      }
    }
    refresh() {
      this.fetch(this.cardId).then((title) => {
        if (this.title != title) {
          this.title = title;
        }
      });
    }
    fetch(id) {
      return this.$q((resolve2, reject2) => {
        if (id) {
          getOrLoadCard(this.cardId, { ignoreErrorHandlers: true }).then((card) => resolve2(card.title), () => resolve2(""));
        } else {
          resolve2("");
        }
      });
    }
  }
});
angular_default.module("kantree").component("cardSelectorInput", {
  template: `<card-title-from-id card-id="$ctrl.value"></card-title-from-id> <button type="button"
    class="btn btn-default" ng-click="$ctrl.browse()" ng-disabled="$ctrl.isDisabled">{{::$ctrl.btnLabel}}</button>`,
  bindings: {
    card: "<?",
    org: "<?",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["cardBrowserModal"];
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.btnLabel = _4("Browse");
    }
    browse() {
      this.$cardBrowserModal.open(this.org, this.card).then((card) => this.ngModel.$setViewValue(card ? card.id : null));
    }
  }
});
angular_default.module("kantree").component("cardTargetInput", {
  template: `<card-title-from-id card-id="$ctrl.value.card_id"></card-title-from-id> <button type="button"
    class="btn btn-default" ng-click="$ctrl.browse()" ng-disabled="$ctrl.isDisabled">{{::$ctrl.btnLabel}}</button>`,
  bindings: {
    card: "<",
    org: "<?",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["cardTargetModal"];
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || {};
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.btnLabel = _4("Browse");
    }
    browse() {
      this.$cardTargetModal.open(this.org, this.card).then((selected) => {
        this.ngModel.$setViewValue({
          card_id: selected.board.id,
          groups: selected.groups.map((g3) => g3.id)
        });
      });
    }
  }
});

// public/app/ui/card/menus/batch-edit-menu.js
angular_default.module("kantree").factory("cardBatchEditMenuFactory", [
  "$q",
  "groupTypesMenuFactory",
  "attributeGroupMenuFactory",
  "cardTargetModal",
  "modelsMenuFactory",
  function($q, groupTypesMenuFactory, attributeGroupMenuFactory, cardTargetModal, modelsMenuFactory) {
    var getItems = function(options2) {
      var items = [];
      var attributes = cardModelStore.getExtendedModelAttributes(null, options2.project).filter(function(attr) {
        return attributeTypeRegistry.get(attr.type).batchable || attr.type === "group_type";
      });
      var batchAttributeGroup = new BatchAttributeGroup(options2.project, attributes, options2.batchParams);
      var _batch = function(op, params, batchParams) {
        batchParams = Object.assign({}, isFunction_default(options2.batchParams) ? options2.batchParams() : options2.batchParams, batchParams || {});
        function execute() {
          return $q.digest(batch3(options2.project, op, params, batchParams));
        }
        if (batchParams.card_ids && batchParams.card_ids.length > 10) {
          confirmDialog({
            title: _4("Confirm your action on many cards"),
            text: _4("{count} cards will be affected", { count: batchParams.card_ids.length })
          }).then(execute);
        } else {
          execute();
        }
      };
      var allCardsCompleted = false;
      if (options2.batchParams.group_id) {
        var groupCardsStore = cardStore.scoped({
          parent_id: function(parent_id) {
            return parent_id === options2.parent.id;
          },
          groups: matchGroup(options2.batchParams.group_id)
        });
        var groupCompletedCardsStore = groupCardsStore.scoped({
          state: function(state) {
            return state === "completed";
          }
        });
        var nbCards = groupCardsStore.count();
        allCardsCompleted = nbCards && nbCards === groupCompletedCardsStore.count();
      }
      var groupsMenuOptions = {
        parent: options2.parent,
        relocated: function(group2) {
          if (options2.parent) {
            _batch("relocate", { group_id: group2.id });
          }
        },
        toggled: function(group2) {
          _batch("add_to_group", { group_id: group2.id });
        },
        removed: function(groupType) {
          _batch("remove_from_group_type", { type_id: groupType.id });
        },
        canSelect: function(group2, opts) {
          if (group2) {
            return isAllowedInProject(options2.project, "card_group", "MOVE_CARDS", group2.id) && (!opts.groupType || !opts.groupType.attribute_id || isAllowedInProject(options2.project, "attribute", "EDIT", opts.groupType.attribute_id));
          } else {
            return isAllowedInProject(options2.project, "card_group", "MOVE_CARDS");
          }
        },
        canCreate: isAllowedInProject(options2.project, "card_group", "CREATE")
      };
      if (isAllowedInProject(options2.project, "card", "EDIT")) {
        items.push(
          {
            label: _4("Mark cards as completed"),
            offline: false,
            action: function() {
              _batch("set_state", { state: "completed" });
            },
            enabled: function() {
              return !allCardsCompleted;
            }
          },
          {
            label: _4("Re-open cards"),
            offline: false,
            action: function() {
              _batch("set_state", { state: "waiting" });
            },
            enabled: function() {
              return allCardsCompleted;
            }
          },
          {
            label: _4("Set type for all cards"),
            offline: false,
            submenu: modelsMenuFactory.getItems(null, {
              project: options2.project,
              canEditModels: false,
              canCreateModels: false,
              onSwitchModel(model) {
                _batch("switch_model", { model_id: model.id });
              }
            })
          }
        );
        var attributeGroupItems = attributeGroupMenuFactory.getItems({
          project: options2.project,
          attributeGroup: batchAttributeGroup,
          obj: { attributes: [], project_id: options2.project.id, parent_id: options2.parent.id },
          groupsMenuOptions: Object.assign({ card: null }, groupsMenuOptions)
        });
        if (attributeGroupItems.length) {
          items.push({
            label: _4("Set field for all cards"),
            offline: false,
            submenu: [{
              desc: _4("Only shows fields that support batch operations")
            }].concat(attributeGroupItems)
          });
        }
      }
      if (isAllowedInProjectFuzzy(options2.project, "card_group", "MOVE_CARDS")) {
        var allCardsTypeMenu = groupTypesMenuFactory.get(groupsMenuOptions);
        items.push(
          {
            label: _4("Set context for all cards"),
            offline: false,
            submenu: allCardsTypeMenu.config,
            options: allCardsTypeMenu.options
          },
          {
            label: _4("Move all cards to"),
            offline: false,
            action: () => {
              cardTargetModal.open().then((selected) => {
                _batch("relocate", { group_id: selected.groups.map((g3) => g3.id), parent_id: selected.board ? selected.board.id : null });
              });
            }
          }
        );
      }
      if (isAllowedInProjectFuzzy(options2.project, "card", "CREATE")) {
        items.push({
          label: _4("Duplicate all cards"),
          offline: false,
          action: () => {
            _batch("copy", {});
          }
        });
      }
      if (isAllowedInProject(options2.project, "card", "ARCHIVE")) {
        items.push({
          label: _4("Archive all cards"),
          offline: false,
          action: function() {
            _batch("archive", {});
          }
        }, {
          label: _4("Restore all cards"),
          offline: false,
          action: function() {
            _batch("restore", {}, { with_archived: true });
          }
        });
      }
      if (isAllowedInProject(options2.project, "card", "DELETE")) {
        items.push({
          label: _4("Delete all cards"),
          offline: false,
          action: function() {
            confirmDeleteDialog2().then(() => {
              _batch("delete", {}, options2.includeArchived ? { with_archived: true } : {});
            });
          }
        });
      }
      if (isAuthenticated()) {
        items.push({
          label: _4("Subscribe to all"),
          offline: false,
          action: function() {
            _batch("subscribe", {});
          }
        }, {
          label: _4("Unsubscribe to all"),
          offline: false,
          action: function() {
            _batch("unsubscribe", {});
          }
        });
      }
      return items;
    };
    return {
      getItems,
      get: function(options2) {
        return {
          config: function() {
            return getItems(options2);
          }
        };
      }
    };
  }
]);

// public/app/ui/card/menus/card-actions.js
angular_default.module("kantree").directive("cardActionsMenuToggle", [
  "cardActionsMenuFactory",
  "menuDropdown",
  function(cardActionsMenuFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        params: "<cardActionsMenuToggle"
      },
      link: function(scope, element2, attr) {
        var menu;
        var drop;
        scope.$watch("params", function(params) {
          if (params && params.card) {
            menu = cardActionsMenuFactory.get(params.card, params.options);
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu) {
            drop = menuDropdown.toggle(drop, element2[0], menu, scope, scope.params.dropConfig, event2);
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("cardActionsMenuFactory", [
  "cardModal",
  "$q",
  "groupTypesMenuFactory",
  "cardMoveModal",
  "modelsMenuFactory",
  "attributeGroupMenuFactory",
  "statesMenuFactory",
  "projectPage",
  "projectSettingsModal",
  "assistantModal",
  function(cardModal, $q, groupTypesMenuFactory, cardMoveModal, modelsMenuFactory, attributeGroupMenuFactory, statesMenuFactory, projectPage, projectSettingsModal, assistantModal) {
    return {
      getItems,
      watch,
      get: function(card, options2) {
        let menuOpts = {};
        if (options2 && !options2.hideGroupTypes) {
          menuOpts.watch = watch.bind(this, card);
        }
        return {
          config: () => getItems(card, options2 || {}),
          options: menuOpts,
          params: { card }
        };
      }
    };
    function watch(card, cb2, scope) {
      return groupTypesMenuFactory.watch({ card }, cb2, scope);
    }
    function getItems(card, {
      dataPrefetched = true,
      hideOpenModal,
      modalLoad,
      editable: editable2,
      hideGroupTypes,
      showCopyLink,
      hideShareableLink,
      showFavorite,
      showPrint,
      hideMakeReccuring,
      hideRequest,
      toggleModalDock,
      isDocked,
      showSelect
    } = {}) {
      const items = [];
      const project = projectStore.getForCard(card);
      const org2 = orgStore.tryGetForProject(project);
      const isArchived = card.is_archived || card.is_parent_archived;
      const isMirrorLink = card.is_link && !card.link_has_own_attributes;
      const _canEditCard = canEditCard(project, card.id);
      function insertSeparator() {
        if (items.length && items[items.length - 1].label !== "--") {
          items.push({ label: "--" });
        }
      }
      if (!hideOpenModal) {
        items.push({
          label: _4("View card"),
          icon: "external-link",
          action: () => {
            if (modalLoad) {
              cardModal.load(card.id);
            } else {
              cardModal.open(card);
            }
          }
        });
      }
      if (!card.parent_id && isSettingsButtonVisible(project)) {
        items.push({
          label: _4("Workspace settings"),
          icon: "sliders",
          offline: false,
          action: () => projectSettingsModal.open(project, null)
        });
      }
      if (card.parent_id && !isArchived && _canEditCard) {
        if (!card.finished) {
          items.push(...cardStateStore.getAvailableForCard(card, "completed").map((s3) => {
            return {
              label: _4("Mark as {state}", { state: s3.label }),
              icon: s3.icon + " fa-fw" || "fw",
              offline: false,
              action: () => $q.digest(setCardState(card, s3))
            };
          }));
        }
        const stateMenu = statesMenuFactory.get(card, {
          withGroupStates: isAllowedInProjectFuzzy(project, "card_group", "MOVE_CARDS")
        });
        items.push({
          label: _4("Mark as ..."),
          icon: "gavel",
          offline: false,
          submenu: stateMenu.config,
          options: stateMenu.options
        });
        if (card.board_created) {
          items.push({
            label: _4("Deactivate board"),
            icon: "times",
            offline: false,
            action: () => $q.digest(removeBoard(card)),
            enabled: () => card.board_created
          });
        }
      } else if (editable2 && !isArchived) {
        const subMenuItems = attributeGroupMenuFactory.getItems({
          project,
          attributeGroup: getCardCompositeModel(card, false).attributes,
          obj: card,
          dataPrefetched
        });
        if (subMenuItems.length) {
          items.push({
            label: _4("Edit field"),
            icon: "bi-pencil",
            offline: false,
            submenu: subMenuItems
          });
        }
      }
      if (!hideGroupTypes && card.parent_id && !isArchived && _canEditCard && isAllowedInProjectFuzzy(project, "card_group", "MOVE_CARDS") && canAddCard(project, card.parent_id)) {
        const groupTypeMenu = groupTypesMenuFactory.get({ card, dataPrefetched });
        items.push({
          label: _4("Set context"),
          icon: "bi-pencil",
          offline: false,
          submenu: groupTypeMenu.config,
          options: groupTypeMenu.options
        });
      }
      if (card.parent_id && editable2 && !isArchived && isAllowedInProject(project, "card", "SWITCH_MODEL", card.id)) {
        const modelMenu = modelsMenuFactory.get(card, { dataPrefetched });
        items.push({
          label: _4("Set card type"),
          icon: "bi-pencil-square",
          offline: false,
          submenu: modelMenu.config,
          options: modelMenu.options
        });
      }
      insertSeparator();
      if (showCopyLink) {
        items.push({
          label: _4("Copy card URL"),
          component: "card-copy-url-menu-item",
          params: { project, card }
        });
      }
      if (!hideShareableLink && !isMirrorLink && !project.is_template && !isArchived && card.parent_id && (canManageMembers(project) || isCurrentUserMemberOfProject(project) && card.share_token)) {
        items.push({
          label: _4("Share"),
          icon: "bi-share-fill",
          offline: false,
          submenu: () => {
            return [{
              component: "sharing-editor-menu-component",
              backAfterAction: true,
              params: {
                object_id: card.id,
                object_type: "card"
              }
            }];
          }
        });
      }
      if (showFavorite && !isMirrorLink && card.parent_id && isAuthenticated() && !project.is_template && !isArchived) {
        if (!isFavorite("card", card.id)) {
          items.push({
            label: _4("Add to favorites"),
            icon: "star-o",
            offline: false,
            action: () => $q.digest(toggleCardAsFavorite(card))
          });
        } else {
          items.push({
            label: _4("Remove from favorites"),
            icon: "star",
            offline: false,
            action: () => $q.digest(toggleCardAsFavorite(card))
          });
        }
      }
      if (!isMirrorLink && showPrint) {
        items.push({
          label: _4("Print"),
          icon: "print",
          action: () => {
            window.print();
          }
        });
      }
      if (org2?.ai_assistant_enabled) {
        items.push({
          label: _4("Ask Kantree Assistant"),
          icon: "bi-stars",
          offline: false,
          action: () => {
            assistantModal.open(org2, { project, card });
          }
        });
      }
      insertSeparator();
      if (!hideMakeReccuring && !isMirrorLink && !project.is_template && !isArchived && card.parent_id && canManageRecurring(project)) {
        const recurringCardMenu = getRecurringCardEditorMenu({
          template_id: card.id,
          groups: (card.groups || []).map((group2) => group2.id)
        });
        items.push({
          label: _4("Make this card recurring"),
          icon: "refresh fa-rotate-90",
          offline: false,
          submenu: recurringCardMenu.config,
          options: recurringCardMenu.options
        });
      }
      if (!hideRequest && !isMirrorLink && card.from_request && isAllowedInProject(project, "request", "DELETE")) {
        items.push({
          label: _4("Delete associated request"),
          icon: "inbox",
          offline: false,
          action: () => {
            $q.digest(confirmDeleteDialog2().then(() => {
              return deleteCardRequest(card);
            }));
          }
        });
      } else if (!hideRequest && !isMirrorLink && !card.from_request && !project.is_template && !isArchived && card.parent_id && isAllowedInProject(project, "request", "CREATE")) {
        const availableRequestForms = requestFormStore.scopedByProject(project).query();
        if (availableRequestForms.length) {
          items.push({
            label: _4("Create a request"),
            icon: "inbox",
            offline: false,
            submenu: [
              { subheader: _4("Select which form to use:") }
            ].concat(availableRequestForms.map((form) => {
              return {
                label: form.name,
                action: () => {
                  let p4;
                  if (form.anonymous_email_field_idx === null && form.email_required) {
                    p4 = inputDialog(_4("Address email to associate with the request:"), {
                      inputValidator(value2) {
                        if (!value2 || !value2.match(/^.*@.*\.[a-z]+/)) {
                          return Promise.reject(_4("Invalid email address!"));
                        }
                        return Promise.resolve(value2);
                      }
                    }).then((email2) => {
                      if (email2 === false) {
                        return Promise.reject();
                      }
                      return email2;
                    });
                  } else {
                    p4 = Promise.resolve(null);
                  }
                  $q.digest(p4.then((email2) => createCardRequest(card, form, email2)));
                }
              };
            }))
          });
        }
      }
      insertSeparator();
      if (toggleModalDock && cardModal.isDockable()) {
        items.push({
          label: isDocked ? _4("Open in a modal window") : _4("Dock to the right"),
          icon: isDocked ? "bi-caret-up-square" : "bi-caret-right-square",
          action: toggleModalDock
        });
      }
      insertSeparator();
      if (!isMirrorLink && !isArchived && card.parent_id && canAddCard(project)) {
        items.push({
          label: _4("Duplicate"),
          icon: "files-o",
          offline: false,
          action: () => $q.digest(duplicateCard(card))
        });
        if (!project.is_template) {
          items.push({
            label: _4("Move"),
            icon: "arrow-right",
            offline: false,
            action: () => cardMoveModal.open(card)
          });
        }
      }
      if (!isArchived && !project.is_template && card.parent_id && canArchiveCard(project, card.id)) {
        items.push({
          label: _4("Archive"),
          icon: "bi-archive",
          offline: false,
          action: () => {
            $q.digest(confirmDeleteDialog2(_4("Are you sure you want to archive?"), null, _4("Archive")).then(() => {
              return archiveCard(card);
            }));
          }
        });
      }
      if (card.parent_id && card.is_archived && canArchiveCard(project, card.id)) {
        items.push({
          label: _4("Restore"),
          icon: "bi-arrow-return-left",
          offline: false,
          action: () => $q.digest(restoreCard(card))
        });
      }
      if (card.parent_id && canDeleteCard(project, card.id)) {
        items.push({
          label: _4("Delete"),
          icon: "trash",
          offline: false,
          action: () => {
            $q.digest(confirmDeleteDialog2(null, _4("This card will be permanently deleted")).then(() => {
              return deleteCard(card);
            }));
          }
        });
      }
      insertSeparator();
      if (projectPage.isProjectActive(project) && showSelect) {
        items.push(
          {
            label: _4("Select"),
            icon: "bi-check2",
            action: () => projectPage.selectCard(card),
            enabled: () => !projectPage.isCardSelected(card)
          },
          {
            label: _4("Unselect"),
            icon: "bi-square",
            action: () => projectPage.unselectCard(card),
            enabled: () => projectPage.isCardSelected(card)
          },
          {
            label: _4("Select all"),
            icon: "bi-check2-all",
            action: () => projectPage.selectAllCards()
          }
        );
      }
      if (items[items.length - 1].label === "--") {
        items.pop();
      }
      return items;
    }
    ;
  }
]);
angular_default.module("kantree").component("cardCopyUrlMenuItem", {
  bindings: {
    params: "<?",
    onClose: "&"
  },
  template: `
    <span class="menu-item-default is-clickable">
      <button class="menu-item-main-action-button">
        <i class="menu-icon fa fa-clipboard"></i>
        <span class="menu-item-label">{{::$ctrl.label}}</span>
      </button>
      <button type="button"
        class="btn btn-sm btn-default btn-text btn-icon menu-item-additional-button"
        ng-click="$ctrl.openQRCode()"
        uib-tooltip="{{::$ctrl.qrcodeLabel}}">
        <i class="menu-icon bi-qr-code"></i>
      </button>
    </span>
  `,
  controller: class extends AngularClass {
    static $inject = ["$element", "$state", "qrcodeModal"];
    $onInit() {
      this.label = _4("Copy card URL");
      this.qrcodeLabel = _4("Get QR Code");
      this.url = makeUrlAbsolute(this.$state.href("project", { projectId: this.params.project.slug, "#": this.params.card.ref }));
    }
    openQRCode() {
      this.$qrcodeModal.open(this.url, this.params.card.title);
    }
    $postLink() {
      this.clip = new clipboard_default(this.$element[0], { text: () => this.url });
      this.$element.on("click", () => this.onClose());
    }
    $onDestroy() {
      this.clip && this.clip.destroy();
    }
  }
});

// public/app/ui/card/menus/card-filter.js
angular_default.module("kantree").factory("cardFilterMenuFactory", [
  function() {
    return {
      getItems: function(project, board, includeArchived, append2) {
        let items = [];
        if (project) {
          const attrsIndex = {};
          const attrItems = cardModelStore.scopedByEnabled(project).getSupportingAttributes("filterable").sort().reduce((accu, attr) => {
            const attrType = attributeTypeRegistry.get(attr.type);
            if (!attrType) return accu;
            const attrItems2 = attrType.getFilters(project, attr, append2);
            if (!attrItems2.length) return accu;
            if (typeof attrsIndex[attr.name] !== "undefined" && attrsIndex[attr.name].indexOf(attr.type) !== -1) {
              return accu;
            }
            if (typeof attrsIndex[attr.name] === "undefined") {
              attrsIndex[attr.name] = [];
            }
            attrsIndex[attr.name].push(attr.type);
            return accu.concat([{
              label: attr.name,
              submenu: attrItems2
            }]);
          }, []);
          if (attrItems.length > 0) {
            items.push(...attrItems, { label: "--" });
          }
          const groupTypeItems = cardGroupTypeStore.scopedByEnabled(project).query({}, { sortBy: "name" }).reduce((accu, groupType) => {
            const groups = cardGroupStore.scopedByType(groupType, board).query();
            if (!groups.length) return accu;
            return accu.concat([{
              label: groupType.name,
              submenu: [
                {
                  label: _4("None"),
                  action: () => {
                    append2("not #" + escapeKqlName(groupType.name) + ":*");
                  }
                },
                {
                  label: _4("Any"),
                  action: () => {
                    append2("#" + escapeKqlName(groupType.name) + ":*");
                  }
                },
                { label: "--" }
              ].concat(groups.map((group2) => {
                return {
                  label: group2.title,
                  color: group2.color,
                  icon: group2.icon,
                  classes: "icon-right",
                  action: () => {
                    append2("#" + escapeKqlName(groupType.name) + ":" + escapeKqlName(group2.title));
                  }
                };
              }))
            }]);
          }, []);
          if (groupTypeItems.length > 0) {
            items.push(...groupTypeItems, { label: "--" });
          }
        }
        items.push({
          label: _4("For me"),
          submenu: [
            {
              label: _4("Assigned or mentionned in any fields or comments"),
              action: () => {
                append2("@me or mentions?(@me)");
              }
            },
            {
              label: _4("Assigned in any fields"),
              action: () => {
                append2("@me");
              }
            },
            {
              label: _4("Mentionned"),
              action: () => {
                append2("mentions?(@me)");
              }
            },
            {
              label: _4("Subscribed to"),
              action: () => {
                append2("is_subscribed?()");
              }
            },
            {
              label: _4("Created by me"),
              action: () => {
                append2("{created by}=@me");
              }
            }
          ]
        });
        if (project) {
          items.push({
            label: _4("Type"),
            submenu: [{
              label: _4("No type"),
              action: () => {
                append2("{type}=empty");
              }
            }].concat((project ? cardModelStore.scopedByEnabled(project).query({ base_model_id: query_exports.isUndefined() }, { sortBy: "name" }) : []).map(function(model) {
              return {
                label: model.name,
                action: () => {
                  append2('{type}="' + model.name + '"');
                }
              };
            }))
          });
        }
        items.push(
          {
            label: _4("State"),
            submenu: cardStateStore.getBuiltinStates().map(function(state) {
              return {
                label: state.label,
                action: () => {
                  append2("{state}=" + state.id);
                }
              };
            })
          },
          {
            label: _4("Has shareable link"),
            submenu: [[_4("Yes"), "yes"], [_4("No"), "no"]].map(function(item) {
              return {
                label: item[0],
                action: () => {
                  append2("{shared}=" + item[1]);
                }
              };
            })
          },
          {
            label: _4("Archived"),
            submenu: [[_4("Yes"), "yes"], [_4("No"), "no"]].map(function(item) {
              return {
                label: item[0],
                action: () => {
                  append2("{archived}=" + item[1]);
                }
              };
            }),
            enabled: function() {
              return includeArchived;
            }
          }
        );
        if (items[items.length - 1].label === "--") {
          items.pop();
        }
        return items;
      },
      transformItemsInPanels: function(items, append2) {
        return items.map((i3) => {
          const item = { ...i3 };
          if (item.items) {
            item.submenu = this.transformItemsInPanels(item.items);
            delete item.items;
          } else if (item.label && !item.action) {
            item.action = () => {
              append2(item.filter);
            };
          }
          return item;
        });
      },
      transformItemsInExpandableItems: function(items, append2) {
        return items.map((i3) => {
          const item = { ...i3 };
          if (item.items) {
            item.type = "expandable-items";
            item.items = this.transformItemsInExpandableItems(item.items);
          } else if (item.submenu) {
            item.type = "expandable-items";
            item.items = this.transformItemsInExpandableItems(item.submenu);
            delete item.submenu;
          } else if (item.label && !item.action) {
            item.action = () => {
              append2(item.filter);
            };
          }
          return item;
        });
      },
      getExpandableItems: function(project, board, includeArchived, append2) {
        return this.transformItemsInExpandableItems(this.getItems(project, board, includeArchived, append2), append2);
      },
      get: function(project, board, includeArchived, append2) {
        return { config: this.getItems(project, board, includeArchived, append2) };
      }
    };
  }
]);

// public/app/ui/card/menus/states.js
angular_default.module("kantree").directive("statesMenuToggle", [
  "statesMenuFactory",
  "menuDropdown",
  function(statesMenuFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        params: "<statesMenuToggle"
      },
      link: function(scope, element2, attr) {
        var menu;
        var drop;
        scope.$watch("params", function(params) {
          if (params && params.card) {
            menu = statesMenuFactory.get(params.card, params.options);
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu) {
            drop = menuDropdown.toggle(drop, element2[0], menu, scope, null, event2);
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("statesMenuFactory", [
  "$q",
  function($q) {
    var defaultOptions4 = {
      filters: void 0,
      withoutTitles: false,
      withGroupStates: true
    };
    var isCardInAliasState = function(card, builtinState) {
      return card && card.groups.map(function(group2) {
        return cardGroupStore.tryGet(group2.id);
      }).filter(function(group2) {
        if (group2 && !group2.is_archived && group2.card_state && group2.card_state === builtinState.id) {
          return true;
        }
      }).length;
    };
    var isCardInGroup = function(card, group2) {
      return card && card.groups.filter(function(g3) {
        if (g3.id === group2.id) {
          return true;
        }
      }).length;
    };
    var getItems = function(card, opts) {
      var options2 = Object.assign({}, defaultOptions4, opts || {});
      var items = [];
      var project;
      var allowedGroupsId;
      if (opts.withGroupStates) {
        project = projectStore.getForCard(card);
        allowedGroupsId = getGroupsEnablingCardMoving(project);
        if (allowedGroupsId === true || !allowedGroupsId.length) {
          allowedGroupsId = null;
        }
        var fromGroupStates = cardStateStore.getAvailableAliasesForCard(card, options2.filters, allowedGroupsId);
        if (fromGroupStates.length) {
          if (!options2.withoutTitles) {
            items.push({
              subheader: _4("Groups linked to a state")
            });
          }
          items.push.apply(items, fromGroupStates.map(function(state) {
            return {
              label: state.label,
              icon: state.icon + " fa-fw" || "fw",
              action: function() {
                return $q.digest(setCardState(card, state));
              },
              selected: function() {
                return state.id === card.state_alias_id || state.alias === card.state && isCardInGroup(card, state);
              }
            };
          }));
          if (!options2.withoutTitles) {
            items.push({ label: "--" });
          }
        }
      }
      var builtinStates = cardStateStore.getBuiltinStates(options2.filters);
      if (builtinStates.length) {
        if (!options2.withoutTitles) {
          items.push({
            subheader: _4("Built-in States")
          });
        }
        items.push.apply(items, builtinStates.map(function(state) {
          return {
            label: _4(state.label),
            icon: state.icon + " fa-fw" || "fw",
            action: function() {
              return $q.digest(setCardState(card, state));
            },
            selected: function() {
              return state.id === card.state && card.state_alias_id === null && !isCardInAliasState(card, state);
            },
            disabled: function() {
              return !state.alias && isCardInAliasState(card, state);
            }
          };
        }));
      }
      return items;
    };
    var watch = function(card, cb2, scope) {
      var off = cardStateStore.$watchAll(scope, function() {
        cb2 && cb2();
      }, false);
      return off;
    };
    return {
      getItems,
      watch,
      get: function(card, options2) {
        var menuOpts = {
          watch: watch.bind(this, card)
        };
        var menuConfig = function() {
          return getItems.bind(this, card, options2);
        };
        return {
          config: menuConfig,
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/ui/card/menus/subscription.js
angular_default.module("kantree").directive("cardSubscriptionMenuToggle", [
  "cardSubscriptionMenuSpecFactory",
  "menuDropdown",
  function(cardSubscriptionMenuSpecFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        card: "<cardSubscriptionMenuToggle",
        subscriptionStateOnly: "<?"
      },
      link: function(scope, element2) {
        var menu;
        var drop;
        scope.$watch("card", function() {
          if (scope.card) {
            menu = cardSubscriptionMenuSpecFactory(scope.card, scope.subscriptionStateOnly);
          } else {
            menu = null;
            if (menuDropdown.isOpened(drop)) {
              menuDropdown.close();
            }
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu) {
            drop = menuDropdown.toggle(drop, element2[0], menu, scope, null, event2);
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("cardSubscriptionMenuSpecFactory", [
  "$q",
  function($q) {
    var translatedTargets = [{
      value: "creator",
      label: _4("me")
    }, {
      value: "subscribers",
      label: _4("card subscribers")
    }, {
      value: "members",
      label: _4("selected members in fields")
    }, {
      value: "project_members",
      label: _4("all workspace members")
    }];
    function formatTargets(targets) {
      return targets.map(function(target) {
        return translatedTargets.find(function(t3) {
          return t3.value === target;
        });
      }).filter(function(target) {
        return target !== null;
      }).map(function(target) {
        return target.label;
      });
    }
    function formatEnum2(recapEnum) {
      if (recapEnum.length <= 1) {
        return recapEnum.join(", ");
      } else {
        return recapEnum.slice(0, -1).join(", ") + " " + _4("and") + " " + recapEnum[recapEnum.length - 1];
      }
    }
    function buildTargetRecap(targets, user_target) {
      if (user_target !== "creator") {
        targets = targets.filter(function(target) {
          return target !== "creator";
        });
      }
      return formatEnum2(formatTargets(targets.slice().reverse()));
    }
    function buildAttributeDateRecap(attr, reminder) {
      var reminderDate = moment_default.utc(reminder.reminding_date);
      var attributeDate = moment_default.utc(attr.value.end);
      if (attr.value.end.indexOf(" ") === -1) {
        attributeDate.startOf("day");
      }
      reminderDate.locale(getCurrentLocale());
      var diff = reminderDate.from(attributeDate, true);
      if (reminderDate.isSameOrBefore(attributeDate)) {
        return _4("{diff} before {attr_name}", {
          diff,
          attr_name: attr.name
        });
      } else {
        return _4("{diff} after {attr_name}", {
          diff,
          attr_name: attr.name
        });
      }
    }
    function buildRecap2(card, reminder) {
      var recap = _4("For {targets}", { targets: buildTargetRecap(reminder.targets, reminder.user_target) });
      if (reminder.attribute_id) {
        var attr = getCardAttribute(card, reminder.attribute_id);
        if (attr) {
          recap += " - " + buildAttributeDateRecap(attr, reminder);
        }
      }
      return recap;
    }
    function getItems(card, stateOnly) {
      var items = [];
      items.push({
        checkbox: true,
        value: cardSubscriptionStore.isSubscribed(card) || cardGroupSubscriptionStore.isSubscribedToCard(card),
        // disables card subscribe action if the user is already subscribed to card through one of its group.
        isDisabled: cardGroupSubscriptionStore.isSubscribedToCard(card),
        label: _4("Subscribed"),
        noCloseAfterToggle: true,
        toggle: function(isChecked) {
          if (cardSubscriptionStore.isSubscribed(card) === isChecked) {
            return;
          }
          return $q.digest(toggleCardSubscription(card));
        }
      });
      var groupSubscriptions = cardGroupSubscriptionStore.getAllForCard(card, true).map(function(g3) {
        return g3[1].title;
      });
      if (groupSubscriptions.length) {
        items.push({
          desc: _n(
            "You are subscribed to this card because you have enabled card notifications in {group} group which contains this card.",
            "You are subscribed to this card because you have enabled card notifications in {group} groups which contain this card.",
            groupSubscriptions.length,
            { group: formatEnum2(groupSubscriptions) }
          ),
          classes: "mod-group-subscribed"
        });
      }
      items.push({
        desc: _4("Subscribers receive notifications when something changes")
      });
      if (stateOnly) {
        return items;
      }
      var project = projectStore.getForCard(card);
      var reminders = cardReminderStore.getForCard(card).filter((reminder) => {
        if (!reminder.attribute_id) return true;
        const attr = getCardAttribute(card, reminder.attribute_id);
        return !!attr && !!attr.value;
      });
      if (reminders && reminders.length) {
        items.push({
          label: "--"
        });
        items.push({
          subheader: _4("Reminders")
        });
        moment_default.locale("en");
        items.push.apply(
          items,
          reminders.sort(function(a3, b3) {
            return moment_default.utc(a3.reminding_date).isBefore(moment_default.utc(b3.reminding_date)) ? -1 : 1;
          }).map(function(reminder) {
            var date = moment_default.utc(reminder.reminding_date).local();
            date.locale(getCurrentLocale());
            return {
              icon: "bell",
              label: date.fromNow(),
              small: buildRecap2(card, reminder),
              classes: "mod-reminder",
              buttons: [{
                icon: "trash",
                classes: "btn-text btn-danger",
                action: function() {
                  $q.digest(deleteCardReminder(card, reminder));
                },
                noCloseAfterAction: true,
                enabled: function() {
                  return isAllowedInProject(project, "project", "MANAGE_REMINDERS");
                }
              }]
            };
          })
        );
        moment_default.locale(getCurrentLocale());
      }
      if (isAllowedInProject(project, "project", "MANAGE_REMINDERS")) {
        items.push({
          label: "--"
        });
        items.push({
          label: _4("Add reminder"),
          icon: "plus",
          offline: false,
          submenu: [{
            component: "reminder-editor-menu-component",
            params: { card },
            backAfterAction: true
          }]
        });
      }
      return items;
    }
    return function(card, stateOnly) {
      return {
        config: function() {
          return getItems.bind(this, card, stateOnly);
        },
        options: {
          watch: function(callback, scope) {
            return offMany([
              cardReminderStore.scopedByCard(card).$watchAll(scope, callback, false),
              cardSubscriptionStore.$on(scope, ["inserted", "removed"], callback)
            ]);
          },
          fetchData: function(callback) {
            $q.digest(loadRemindersForCard(card, callback));
          }
        }
      };
    };
  }
]);

// public/app/ui/card/modals/add-link.js
angular_default.module("kantree").factory("addCardLinkModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(card, groups, dynamicGroups, attributes) {
        var scope = $rootScope.$new();
        scope.card = card;
        scope.groups = groups;
        scope.dynamicGroups = dynamicGroups;
        scope.attributes = attributes;
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/card/modals/templates/add-link-modal.html",
          windowClass: "add-link-modal",
          controller: "addCardLinkModalCtrl",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("addCardLinkModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.mirroredCard = !$scope2.dynamicGroups || !$scope2.dynamicGroups.length;
    $scope2.addLink = function(target) {
      $q.when(createCardLink($scope2.card, target.id, !$scope2.mirroredCard, $scope2.groups, $scope2.attributes), (card) => {
        if (!$scope2.mirroredCard) {
          $scope2.dynamicGroups.forEach((group2) => {
            $q.digest(group2.handleCardEnter(card, false));
          });
        }
        $uibModalInstance.close();
      });
    };
    $scope2.selectCard = function(card) {
      $scope2.selectedCard = card;
    };
  }
]);

// public/app/ui/card/modals/browser.js
angular_default.module("kantree").factory("cardBrowserModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(org2, card) {
        var scope = $rootScope.$new();
        scope.org = org2;
        scope.card = card;
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/card/modals/templates/browser-modal.html",
          windowClass: "card-browser-modal",
          controller: "cardBrowserModalCtrl",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance.result;
      }
    };
  }
]);
angular_default.module("kantree").controller("cardBrowserModalCtrl", [
  "$scope",
  function($scope2) {
    $scope2.selectCard = function(card) {
      $scope2.selectedCard = card;
    };
  }
]);

// public/app/ui/card/modals/icalendar.js
angular_default.module("kantree").factory("cardICalendarModal", [
  "iCalendarModal",
  "$q",
  function(iCalendarModal, $q) {
    return {
      open(card, attrId) {
        let params = { card_id: card.id };
        if (attrId) {
          params["attr_id"] = attrId;
        }
        iCalendarModal.open($q.digest(api_default.calendar.get_url.get(params)));
      }
    };
  }
]);

// public/app/ui/card/modals/move.js
angular_default.module("kantree").factory("cardMoveModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(card, callback) {
        var scope = $rootScope.$new();
        scope.card = card;
        var project = projectStore.get(card.project_id);
        scope.defaultSelectedCard = project.top_level_card === card ? { id: "new", project_id: project.id } : project.top_level_card;
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/card/modals/templates/move-modal.html",
          windowClass: "card-move-modal",
          controller: "cardMoveModalCtrl",
          scope
        });
        instance.result.finally(function() {
          callback && callback();
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("cardMoveModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$state",
  "$q",
  function($scope2, $uibModalInstance, $state, $q) {
    $scope2.withCopy = false;
    $scope2.disableWithCopy = $scope2.card.parent_id === null;
    $scope2.textColor = textColor;
    $scope2.isReadable = colors_exports.isReadable;
    var defaultSelectedGroups = $scope2.card.groups.reduce(function(accu, group2) {
      if (!cardGroupStore.exists(group2.id)) {
        return accu;
      }
      var g3 = cardGroupStore.get(group2.id);
      var gt = cardGroupTypeStore.tryGet(g3.type_id);
      if (!gt || gt.attribute_id) {
        return accu;
      }
      return accu.concat(g3);
    }, []);
    var firstLoad = true;
    function isCardInSelectedBoardPath() {
      return !!$scope2.selectedOrg && !!$scope2.selectedBoard && $scope2.selectedBoard.id !== "new" && ($scope2.selectedBoard.id === $scope2.card.id || $scope2.selectedBoard.path.some(function(board) {
        return parseInt(board.id, 10) === $scope2.card.id;
      }));
    }
    function isCardTopLevelAndSelectedBoardHasSameOwner() {
      var cardProject = projectStore.get($scope2.card.project_id);
      return !$scope2.card.parent_id && $scope2.selectedBoard && $scope2.selectedBoard.id === "new" && $scope2.selectedOrg.id === cardProject.owner.id && (!$scope2.selectedTeam && !cardProject.team || $scope2.selectedTeam && cardProject.team && cardProject.team.id === $scope2.selectedTeam.id);
    }
    $scope2.allow = function() {
      return !!$scope2.selectedOrg && !!$scope2.selectedBoard && ($scope2.selectedBoard.id === "new" && !isCardTopLevelAndSelectedBoardHasSameOwner() || $scope2.selectedBoard.id !== "new" && !isCardInSelectedBoardPath());
    };
    function updateSelectedGroups(groups) {
      $scope2.selectedGroups = groups;
    }
    function resetSelectedGroups() {
      updateSelectedGroups([]);
    }
    function filterSelectedGroupsWithEnabledGroupType() {
      function filterWithEnabledGroupType(groups) {
        return groups.filter(function(group2) {
          var groupParent = group2.parent_id ? cardStore.tryGet(group2.parent_id) : null;
          var groupType = cardGroupTypeStore.tryGet(group2.type_id);
          return group2.scope === "org" && groupType && groupType.used_by.indexOf($scope2.selectedBoard.project_id) !== -1 || group2.scope === "project" && groupParent && groupParent.project_id === $scope2.selectedBoard.project_id || group2.scope === "card" && group2.parent_id === $scope2.selectedBoard.id;
        });
      }
      var newSelectedGroups;
      if (firstLoad) {
        newSelectedGroups = filterWithEnabledGroupType(defaultSelectedGroups);
        firstLoad = false;
      } else {
        newSelectedGroups = filterWithEnabledGroupType($scope2.selectedGroups);
      }
      updateSelectedGroups(newSelectedGroups);
    }
    $scope2.handleSelectionUpdate = function(board, project, org2, team) {
      $scope2.selectedBoard = board;
      $scope2.selectedOrg = org2;
      $scope2.selectedTeam = team;
      $scope2.selectedProject = project;
      $scope2.isCardInSelectedBoardPath = isCardInSelectedBoardPath();
      $scope2.isCardTopLevelAndSelectedBoardHasSameOwner = isCardTopLevelAndSelectedBoardHasSameOwner();
      $scope2.isMoveDisabled = !$scope2.allow();
      if (!board || board.id === "new") {
        resetSelectedGroups();
        $scope2.canSelectGroups = false;
        return;
      }
      filterSelectedGroupsWithEnabledGroupType();
      $q.when(loadAllAvailableGroupsForCard(board), (groups) => {
        $scope2.canSelectGroups = groups.length > 0;
      });
    };
    $scope2.handleGroupSelect = function(groups) {
      updateSelectedGroups(groups);
    };
    $scope2.moveTo = function() {
      const cardRespHandler = (data2) => {
        const [card, target_project_slug] = data2;
        $uibModalInstance.close();
        if (target_project_slug) {
          $state.go("project", { projectId: target_project_slug });
        }
      };
      const projectRespHandler = (project) => {
        $uibModalInstance.close();
        if (project && project.slug) {
          $state.go("project", { projectId: project.slug });
        }
      };
      const selectedBoard = $scope2.selectedBoard && $scope2.selectedBoard.id !== "new" ? $scope2.selectedBoard : null;
      if (!selectedBoard) {
        if ($scope2.card.parent_id) {
          $q.when(convertCardToProject($scope2.card, $scope2.selectedOrg, $scope2.selectedTeam, $scope2.withCopy), projectRespHandler);
        } else {
          $q.when(moveProjectTo(
            { id: $scope2.card.project_id },
            { id: $scope2.selectedOrg.type === "org" ? $scope2.selectedOrg.id : null },
            $scope2.selectedTeam,
            $scope2.withCopy
          ), projectRespHandler);
        }
      } else {
        $q.when(moveCardTo($scope2.card, selectedBoard, $scope2.selectedGroups, $scope2.withCopy), cardRespHandler);
      }
    };
  }
]);

// public/app/ui/card/modals/save-as-tpl.js
angular_default.module("kantree").factory("cardSaveAsTplModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(card) {
        var scope = $rootScope.$new();
        scope.project = projectStore.getForCard(card);
        scope.board = card;
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/card/modals/templates/save-as-tpl-modal.html",
          windowClass: "card-save-as-tpl-modal",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);

// public/app/ui/card/modals/self-attributes.js
angular_default.module("kantree").factory("cardSelfAttributesModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(card) {
        var scope = $rootScope.$new();
        scope.card = card;
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/card/modals/templates/self-attributes-modal.html",
          windowClass: "card-self-attributes-modal",
          controller: "cardSelfAttributesModalCtrl",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("cardSelfAttributesModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.selfModel = { attributes: [] };
    if ($scope2.card.has_self_attributes) {
      $q.when(api_default.cards.get_self_attributes.get({ card_id: $scope2.card.id }), (attrs2) => {
        $scope2.selfModel.attributes = attrs2;
      });
    }
    var resetAttrOptions = function() {
      $scope2.selfModel.attributes.forEach(function(attr) {
        for (var opt in attr.opts) {
          if (attr.opts[opt] === "") {
            delete attr.opts[opt];
          }
        }
        attr.options = attr.opts;
        delete attr.opts;
      });
    };
    $scope2.save = function() {
      resetAttrOptions();
      if ($scope2.selfModel.attributes.length) {
        $q.when(api_default.cards.update_self_attributes.put({ card_id: $scope2.card.id, attributes: $scope2.selfModel.attributes }), (attrs2) => {
          cardStore.update($scope2.card, { has_self_attributes: attrs2.length > 0 });
          $uibModalInstance.close();
        });
      }
    };
  }
]);

// public/app/ui/card/modals/target.js
angular_default.module("kantree").factory("cardTargetModal", [
  "$uibModal",
  "$rootScope",
  function($uibModal, $rootScope) {
    return {
      open: function(card) {
        var scope = $rootScope.$new();
        scope.card = card;
        if (card) {
          var project = projectStore.get(card.project_id);
          scope.defaultSelectedCard = project.top_level_card === card ? { id: "new", project_id: project.id } : project.top_level_card;
        }
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/card/modals/templates/target-modal.html",
          windowClass: "card-move-target-modal",
          controller: "cardTargetModalCtrl",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance.result;
      }
    };
  }
]);
angular_default.module("kantree").controller("cardTargetModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.textColor = textColor;
    $scope2.isReadable = colors_exports.isReadable;
    var firstLoad = true;
    var defaultSelectedGroups = [];
    if ($scope2.card) {
      defaultSelectedGroups = $scope2.card.groups.reduce(function(accu, group2) {
        if (!cardGroupStore.exists(group2.id)) {
          return accu;
        }
        var g3 = cardGroupStore.get(group2.id);
        var gt = cardGroupTypeStore.tryGet(g3.type_id);
        if (!gt || gt.attribute_id) {
          return accu;
        }
        return accu.concat(g3);
      }, []);
    }
    function updateSelectedGroups(groups) {
      $scope2.selectedGroups = groups;
    }
    function resetSelectedGroups() {
      updateSelectedGroups([]);
    }
    function filterSelectedGroupsWithEnabledGroupType() {
      function filterWithEnabledGroupType(groups) {
        return groups.filter(function(group2) {
          var groupParent = group2.parent_id ? cardStore.tryGet(group2.parent_id) : null;
          var groupType = cardGroupTypeStore.tryGet(group2.type_id);
          return group2.scope === "org" && groupType && groupType.used_by.indexOf($scope2.selectedBoard.project_id) !== -1 || group2.scope === "project" && groupParent && groupParent.project_id === $scope2.selectedBoard.project_id || group2.scope === "card" && group2.parent_id === $scope2.selectedBoard.id;
        });
      }
      var newSelectedGroups;
      if (firstLoad) {
        newSelectedGroups = filterWithEnabledGroupType(defaultSelectedGroups);
        firstLoad = false;
      } else {
        newSelectedGroups = filterWithEnabledGroupType($scope2.selectedGroups);
      }
      updateSelectedGroups(newSelectedGroups);
    }
    $scope2.handleSelectionUpdate = function(board, project, org2, team) {
      $scope2.selectedBoard = board;
      $scope2.selectedOrg = org2;
      $scope2.selectedTeam = team;
      $scope2.selectedProject = project;
      $scope2.isMoveDisabled = !$scope2.selectedOrg || !$scope2.selectedBoard;
      if (!board) {
        resetSelectedGroups();
        $scope2.canSelectGroups = false;
        return;
      }
      filterSelectedGroupsWithEnabledGroupType();
      $q.when(loadAllAvailableGroupsForCard(board), (groups) => {
        $scope2.canSelectGroups = groups.length > 0;
      });
    };
    $scope2.handleGroupSelect = function(groups) {
      updateSelectedGroups(groups);
    };
    $scope2.select = function() {
      $uibModalInstance.close({
        org: $scope2.selectedOrg,
        team: $scope2.selectedTeam,
        project: $scope2.selectedProject,
        board: $scope2.selectedBoard,
        groups: $scope2.selectedGroups
      });
    };
  }
]);

// public/app/ui/card/selector.js
var cardHotkeyCombos = [
  {
    combo: "x",
    description: _lazy("Mark as completed") + "/" + _lazy("Re-open card"),
    callback: function(card) {
      $digest("$q", ($q) => $q.digest(toggleCardAsCompleted(card)));
    }
  },
  {
    combo: "r",
    description: _lazy("Rename"),
    callback: function(card, selector) {
      selector.$scope.$broadcast("hotkeys:rename", card);
    }
  },
  {
    combo: "e",
    description: _lazy("Toggle archive"),
    callback: function(card) {
      if (card.is_archived) {
        $digest("$q", ($q) => $q.digest(restoreCard(card)));
      } else {
        $digest("$q", ($q) => $q.digest(confirmDeleteDialog2(_4("Are you sure you want to archive?"), null, _4("Archive")).then(() => archiveCard(card))));
      }
    }
  },
  {
    combo: "#",
    description: _lazy("Delete"),
    callback: function(card) {
      $digest("$q", ($q) => $q.digest(confirmDeleteDialog2(_4("Are you sure you want to delete?")).then(() => deleteCard(card))));
    }
  }
];
angular_default.module("kantree").service("cardsSelector", [
  "hotkeys",
  "cardModal",
  function(hotkeys, cardModal) {
    var selectorStack = [];
    var currentSelector;
    var hotkeysBinded = false;
    var navigationHotkeysBinded = false;
    var wrapHotkeysCallback = function(cb2, needsCard, validator) {
      return function(e3) {
        var isSwalVisible = jquery_default(".sweet-alert").is(":visible");
        if (currentSelector && (!needsCard || currentSelector.selected) && !isSwalVisible && (!validator || validator(currentSelector, e3))) {
          return cb2(currentSelector.selected, currentSelector, e3);
        }
      };
    };
    this.push = function(scope, withNavigation) {
      this.bindHotkeys(scope, withNavigation);
      currentSelector = new selector_default();
      currentSelector.$scope = scope;
      var index2 = selectorStack.length;
      selectorStack.push(currentSelector);
      var self2 = this;
      scope.$on("$destroy", function() {
        selectorStack.splice(index2, 1);
        if (selectorStack.length > 0) {
          currentSelector = selectorStack[selectorStack.length - 1];
        } else {
          currentSelector = null;
        }
      });
      return currentSelector;
    };
    this.top = function() {
      return currentSelector;
    };
    this.areHotkeysBinded = function() {
      return hotkeysBinded;
    };
    this.bindHotkeys = function(scope, navKeysSpecs) {
      if (!hotkeysBinded) {
        this.hotkeys(scope, cardHotkeyCombos);
        hotkeysBinded = true;
        scope.$on("$destroy", function() {
          hotkeysBinded = false;
        });
      }
      if (navKeysSpecs === void 0 || navKeysSpecs) {
        this.bindNavigationHotkeys(scope, navKeysSpecs);
      }
    };
    this.areNavigationHotkeysBinded = function() {
      return navigationHotkeysBinded;
    };
    this.bindNavigationHotkeys = function(scope, customKeysSpecs) {
      if (navigationHotkeysBinded) return;
      navigationHotkeysBinded = true;
      scope.$on("$destroy", function() {
        navigationHotkeysBinded = false;
      });
      var navKeysSpecs = customKeysSpecs || [
        {
          combo: ["up", "k"],
          description: _4("Navigate up"),
          needsCard: false,
          callback: function(card, selector) {
            if (!cardModal.current && selector.hasItems()) {
              selector.prev();
            }
          }
        },
        {
          combo: ["down", "j"],
          description: _4("Navigate down"),
          needsCard: false,
          callback: function(card, selector) {
            if (!cardModal.current && selector.hasItems()) {
              selector.next();
            }
          }
        },
        {
          combo: "left",
          description: _4("Navigate left"),
          needsCard: false,
          callback: function(card, selector) {
            if (!cardModal.current && selector.hasItems()) {
              selector.prevPage();
            }
          }
        },
        {
          combo: "right",
          description: _4("Navigate right"),
          needsCard: false,
          callback: function(card, selector) {
            if (!cardModal.current && selector.hasItems()) {
              selector.nextPage();
            }
          }
        },
        {
          combo: "enter",
          description: _4("Open card"),
          callback: function(card, selector) {
            cardModal.open(card, { parentSelector: selector });
          }
        }
      ];
      this.hotkeys(scope, navKeysSpecs);
    };
    this.hotkeys = function(scope, combos, validator) {
      var binded = hotkeys.bindTo(scope);
      combos.forEach(function(spec) {
        var needsCard = typeof spec.needsCard === "undefined" || spec.needsCard;
        spec.callback = wrapHotkeysCallback(spec.callback, needsCard, validator);
        binded.add(spec);
      });
    };
    var methods = [
      "reset",
      "addPage",
      "resetPages",
      "findPage",
      "replacePageItems",
      "removePage",
      "prev",
      "next",
      "prevPage",
      "nextPage",
      "select",
      "select",
      "selectPosition",
      "unselect",
      "on",
      "off",
      "$on",
      "$off"
    ];
    methods.forEach(function(name2) {
      this[name2] = function() {
        if (currentSelector) {
          return currentSelector[name2].apply(currentSelector, arguments);
        }
      };
    }, this);
    this.nextHorizontalPage = function() {
      this.nextPage();
    };
    this.prevHorizontalPage = function() {
      this.prevPage();
    };
  }
]);

// public/app/ui/card-groups/ng-components/group-selector.js
angular_default.module("kantree").component("groupSelector", {
  bindings: {
    groups: "<",
    card: "<",
    board: "<",
    project: "<",
    onUpdate: "&",
    withAttributes: "<"
  },
  templateUrl: "/static/app/ui/card-groups/ng-components/templates/group-selector.html",
  controller: [
    function() {
      var $ctrl = this;
      $ctrl.textColor = textColor;
      $ctrl.isReadable = colors_exports.isReadable;
      $ctrl.dropConfig = {
        _closeOtherDrops: false,
        tetherOptions: {
          constraints: [
            {
              to: "window",
              attachment: "together",
              pin: true
            }
          ]
        }
      };
      function unselectGroupFromGroupType(groupTypeId) {
        var newGroups = $ctrl.groups.filter(function(g3) {
          return g3.type_id !== groupTypeId;
        });
        updateGroups(newGroups);
      }
      function isGroupSelected(group2) {
        return $ctrl.groups.some(function(g3) {
          return group2.id === g3.id;
        });
      }
      function unselectGroup(group2) {
        var newGroups = $ctrl.groups.filter(function(g3) {
          return g3.id !== group2.id;
        });
        updateGroups(newGroups);
      }
      function selectGroup(group2) {
        var newGroups = $ctrl.groups.concat(group2);
        updateGroups(newGroups);
      }
      function toggleGroupSelection(group2) {
        if (isGroupSelected(group2)) {
          unselectGroup(group2);
        } else {
          selectGroup(group2);
        }
      }
      function createGroupMenuItemsSpec(group2, board) {
        return {
          parent: board,
          withTitle: true,
          canCreate: false,
          groupType: cardGroupTypeStore.tryGet(group2.type_id),
          relocated: function(group3) {
            unselectGroupFromGroupType(group3.type_id);
            selectGroup(group3);
          },
          toggled: toggleGroupSelection,
          removed: function(groupType) {
            unselectGroupFromGroupType(groupType.id);
          },
          isInGroup: isGroupSelected
        };
      }
      function formatGroup(group2) {
        return {
          obj: group2,
          groupType: cardGroupTypeStore.tryGet(group2.type_id),
          menuSpec: createGroupMenuItemsSpec(group2, $ctrl.board)
        };
      }
      function updateGroups(groups) {
        $ctrl.groups = groups;
        $ctrl.groupsFormatted = $ctrl.groups.map(formatGroup);
        $ctrl.onUpdate({ $groups: $ctrl.groups });
      }
      function createAddGroupMenuItemsSpec(card, parent, project) {
        return {
          parent,
          groupTypes: cardGroupTypeStore.scopedByAvailableForCard(project, card, !!$ctrl.withAttributes).query({}, { sortBy: "name" }),
          dataPrefetched: true,
          includeAttrGroup: true,
          canCreate: false,
          noCloseAfterToggle: true,
          relocated: function(group2) {
            var menu = this;
            unselectGroupFromGroupType(group2.type_id);
            selectGroup(group2);
            menu.update();
          },
          toggled: function(group2) {
            var menu = this;
            toggleGroupSelection(group2);
            menu.update();
          },
          removed: function(groupType) {
            var menu = this;
            unselectGroupFromGroupType(groupType.id);
            menu.update();
          },
          isInGroup: isGroupSelected,
          setLabel: function(groupType) {
            return groupType.one_group_per_card ? groupType.singular_name : groupType.plural_name;
          },
          title: _4("Select a type of group")
        };
      }
      $ctrl.$onInit = function() {
        $ctrl.groups = $ctrl.groups || [];
        $ctrl.groupsFormatted = $ctrl.groups.map(formatGroup);
        $ctrl.groupTypesMenuFactoryParams = createAddGroupMenuItemsSpec($ctrl.card, $ctrl.board, $ctrl.project);
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.groups && !changes.groups.isFirstChange()) {
          $ctrl.groups = $ctrl.groups || [];
          $ctrl.groupsFormatted = $ctrl.groups.map(formatGroup);
        }
        if (changes.card && !changes.card.isFirstChange() || changes.board && !changes.board.isFirstChange() || changes.project && !changes.project.isFirstChange()) {
          $ctrl.groupTypesMenuFactoryParams = createAddGroupMenuItemsSpec($ctrl.card, $ctrl.board, $ctrl.project);
        }
      };
      $ctrl.handleGroupRemove = function(group2, event2) {
        event2.stopPropagation();
        unselectGroup(group2);
      };
    }
  ]
});

// public/app/ui/card-groups/ng-components/type-editor.js
angular_default.module("kantree").directive("cardGroupTypeEditor", [
  function() {
    return {
      replace: true,
      templateUrl: "/static/app/ui/card-groups/ng-components/templates/type-editor.html",
      restrict: "E",
      scope: {
        groupType: "=",
        project: "=?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.scopes = [
            { id: "project", label: _4("Workspace (groups are available for all boards in the workspace in which they are created)") }
          ];
          if ($scope2.groupType && $scope2.groupType.scope === "card") {
            $scope2.scopes.unshift({ id: "card", label: _4("Board (groups are only available for the board on which they are created)") });
          }
          if (!$scope2.project) {
            $scope2.scopes.push({ id: "org", label: _4("Team (groups are available in all workspaces of the team)") });
          }
          $scope2.loadProjects = function() {
            if (typeof $scope2.groupType.id !== "undefined") {
              $q.when(api_default.card_group_types.list_enabled_in_projects.get({ type_id: $scope2.groupType.id }), (projects) => {
                $scope2.projects = projects;
                $scope2.showProjects = true;
              });
            }
          };
          $scope2.showProjects = false;
        }
      ],
      link: function(scope, el2, attrs2) {
        var singular = el2.find('input[name="gtSingularName"]');
        var plural = el2.find('input[name="gtPluralName"]');
        el2.find('input[name="gtName"]').on("keyup", function() {
          var value2 = this.value.toLowerCase();
          scope.$apply(function() {
            if (singular.hasClass("autofill")) {
              if (value2 && value2.length > 3 && value2.substr(value2.length - 3) === "ies") {
                value2 = value2.substr(0, value2.length - 3) + "y";
              } else if (value2 && value2.charAt(value2.length - 1) === "s") {
                value2 = value2.substr(0, value2.length - 1);
              }
              scope.groupType.singular_name = value2;
            }
            if (plural.hasClass("autofill")) {
              if (value2 && value2.charAt(value2.length - 1) === "y") {
                value2 = value2.substr(0, value2.length - 1) + "ies";
              } else if (value2) {
                value2 += "s";
              }
              scope.groupType.plural_name = value2;
            }
          });
        });
        jquery_default([singular[0], plural[0]]).on("keypress", function() {
          jquery_default(this).removeClass("autofill");
        });
      }
    };
  }
]);

// public/app/ui/card-groups/menus/actions.js
angular_default.module("kantree").service("cardGroupsActionsMenu", class extends AngularClass {
  static $inject = [
    "cardGroupsSortByMenu",
    "groupAutomationsMenuFactory",
    "appearanceGroupMenuFactory",
    "projectPage",
    "datesGroupMenuFactory",
    "rulesGroupMenuFactory",
    "cardGroupRolesModal",
    "$q",
    "$timeout"
  ];
  getItems(group2, parent, options2) {
    const items = [];
    const project = parent ? projectStore.tryGetForCard(parent) : null;
    const { sortByMenuParams, withBatch, includeArchived, includeDescendants, filter: filter4 } = options2;
    const editable2 = !!project && !project.is_archived && isConnected() && canEditGroup(project, group2.id);
    function insertSeparator() {
      if (items.length && items[items.length - 1].label !== "--") {
        items.push({ label: "--" });
      }
    }
    if (editable2) {
      const availableStates = cardStateStore.getBuiltinStates();
      const nullValueForCardState = {
        id: -1,
        label: _4("None")
      };
      items.push({
        colorpicker: true,
        getValue: () => group2.color || null,
        action: (event2, color) => {
          if (group2.color === color) {
            return;
          }
          this.$q.digest(saveGroup({ ...group2, color }, parent));
        },
        watcher: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false),
        noCloseAfterAction: true,
        hasColorPalette: true,
        ...this.$appearanceGroupMenuFactory.getSubmenuMixin(group2, parent)
      });
      if (!project.is_portfolio) {
        items.push(
          { subheader: _4("Associate a state to this group:") },
          {
            selectbox: true,
            select: (obj) => {
              const card_state = obj.id === -1 ? null : obj.id;
              if (group2.card_state === card_state) return;
              this.$q.when(saveGroup({ ...group2, card_state }, parent), () => {
                if (!card_state) return;
                if (parent && project && canEditCard(project)) {
                  this.$timeout(() => {
                    const cards = cardStore.scopedByParentAndGroup(parent, group2, false).query({ state: query_exports.not(card_state) });
                    if (cards.length > 0) {
                      yesNoDialog({
                        title: _4("Update cards?"),
                        text: _4("Update the status of cards already in the group")
                      }).then(() => this.$q.digest(setCardsStateFromGroup(group2, parent, card_state)));
                    }
                  });
                }
              });
            },
            selectOptions: [nullValueForCardState].concat(availableStates),
            optionsLabelProperty: "label",
            defaultValue: group2.card_state ? availableStates.find((s3) => s3.id === group2.card_state) : nullValueForCardState
          }
        );
      }
    }
    insertSeparator();
    if (sortByMenuParams) {
      const sortByMenu = this.$cardGroupsSortByMenu.get(...sortByMenuParams);
      items.push({
        label: _4("Sort by"),
        icon: "bi-sort-down",
        submenu: sortByMenu.config
      });
    }
    if (parent && project && !project.is_archived && isConnected()) {
      if (withBatch && this.$projectPage.isProjectActive(project) && !project.is_portfolio) {
        items.push({
          label: _4("Select all cards"),
          icon: "bi-check2-all",
          action: () => {
            this.$projectPage.clearSelectedCards();
            this.$projectPage.broadcast("selectAllCardsInGroup", group2.id);
          }
        });
      }
      if (!project.is_portfolio) {
        items.push({
          label: _4("Automations"),
          icon: "bolt",
          ...this.$groupAutomationsMenuFactory.getSubmenuMixin(group2, { parent, project }),
          enabled: () => !group2.is_archived
        });
      }
      insertSeparator();
      if (editable2) {
        items.push({
          label: _4("Set date range"),
          icon: "calendar",
          offline: false,
          ...this.$datesGroupMenuFactory.getSubmenuMixin(group2, parent),
          enabled: () => !group2.is_archived
        });
      }
      if (!!project && !project.is_archived && isConnected() && canManageMembers(project) && project.owner && project.owner.type !== "user") {
        items.push({
          label: _4("Permissions"),
          icon: "bi-key-fill",
          offline: false,
          action: () => {
            const groupType = cardGroupTypeStore.tryGet(group2.type_id);
            const groups = cardGroupStore.scopedByType(groupType, parent, false).query();
            this.$cardGroupRolesModal.open(project, groups, group2);
          },
          enabled: () => !group2.is_archived
        });
      }
    }
    insertSeparator();
    if (isConnected() && project && !project.is_archived && !project.is_template && isCurrentUserMemberOf(project.owner) && !project.is_portfolio) {
      items.push(
        {
          label: _4("Subscribe"),
          icon: "bell",
          offline: false,
          action: () => this.$q.digest(toggleGroupSubscribed(group2, parent)),
          enabled: () => !cardGroupSubscriptionStore.isSubscribed(group2),
          disabled: () => group2.is_archived
        },
        {
          label: _4("Unsubscribe"),
          icon: "bell",
          offline: false,
          action: () => this.$q.digest(toggleGroupSubscribed(group2, parent)),
          enabled: () => cardGroupSubscriptionStore.isSubscribed(group2)
        },
        {
          label: _4("Card notifications"),
          offline: false,
          submenu: [
            { desc: _4("Whether to be notified of changes to cards in this group") },
            {
              label: _4("Enabled"),
              offline: false,
              selected: () => cardGroupSubscriptionStore.getForGroup(group2).notify_card_changes,
              action: () => this.$q.digest(toggleCardNotifications(group2, parent)),
              disabled: () => group2.is_archived
            },
            {
              label: _4("Disabled"),
              offline: false,
              selected: () => !cardGroupSubscriptionStore.getForGroup(group2).notify_card_changes,
              action: () => this.$q.digest(toggleCardNotifications(group2, parent))
            }
          ],
          enabled: () => cardGroupSubscriptionStore.isSubscribed(group2)
        }
      );
    }
    insertSeparator();
    if (editable2 && project && !project.is_template) {
      items.push(
        {
          label: _4("Archive"),
          icon: "archive",
          action: () => {
            const cardsCount = cardStore.scopedByParentAndGroup(parent, group2, false, includeDescendants).count();
            if (cardsCount > 0 && canArchiveCard(project) && !project.is_portfolio) {
              dialog({
                title: _4("Archive this group?"),
                text: _n("This group contains {count} card", "This group contains {count} cards", cardsCount) + (includeDescendants ? " " + _4("(including descendants)") : "") + ".",
                showCloseButton: true,
                showCancelButton: true,
                buttonsStyling: false,
                confirmButtonText: _4("Archive with cards"),
                confirmButtonClass: "btn btn-primary btn-lg",
                confirmButtonColor: null,
                cancelButtonText: _4("Archive"),
                cancelButtonClass: "btn btn-link btn-lg",
                cancelButtonColor: null,
                closeOnConfirm: true
              }).then((success) => {
                if (success === true) this.$q.digest(archiveGroup(group2, parent, true));
                if (success === false) this.$q.digest(archiveGroup(group2, parent));
              });
            } else {
              this.$q.digest(archiveGroup(group2, parent));
            }
          },
          enabled: () => !group2.is_archived
        },
        {
          label: _4("Restore"),
          icon: "repeat fa-rotate-270",
          action: () => this.$q.digest(restoreGroup(group2, parent)),
          enabled: () => group2.is_archived
        }
      );
    }
    if (project && !project.is_archived && isConnected() && canDeleteGroup(project, group2.id)) {
      items.push({
        label: _4("Delete"),
        icon: "trash",
        action: () => {
          confirmDeleteDialog2(
            null,
            _4("This group will be permanently deleted")
          ).then(() => this.$q.digest(deleteGroup(group2, parent)));
        }
      });
    }
    if (items[items.length - 1].label === "--") {
      items.pop();
    }
    return items;
  }
  get(group2, parent, options2) {
    if (group2.is_dynamic) {
      throw new Error("Group Action Menu is not available for dynamic group");
    }
    return {
      config: () => this.getItems(group2, parent, options2),
      options: { watch: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false) }
    };
  }
});
angular_default.module("kantree").directive("cardGroupActionsMenuToggle", [
  "cardGroupsActionsMenu",
  "menuDropdown",
  function(cardGroupsActionsMenu, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        group: "<",
        parent: "<",
        options: "<",
        dropConfig: "<"
      },
      link: function(scope, element2, attr) {
        let menu;
        let drop;
        scope.$watch("group", (group2) => {
          if (group2) {
            menu = cardGroupsActionsMenu.get(group2, scope.parent, scope.options || {});
          } else {
            menu = null;
          }
        });
        scope.$watch("options", (options2) => {
          if (scope.group) {
            menu = cardGroupsActionsMenu.get(scope.group, scope.parent, options2 || {});
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", (event2) => {
          if (menu) {
            const dropConfig = Object.assign({
              classes: "drop-theme-menu drop-theme-arrow drop-theme-group-menu"
            }, scope.dropConfig || {});
            drop = menuDropdown.toggle(drop, element2[0], menu, scope, dropConfig, event2);
          }
        });
      }
    };
  }
]);

// public/app/ui/card-groups/menus/appearance.js
angular_default.module("kantree").factory("appearanceGroupMenuFactory", [
  "$q",
  function($q) {
    return {
      getItems(group2, parent) {
        const items = [];
        items.push({
          subheader: _4("Icon")
        }, {
          iconpicker: true,
          emptyIcon: true,
          getValue: () => group2.icon || null,
          color: group2.color || null,
          action: function(event2, icon) {
            if (group2.icon === icon) return;
            $q.digest(saveGroup({ ...group2, icon }, parent));
          },
          noCloseAfterAction: true,
          extended: true,
          options: {
            watch: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false)
          }
        });
        items.push({
          subheader: _4("Background color")
        }, {
          colorpicker: true,
          getValue: () => group2.color || null,
          action: function(event2, color) {
            if (group2.color === color) return;
            $q.digest(saveGroup({ ...group2, color }, parent));
          },
          noCloseAfterAction: true,
          hasColorPalette: true
        });
        items.push({
          subheader: _4("Description")
        }, {
          content: true,
          submit: function(description) {
            description = description && description.length ? description : null;
            if (group2.description === description) return;
            $q.digest(saveGroup({ ...group2, description }, parent));
          },
          allowEmptyValue: true,
          submitOnBlur: true,
          defaultValue: group2.description || null
        }, {
          checkbox: true,
          value: group2.always_show_description,
          label: _4("Always show description"),
          toggle: function(isChecked) {
            if (group2.always_show_description === isChecked) return;
            $q.digest(saveGroup({ ...group2, always_show_description: isChecked }, parent));
          }
        });
        items.push({
          checkbox: true,
          value: group2.show_flow_indicator,
          label: _4("Show flow indicator"),
          help: _4("This will add arrows pointing to the right as the background of the group header"),
          toggle: function(isChecked) {
            if (group2.show_flow_indicator === isChecked) return;
            $q.digest(saveGroup({ ...group2, show_flow_indicator: isChecked }, parent));
          }
        });
        items.push({
          checkbox: true,
          value: group2.is_creation_hidden,
          label: _4("Hide card creation button"),
          help: _4("Indicate in which groups you want the cards to be created"),
          toggle: function(isChecked) {
            if (group2.is_creation_hidden === isChecked) return;
            $q.digest(saveGroup({ ...group2, is_creation_hidden: isChecked }, parent));
          }
        });
        items.push(
          {
            subheader: _4("Maximum number of cards"),
            help: _4("A red alert will appear if you cross the limit")
          },
          {
            input: true,
            inputType: "number",
            submit(max_cards_limit) {
              if (group2.max_cards_limit === max_cards_limit) return;
              $q.digest(saveGroup({ ...group2, max_cards_limit }, parent));
            },
            allowEmptyValue: true,
            submitOnBlur: true,
            defaultValue: group2.max_cards_limit || null,
            offline: false,
            disabled: () => !parent
          }
        );
        return items;
      },
      get(group2) {
        return { config: this.getItems(...arguments) };
      },
      getSubmenuMixin(group2, parent) {
        return {
          submenu: () => () => this.getItems(group2, parent),
          submenuIcon: "bi-palette-fill",
          submenuTooltip: _4("Customize style"),
          options: {
            title: _4("Customize style"),
            watch: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false)
          }
        };
      }
    };
  }
]);

// public/app/ui/card-groups/menus/automations.js
angular_default.module("kantree").service("groupAutomationsMenuFactory", class extends AngularClass {
  static $inject = ["$q", "$state", "projectPage", "$timeout"];
  getItems(group2, { parent, project }) {
    const items = [{
      desc: _4("Automations that will trigger when a card is added to this group."),
      big: true
    }];
    automationRuleStore.scopedByGroup(project, group2).query({}, { sortBy: "id" }).forEach((rule) => {
      items.push({
        label: rule.name,
        action: () => {
          this.$projectPage.gotoApp("automations");
          this.$timeout(() => {
            this.$projectPage.trigger("editRule", rule.id);
          }, 200);
        }
      });
    });
    if (canManageAutomations(project)) {
      items.push({
        label: _4("Add automation rule"),
        icon: "plus",
        action: () => {
          this.$projectPage.gotoApp("automations");
          this.$timeout(() => {
            this.$projectPage.trigger("createGroupRule", group2);
          }, 200);
        }
      });
    }
    if (canEditGroup(project, group2.id)) {
      const nullValueForCardModel = {
        id: -1,
        name: _4("--Inherit--")
      };
      let models = [];
      let modelStore;
      if (project) {
        modelStore = cardModelStore.scopedByEnabled(project);
      } else if (group2.scope === "org") {
        modelStore = cardModelStore.scopedByOrg(group2.owner);
      }
      if (modelStore) {
        const groupType = cardGroupTypeStore.get(group2.type_id);
        if (!groupType.is_project_specific) {
          modelStore = modelStore.scoped({ is_project_specific: query_exports.isFalsy() });
        }
        models = modelStore.query({ base_model_type: query_exports.isNull() });
      }
      items.push(
        { label: "--" },
        { subheader: _4("Apply a type to cards created in this group") },
        {
          selectbox: true,
          select: (obj) => {
            const default_card_model_id = obj.id === -1 ? null : obj.id;
            if (group2.default_card_model_id === default_card_model_id) {
              return;
            }
            this.$q.digest(saveGroup({ ...group2, default_card_model_id }, parent));
          },
          selectOptions: [nullValueForCardModel].concat(models),
          optionsLabelProperty: "name",
          defaultValue: group2.default_card_model_id ? models.find((m3) => m3.id === group2.default_card_model_id) : nullValueForCardModel
        }
      );
    }
    return items;
  }
  async fetchData(group2, parent, project) {
    if (group2.scope === "org") {
      if (group2.owner && group2.owner.type === "user") {
        await loadAllModelsForUser(resolve);
      } else if (group2.owner && group2.owner.type === "org") {
        await loadAllModelsForOrg(group2.owner, resolve);
      }
    } else {
      await Promise.all([
        loadAutomationRulesForProject(project),
        getOrLoadCard(parent.id).then(() => loadAllEnabledModelsForProject(project))
      ]);
    }
  }
  get() {
    return { config: this.getItems(...arguments) };
  }
  getSubmenuMixin(group2, { parent, project, editable: editable2 }) {
    return {
      submenu: () => () => this.getItems(...arguments),
      options: {
        watch: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false),
        fetchData: (cb2) => this.$q.when(this.fetchData(group2, parent, project), cb2)
      }
    };
  }
});

// public/app/ui/card-groups/menus/dates.js
angular_default.module("kantree").factory("datesGroupMenuFactory", [
  "$q",
  function($q) {
    return {
      getItems(group2, parent) {
        const items = [];
        items.push(
          {
            desc: _4("Pick dates for this group to make it appear in the calendar view and use it in some analytics graph like the burndown charts"),
            big: true
          },
          {
            label: "--"
          }
        );
        items.push(
          {
            subheader: "Start date"
          },
          {
            datepicker: true,
            select: function(start_date) {
              if (group2.start_date === start_date) return;
              return $q.digest(saveGroup({ ...group2, start_date }, parent));
            },
            defaultValue: group2.start_date || null
          },
          {
            label: "--"
          }
        );
        items.push(
          {
            subheader: "End date"
          },
          {
            datepicker: true,
            select: function(end_date) {
              if (group2.end_date === end_date) return;
              return $q.digest(saveGroup({ ...group2, end_date }, parent));
            },
            defaultValue: group2.end_date || null
          }
        );
        return items;
      },
      get(group2, parent) {
        return { config: this.getItems(group2, parent) };
      },
      getSubmenuMixin(group2, parent) {
        return {
          submenu: () => () => this.getItems(group2, parent),
          options: { watch: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false) }
        };
      }
    };
  }
]);

// public/app/ui/card-groups/menus/groups.js
angular_default.module("kantree").directive("groupsMenuToggle", [
  "groupsMenuFactory",
  "menuDropdown",
  function(groupsMenuFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        params: "<groupsMenuToggle",
        dropConfig: "<?"
      },
      link: function(scope, element2, attr) {
        var menu;
        var drop;
        var loaded, loading;
        scope.$watch("params", function(params) {
          if (params) {
            params.dataPrefetched = true;
            menu = groupsMenuFactory.get(params);
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu && !loading) {
            if (!loaded) {
              loading = true;
              menu.options.fetchData(function() {
                loaded = true;
                loading = false;
                drop = menuDropdown.toggle(drop, element2[0], menu, scope, scope.dropConfig, event2);
              });
            } else {
              drop = menuDropdown.toggle(drop, element2[0], menu, scope, scope.dropConfig, event2);
            }
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("groupsMenuFactory", [
  "$q",
  "cardGroupTypeGroupsModal",
  function($q, cardGroupTypeGroupsModal) {
    var defaultsOptions = {
      withTitle: true,
      withSettings: true,
      noCloseAfterToggle: true,
      backAfterToggle: false,
      resetAfterToggle: false,
      menuOpts: null,
      dataPrefetched: false,
      groups: null,
      groupType: null,
      parent: null,
      card: null,
      isInGroup: null,
      toggled: null,
      relocated: null,
      removed: null,
      canSelect: (group2, options2) => true,
      canCreate: true,
      canSort: false
    };
    function isOptionsEnableGroupCreation(options2) {
      return options2.canCreate && options2.groupType && options2.parent;
    }
    var handleBaseGroupSelection = function(group2, options2) {
      if (options2.groupType && options2.groupType.one_group_per_card && options2.canSelect() && options2.relocated) {
        return options2.relocated.call(this, group2);
      }
      if (options2.toggled) {
        return options2.toggled.call(this, group2);
      }
    };
    function buidBaseGroupItem(group2, options2) {
      var item = {
        label: group2.title,
        enableActionOnselected: options2.groupType && !options2.groupType.one_group_per_card ? true : false,
        classes: "icon-right",
        noCloseAfterAction: options2.noCloseAfterToggle,
        backAfterAction: options2.backAfterToggle,
        resetAfterAction: options2.resetAfterToggle,
        selected: function() {
          if (options2.isInGroup) {
            return options2.isInGroup(group2);
          }
          return false;
        }
      };
      if (options2.canSelect(group2, options2) && (options2.relocated || options2.toggled)) {
        item.action = function() {
          return handleBaseGroupSelection.call(this, group2, options2);
        };
        item.filterable = true;
        item.filterPredicate = function(filter4) {
          return group2.title.toLowerCase().indexOf(filter4.toLowerCase()) >= 0;
        };
      } else {
        item.disabled = function() {
          return true;
        };
      }
      if (options2.canSort) {
        item.sortable = true;
      }
      if (group2.color) {
        item.color = group2.color;
      }
      if (group2.icon) {
        item.icon = group2.icon;
      }
      return item;
    }
    function buildBaseUnselectItem(options2) {
      return {
        label: _4("None"),
        action: function() {
          return options2.removed(options2.groupType, options2.groups);
        },
        noCloseAfterAction: options2.noCloseAfterToggle,
        backAfterAction: options2.backAfterToggle,
        resetAfterAction: options2.resetAfterToggle
      };
    }
    function buildBaseCreateItem(groups, options2) {
      return {
        input: true,
        useAsFilter: true,
        focusOnLoad: true,
        placeholder: _4("Add new {grouptype}", { grouptype: options2.groupType.singular_name }),
        resetOnSubmit: true,
        submit: function(value2) {
          var self2 = this;
          var existingGroup = groups.find(function(group2) {
            return group2.title.toLowerCase() === value2.toLowerCase();
          });
          if (existingGroup) {
            handleBaseGroupSelection.call(this, existingGroup, options2);
          } else {
            $q.when(createGroup(options2.groupType, options2.parent, value2), (group2) => {
              handleBaseGroupSelection.call(self2, group2, options2);
            });
          }
        }
      };
    }
    function getBaseItems(groups, options2) {
      var items = groups.map(function(group2) {
        return buidBaseGroupItem(group2, options2);
      });
      if (options2.canSelect() && options2.removed) {
        items.push({
          label: "--",
          enabled: function() {
            return groups.length;
          }
        });
        items.push(buildBaseUnselectItem(options2));
      }
      if (isOptionsEnableGroupCreation(options2) && (options2.relocated || options2.toggled)) {
        items.push(buildBaseCreateItem(groups, options2));
      }
      return items;
    }
    function isCardInGroup(card, group2) {
      if (!card || !card.groups) {
        return false;
      }
      for (var i3 = 0; i3 < card.groups.length; i3++) {
        if (card.groups[i3].id === group2.id) {
          return true;
        }
      }
      return false;
    }
    function handleGroupSelectionForCard(group2, card, options2) {
      if (options2.groupType.one_group_per_card) {
        return $q.digest(relocateCard(card, group2));
      } else {
        return $q.digest(toggleCardGroup(card, group2));
      }
    }
    function buildGroupItemMixinForCard(group2, card, options2) {
      var project = projectStore.getForCard(card);
      var mixin3 = {
        selected: function() {
          return isCardInGroup(card, group2);
        }
      };
      if (options2.canSelect(group2, options2) && project && isAllowedInProject(project, "card_group", "MOVE_CARDS", group2.id) && (!options2.groupType || !options2.groupType.attribute_id || isAllowedInProject(project, "attribute", "EDIT", options2.groupType.attribute_id))) {
        mixin3.action = function() {
          return handleGroupSelectionForCard.call(this, group2, card, options2);
        };
        mixin3.filterable = true;
        mixin3.filterPredicate = function(filter4) {
          return group2.title.toLowerCase().indexOf(filter4.toLowerCase()) >= 0;
        };
        if (canEditGroup(project, group2.id)) {
          mixin3.color = null;
          mixin3.icon = null;
          mixin3.submenu = function() {
            return function() {
              return [
                { subheader: _4("Title") },
                {
                  input: true,
                  submit: function(title) {
                    if (group2.title === title) {
                      return;
                    }
                    $q.digest(saveGroup({ ...group2, title }, options2.parent));
                  },
                  defaultValue: group2.title
                },
                { subheader: _4("Icon") },
                {
                  iconpicker: true,
                  emptyIcon: true,
                  getValue: function() {
                    return group2.icon || null;
                  },
                  color: group2.color || null,
                  action: function(event2, icon) {
                    if (group2.icon === icon) return;
                    $q.digest(saveGroup({ ...group2, icon }, options2.parent));
                  },
                  noCloseAfterAction: true,
                  extended: true
                },
                { subheader: _4("Background color") },
                {
                  colorpicker: true,
                  getValue: function() {
                    return group2.color || null;
                  },
                  action: function(event2, color) {
                    if (group2.color === color) return;
                    $q.digest(saveGroup({ ...group2, color }, options2.parent));
                  },
                  noCloseAfterAction: true,
                  hasColorPalette: true
                },
                { label: "--" },
                {
                  label: _4("Delete"),
                  icon: "trash",
                  action: () => confirmDeleteDialog2().then(() => $q.digest(deleteGroup(group2, options2.parent)))
                }
              ];
            };
          };
          mixin3.submenuKey = "iconAndColorPicker", mixin3.options = {
            watch: function(callback, scope) {
              return cardGroupStore.$watch(scope, group2, "updated", callback, false);
            },
            title: _4("Edit")
          };
          mixin3.buttons = [{
            classes: "btn-default btn-text mod-group-color-icon",
            icon: group2.icon || null,
            color: group2.color || "transparent",
            action: "openIconAndColorPickerSubmenu",
            tooltip: _4("Edit")
          }];
        }
        mixin3.disabled = function() {
          return false;
        };
      } else {
        mixin3.disabled = function() {
          return true;
        };
      }
      return mixin3;
    }
    function buildUnselectItemMixinForCard(card, options2) {
      return {
        action: function() {
          return $q.digest(removeCardFromGroupType(card, options2.groupType, card.position));
        }
      };
    }
    function buildCreateItemMixinForCard(groups, card, options2) {
      return {
        submit: function(value2) {
          var existingGroup = groups.find(function(group2) {
            return group2.title.toLowerCase() === value2.toLowerCase();
          });
          if (existingGroup) {
            handleGroupSelectionForCard(existingGroup, card, options2);
          } else {
            $q.when(createGroup(options2.groupType, options2.parent, value2), (group2) => {
              handleGroupSelectionForCard(group2, card, options2);
            });
          }
        }
      };
    }
    function canUnselectAll(card, project, options2) {
      if (options2.groupType.attribute_id && !isAllowedInProject(project, "attribute", "EDIT", options2.groupType.attribute_id)) {
        return false;
      } else {
        return card.groups.filter(function(group2) {
          return group2.type_id === options2.groupType.id;
        }).every(function(group2) {
          return isAllowedInProject(project, "card_group", "MOVE_CARDS", group2.id);
        });
      }
    }
    function getItemsForCard(groups, card, options2) {
      var project = projectStore.getForCard(card);
      var items = groups.map(function(group2) {
        return Object.assign(
          {},
          buidBaseGroupItem(group2, options2),
          buildGroupItemMixinForCard(group2, card, options2)
        );
      });
      if (options2.canSelect() && options2.groupType && project && canUnselectAll(card, project, options2)) {
        items.push({
          label: "--",
          enabled: function() {
            return groups.length;
          }
        });
        items.push(Object.assign(
          {},
          buildBaseUnselectItem(options2),
          buildUnselectItemMixinForCard(card, options2)
        ));
      }
      if (isOptionsEnableGroupCreation(options2) && project && isAllowedInProject(project, "card_group", "MOVE_CARDS") && (!options2.groupType || !options2.groupType.attribute_id || isAllowedInProject(project, "attribute", "EDIT", options2.groupType.attribute_id)) && isAllowedInProject(project, "card_group", "CREATE")) {
        items.push(Object.assign(
          {},
          buildBaseCreateItem(groups, options2),
          buildCreateItemMixinForCard(groups, card, options2)
        ));
      }
      return items;
    }
    var getItems = function(options2) {
      var groups = [];
      if (options2.groups) {
        groups = options2.groups;
      } else if (options2.groupType && options2.parent) {
        groups = cardGroupStore.scopedByType(options2.groupType, options2.parent, false).query({}, { sortBy: "position" });
      }
      var items = [];
      if (options2.card) {
        items = getItemsForCard(groups, options2.card, options2);
      } else {
        items = getBaseItems(groups, options2);
      }
      return items;
    };
    var watch = function(options2, cb2, scope) {
      var typeStoreOff;
      var cardStoreOff;
      if (options2.groupType && options2.parent) {
        typeStoreOff = cardGroupStore.scopedByType(options2.groupType, options2.parent, false).$watchAll(scope, cb2, false);
      }
      if (options2.card) {
        cardStoreOff = cardStore.$watch(scope, options2.card, "updated", cb2);
      }
      return function() {
        typeStoreOff && typeStoreOff();
        cardStoreOff && cardStoreOff();
      };
    };
    var fetchData = function(options2, cb2) {
      if (options2.groupType && options2.parent && options2.parent.id) {
        $q.when(loadAllGroupsForTypeAndParent(options2.groupType, options2.parent), cb2);
      } else {
        cb2();
      }
    };
    return {
      getItems,
      watch,
      fetchData,
      get: function(options2) {
        options2 = Object.assign({}, defaultsOptions, options2);
        var menuOpts = {
          watch: watch.bind(this, options2),
          fetchData: fetchData.bind(this, options2)
        };
        if (options2.withTitle) {
          menuOpts.title = function() {
            return capitalize(options2.groupType.one_group_per_card ? options2.groupType.singular_name : options2.groupType.name);
          };
        }
        if (options2.withSettings && options2.groupType && options2.parent && !options2.groupType.attribute_id) {
          menuOpts.settings = function() {
            cardGroupTypeGroupsModal.open(options2.groupType, options2.parent);
          };
        }
        if (options2.dataPrefetched) {
          menuOpts.dataPrefetched = options2.dataPrefetched;
        }
        if (options2.canSort) {
          menuOpts.sort = options2.canSort;
        }
        if (options2.menuOpts) {
          Object.assign(menuOpts, options2.menuOpts);
        }
        var menuConfig = function() {
          return getItems.bind(this, options2);
        };
        return {
          config: menuConfig,
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/ui/card-groups/menus/order-by.js
angular_default.module("kantree").service("cardGroupsSortByMenu", class extends AngularClass {
  getItems(sortBy3, { canFreeSort: canFreeSort2, sortByChanged, choices } = {}) {
    const items = [];
    items.push({
      label: _4("Custom ordering"),
      action: () => sortByChanged(null, false),
      selected: () => !sortBy3,
      disabled: () => canFreeSort2 === false,
      offline: false
    }, { desc: _4("Drag & drop to re-order cards") });
    if (items.length && items[items.length - 1].label !== "--") {
      items.push({ label: "--" });
    }
    items.push(...this.formatItems(cardGroupStaticSortBy, sortBy3, sortByChanged));
    if (items.length && items[items.length - 1].label !== "--") {
      items.push({ label: "--" });
    }
    if (choices && choices.length > 0) {
      items.push(...this.formatItems(choices, sortBy3, sortByChanged));
    }
    if (items.length && items[items.length - 1].label !== "--") {
      items.push({ label: "--" });
    }
    items.push({
      label: _4("Reverse"),
      action: () => {
        if (sortBy3) {
          sortByChanged(sortBy3.value, !sortBy3.reverse);
        }
      },
      selected: () => sortBy3 && sortBy3.reverse,
      disabled: () => !sortBy3,
      enableActionOnselected: true
    });
    return items;
  }
  formatItems(items, sortBy3, sortByChanged) {
    return items.map((item) => ({
      label: item.label,
      action: () => sortByChanged(item.value, sortBy3 ? sortBy3.reverse : false),
      selected: () => sortBy3 && (sortBy3.value === item.value || typeof sortBy3.value === "number" && sortBy3.value === item.id)
    }));
  }
  get() {
    return { config: this.getItems(...arguments) };
  }
});

// public/app/ui/card-groups/menus/rules.js
angular_default.module("kantree").factory("rulesGroupMenuFactory", [
  "$q",
  "$timeout",
  function($q, $timeout2) {
    return {
      // every items will be disabled if project = null
      getItems(group2, options2) {
        const items = [];
        const { parent, project } = options2;
        const editable2 = options2.editable !== false && project && canEditGroup(project, group2.id);
        items.push(
          {
            subheader: _4("Maximum number of cards"),
            help: _4("A red alert will appear if you cross the limit")
          },
          {
            input: true,
            inputType: "number",
            submit(max_cards_limit) {
              if (group2.max_cards_limit === max_cards_limit) return;
              $q.digest(saveGroup({ ...group2, max_cards_limit }, parent));
            },
            allowEmptyValue: true,
            submitOnBlur: true,
            defaultValue: group2.max_cards_limit || null,
            offline: false,
            disabled: () => !editable2 || !parent
          }
        );
        let models = [];
        let modelStore;
        if (project) {
          modelStore = cardModelStore.scopedByEnabled(project);
        } else if (group2.scope === "org") {
          modelStore = cardModelStore.scopedByOrg(group2.owner);
        }
        if (modelStore) {
          models = modelStore.query({ base_model_type: query_exports.isNull() });
        }
        if (group2.default_card_model_id && !modelStore.exists(group2.default_card_model_id) && cardModelStore.exists(group2.default_card_model_id)) {
          const unavailableSelectedModel = angular_default.copy(cardModelStore.get(group2.default_card_model_id));
          unavailableSelectedModel.name = unavailableSelectedModel.name + " --not available in this project--";
          models = [unavailableSelectedModel].concat(models);
        }
        const nullValueForCardModel = {
          id: -1,
          name: _4("--Inherit from workspace--")
        };
        items.push(
          {
            subheader: _4("Apply a type to cards created in this group")
          },
          {
            selectbox: true,
            offline: false,
            disabled: () => !editable2,
            select: (obj) => {
              const default_card_model_id = obj.id === -1 ? null : obj.id;
              if (group2.default_card_model_id === default_card_model_id) return;
              $q.digest(saveGroup({ ...group2, default_card_model_id }, parent));
            },
            selectOptions: [nullValueForCardModel].concat(models),
            optionsLabelProperty: "name",
            defaultValue: group2.default_card_model_id ? models.find((m3) => m3.id === group2.default_card_model_id) : nullValueForCardModel
          }
        );
        if (group2.default_card_model_id && !modelStore.exists(group2.default_card_model_id)) {
          items.push({
            desc: _4("The selected type comes from another workspace, in which this group is also available. It won't be applied on cards created here.")
          });
        }
        const nullValueForCardState = {
          id: -1,
          label: _4("None")
        };
        const availableStates = cardStateStore.getBuiltinStates();
        items.push(
          {
            subheader: _4("Change state of the card created or moved to this group to")
          },
          {
            selectbox: true,
            offline: false,
            disabled: () => !editable2,
            select: (obj) => {
              const card_state = obj.id === -1 ? null : obj.id;
              if (group2.card_state === card_state) return;
              $q.when(saveGroup({ ...group2, card_state }, parent), () => {
                if (!card_state) return;
                if (parent && project && canEditCard(project)) {
                  $timeout2(() => {
                    const cards = cardStore.scopedByParentAndGroup(parent, group2, false).query({ state: query_exports.not(card_state) });
                    if (cards.length > 0) {
                      yesNoDialog({
                        title: _4("Update cards?"),
                        text: _4("Update the status of cards already in the group")
                      }).then(() => $q.digest(setCardsStateFromGroup(group2, parent, card_state)));
                    }
                  });
                }
              });
            },
            selectOptions: [nullValueForCardState].concat(availableStates),
            optionsLabelProperty: "label",
            defaultValue: group2.card_state ? availableStates.find((s3) => s3.id === group2.card_state) : nullValueForCardState
          }
        );
        if (items[items.length - 1].label === "--") {
          items.pop();
        }
        return items;
      },
      get() {
        return { config: this.getItems(...arguments) };
      },
      getSubmenuMixin(group2, { parent, project }) {
        return {
          submenu: () => () => this.getItems(...arguments),
          options: {
            watch: (cb2, scope) => cardGroupStore.$watch(scope, group2, "updated", cb2, false),
            fetchData: (cb2) => {
              $q.when((async () => {
                if (group2.scope === "org") {
                  if (group2.owner && group2.owner.type === "user") {
                    await loadAllModelsForUser();
                  } else if (group2.owner && group2.owner.type === "org") {
                    await loadAllModelsForOrg(group2.owner);
                  }
                } else {
                  await getOrLoadCard(parent.id).then(() => loadAllEnabledModelsForProject(project));
                }
                if (group2.default_card_model_id) {
                  await getOrLoadModel(group2.default_card_model_id);
                }
              })(), cb2);
            }
          }
        };
      }
    };
  }
]);

// public/app/ui/card-groups/menus/types.js
angular_default.module("kantree").directive("groupTypesMenuToggle", [
  "groupTypesMenuFactory",
  "menuDropdown",
  function(groupTypesMenuFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        params: "<groupTypesMenuToggle",
        dropConfig: "<?"
      },
      link: function(scope, element2, attr) {
        var menu;
        var drop;
        var loaded, loading;
        scope.$watch("params", function(params) {
          if (params) {
            params.dataPrefetched = true;
            menu = groupTypesMenuFactory.get(params);
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu && !loading) {
            if (!loaded) {
              loading = true;
              groupTypesMenuFactory.fetchData(scope.params, function() {
                loaded = true;
                loading = false;
                drop = menuDropdown.toggle(drop, element2[0], menu, scope, scope.dropConfig, event2);
              });
            } else {
              drop = menuDropdown.toggle(drop, element2[0], menu, scope, scope.dropConfig, event2);
            }
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("groupTypesMenuFactory", [
  "groupsMenuFactory",
  "$q",
  function(groupsMenuFactory, $q) {
    var defaultOptions4 = {
      card: null,
      parent: null,
      groupTypes: null,
      includeAttrGroup: false,
      setLabel: null,
      noCloseAfterToggle: null,
      otherLabel: null,
      dataPrefetched: false,
      title: null,
      handleCardRelocate: true
    };
    function buildBaseGroupTypeItem(groupType, options2) {
      var groupsOpts = Object.assign({}, options2, {
        groupType,
        noCloseAfterToggle: options2.noCloseAfterToggle !== null ? options2.noCloseAfterToggle : !groupType.one_group_per_card,
        dataPrefetched: options2.dataPrefetched
      });
      if (!groupsOpts.parent) {
        groupsOpts.parent = cardStore.get(groupsOpts.card.parent_id);
      }
      var groupsMenu = groupsMenuFactory.get(groupsOpts);
      var label = options2.setLabel && options2.setLabel(groupType) || _4("Set {grouptype}", {
        grouptype: groupType.one_group_per_card ? groupType.singular_name : groupType.plural_name
      });
      return {
        label,
        submenu: groupsMenu.config,
        options: groupsMenu.options
      };
    }
    var getItems = function(options2, beginning, range2) {
      options2 = Object.assign({}, defaultOptions4, options2);
      var project = projectStore.getForCard(options2.card || options2.parent);
      var groupTypes;
      if (options2.groupTypes) {
        groupTypes = options2.groupTypes;
      } else {
        if (options2.card) {
          groupTypes = cardGroupTypeStore.scopedByAvailableForCard(project, options2.card, options2.includeAttrGroup).query({}, { sortBy: "name" });
        } else {
          groupTypes = cardGroupTypeStore.scopedByEnabled(project, options2.includeAttrGroup).query({}, { sortBy: "name" });
        }
      }
      groupTypes = groupTypes.filter(function(groupType) {
        if (options2.handleCardRelocate && (groupType.attribute_id && !isAllowedInProject(project, "attribute", "EDIT", groupType.attribute_id) || !canMoveCardsInThisGroupType(project, groupType.id))) {
          return false;
        }
        return true;
      });
      var groupTypesNb = groupTypes.length;
      if (typeof beginning !== "undefined" || typeof last !== "undefined" && groupTypesNb > range2) {
        groupTypes = groupTypes.slice(beginning, range2);
      }
      var config3 = groupTypes.map(function(groupType) {
        return buildBaseGroupTypeItem(groupType, options2);
      });
      if (groupTypesNb > range2) {
        config3.push({
          label: options2.otherLabel || _4("Other groups"),
          submenu: function() {
            return getItems.bind(this, options2, range2, void 0);
          },
          options: {
            watch: watch.bind(this, options2)
          }
        });
      }
      return config3;
    };
    var watch = function(options2, cb2, scope) {
      if (!options2.groupTypes) {
        var project = projectStore.getForCard(options2.card || options2.parent);
        return cardGroupTypeStore.scopedByEnabled(project, options2.card && options2.includeAttrGroup).$watchAll(scope, cb2, false);
      } else {
        return angular_default.noop;
      }
    };
    var fetchData = function(options2, cb2) {
      if (!options2.parent && options2.card.parent_id && !cardStore.exists(options2.card.parent_id)) {
        $q.digest(getOrLoadCard(options2.card.parent_id), cb2);
      } else {
        cb2();
      }
    };
    return {
      getItems,
      watch,
      fetchData,
      get: function(options2, beginning, range2) {
        var menuOpts = {
          watch: watch.bind(this, options2),
          fetchData: fetchData.bind(this, options2)
        };
        if (options2.dataPrefetched) {
          menuOpts.dataPrefetched = options2.dataPrefetched;
        }
        if (options2.title) {
          menuOpts.title = options2.title;
        }
        return {
          config: function() {
            return getItems.bind(this, options2, beginning, range2);
          },
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/ui/card-groups/modals/copy-group.js
angular_default.module("kantree").factory("cardGroupCopyModal", class extends AngularClass {
  static $inject = ["$rootScope", "$uibModal"];
  open(group2) {
    const scope = this.$rootScope.$new();
    scope.group = group2;
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/ui/card-groups/modals/templates/copy-group-modal.html",
      controller: "cardGroupCopyModalCtrl",
      windowClass: "card-group-copy-modal",
      scope
    });
    instance.result.finally(() => scope.$destroy());
    return instance;
  }
});
angular_default.module("kantree").controller("cardGroupCopyModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.groupType = cardGroupTypeStore.get($scope2.group.type_id);
    $scope2.parent = cardStore.get($scope2.group.parent_id);
    $scope2.selected = null;
    $scope2.copyCards = true;
    $scope2.selectBoard = function(board) {
      $scope2.selectedBoard = board;
    };
    $scope2.copyTo = function(newParent) {
      let p4;
      if ($scope2.parent.project_id !== newParent.project_id) {
        p4 = confirmDialog({
          title: _4("Copy information"),
          text: _4("Changing the workspace of a card will involve recomputing all card references. Note that access rights may also be impacted"),
          confirmButtonText: _4("Copy")
        });
      } else {
        p4 = Promise.resolve();
      }
      p4.then(() => {
        $q.when(copyGroup($scope2.group, $scope2.parent, newParent, false, $scope2.copyCards), () => {
          $uibModalInstance.close();
        });
      });
    };
  }
]);

// public/app/ui/card-groups/modals/group-roles.js
angular_default.module("kantree").service("cardGroupRolesModal", class extends AngularClass {
  static $inject = ["roleObjExceptionsModal"];
  open(project, groups, focusGroup) {
    return this.$roleObjExceptionsModal.open({
      title: _4("Edit which roles can move cards from/to groups"),
      project,
      objectType: "card_group",
      objects: groups.map(function(g3) {
        return { id: g3.id, name: g3.title };
      }),
      focusObject: focusGroup ? { id: focusGroup.id, name: focusGroup.title } : null,
      actions: [
        {
          label: _4("Move cards"),
          map: [{ object_type: "card_group", actions: ["MOVE_CARDS"] }]
        }
      ]
    });
  }
});

// public/app/ui/card-groups/modals/group-type-groups.js
angular_default.module("kantree").service("cardGroupTypeGroupsModal", class extends AngularClass {
  static $inject = ["$uibModal", "$rootScope"];
  open(groupType, parent) {
    var scope = this.$rootScope.$new();
    scope.groupType = groupType;
    scope.parent = parent;
    var instance = this.$uibModal.open({
      templateUrl: "/static/app/ui/card-groups/modals/templates/group-type-groups-modal.html",
      controller: "cardGroupTypeGroupsModalCtrl",
      windowClass: "card-group-type-groups-modal",
      scope
    });
    instance.result.finally(function() {
      scope.$destroy();
    });
    return instance;
  }
});
angular_default.module("kantree").controller("cardGroupTypeGroupsModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    injectI18nHelpersIntoScope($scope2);
    $scope2.section = 0;
    $scope2.openedGroups = [];
    $scope2.archivedGroups = [];
    $scope2.project = projectStore.getForCard($scope2.parent);
    $scope2.settingsSelected = false;
    $scope2.textColor = textColor;
    $scope2.formatDate = formatDate;
    var refreshEditable = function() {
      $scope2.editable = $scope2.project && !$scope2.project.is_archived;
      $scope2.editableOnline = $scope2.editable && isConnected();
      $scope2.canCreateGroups = $scope2.editableOnline && isAllowedInProject(
        $scope2.project,
        "card_group",
        "CREATE"
      );
      $scope2.canManageGrouptype = $scope2.editableOnline && isAllowedInProject(
        $scope2.project,
        "card_group_type",
        ["CREATE", "EDIT", "DELETE"]
      );
      $scope2.canEditGroupType = $scope2.editableOnline && !$scope2.groupType.attribute_id && isAllowedInProject(
        $scope2.project,
        "card_group_type",
        "EDIT",
        $scope2.groupType.id
      );
    };
    $scope2.$on("connectivityChanged", refreshEditable);
    refreshEditable();
    $q.all([
      loadAllGroupsForTypeAndParent($scope2.groupType, $scope2.parent),
      loadAllArchivedGroupsForTypeAndParent($scope2.groupType, $scope2.parent)
    ]);
    const scopedCardGroupStore = cardGroupStore.scopedByType($scope2.groupType, $scope2.parent);
    scopedCardGroupStore.$watchAll($scope2, function() {
      $scope2.openedGroups = scopedCardGroupStore.query({ is_archived: false }, { sortBy: "position" });
      $scope2.archivedGroups = scopedCardGroupStore.query({ is_archived: true }, { sortBy: "id" });
      $scope2.groups = $scope2.section === 0 ? $scope2.openedGroups : $scope2.archivedGroups;
    });
    $scope2.canEditGroup = function(group2) {
      return $scope2.editableOnline && canOpenGroupActionsMenu($scope2.project, group2.id);
    };
    $scope2.archive = function(group2) {
      $q.digest(archiveGroup(group2, $scope2.parent));
    };
    $scope2.restore = function(group2) {
      $q.digest(restoreGroup(group2, $scope2.parent));
    };
    $scope2.remove = function(group2) {
      confirmDeleteDialog2().then(() => {
        $q.digest(deleteGroup(group2, $scope2.parent));
      });
    };
    $scope2.startCreate = function() {
      $scope2.creating = true;
      $scope2.section = 0;
      $scope2.titleInput = $scope2.groupType.singular_name + " " + ($scope2.groups.length + 1);
    };
    $scope2.create = function(title) {
      $q.when(createGroup($scope2.groupType, $scope2.parent, title), () => {
        $scope2.creating = false;
      });
    };
    $scope2.showSettings = function() {
      $scope2.groupTypeEdit = angular_default.copy($scope2.groupType);
      $scope2.settingsSelected = true;
    };
    $scope2.saveSettings = function() {
      $q.when(saveGroupType($scope2.groupTypeEdit, null, $scope2.project), () => {
        $scope2.settingsSelected = false;
      });
    };
    $scope2.cancelSettings = function() {
      $scope2.settingsSelected = false;
    };
    $scope2.deleteGroupType = function() {
      $q.when(disableOrDeleteGroupType($scope2.groupType, $scope2.project), () => {
        $uibModalInstance.close();
      });
    };
  }
]);

// public/app/ui/card-groups/modals/move-group.js
angular_default.module("kantree").factory("cardGroupMoveModal", class extends AngularClass {
  static $inject = ["$rootScope", "$uibModal"];
  open(group2) {
    const scope = this.$rootScope.$new();
    scope.group = group2;
    const instance = this.$uibModal.open({
      templateUrl: "/static/app/ui/card-groups/modals/templates/move-group-modal.html",
      controller: "cardGroupMoveModalCtrl",
      windowClass: "card-group-move-modal",
      scope
    });
    instance.result.finally(() => scope.$destroy());
    return instance;
  }
});
angular_default.module("kantree").controller("cardGroupMoveModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$q",
  function($scope2, $uibModalInstance, $q) {
    $scope2.groupType = cardGroupTypeStore.get($scope2.group.type_id);
    $scope2.parent = cardStore.get($scope2.group.parent_id);
    $scope2.selected = null;
    $scope2.relocateCards = true;
    $scope2.selectBoard = function(board) {
      $scope2.selectedBoard = board;
    };
    $scope2.moveTo = function(newParent) {
      let p4;
      if ($scope2.parent.project_id !== newParent.project_id) {
        p4 = confirmDialog({
          title: _4("Move information"),
          text: _4("Changing the root-board of a card will involve recomputing all card references. Note that access rights may also be impacted"),
          confirmButtonText: _4("Move")
        });
      } else {
        p4 = Promise.resolve();
      }
      p4.then(() => {
        $q.when(relocateGroup($scope2.group, $scope2.parent, newParent, $scope2.relocateCards), () => {
          $uibModalInstance.close();
        });
      });
    };
  }
]);

// public/app/ui/card-models/ng-components/attributes.js
angular_default.module("kantree").directive("modelAttrListEditor", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/card-models/ng-components/templates/attributes.html",
      replace: true,
      scope: {
        model: "=?",
        attributes: "=?",
        org: "=?",
        project: "=?"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          if ($scope2.model) {
            $scope2.attributes = $scope2.model.attributes;
          }
          $scope2.addAttribute = function() {
            if (!$scope2.attributes) {
              $scope2.attributes = [];
            }
            $scope2.attributes.push({
              position: null,
              inputType: "text",
              is_pii: false
            });
          };
          $scope2.removeAttribute = function(key2) {
            $scope2.attributes.splice(key2, 1);
          };
        }
      ]
    };
  }
]);

// public/app/ui/card-models/ng-components/editor.js
angular_default.module("kantree").directive("modelEditor", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/card-models/ng-components/templates/editor.html",
      replace: true,
      scope: {
        models: "=",
        model: "=",
        project: "=?",
        org: "=?"
      },
      controller: [
        "$q",
        "$scope",
        function($q, $scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.loadProjects = function() {
            if (typeof $scope2.model.id !== "undefined") {
              $q.when(api_default.card_models.list_enabled_model_in_projects.get({ model_id: $scope2.model.id }), (projects) => {
                $scope2.projects = projects;
                $scope2.showProjects = true;
              });
            }
          };
          $scope2.showProjects = false;
          if ($scope2.project && !$scope2.org && $scope2.project.owner.type === "org") {
            $scope2.org = $scope2.project.owner;
          }
          $scope2.display = {
            showMoreOpts: false,
            showInheritedAttr: false
          };
          $scope2.$watch("model.extends_id", function() {
            $scope2.extendedAttributes = [];
            var findModel = function(id) {
              $scope2.models.forEach(function(model) {
                if (model.id === id) {
                  walk(model);
                  return false;
                }
              });
            };
            var walk = function(model) {
              if (model.extends) {
                walk(model.extends);
              }
              $scope2.extendedAttributes = $scope2.extendedAttributes.concat(model.attributes);
            };
            findModel(parseInt($scope2.model.extends_id));
          });
        }
      ]
    };
  }
]);

// public/app/ui/card-models/menus/model-editor.js
angular_default.module("kantree").factory("modelEditorMenuFactory", [
  "$q",
  function($q) {
    var getAppearanceItems = function(model, project) {
      var items = [];
      items.push(
        {
          subheader: _4("Name")
        },
        {
          input: true,
          submit: function(name2) {
            if (model.name === name2) {
              return;
            }
            return $q.digest(updateModel(Object.assign({}, model, { name: name2 })));
          },
          defaultValue: model && model.name ? model.name : null
        }
      );
      items.push(
        {
          subheader: _4("Icon"),
          help: _4("This icon will be displayed on card tiles.")
        },
        {
          iconpicker: true,
          getValue: function() {
            return model ? model.indicator : null;
          },
          color: model ? model.card_color : null,
          action: function(event2, indicator) {
            if (model.indicator === indicator) {
              return;
            }
            return $q.digest(updateModel(Object.assign({}, model, { indicator })));
          },
          emptyIcon: true,
          noCloseAfterAction: true,
          extended: true,
          options: {
            watch: watchModel.bind(this, model)
          }
        }
      );
      items.push(
        {
          subheader: _4("Background color"),
          help: _4("All cards using this type will use this background color.")
        },
        {
          colorpicker: true,
          getValue: function() {
            return model ? model.card_color : null;
          },
          action: function(event2, color) {
            if (model.card_color === color) {
              return;
            }
            return $q.digest(updateModel(Object.assign({}, model, { card_color: color })));
          },
          noCloseAfterAction: true,
          hasColorPalette: true
        }
      );
      return items;
    };
    var getSettingsItems = function(model, project) {
      var modelStore = cardModelStore.scopedByEnabled(project, true).scoped({ base_model_type: query_exports.isFalsy() });
      if (!model.is_project_specific) {
        modelStore = modelStore.scoped({ is_project_specific: query_exports.isFalsy() });
      }
      var models = modelStore.query({}, { sortBy: "id" }).filter(function(m3) {
        return m3.name && m3.name.length && m3.id !== model.id;
      });
      var nullValueForSubCards = {
        id: -1,
        name: _4("None")
      };
      var currentModelForSubCards = {
        id: model.id,
        name: _4("This one")
      };
      var modelsOptions = [currentModelForSubCards].concat(models);
      var items = [
        {
          subheader: _4("Default type for sub-cards"),
          help: _4("New child cards of a card which is using this type, will use the type selected above as their default one.")
        },
        {
          selectbox: true,
          select: function(obj) {
            var children_default_model_id = obj.id === -1 ? null : obj.id;
            if (model.children_default_model_id === children_default_model_id) {
              return;
            }
            return $q.digest(updateModel(Object.assign({}, model, { children_default_model_id })));
          },
          selectOptions: [nullValueForSubCards].concat(modelsOptions),
          optionsLabelProperty: "name",
          defaultValue: model.children_default_model_id ? modelsOptions.find(function(m3) {
            return m3.id === model.children_default_model_id;
          }) : nullValueForSubCards
        }
      ];
      if (model.extends_id) {
        items.push(
          {
            subheader: _4("Extends from"),
            help: _4("When a type extends from another one, it inherits all the fields of the parent.")
          },
          {
            desc: _4("This feature is now deprecated. You can click the button below to remove the extend on this type. Inconsistencies may appear in the future if you don't remove it.")
          },
          {
            label: _4("Remove extend"),
            action: function(obj) {
              return $q.digest(updateModel(Object.assign({}, model, { extends_id: null })));
            }
          }
        );
      }
      items.push({ value: "--" }, {
        checkbox: true,
        value: model.only_show_own_attributes,
        label: _4("Hide workspace and organization fields (BETA)"),
        toggle: (only_show_own_attributes) => {
          $q.digest(updateModel(Object.assign({}, model, { only_show_own_attributes })));
        }
      });
      items.push({ value: "--" }, {
        checkbox: true,
        value: model.hide_children_attributes,
        label: _4("Hide sub-card attributes"),
        toggle: (hide_children_attributes) => {
          $q.digest(updateModel(Object.assign({}, model, { hide_children_attributes })));
        }
      });
      return items;
    };
    var watchModel = function(model, cb2, scope) {
      var off = cardModelStore.$watch(scope, model, "updated", function() {
        cb2 && cb2();
      }, false);
      return off;
    };
    var getTabs = function(model, project) {
      return [{
        icon: "paint-brush",
        title: _4("Appearance"),
        items: getAppearanceItems(model, project)
      }, {
        icon: "cogs",
        title: _4("Advanced"),
        items: getSettingsItems(model, project),
        watch: function(cb2, scope) {
          var off = cardModelStore.scopedByOrg(project.owner).$watchAll(scope, function() {
            cb2 && cb2();
          }, false);
          return off;
        },
        fetchData: function(cb2) {
          $q.when(loadAllModelsForProjectOwner(project), cb2);
        }
      }];
    };
    return {
      getTabs,
      watch: watchModel,
      get: function(model, project) {
        var menuOpts = {
          withTabs: true,
          watch: watchModel.bind(this, model),
          title: function() {
            return _4("Edit {model} card type", { model: model.name });
          }
        };
        var menuConfig = function() {
          return getTabs.bind(this, model, project);
        };
        return {
          config: menuConfig,
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/ui/card-models/menus/models.js
angular_default.module("kantree").directive("modelsMenuToggle", [
  "modelsMenuFactory",
  "menuDropdown",
  function(modelsMenuFactory, menuDropdown) {
    return {
      restrict: "A",
      scope: {
        params: "<modelsMenuToggle"
      },
      link: function(scope, element2, attr) {
        var menu;
        var drop;
        var loaded, loading;
        scope.$watch("params", function(params) {
          if (params && params.card) {
            menu = modelsMenuFactory.get(params.card, Object.assign({
              dataPrefetched: true
            }, params.options || {}));
          } else {
            menu = null;
          }
        });
        element2.on("click touchstart", function(event2) {
          if (menu && !loading) {
            if (!loaded) {
              loading = true;
              modelsMenuFactory.fetchData(scope.params.card, function() {
                loaded = true;
                loading = false;
                drop = menuDropdown.toggle(drop, element2[0], menu, scope, null, event2);
              });
            } else {
              drop = menuDropdown.toggle(drop, element2[0], menu, scope, null, event2);
            }
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").factory("modelsMenuFactory", [
  "projectSettingsModal",
  "modelEditorMenuFactory",
  "$q",
  function(projectSettingsModal, modelEditorMenuFactory, $q) {
    var defaultOptions4 = {
      canSwitchModels: true,
      canEditModels: true,
      canCreateModels: true
    };
    function switchModel(card, sourceModel, targetModel, options2) {
      if (card?.id) {
        $q.digest(switchCardModel(card, targetModel, sourceModel));
      } else if (options2.onSwitchModel) {
        if (card) {
          card.model_id = targetModel.id;
        }
        options2.onSwitchModel(targetModel);
      }
    }
    function getEditButtonMixin(model, project) {
      var modelEditorMenu = modelEditorMenuFactory.get(model, project);
      return {
        submenu: modelEditorMenu.config,
        options: modelEditorMenu.options,
        buttons: [{
          icon: "pencil",
          action: "openSubmenu"
        }]
      };
    }
    function buildModelBaseItem(card, cardModel, model, project, options2) {
      var item = {
        label: model.name,
        selected: function() {
          return card?.model_id === model.id;
        },
        icon: model.indicator || null,
        color: model.card_color || "transparent"
      };
      if ((!card || isAllowedInProject(project, "card", "SWITCH_MODEL", card.id)) && options2.canSwitchModels) {
        item.action = function() {
          return switchModel(card, cardModel, model, options2);
        };
      }
      return item;
    }
    function buildItemForProjectModel(card, cardModel, model, project, options2) {
      var item = buildModelBaseItem(card, cardModel, model, project, options2);
      if (canEditCardModel(project, model.id) && options2.canEditModels) {
        var mixin3 = getEditButtonMixin(model, project);
        item = Object.assign({}, item, mixin3);
      }
      return item;
    }
    function buildItemForOrgModel(card, cardModel, model, project, options2, org2) {
      var item = buildModelBaseItem(card, cardModel, model, project, options2);
      item.small = _4("TEAM");
      if (isCurrentUserManagerOf(org2) && options2.canEditModels) {
        var mixin3 = getEditButtonMixin(model, project);
        item = Object.assign({}, item, mixin3);
      }
      return item;
    }
    var getItems = function(card, options2) {
      options2 = Object.assign({}, defaultOptions4, options2 || {});
      if (!isConnected()) {
        Object.assign(options2, {
          canSwitchModels: false,
          canEditModels: false,
          canCreateModels: false
        });
      }
      var project = card ? projectStore.getForCard(card) : options2.project;
      var models = cardModelStore.scopedByEnabled(project).query({ base_model_id: query_exports.isUndefined() }, { sortBy: "name" });
      models.unshift({ name: _4("None"), id: null });
      var cardModel = card?.model_id ? cardModelStore.getCardModel(card) : null;
      var items = models.map(function(model) {
        const org2 = model.owner ? orgStore.tryGet(model.owner.id) : null;
        if (model.is_project_specific && model.used_by.indexOf(project.id) !== -1) {
          return buildItemForProjectModel(card, cardModel, model, project, options2);
        } else if (org2 && isCurrentUserMemberOf(org2)) {
          return buildItemForOrgModel(card, cardModel, model, project, options2, org2);
        } else {
          return buildModelBaseItem(card, cardModel, model, project, options2);
        }
      });
      items.push({
        label: "--",
        enabled: function() {
          return models.length > 0 && canCreateCardModel(project) && options2.canCreateModels;
        }
      });
      if (canCreateCardModel(project) && options2.canCreateModels) {
        items.push({
          input: true,
          placeholder: _4("Create new type"),
          submit: function(name2) {
            $q.when(createModelInProject({ name: name2 }, project), (model) => {
              if (isAllowedInProject(project, "card", "SWITCH_MODEL", card.id) && options2.canSwitchModels) {
                switchModel(card, cardModel, model);
              }
            });
          },
          resetOnSubmit: true
        });
      }
      if (options2.canEditToolbar) {
        if (items.length && items[items.length - 1].label !== "--") {
          items.push({ label: "--" });
        }
        const toolbarItem = {
          icon: options2.hasToolbar ? "bi-trash" : "bi-plus",
          label: options2.hasToolbar ? card.model_id ? _4("Remove toolbar for {type}", { type: cardModel?.name || _4("this type") }) : _4("Remove toolbar for all cards") : card.model_id ? _4("Add toolbar for {type}", { type: cardModel?.name || _4("this type") }) : _4("Add toolbar for all cards"),
          action: () => {
            options2.onToggleToolbar?.();
          }
        };
        items.push(toolbarItem);
      }
      return items;
    };
    var watch = function(card, cb2, scope) {
      var project = projectStore.getForCard(card);
      return offMany([
        cardModelStore.scopedByEnabled(project).$watchAll(scope, cb2, false),
        scope.$on("connectivityChanged", cb2)
      ]);
    };
    var fetchData = function(card, cb2) {
      const project = projectStore.getForCard(card);
      $q.when(loadAllEnabledModelsForProject(project), cb2);
    };
    return {
      getItems,
      watch,
      fetchData,
      get: function(card, options2) {
        var menuOpts = {
          watch: watch.bind(this, card),
          fetchData: fetchData.bind(this, card),
          title: _4("Card types")
        };
        var project = projectStore.getForCard(card);
        if (!structureIsLocked(project) && isAllowedInProject(project, "card_model", ["CREATE", "EDIT", "DELETE"])) {
          menuOpts.settings = function() {
            projectSettingsModal.open(project, "models");
          };
        }
        if (options2 && options2.dataPrefetched) {
          menuOpts.dataPrefetched = options2.dataPrefetched;
        }
        var menuConfig = function() {
          return getItems.bind(this, card, options2);
        };
        return {
          config: menuConfig,
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/ui/card-models/ng-filters.js
angular_default.module("kantree").filter("formatModelAttributes", function() {
  return function(model, project) {
    if (typeof model.attributes === "undefined") {
      return "";
    }
    var attrs2 = model.attributes;
    if (project) {
      attrs2 = cardModelStore.getExtendedModelAttributes(model, project);
    }
    return attrs2.map(function(a3) {
      return a3.name;
    }).join(", ");
  };
});
angular_default.module("kantree").filter("modelsFilter", function() {
  return function(models, selected) {
    var filtered = [];
    angular_default.forEach(models, function(m3) {
      if (m3.name && m3.name.length && m3.id !== selected.id && !m3.base_model_type) {
        filtered.push(m3);
      }
    });
    return filtered;
  };
});

// public/app/ui/coach/ng-components.js
angular_default.module("kantree").component("coachPanel", {
  bindings: {
    context: "<?",
    onClose: "&"
  },
  template: `
    <div class="header">
      <img ng-attr-src="{{'/static/assets/coach.png'|baseUrl}}" width="16" height="16" class="me-2">
      <span>{{$ctrl.title}}</span>
      <span class="badge">BETA</span>
      <button class="btn btn-icon" ng-click="$ctrl.onClose()"><i class="bi-x-lg"></i></button>
    </div>
    <iframe ng-src="{{$ctrl.url}}"></iframe>
  `,
  controller: class extends AngularClass {
    static $inject = ["$sce"];
    $onInit() {
      this.title = _4("Coach");
    }
    $onChanges(changes) {
      const payload = Object.assign({ user: currentUser2.id, host: document.location.host }, this.context);
      const context = encodeURIComponent(btoa(JSON.stringify(payload)));
      this.url = this.$sce.trustAsResourceUrl(serverConfig.coach_url + "?locale=" + getCurrentLocale() + "&context=" + context);
    }
  }
});
angular_default.module("kantree").directive("coachBtn", function() {
  return {
    scope: {},
    template: `
      <button class="btn btn-topbar btn-primary" ng-click="$ctrl.$coach.toggle()" ng-show="$ctrl.$coach.available && !$ctrl.$coach.visible">
        <img ng-attr-src="{{'/static/assets/coach.png'|baseUrl}}" width="16" height="16" class="me-1"> {{::$ctrl.label}}
      </button>
    `,
    replace: true,
    bindToController: true,
    controllerAs: "$ctrl",
    controller: class extends AngularClass {
      static $inject = ["coach"];
      $onInit() {
        this.label = _4("Coach");
      }
    }
  };
});

// public/app/ui/coach/service.js
angular_default.module("kantree").service("coach", class extends AngularClass {
  static $inject = ["$rootScope", "$compile", "$document"];
  constructor(...args) {
    super(...args);
    this.visible = false;
    this.available = !!serverConfig.coach_url && getCurrentLocale() === "fr";
  }
  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      this.scope = this.$rootScope.$new();
      this.scope.coach = this;
      this.element = this.$compile('<coach-panel context="coach.context" on-close="coach.toggle()"></coach-panel>')(this.scope);
      $("#app-container").prepend(this.element);
    } else {
      this.scope.$destroy();
      this.element.remove();
    }
  }
  setupContext(ctx) {
    this.context = ctx;
    return () => {
      this.context = null;
    };
  }
  setupContextOnScope(scope, ctx) {
    scope.$on("$destroy", this.setupContext(ctx));
  }
});

// public/app/ui/editors/content-editor/content-composer.js
angular_default.module("kantree").component("contentComposer", {
  bindings: {
    content: "<?",
    options: "<?",
    onSubmit: "&",
    onEdit: "&",
    onCancel: "&",
    onClear: "&",
    onDraftChange: "&"
  },
  templateUrl: "/static/app/ui/editors/content-editor/templates/content-composer.html",
  controller: [
    "$element",
    "$q",
    "$sce",
    "$document",
    "$timeout",
    "hotkeys",
    "$scope",
    function($element2, $q, $sce, $document, $timeout2, hotkeys, $scope2) {
      var $ctrl = this;
      var defaultOpts = {
        data: {},
        type: "default",
        defaultActiveEditor: null,
        draftDelay: -1,
        // or object with draft id and debounce delay,
        placeholder: null,
        uuid: uuid4(),
        container: null,
        on: {
          blur: "saveDraft cancel"
        },
        buttons: [
          {
            label: _4("Save"),
            class: "btn btn-success",
            on: "submit clear"
          },
          {
            label: _4("Cancel"),
            class: "btn btn-icon",
            content: '<i class="fa fa-times"></i>',
            on: "clear cancel"
          }
        ]
      };
      $ctrl.submit = function() {
        $ctrl.disableButtons = true;
        var promise;
        if ($ctrl.onSubmit) {
          promise = $ctrl.onSubmit({ submittedText: $ctrl.text });
        }
        if (!isObject2(promise) || !(promise.then instanceof Function)) {
          var deferred = $q.defer();
          promise = deferred.promise;
          deferred.resolve();
        }
        if ($ctrl.saveDraft) {
          promise.then(function() {
            $ctrl.saveDraft.immediate($ctrl.composerOptions.uuid, null);
          });
        }
        promise.finally(() => {
          $ctrl.disableButtons = false;
        });
        return promise;
      };
      $ctrl.clear = function() {
        $ctrl.text = $ctrl.content;
        $ctrl.contentChanged = false;
        if ($ctrl.saveDraft) {
          $ctrl.saveDraft.immediate($ctrl.composerOptions.uuid, null);
        }
        if ($ctrl.onClear) {
          $ctrl.onClear({ clearedText: $ctrl.text });
        }
      };
      $ctrl.cancel = function() {
        if ($ctrl.onCancel) {
          $ctrl.onCancel({ cancelledText: $ctrl.text });
        }
      };
      $ctrl.triggerHandlers = function(handlers3, event2) {
        var promise;
        var deffered = $q.defer();
        promise = deffered.promise;
        deffered.resolve();
        if (!handlers3 || !handlers3.length) {
          return promise;
        }
        handlers3.split(" ").forEach(function(value2) {
          switch (value2) {
            case "submit":
              promise = $ctrl.submit();
              break;
            case "clear":
              promise.then(function() {
                $ctrl.clear();
              });
              break;
            case "cancel":
              promise.then(function() {
                $ctrl.cancel();
              });
              break;
            case "saveDraft":
              promise.then(function() {
                if ($ctrl.saveDraft) {
                  $ctrl.saveDraft.immediate($ctrl.composerOptions.uuid, $ctrl.contentChanged ? $ctrl.text : null);
                }
              });
              break;
          }
        });
        return promise;
      };
      $ctrl.onTextChange = function(text3) {
        $ctrl.text = text3;
        const _contentChanged = $ctrl.contentChanged;
        $ctrl.contentChanged = doesContentHasChanged();
        if (_contentChanged !== $ctrl.contentChanged) {
          $scope2.$applyAsync();
        }
        if ($ctrl.saveDraft) {
          $ctrl.saveDraft($ctrl.composerOptions.uuid, $ctrl.contentChanged ? $ctrl.text : null);
        }
        if ($ctrl.onEdit) {
          $ctrl.onEdit({ editedText: $ctrl.text, contentChanged: $ctrl.contentChanged });
        }
      };
      function doesContentHasChanged() {
        return $ctrl.text !== $ctrl.content;
      }
      function refreshOptions() {
        $ctrl.composerOptions = angular_default.merge({}, defaultOpts, $ctrl.options);
        if (angular_default.isArray($ctrl.composerOptions.buttons)) {
          $ctrl.composerOptions.buttons.forEach(function(button) {
            if (!button.content) {
              button.content = button.label;
            }
            if (angular_default.isString(button.content)) {
              button.content = $sce.trustAsHtml(button.content);
            }
          });
        } else {
          $ctrl.composerOptions.buttons = [];
        }
      }
      function focusSubmitButton() {
        var submitButtonIndex = ($ctrl.composerOptions.buttons || []).findIndex(function(button) {
          return button.on && button.on.indexOf("submit") !== -1;
        });
        if (submitButtonIndex !== -1) {
          $element2.find("> button").get(submitButtonIndex).focus();
        }
      }
      $ctrl.$onInit = function() {
        $ctrl.content = $ctrl.content || "";
        $ctrl.disableButtons = false;
        refreshOptions();
        if ($ctrl.composerOptions.draftDelay > 0) {
          $ctrl.saveDraft = debounce2(function(draftId, value2) {
            jsonLocalStorage.setItem(draftId, value2);
            if ($ctrl.onDraftChange) $ctrl.onDraftChange({ draftedText: value2 });
          }, $ctrl.composerOptions.draftDelay);
        } else if ($ctrl.composerOptions.draftDelay === 0) {
          $ctrl.saveDraft = function(draftId, value2) {
            jsonLocalStorage.setItem(draftId, value2);
            if ($ctrl.onDraftChange) $ctrl.onDraftChange({ draftedText: value2 });
          };
        }
        var draft = jsonLocalStorage.getItem($ctrl.composerOptions.uuid);
        if ($ctrl.composerOptions.draftDelay >= 0 && draft) {
          $ctrl.text = draft;
        } else {
          $ctrl.text = $ctrl.content;
        }
        $ctrl.contentChanged = doesContentHasChanged();
        $ctrl.hotkeys = [{
          combo: "tab",
          description: _4("Focus save"),
          callback: function() {
            focusSubmitButton();
            return true;
          },
          allowIn: ["TEXTAREA"]
        }, {
          combo: "mod+enter",
          description: _4("Save"),
          callback: function() {
            var submitButton = ($ctrl.composerOptions.buttons || []).find(function(button) {
              return button.on && button.on.indexOf("submit") !== -1;
            });
            if (submitButton) {
              $ctrl.triggerHandlers(submitButton.on);
            }
            return true;
          },
          allowIn: ["TEXTAREA"]
        }];
        hotkeys.bindTo($scope2).add({
          combo: "enter",
          callback: function(event2) {
            event2.stopPropagation();
          }
        });
      };
      $ctrl.$onChanges = function(changes) {
        if (changes.options && !changes.options.isFirstChange()) {
          refreshOptions();
        }
      };
      function onScroll() {
        $ctrl.scrolled = true;
      }
      function onClick(event2) {
        if (event2.data.uuid !== $ctrl.composerOptions.uuid) {
          return;
        }
        var container = $element2;
        if ($ctrl.composerOptions.container) {
          container = $element2.parents($ctrl.composerOptions.container);
        }
        if (!jquery_default(event2.target).closest(container).length && container.is(":visible")) {
          $ctrl.clickedOutside = true;
          $ctrl.scrolled = false;
          $document[0].addEventListener("scroll", onScroll, true);
        }
      }
      function onMouseUp(event2) {
        var container = $element2;
        if ($ctrl.composerOptions.container) {
          container = $element2.parents($ctrl.composerOptions.container);
        }
        if (!jquery_default(event2.target).closest(container).length && !jquery_default(event2.target).closest(".drop-theme-prosemirror").length && container.is(":visible")) {
          if ($ctrl.clickedOutside && !$ctrl.scrolled) {
            $timeout2(function() {
              $ctrl.triggerHandlers($ctrl.composerOptions.on.blur);
            });
          } else {
            event2.stopPropagation();
            event2.stopImmediatePropagation();
            event2.preventDefault();
          }
        }
        $ctrl.clickedOutside = false;
        $ctrl.scrolled = false;
        $document[0].removeEventListener("scroll", onScroll, true);
      }
      $ctrl.$postLink = function() {
        $ctrl.clickedOutside = false;
        $ctrl.scrolled = false;
        $timeout2(function() {
          $document.on("mousedown", { uuid: $ctrl.composerOptions.uuid }, onClick);
          $document[0].addEventListener("click", onMouseUp, true);
        }, 0, false);
      };
      $ctrl.$onDestroy = function() {
        $document.off("mousedown", onClick);
        $document[0].removeEventListener("click", onMouseUp, true);
      };
    }
  ]
});

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

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

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

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

// public/app/ui/editors/content-editor/content-editor.js
angular_default.module("kantree").component("contentEditor", {
  restrict: "E",
  templateUrl: "/static/app/ui/editors/content-editor/templates/content-editor.html",
  require: { ngModel: "?ngModel" },
  bindings: {
    "content": "<?",
    "defaultEditor": "@",
    "forceEditor": "@",
    "editorType": "@",
    "editorData": "<",
    "placeholder": "@",
    "hotkeys": "<",
    "onChange": "&",
    "focusOnLoad": "<"
  },
  controller: [
    "$scope",
    "$element",
    function($scope2, $element2) {
      var $ctrl = this;
      this.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
        if (this.ngModel) {
          this.ngModel.$render = function() {
            $ctrl.text = $ctrl.ngModel.$viewValue || "";
          };
          this.text = this.ngModel.$viewValue || "";
        }
        if (this.forceEditor && this.forceEditor.length) {
          this.activeEditor = this.forceEditor;
        } else if (this.placeholder) {
          this.activeEditor = "markdown";
        } else {
          this.activeEditor = jsonLocalStorage.getItem("activeEditor") || this.defaultEditor || "prosemirror";
        }
        $element2.addClass(this.activeEditor);
      };
      this.$onChanges = function() {
        if (typeof this.content !== "undefined") {
          this.text = this.content;
        }
      };
      this._onChange = function(text3) {
        this.text = text3;
        if (this.ngModel) {
          this.ngModel.$setViewValue(text3);
        }
        this.onChange({ $text: text3 });
      };
      this.switchEditor = function(name2) {
        $element2.removeClass(this.activeEditor);
        $element2.addClass(name2);
        this.activeEditor = name2;
        if (!this.forceEditor || !this.forceEditor.length) {
          jsonLocalStorage.setItem("activeEditor", name2);
        }
      };
    }
  ]
});
angular_default.module("kantree").directive("ngProsemirror", [
  "$q",
  "prosemirror",
  function($q, prosemirror) {
    return {
      restrict: "A",
      scope: {
        "onChange": "&",
        "text": "=",
        "type": "<ngProsemirror",
        "data": "=editorData",
        "hotkeys": "<",
        "focusOnLoad": "<"
      },
      link: function(scope, element2, attr) {
        var textValue = scope.text;
        async function loadProjectData() {
          const project = await getOrLoadProject(scope.data.project_id, { ignoreErrorHandlers: true });
          return loadAllProjectMembers(project, true, { ignoreErrorHandlers: true });
        }
        if (scope.type === "comment" || scope.type === "content") {
          $q.digest(loadProjectData());
        }
        var onTransaction = function(transaction, pmView2) {
          textValue = prosemirror.toMarkdown(pmView2);
          scope.onChange({ $text: textValue });
        };
        var pmView = prosemirror.createEditor(element2[0], scope.type, scope.text, scope.data, scope.hotkeys, scope, onTransaction);
        if (!pmView.hasFocus() && scope.focusOnLoad) {
          pmView.focus();
        }
        scope.$watch("text", function(newVal) {
          if (textValue !== newVal) {
            var stateConfig = {
              schema: pmView.state.schema,
              plugins: pmView.state.plugins,
              doc: prosemirror.fromMarkdown(pmView, newVal)
            };
            pmView.updateState(EditorState.create(stateConfig));
          }
        });
        scope.$on("$destroy", function() {
          pmView.props.on.editorDestroy.dispatch();
          pmView.destroy();
        });
        element2.on("$destroy", function() {
          scope.$destroy();
        });
      }
    };
  }
]);
angular_default.module("kantree").directive("markdownEditor", [
  "$rootScope",
  "hotkeys",
  function($rootScope, hotkeys) {
    return {
      restrict: "A",
      scope: {
        "onChange": "&",
        "text": "=",
        "hotkeys": "<",
        "focusOnLoad": "<"
      },
      link: function(scope, element2) {
        var textValue = scope.text;
        element2.val(textValue);
        element2.autosize();
        if (scope.focusOnLoad) {
          jquery_default(element2).trigger("focus");
        }
        scope.$watch("text", function(newVal) {
          if (textValue !== newVal) {
            element2.val(newVal);
            if (!newVal || newVal === "") {
              element2.trigger("autosize.resize");
            }
          }
        });
        element2.on("keyup", function(event2) {
          textValue = jquery_default(this).val();
          scope.onChange({ $text: textValue });
        });
        if (scope.hotkeys) {
          scope.hotkeys.forEach(function(hotkey) {
            hotkeys.bindTo(scope).add(hotkey);
          });
        }
        element2.on("$destroy", function() {
          scope.$destroy();
        });
        scope.$on("$destroy", function() {
          element2.trigger("autosize.destroy");
        });
      }
    };
  }
]);

// public/app/ui/editors/content-editor/text-composer.js
angular_default.module("kantree").directive("textComposer", [
  "$document",
  "$timeout",
  "$compile",
  function($document, $timeout2, $compile) {
    return {
      restrict: "A",
      scope: {
        customOpts: "=textComposer",
        isFocused: "=?",
        initValue: "=",
        draftValue: "="
      },
      templateUrl: function(tElement, tAttrs) {
        return tAttrs.customTemplate || "/static/app/ui/editors/content-editor/templates/text-composer.html";
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.options = {
            "saveChange": function(event2, newTitle, cb2) {
              return cb2();
            },
            "cancelChange": function(event2, cb2) {
              return cb2();
            },
            "onEdit": null,
            // is a function
            "saveDraft": null,
            // is a function
            "saveOn": {
              enter: true,
              shiftEnter: false,
              tab: false,
              clickOutside: false,
              clickElArray: null
              // function with parameter $el that return an array of elements
            },
            "cancelOn": {
              escape: true,
              tab: false,
              clickOutside: true
            },
            "hideOn": {
              // clickOutside, escape, tab can be set as well
              cancel: true,
              save: false
            },
            "resetOn": {
              cancel: true,
              save: true
            },
            "rows": 2,
            "saveBtn": true,
            "cancelBtn": true,
            "saveBtnLabel": _4("Save"),
            "cancelBtnLabel": _4("Cancel"),
            "selectOnFocus": true,
            "markdownSupport": false,
            "emptyInput": false,
            "placeholder": null,
            "expandableInput": true,
            "autosizeOpts": {},
            "inputType": "textarea",
            "uuid": uuid4(),
            "watchingInitValue": false
          };
          jquery_default.extend(true, $scope2.options, $scope2.customOpts);
          $scope2.$watchCollection("customOpts", function(value2) {
            if (value2) {
              jquery_default.extend(true, $scope2.options, value2);
            }
          });
          $scope2.isSaving = false;
        }
      ],
      link: function(scope, element2, attrs2) {
        var wasChanged = false;
        var $el = jquery_default(element2);
        var html5;
        if (scope.options.inputType === "input") {
          html5 = '<input class="form-control" type="text" ng-attr-placeholder="{{ options.placeholder }}"></input>';
          $el.find("textarea").remove();
          $el.prepend($compile(html5)(scope));
        }
        var $textEl = $el.find("textarea, input");
        var hide = function() {
          scope.isFocused = false;
          $textEl.trigger("autosize.destroy");
          scope.$emit("textComposer.hidden");
        };
        var save = function(e3) {
          if (scope.isSaving) return;
          e3 && e3.preventDefault();
          var $textEl2 = $el.find("textarea, input");
          if (!scope.options.emptyInput && !$textEl2.val().trim().length) {
            return;
          }
          scope.isSaving = true;
          scope.options.saveChange && scope.options.saveChange(e3, $textEl2.val(), function(mustHide, newVal) {
            try {
              scope.options.saveDraft && scope.options.saveDraft(null);
              if (newVal) {
                $textEl2.val(newVal);
              }
              if (scope.options.hideOn.save || mustHide) {
                hide();
              } else {
                $textEl2.focus();
                if (scope.options.selectOnFocus) $textEl2.select();
              }
              if (scope.options.resetOn.save) resetText(true);
            } finally {
              scope.isSaving = false;
            }
          });
        };
        var cancel = function(e3, discardDraft) {
          scope.options.cancelChange && scope.options.cancelChange(e3, function() {
            if (!discardDraft) {
              scope.options.saveDraft && scope.options.saveDraft($el.find("textarea, input").val());
            }
            if (scope.options.hideOn.cancel) {
              hide();
            } else {
              $textEl.blur();
            }
            if (scope.options.resetOn.cancel && !scope.options.saveDraft) {
              resetText();
            }
          });
        };
        var resetText = function(withoutDraft, value2) {
          wasChanged = false;
          if (withoutDraft) {
            $textEl.val(value2 || scope.initValue || "");
          } else {
            if (scope.draftValue) {
              wasChanged = true;
            }
            $textEl.val(scope.draftValue || value2 || scope.initValue || "");
          }
          if (scope.options.expandableInput && scope.options.inputType === "textarea") {
            $textEl.trigger("autosize.resize");
          }
        };
        var $timeoutWrap = function(func) {
          return function(e3) {
            if (!func) {
              return;
            }
            scope.$evalAsync(function() {
              func(e3);
            });
          };
        };
        var onClickOutside = function(e3) {
          if (scope.isSaving) return;
          if (e3.data.uuid !== scope.options.uuid) {
            return;
          }
          if (scope.options.saveOn.clickElArray) {
            var clicked = false;
            angular_default.forEach(scope.options.saveOn.clickElArray($el), function(clickEl) {
              if (jquery_default(e3.target).closest(clickEl).length) {
                clicked = true;
              }
            });
            if (clicked) {
              $timeoutWrap(save)(e3);
              return;
            }
          }
          if (!jquery_default(e3.target).closest($el).length && $el.is(":visible")) {
            if (scope.options.saveOn.clickOutside) {
              $timeoutWrap(save)(e3);
              return;
            }
            if (scope.options.cancelOn.clickOutside) {
              $timeoutWrap(cancel)(e3);
              return;
            }
          }
        };
        resetText(false, $textEl.val());
        scope.$watch("isFocused", function(newVal, oldVal) {
          if (newVal) {
            resetText(false, $textEl.val());
            $timeout2(function focusTextComposer() {
              if (scope.options.expandableInput && scope.options.inputType === "textarea") {
                $el.find("textarea").autosize(scope.options.autosizeOpts);
              }
              $document.on("mousedown", { uuid: scope.options.uuid }, onClickOutside);
              $textEl.focus();
              if (scope.options.selectOnFocus) $textEl.select();
            }, 0, false);
          } else if (newVal !== oldVal && !newVal) {
            $document.off("mousedown", onClickOutside);
            $textEl.blur();
          }
        });
        $el.on("focus", "textarea, input", function(e3) {
          e3.stopPropagation();
          $timeoutWrap(function(e4) {
            if (!scope.isFocused) {
              scope.isFocused = true;
            }
          })(e3);
        });
        $el.on("click", ".js-submit", $timeoutWrap(save));
        $el.on("click", ".js-close", $timeoutWrap(function(e3) {
          cancel(e3, true);
          if (scope.options.saveDraft) {
            scope.options.saveDraft(null, function() {
              resetText(true);
            });
          } else {
            resetText();
          }
        }));
        $el.on("keydown", "textarea, input", function(e3) {
          if (e3.keyCode === 27 && scope.options.cancelOn.escape) {
            e3.preventDefault();
            $timeoutWrap(cancel)(e3);
            return;
          }
          if (e3.keyCode === 9 && !e3.ctrlKey) {
            if (scope.options.cancelOn.tab) {
              e3.preventDefault();
              $timeoutWrap(cancel)(e3);
              return;
            }
            if (scope.options.saveOn.tab) {
              e3.preventDefault();
              $timeoutWrap(save)(e3);
              return;
            }
          }
          if (e3.keyCode === 13) {
            if (scope.options.saveOn.enter && !e3.shiftKey || e3.shiftKey && scope.options.saveOn.shiftEnter) {
              e3.preventDefault();
              if (scope.isSaving) return;
              $timeoutWrap(save)(e3);
              return;
            }
          }
          wasChanged = true;
          scope.options.onEdit && scope.options.onEdit(e3, this.value);
        });
        if (scope.options.watchingInitValue) {
          scope.$watch("initValue", function(newVal, oldVal) {
            if (typeof newVal !== "undefined" && newVal !== oldVal && !wasChanged) {
              resetText();
            }
          });
        }
        scope.$on("saveDraft", function() {
          if (scope.options.saveDraft) {
            $timeout2(function() {
              scope.options.saveDraft($el.find("textarea, input").val());
            }, 0, false);
          }
        });
        scope.$on("draftDiscarded", function(event2, uuid) {
          if (scope.options.uuid !== uuid) {
            return;
          }
          scope.options.saveDraft && scope.options.saveDraft(null, function() {
            resetText(true);
          });
        });
        $el.on("$destroy", function() {
          scope.$destroy();
        });
        scope.$on("$destroy", function() {
          if (scope.isFocused && scope.options.saveDraft) {
            scope.options.saveDraft($el.find("textarea, input").val());
          }
          $textEl.trigger("autosize.destroy");
          $document.off("mousedown", onClickOutside);
        });
      }
    };
  }
]);

// public/app/ui/editors/filter-editor/filter-editor.js
angular_default.module("kantree").value("filterEditorFieldsCache", {});
angular_default.module("kantree").component("filterEditor", {
  templateUrl: "/static/app/ui/editors/filter-editor/templates/filter-editor.html",
  bindings: {
    stores: "<?",
    filterScopes: "<?",
    source: "<",
    variables: "<?",
    project: "<?",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$q", "filterEditorFieldsCache", "$timeout"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.editor = "visual";
      if (jsonLocalStorage.getItem("filterEditor")) {
        this.editor = jsonLocalStorage.getItem("filterEditor");
      } else if (jsonLocalStorage.getItem("useFilterKQLEditor")) {
        this.editor = "kql";
      }
      this.askQuestion = "";
      if (this.project) {
        this.org = orgStore.tryGetForProject(this.project);
        this.askAvailable = this.org?.ai_enabled || serverConfig.has_global_ai_config;
      }
      const loadingPromises = [this.loadFields()];
      if (!this.useTextEditor || !this.source) {
        loadingPromises.push(this.$q((resolve2) => this.parse(this.source, () => resolve2())));
      }
      this.loading = true;
      this.$q.all(loadingPromises).then(() => {
        this.loading = false;
        if (!this.useTextEditor) {
          this.$timeout(() => {
            this.$element.find("filter-editor-node input").focus();
          }, 10);
        }
      });
    }
    toggleEditor(editor) {
      this.editor = editor;
      jsonLocalStorage.setItem("filterEditor", editor);
    }
    notifyChange(source) {
      this.source = source ? stripParentheses(source) : source;
      this.onChange({ $source: this.source, $askQuestion: this.askQuestion || null });
    }
    clear() {
      this.notifyChange("");
      this.parse("");
    }
    parse(value2, callback) {
      if (abortCtrl) abortCtrl.abort();
      if (value2) {
        var abortCtrl = new AbortController();
        this.$q.when(api_default.kql.parse_filter.get({ source: value2 }, { signal: abortCtrl.signal }), (r3) => {
          this.handleParseResult(r3);
          if (callback) {
            callback(r3.success, r3.error);
          }
          if (r3.error) {
            this.editor = "kql";
          }
        });
      } else {
        this.group = ["And", null, [null]];
        callback && callback(true);
      }
    }
    handleParseResult({ success, error: error2, ast }) {
      if (success) {
        if (!["And", "Or"].includes(ast[0])) {
          ast = ["And", null, ast];
        }
        this.group = ast;
      } else {
        this.group = null;
      }
    }
    loadFields() {
      return this.$q.resolve(this.filterScopes ? this.loadFieldsForScope() : this.computeFieldsFromStores()).then((fields2) => {
        this.fields = fields2.sort((a3, b3) => a3.name && b3.name && a3.name.localeCompare(b3.name));
      });
    }
    loadFieldsForScope() {
      const scope = filterScopesToString(this.filterScopes);
      if (this.$filterEditorFieldsCache[scope]) {
        return this.$filterEditorFieldsCache[scope];
      }
      const titleField = { type: "text", name: "title", label: _4("Title") };
      return this.$q.when(api_default.search.list_filterable_fields.get({ filter_scopes: scope }, { ignoreErrorHandlers: true }), (fields2) => {
        const out = [titleField];
        for (let [name2, type] of Object.entries(fields2)) {
          out.push({ type, name: name2 });
        }
        this.$filterEditorFieldsCache[scope] = out;
        return out;
      }, () => {
        return [titleField];
      });
    }
    computeFieldsFromStores() {
      const fields2 = [{ type: "text", name: "title", label: _4("Title") }];
      this.stores["cardModel"].getSupportingAttributes("filterable").sort().forEach((attr) => {
        const attrType = attributeTypeRegistry.get(attr.type);
        if (attrType) {
          fields2.push({ type: attr.type, name: attr.name, id: attr.id, attribute: attr, model: !attr.model_is_base ? attr.model_name : null });
        }
      });
      this.stores["groupType"].query({}, { sortBy: "name" }).forEach((groupType) => {
        fields2.push({ type: "context", name: groupType.name, id: groupType.id });
      });
      return fields2;
    }
    onAskEditorKeyDown(event2) {
      if (event2.keyCode !== 13 || event2.ctrlKey || !this.askQuestion) {
        return;
      }
      event2.preventDefault();
      this.askProcessing = true;
      this.askError = null;
      this.$q.when(api_default.kql.kql_ask.post({
        project_id: this.project.id,
        prompt: this.askQuestion
      }, { ignoreErrorHandlers: true }), (resp) => {
        this.askProcessing = false;
        this.handleParseResult(resp);
        if (resp.success) {
          this.toggleEditor("visual");
          this.notifyChange(resp.source);
        } else {
          this.askError = resp.error;
          this.source = resp.source;
          this.group = null;
          this.editor = "kql";
        }
      });
    }
  }
});
angular_default.module("kantree").component("filterEditorGroup", {
  templateUrl: "/static/app/ui/editors/filter-editor/templates/filter-editor-group.html",
  bindings: {
    stores: "<?",
    fields: "<",
    node: "<",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      if (changes.node) {
        if (this.node) {
          this.op = this.node[0].toLowerCase();
          this.nodes = this.node.slice(2);
        } else {
          this.op = "and";
          this.nodes = [];
        }
      }
    }
    transformToString() {
      return "(" + this.nodes.map((n4) => n4[1]).filter(Boolean).join(` ${this.op.toUpperCase()} `) + ")";
    }
    notifyChange() {
      this.onChange({ $source: this.transformToString() });
    }
    notifyNodeChange(node, source) {
      node[1] = source;
      this.notifyChange();
    }
    addNode() {
      this.nodes.push([null]);
    }
    addGroup() {
      this.nodes.push(["And", [null]]);
    }
    removeNode(node) {
      this.nodes.splice(this.nodes.indexOf(node), 1);
      this.notifyChange();
    }
  }
});
angular_default.module("kantree").component("filterEditorNode", {
  templateUrl: "/static/app/ui/editors/filter-editor/templates/filter-editor-node.html",
  bindings: {
    stores: "<?",
    fields: "<",
    node: "<",
    onChange: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.notifyChangeDebounced = debounce2(() => this.notifyChange(), 200);
    }
    $onChanges(changes) {
      if (changes.fields) {
        this.refreshNodeTypes();
      }
    }
    refreshNodeTypes() {
      this.nodeTypes = buildNodeTypeList(this.stores, this.fields);
      this.refreshNode();
    }
    refreshNode() {
      if (!this.node || this.node[0] === null) {
        this.nodeType = this.nodeTypes[0];
        this.onNodeTypeChange(true);
        return;
      }
      for (let nodeType of this.nodeTypes) {
        try {
          let m3 = nodeType.match(this.node);
          if (m3) {
            const availableOperators = !nodeType.operators ? [null] : nodeType.operators.map((o3) => o3.op);
            if (availableOperators.includes(m3[0])) {
              this.nodeType = nodeType;
              [this.cmpOperator, this.value] = m3;
              return;
            }
          }
        } catch (e3) {
          console.error(e3);
        }
      }
      this.isKQL = true;
      this.nodeType = null;
      this.cmpOperator = null;
      this.value = this.node[1];
    }
    transformToString() {
      if (!this.nodeType) {
        return this.value;
      }
      return this.nodeType.transform(this.value, this.cmpOperator);
    }
    onNodeTypeChange(firstChange) {
      if (this.nodeType.operators) {
        this.cmpOperator = this.nodeType.operators[0].op;
      } else {
        this.cmpOperator = null;
      }
      this.setDefaultValueOnChange();
      if (!firstChange) {
        this.notifyChange();
      }
    }
    onOperatorChange() {
      this.setDefaultValueOnChange();
      this.notifyChange();
    }
    setDefaultValueOnChange() {
      this.value = "";
      if (this.nodeType.noDefaultValue) {
        return;
      }
      if (this.nodeType.operators && this.nodeType.options && this.nodeType.options[this.cmpOperator] !== void 0 && this.nodeType.options[this.cmpOperator] !== false && (!Array.isArray(this.nodeType.options[this.cmpOperator]) || this.nodeType.options[this.cmpOperator].length > 0)) {
        this.value = this.nodeType.options[this.cmpOperator][0].value;
      } else if (!this.nodeType.operators && this.nodeType.options && this.nodeType.options.length) {
        this.value = this.nodeType.options[0].value;
      }
    }
    notifyChange() {
      let needValue = !this.nodeType || this.nodeType.operators && (!this.nodeType.options || this.nodeType.options[this.cmpOperator] === void 0) || !this.nodeType.noValue && !this.nodeType.operators && !this.nodeType.options;
      if (!needValue || this.value) {
        this.onChange({ $source: this.transformToString() });
      }
    }
  }
});
angular_default.module("kantree").component("filterEditorInput", {
  template: `
    <input type="text" class="form-control" ng-required="$ctrl.isRequired" ng-attr-placeholder="{{$ctrl.placeholder}}"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.setViewValue($ctrl.value)">
  `,
  bindings: {
    stores: "<?",
    filterScopes: "<?",
    isRequired: "<?",
    isDisabled: "<?",
    placeholder: "@",
    onChange: "&"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "dropdown", "$element"];
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
    $postLink() {
      const html5 = `<filter-editor stores="$ctrl.stores" source="$ctrl.value" filter-scopes="$ctrl.filterScopes"
        on-change="$ctrl.setViewValue($source)"></filter-editor>`;
      this.$element.on("click", () => {
        this.drop = this.$dropdown.openCompile(this.$element[0], html5, this.$scope, {
          classes: "cards-app-filter-btn-drop drop-theme-menu drop-theme-arrow",
          tetherOptions: {
            constraints: [{
              to: "window",
              attachment: "together",
              pin: true
            }]
          }
        });
      });
    }
    setViewValue(value2) {
      this.ngModel.$setViewValue(value2);
      this.onChange({ $value: value2 });
    }
  }
});

// public/app/loaders/kql-autocomplete.js
var autocompleteFieldsCache;
function getAutocompleteFields(project) {
  let p4;
  if (autocompleteFieldsCache) {
    p4 = Promise.resolve(autocompleteFieldsCache);
  } else {
    p4 = api_default.kql.list_kql_special_card_attrs.get().then((r3) => {
      r3.sort((a3, b3) => a3.name.localeCompare(b3.name));
      autocompleteFieldsCache = r3;
      return r3;
    });
  }
  if (!project) {
    return p4;
  }
  return p4.then((fields2) => getProjectFields(project).concat(fields2));
}
var autocompleteFuncsCache;
function getAutocompleteFunctions() {
  if (autocompleteFuncsCache) {
    return Promise.resolve(autocompleteFuncsCache);
  }
  return api_default.kql.list_kql_functions.get().then((r3) => {
    r3.sort((a3, b3) => a3.name.localeCompare(b3.name));
    autocompleteFuncsCache = r3;
    return r3;
  });
}
function getProjectFields(project) {
  const dedupAttributesFromModels = {};
  cardModelStore.scopedByEnabled(project).getAttributesFromModels().sort().filter((attr) => !attributeTypeRegistry.get(attr.type).decorative).forEach((attr) => {
    dedupAttributesFromModels[attr.name] = attr;
  });
  const attrs2 = [Object.values(dedupAttributesFromModels)];
  return [].concat(...attrs2).map((attr) => {
    return { "name": attr.name, "type": attr.type };
  });
}

// public/app/ui/editors/kql-editor/formula-editor.js
angular_default.module("kantree").component("formulaEditor", {
  bindings: {
    project: "<",
    card: "<?",
    value: "<",
    onSave: "&",
    onEditorResize: "&",
    variables: "<?",
    validate: "<?"
  },
  template: `
    <kql-editor
      autocomplete-fields="$ctrl.autocompleteFields"
      autocomplete-funcs="$ctrl.autocompleteFuncs"
      field-doc="{{$ctrl.fieldDoc}}"
      placeholder="{{::_('Type a formula')}}"
      show-hint="true"
      save-btn="{{::_('Save')}}"
      ng-model="$ctrl.value"
      on-validate="$ctrl.onValidate($value, $callback)"
      on-save="$ctrl.onSave({$value})"
      on-editor-resize="$ctrl.onEditorResize()"
    ></kql-editor>
  `,
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.$q.when(getAutocompleteFields(this.project), (fields2) => {
        this.autocompleteFields = fields2;
      });
      this.$q.when(getAutocompleteFunctions(), (funcs) => {
        this.autocompleteFuncs = funcs;
      });
      this.fieldDoc = _4("You can use fields inside of expressions:\n\n```\n{{field}} + {other field}\n```");
    }
    onValidate(value2, callback) {
      if (this.validate === false) {
        callback(true);
        return;
      }
      let req;
      if (this.card) {
        if (!this.card.id) {
          req = api_default.kql.validate.get({ source: value2, type: "formula" }, { ignoreErrorHandlers: true }).then((r3) => {
            if (r3.valid) {
              return r3;
            }
            return Promise.reject({ json: () => Promise.resolve(r3) });
          });
        } else {
          req = api_default.cards.query_card.get({ card_id: this.card.id, q: value2, ...this.variables }, { ignoreErrorHandlers: true });
        }
      } else if (this.project) {
        req = api_default.projects.query_project.get({ project_id: this.project.id, q: value2, ...this.variables }, { ignoreErrorHandlers: true });
      } else {
        callback(true);
        return;
      }
      this.$q.when(req, (r3) => {
        callback(true, r3.result);
      }, (r3) => {
        r3.json().then((data2) => callback(false, data2.error));
      });
    }
  }
});

// public/app/ui/editors/kql-editor/kql-editor.js
angular_default.module("kantree").component("kqlEditor", {
  templateUrl: "/static/app/ui/editors/kql-editor/templates/kql-editor.html",
  bindings: {
    autocompleteFields: "<?",
    autocompleteFuncs: "<?",
    fieldDoc: "@",
    placeholder: "@",
    showHint: "<?",
    saveBtn: "@",
    saveOnEnter: "<?",
    onValidate: "&?",
    onChange: "&",
    onSave: "&",
    onEditorResize: "&"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isValid = true;
      this.isFirstChange = true;
      this.validate = debounce2(this.validate, 500, this);
      this.doc = _4("Hover an item on the left to learn more");
      this.result = null;
      if (this.ngModel) {
        this.ngModel.$render = () => this.renderValue();
        this.ngModel.$viewChangeListeners.push(() => this.renderValue());
      } else {
        this.value = "";
      }
      if (!this.autocompleteFields) {
        this.autocompleteFields = [];
      }
      if (!this.autocompleteFuncs) {
        this.autocompleteFuncs = [];
      }
    }
    $postLink() {
      this.$element.find("textarea").autosize();
      this.$element.find("textarea").on("autosize.resized", () => this.onEditorResize());
    }
    setViewValue(value2) {
      if (this.ngModel) {
        this.ngModel.$setViewValue(value2);
      }
      this.onChange({ $value: value2 });
    }
    renderValue() {
      this.value = this.ngModel.$viewValue || "";
      if (this.isFirstChange) {
        this.isFirstChange = false;
        this.validate(false);
      }
    }
    showFieldDoc(field2) {
      this.doc = _4("Access the value of fields and other information in your formulas.\n\nUse a field by surrounding it with curly braces:\n\n```\n{{field}}\n```\n\n", { field: field2.name });
      if (this.fieldDoc) {
        this.doc += this.fieldDoc.replace("{field}", field2.name);
      }
    }
    showDoc(doc4) {
      this.doc = doc4;
    }
    insertField(field2) {
      this.value = (this.value + " " + escapeKqlName(field2.name)).trim();
      this.validate();
    }
    insertFunc(func) {
      this.value = (this.value + " " + func.name + "()").trim();
      this.validate();
    }
    validate(setValue2 = true) {
      if (!this.onValidate) {
        this.isValid = true;
        if (setValue2) {
          this.setViewValue(this.value);
        }
        return;
      }
      this.onValidate({ $value: this.value, $callback: (success, data2) => {
        if (success) {
          this.isValid = true;
          this.result = data2;
          if (setValue2) {
            this.setViewValue(this.value);
          }
        } else {
          this.isValid = false;
          this.validationError = data2;
        }
      } });
    }
    notifyEnterPress(event2) {
      if (event2.keyCode === 13 && !event2.shiftKey && this.saveOnEnter) {
        event2.preventDefault();
        if (this.isValid && this.value) {
          this.onSave({ $value: this.value });
        }
      }
    }
    $onDestroy() {
      this.validate.clear();
      this.$element.find("textarea").trigger("autosize.destroy");
    }
  }
});

// public/app/ui/editors/options-editor/ng-components/editor.js
angular_default.module("kantree").component("optionsEditorField", {
  template: `
    <div class="form-group" ng-class="{'mb-0': $ctrl.compact}">
      <label class="form-label" for="{{::$ctrl.option.name}}" ng-if="!$ctrl.hideLabel && !!$ctrl.option.title">
        {{::$ctrl.option.title}}:
        <a class="helplink" ng-href="{{::$ctrl.option.helplink}}" target="_blank" ng-show="::!!$ctrl.option.helplink"
          uib-tooltip="{{::$ctrl.tooltipLabel}}"><i class="fa fa-question-circle"></i></a>
      </label>
      <dynamic-directive directive="options-widget-{{$ctrl.option.widget}}" is-required="{{$ctrl.option.required}}"
        is-disabled="!$ctrl.editable || !!$ctrl.option.disabled" options="$ctrl.option.widget_options"
        ng-model="$ctrl._value" ng-change="$ctrl.notifyChange()"></dynamic-directive>
      <p class="form-text" ng-if="!$ctrl.hideDescription && !!$ctrl.option.description">{{::$ctrl.option.description}}</p>
    </div>
  `,
  bindings: {
    option: "<",
    value: "<",
    editable: "<?",
    onChange: "&",
    hideLabel: "<?",
    hideDescription: "<?",
    compact: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.editable = this.editable !== false;
      this.tooltipLabel = _4("Open help page");
    }
    $onChanges(changes) {
      if (changes.value) {
        this._value = this.value;
      }
    }
    notifyChange() {
      this.onChange({ $value: this._value });
    }
  }
});
angular_default.module("kantree").directive("optionsEditor", [
  function() {
    return {
      template: `
        <options-editor-field ng-repeat="option in $ctrl._options track by option.name"
          option="option" value="$ctrl.viewValues[option.name]" editable="$ctrl.editable"
          on-change="$ctrl.setViewValue(option, $value)"></options-editor-field>`,
      restrict: "E",
      scope: {
        options: "<",
        values: "=",
        org: "<?",
        project: "<?",
        card: "<?",
        editable: "<?",
        onChange: "&?"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$scope", "$timeout"];
        $onInit() {
          this.editable = this.editable || typeof this.editable === "undefined";
          if (this.project && !this.org) {
            this.org = this.project.owner;
          }
          this.$timeout(() => {
            this.formatOptions();
          });
          this.$scope.$watch("$ctrl.values", (newVal, oldVal) => {
            this.$timeout(() => {
              this.renderViewValues();
            });
          });
          this.tooltipLabel = _4("Open help page");
        }
        $onChanges(changes) {
          if (changes.options && !changes.options.isFirstChange()) {
            this.formatOptions();
          }
          if (changes.project && !changes.project.isFirstChange()) {
            this.formatOptions();
          }
        }
        formatOptions() {
          const oldFormattedOptions = this._options || this.options;
          this._options = this.options || [];
          if (!this._options.length) return;
          this._options = this._options.reduce((result2, o3, idx) => {
            const opt = { ...o3 };
            let defaultChanged = false;
            if (opt.widget === "bool") {
              opt.widget_options = { ...opt.widget_options, name: opt.name, title: opt.title };
              delete opt.title;
            }
            if (!opt.widget) {
              opt.widget = "text";
            }
            if (opt.name === "viz") {
              opt.widget = "viz";
              opt.default = !!this.values.group_by ? "table" : void 0;
              defaultChanged = oldFormattedOptions && oldFormattedOptions.default !== opt.default;
            }
            if (this.project) {
              opt.widget_options = { ...opt.widget_options, project: this.project };
            }
            if (this.card) {
              opt.widget_options = { ...opt.widget_options, card: this.card };
            }
            if (this.org) {
              opt.widget_options = { ...opt.widget_options, org: this.org };
            }
            if (opt.widget_options.depends_on) {
              opt.widget_options = { ...opt.widget_options, depends_on_value: this.values[opt.widget_options.depends_on] };
            }
            if ((opt.default || defaultChanged) && this.viewValues && this.viewValues[opt.name] === void 0) {
              this.setViewValue(o3, opt.default);
            }
            const showWhen = this.values[opt.widget_options?.show_when] || void 0;
            if (!showWhen) {
              result2.push(opt);
            } else {
              if ((opt.widget_options?.invalid || []).length > 0 && (opt.widget_options?.invalid || []).indexOf(showWhen) == -1) {
                result2.push(opt);
              } else if ((opt.widget_options?.valid || []).length > 0 && (opt.widget_options?.valid || []).indexOf(showWhen) >= 0) {
                result2.push(opt);
              }
            }
            return result2;
          }, []);
        }
        formatValues(newValues) {
          return { ...newValues };
        }
        parseViewValues(newViewValues) {
          for (const opt of this._options) {
            if (!!opt?.widget_options?.depends_on) {
              const oldVal = this.values[opt.widget_options.depends_on];
              const newVal = newViewValues[opt.widget_options.depends_on];
              if (oldVal !== newVal) {
                newViewValues[opt.name] = null;
              }
            }
          }
          return { ...newViewValues };
        }
        renderViewValues(newValue) {
          const formattedValues = this.formatValues(this.values);
          if (!equals(this.viewValues, formattedValues)) {
            this.viewValues = formattedValues;
          }
        }
        setViewValue(option2, newValue) {
          if (option2) {
            this.viewValues[option2.name] = newValue;
          }
          const parsedValues = this.parseViewValues(this.viewValues);
          if (!equals(parsedValues, this.values)) {
            const needsFormatOptions = this.needsFormatOptions(parsedValues);
            this.values = parsedValues;
            if (needsFormatOptions) {
              this.formatOptions();
            }
            if (this.onChange) {
              this.onChange({
                $values: this.values
              });
            }
          }
        }
        needsFormatOptions(newValues) {
          const valueKeys = this._options.filter((o3) => !!o3.widget_options.depends_on).map((o3) => o3.widget_options.depends_on);
          if (valueKeys.length > 0) {
            if (valueKeys.some((key2) => newValues[key2] != this.values[key2])) return true;
          }
          return this._options.find((o3) => o3.name === "viz") && this.values.group_by !== newValues.group_by;
        }
      }
    };
  }
]);

// public/app/ui/editors/options-editor/ng-components/form.js
angular_default.module("kantree").component("optionsForm", {
  template: `
    <options-editor options="$ctrl.options" values="$ctrl.values" org="$ctrl.org"
      project="$ctrl.project" card="$ctrl.card"></options-editor>
    <button type="button" class="btn btn-primary" ng-click="$ctrl.submit()">{{::$ctrl.label}}</button>
  `,
  bindings: {
    options: "<",
    org: "<?",
    project: "<?",
    card: "<?",
    values: "<?",
    btnLabel: "@",
    onSubmit: "&"
  },
  controller: class extends AngularClass {
    $onInit() {
      if (!this.values) {
        this.values = {};
      }
      this.label = this.btnLabel || _4("Save");
    }
    submit() {
      this.onSubmit({ "$values": this.values });
    }
  }
});

// public/app/ui/editors/options-editor/ng-components/menu.js
angular_default.module("kantree").component("optionsMenuComponent", {
  bindings: {
    params: "<?"
  },
  template: `
    <options-editor
      options="$ctrl.params.options"
      values="$ctrl.params.values"
      org="$ctrl.params.org"
      project="$ctrl.params.project"
      card="$ctrl.params.card"
      editable="$ctrl.params.editable"
    ></options-editor>
  `
});
angular_default.module("kantree").component("optionsFormMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&",
    onUpdate: "&"
  },
  template: `
    <options-form
      options="$ctrl.params.options"
      values="$ctrl.params.values"
      org="$ctrl.params.org"
      project="$ctrl.params.project"
      card="$ctrl.params.card"
      btn-label="{{$ctrl.params.btnLabel}}"
      on-submit="$ctrl.handleSubmit($values)"
    ></options-form>
  `,
  controller: class {
    handleSubmit(values2) {
      this.params.onSubmit(values2);
      this.onClose();
    }
  }
});

// public/app/ui/editors/options-editor/widgets/abstract.js
angular_default.module("kantree").component("optionsWidgetSelect", {
  template: `
    <pretty-select class="block" ng-model="$ctrl.value" ng-change="$ctrl.setViewValue()"
      options="$ctrl.items" label-prop="1" value-prop="0" group-by="3" multiple="$ctrl.multiple" placeholder="{{$ctrl.placeholder}}"
      disabled="$ctrl.isDisabled || (!$ctrl.items || $ctrl.items.length === 0) && $ctrl.isRequired" is-required="$ctrl.isRequired"
      allow-unknown-value="$ctrl.allowUnknownValue" unknown-value-input-placeholder="{{$ctrl.unknownValueInputPlaceholder}}"
    ></pretty-select>
  `,
  bindings: {
    items: "<",
    multiple: "@",
    isRequired: "<?",
    isDisabled: "<?",
    placeholder: "<?",
    allowUnknownValue: "<?",
    unknownValueInputPlaceholder: "@"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = angular_default.copy(this.ngModel.$viewValue);
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = angular_default.copy(this.ngModel.$viewValue);
      });
    }
    setViewValue() {
      this.ngModel.$setViewValue(this.value);
    }
  }
});
angular_default.module("kantree").component("optionsWidgetSelectRef", {
  template: `
    <options-widget-select ng-model="$ctrl.value" ng-change="$ctrl.setViewValue()"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled" multiple="{{$ctrl.multiple}}" placeholder="$ctrl.placeholder"
      allow-unknown-value="$ctrl.allowUnknownValue" unknown-value-input-placeholder="{{$ctrl.unknownValueInputPlaceholder}}"></options-widget-select>
  `,
  bindings: {
    items: "<",
    multiple: "@",
    isRequired: "<?",
    isDisabled: "<?",
    placeholder: "@",
    allowUnknownValue: "<?",
    unknownValueInputPlaceholder: "@"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this._isMultiple = "" + this.multiple === "true";
      this.ngModel.$render = () => {
        this.value = this.formatValue(this.ngModel.$viewValue);
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.formatValue(this.ngModel.$viewValue);
      });
    }
    $onChanges(changes) {
      if (changes.items && !changes.items.isFirstChange()) {
        this.value = this.formatValue(this.ngModel.$viewValue);
      }
    }
    normId(x3) {
      if (x3 && typeof x3 === "object") {
        if (x3.id != null) return String(x3.id);
        if (x3.name != null) return String(x3.name);
        if (x3.value != null) return String(x3.value);
        if (x3[0] != null) return String(x3[0]);
      }
      return x3 != null ? String(x3) : null;
    }
    coerceToItemValue(idLike) {
      const idStr = this.normId(idLike);
      const it2 = (this.items || []).find((i3) => String(i3[0]) === idStr);
      return it2 ? it2[0] : idStr;
    }
    formatValue(value2) {
      if (this._isMultiple) {
        if (!value2) return [];
        if (Array.isArray(value2)) {
          return this.items && this.items.length ? value2.map((v3) => this.coerceToItemValue(v3)) : value2.map((v3) => this.normId(v3));
        }
        return [];
      } else {
        if (value2 && typeof value2 === "object") {
          return this.coerceToItemValue(value2);
        }
        return this.coerceToItemValue(value2);
      }
    }
    setViewValue() {
      const eq2 = (a3, b3) => String(a3) === String(b3);
      if (this._isMultiple) {
        const ids = Array.isArray(this.value) ? this.value : [];
        const mapped = ids.map((id) => {
          const item = (this.items || []).find((i3) => eq2(i3[0], id));
          if (item) return { id: item[0], name: item[1] };
          if (this.allowUnknownValue) return { name: String(id) };
          return null;
        }).filter(Boolean);
        this.ngModel.$setViewValue(mapped);
      } else {
        const v3 = (this.items || []).find((i3) => eq2(i3[0], this.value));
        if (v3) {
          this.ngModel.$setViewValue({ id: v3[0], name: v3[1] });
        } else if (this.allowUnknownValue && this.value) {
          this.ngModel.$setViewValue({ name: String(this.value) });
        } else {
          this.ngModel.$setViewValue(null);
        }
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetMenu", {
  template: `
    <p class="form-control-plaintext">
      <button class="btn btn-default btn-ghost" type="button" drop-menu="$ctrl.menu" drop-config="$ctrl.dropConfig">
        <i ng-class="{{$ctrl.options.buttonIcon|iconClass}}" ng-show="$ctrl.options.buttonIcon"></i> {{$ctrl.options.buttonLabel}}
        <span class="bi-caret-down-fill" ng-show="$ctrl.options.withCaret"></span>
      </button>
    </p>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
        this.menu = this.buildMenu();
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
        this.menu = this.buildMenu();
      });
      this.dropConfig = (this.options || {}).dropConfig;
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged) {
        this.menu = this.buildMenu();
        this.dropConfig = (this.options || {}).dropConfig;
      }
    }
    buildMenu() {
      if (!this.options || !this.options.menu) return null;
      return this.options.menu.build(this.value, (newVal) => {
        this.ngModel.$setViewValue(this.options.menu.parseNewValue(newVal, this.value));
      });
    }
  }
});

// public/app/ui/editors/options-editor/widgets/attributes.js
angular_default.module("kantree").component("optionsWidgetAttribute", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.setViewValue()"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"
      allow-unknown-value="$ctrl.options.allow_custom_name"
      unknown-value-input-placeholder="{{$ctrl.unknownValueInputPlaceholder}}"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.unknownValueInputPlaceholder = _4("Field name");
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshItems();
    }
    $onChanges(changes) {
      const filterOrFilterScopesChanged = changes.options && !changes.options.isFirstChange() && ((changes.options.previousValue || {}).filter !== (this.options || {}).filter || (changes.options.previousValue || {}).filter_scopes !== (this.options || {}).filter_scopes);
      if (filterOrFilterScopesChanged) {
        this.refreshItems();
      }
    }
    refreshItems() {
      return this.$q.when((() => {
        if (this.options.filter_scopes && this.options.filter_scopes.length > 0 || this.options.filter) {
          return api_default.search.list_filterable_fields.get({ filter_scopes: filterScopesToString(this.options.filter_scopes) }).then((fields2) => {
            return Object.keys(fields2).filter((fieldName) => this.isValidType(fields2[fieldName])).map((fieldName) => ({ "id": fieldName, "name": fieldName }));
          });
        }
        if (this.options.project) {
          return loadAllEnabledModelsForProject(this.options.project).then(() => {
            return cardModelStore.scopedByEnabled(this.options.project).getAttributesFromModels({ type: (t3) => this.isValidType(t3) });
          });
        }
        if (this.options.org) {
          return loadAllModelsForOrg(this.options.project).then(() => {
            return cardModelStore.scopedByOrg(this.options.project).getAttributesFromModels({ type: (t3) => this.isValidType(t3) });
          });
        }
        return Promise.reject();
      })()).then((attributes) => {
        this.items = attributes.sort((a3, b3) => a3.name.localeCompare(b3.name)).map((attr) => {
          return [attr.id, attr.name, attr.model_name || _4("Fields")];
        });
      }).catch(() => {
        this.items = [];
      });
    }
    isValidType(type) {
      if (Array.isArray(this.options.type)) {
        return this.options.type.includes(type);
      }
      if (this.options.type && type !== this.options.type) {
        return false;
      }
      const attrType = attributeTypeRegistry.get(type);
      if (this.options.computed === false && attrType.computed) {
        return false;
      }
      return this.options.computed === true && attrType.computed || !attrType.computed && !attrType.decorative && !attrType.stateless && !attrType.statelessAsync;
    }
    setViewValue() {
      if (!this.value) {
        this.ngModel.$setViewValue(this.value);
      } else {
        if (this.options.filter_scopes || this.options.filter) {
          this.ngModel.$setViewValue({ "name": this.value.name });
        } else {
          this.ngModel.$setViewValue(this.value);
        }
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetVisibleAttributes", {
  template: `
    <options-widget-menu ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      options="$ctrl.options" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-menu>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.options.buttonLabel = _4("Displayed fields");
      this.options.buttonIcon = "eye";
      this.options.menu = {
        build: (visibleAttributes, setValue2) => {
          const attrVisibilityMenuOptions = {
            specialFields: ["__ref__", "__comments__", "__children__", "__cover__"],
            visibles: visibleAttributes,
            // Hide attributes with type.visibleByDefault === false, while we don't find a good UX for this
            hideAttrsHiddenByDefault: true
          };
          throw new Error("Not implemented");
          return getAttrsVisibilityMenu(null, null, null, attrVisibilityMenuOptions, (newVal) => setValue2(newVal));
        },
        parseNewValue: (newVal, oldVal) => {
          return Array.isArray(newVal) ? [...newVal] : newVal;
        }
      };
    }
  }
});
angular_default.module("kantree").component("optionsWidgetAttributeValue", {
  template: `
    <options-widget-select-ref class="form-group" ng-model="$ctrl.selectedAttr" ng-change="$ctrl.updateAttr()"
      items="$ctrl.attributesSelectable" is-required="true"></options-widget-select-ref>
    <div ng-if="$ctrl.attribute">
      <label class="form-label">{{::_('Value')}}</label>
      <attribute-widget project="$ctrl.options.project" attribute-group="$ctrl.attributeGroup"
        attribute="$ctrl.attribute" obj="$ctrl.obj" embedded="true"
        directive-property="formDirective" editable="true" is-template="true" hide-header="true"></attribute-widget>
    </div>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.attributes = [];
      this.attribute = null;
      this.refreshAttributes().then(() => {
        this.ngModel.$render = () => this.selectFromViewValue();
        this.ngModel.$viewChangeListeners.push(() => this.selectFromViewValue());
        this.selectFromViewValue();
      });
    }
    selectFromViewValue() {
      this.resetObj();
      const viewValue = this.ngModel.$viewValue;
      if (!viewValue) {
        this.selectedAttr = this.ngModel.$viewValue;
        return;
      }
      let selected = this.attributesSelectable.find((a3) => a3[1].toLowerCase() === viewValue.name.toLowerCase());
      this.selectedAttr = selected ? { id: selected[0], name: selected[1] } : null;
      this.attribute = this.selectedAttr ? this.attributes.find((a3) => a3.id === this.selectedAttr.id) : null;
      if (!this.attribute) {
        return;
      }
      if (this.attribute.type === "group_type") {
        if (viewValue.value) {
          let groupTypeAttr = { id: this.attribute.id, type: this.attribute.type, value: [] };
          this.obj.attributes.push(groupTypeAttr);
          for (const group_id of viewValue.value) {
            this.obj.groups.push({ id: group_id });
            groupTypeAttr.value.push({ id: group_id });
          }
        }
      } else {
        this.obj.attributes.push({
          id: this.attribute.id,
          type: this.attribute.type,
          value: Array.isArray(viewValue.value) ? Array.from(viewValue.value) : viewValue.value
        });
      }
    }
    refreshAttributes() {
      return this.$q.when((() => {
        if (this.options.filter_scopes && this.options.filter_scopes.length > 0 || this.options.filter) {
          return api_default.search.list_filterable_fields.get({ filter_scopes: filterScopesToString(this.options.filter_scopes) }).then((fields2) => {
            return Object.keys(fields2).filter((fieldName) => this.isValidType(fields2[fieldName])).map((fieldName) => ({ "id": fieldName, "name": fieldName }));
          });
        }
        if (this.options.project) {
          return loadAllEnabledModelsForProject(this.options.project).then(() => {
            return cardModelStore.scopedByEnabled(this.options.project).getAttributesFromModels({ type: (t3) => this.isValidType(t3) });
          });
        }
        if (this.options.org) {
          return loadAllModelsForOrg(this.options.project).then(() => {
            return cardModelStore.scopedByOrg(this.options.project).getAttributesFromModels({ type: (t3) => this.isValidType(t3) });
          });
        }
        return Promise.reject();
      })()).then((attributes) => {
        this.attributes = attributes;
        this.attributesSelectable = attributes.sort((a3, b3) => a3.name.localeCompare(b3.name)).map((attr) => {
          return [attr.id, attr.name, attr.model_name || _4("Fields")];
        });
        this.initAttrGroup();
      }).catch(() => {
        this.attributes = [];
        this.attributesSelectable = [];
        return this.$q.resolve();
      });
    }
    initAttrGroup() {
      this.attributeGroup = new OptionsWidgetAttributeGroup(this.attributes, this.options.project);
      this.attributeGroup.$listen(this.$scope, () => {
        let value2 = this.attributeGroup.formatObjToServer(this.obj)[this.attribute.id];
        this.ngModel.$setViewValue({
          name: this.attribute.name,
          type: this.attribute.type,
          value: value2
        });
      });
    }
    isValidType(type) {
      const attrType = attributeTypeRegistry.get(type);
      if (attrType && attrType.decorative) {
        return false;
      }
      if (Array.isArray(this.options.type)) {
        return this.options.type.includes(type);
      }
      return !this.options.type || type === this.options.type;
    }
    resetObj() {
      this.obj = { attributes: [], groups: [], project_id: this.options.project.id };
    }
    updateAttr() {
      const attribute2 = this.selectedAttr ? this.attributes.find((a3) => a3.id === this.selectedAttr.id) : null;
      this.ngModel.$setViewValue(attribute2 ? {
        name: attribute2.name,
        type: attribute2.type,
        value: null
      } : null);
    }
  }
});

// public/app/ui/editors/options-editor/widgets/charts.js
angular_default.module("kantree").component("optionsWidgetKql", {
  template: `
    <input type="text" class="form-control" ng-required="$ctrl.isRequired" ng-attr-placeholder="{{$ctrl.options.placeholder}}"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)">
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "dropdown"];
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
    $postLink() {
      const html5 = `<formula-editor on-save="$ctrl.ngModel.$setViewValue($value); $ctrl.$dropdown.close($ctrl.drop)"
        value="$ctrl.value" project="$ctrl.options.project" card="$ctrl.options.card"
        on-editor-resize="$ctrl.$dropdown.updateOnNextFrame($ctrl.drop)"
        validate="$ctrl.options.validate !== false"></formula-editor>`;
      this.drop = this.$dropdown.openCompile(this.$element[0], html5, this.$scope, {
        classes: "kql-drop",
        _autoOpen: false,
        _destroyOnClose: false,
        tetherOptions: {
          constraints: [{
            to: "window",
            attachment: "together",
            pin: true
          }]
        }
      });
    }
    $onDestroy() {
      this.drop.destroy();
    }
  }
});
angular_default.module("kantree").component("optionsWidgetKqlFilter", {
  template: `
    <input type="text" class="form-control" ng-required="$ctrl.isRequired" ng-attr-placeholder="{{$ctrl.options.placeholder}}"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)">
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "dropdown"];
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshStores();
    }
    $postLink() {
      const html5 = `<filter-editor on-change="$ctrl.ngModel.$setViewValue($source); $ctrl.$dropdown.close($ctrl.drop)"
        source="$ctrl.value" stores="$ctrl.stores" validate="$ctrl.options.validate === false"></filter-editor>`;
      this.drop = this.$dropdown.openCompile(this.$element[0], html5, this.$scope, {
        _autoOpen: false,
        _destroyOnClose: false,
        tetherOptions: {
          constraints: [{
            to: "window",
            attachment: "together",
            pin: true
          }]
        }
      });
    }
    refreshStores() {
      if (this.options.project) {
        const org2 = orgStore.tryGetForProject(this.options.project);
        this.stores = {
          "cardModel": cardModelStore.scopedByEnabled(this.options.project),
          "groupType": cardGroupTypeStore.scopedByEnabled(this.options.project),
          "projectMember": projectMemberStore.scopedByProject(this.options.project),
          "role": org2 ? roleStore.scopedByOrg(org2) : void 0,
          "group": (groupType) => {
            return groupType ? cardGroupStore.scopedByType(groupType, this.options.project.top_level_card) : cardGroupStore.scopedByAvailableForChildren(this.options.project.top_level_card);
          }
        };
      }
    }
    $onDestroy() {
      this.drop.destroy();
    }
  }
});
angular_default.module("kantree").component("optionsWidgetGroupBy", {
  template: `
    <options-widget-select ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshItems();
    }
    $onChanges(changes) {
      const filterOrFilterScopesChanged = changes.options && !changes.options.isFirstChange() && ((changes.options.previousValue || {}).filter !== (this.options || {}).filter || (changes.options.previousValue || {}).filter_scopes !== (this.options || {}).filter_scopes);
      if (filterOrFilterScopesChanged) {
        this.refreshItems();
      }
    }
    get projectScoped() {
      return !!this.options.project;
    }
    get portfolioScoped() {
      return this.options.filter_scopes?.[0]?.[0] === "portfolio";
    }
    get orgScoped() {
      return !!this.options.org;
    }
    get projectOrOrgScoped() {
      return this.projectScoped || this.orgScoped;
    }
    refreshItems() {
      this.fetchGroupBy().then((r3) => {
        const [groupTypes, attributes] = r3;
        const items = [];
        const groupTypePrefix = this.projectOrOrgScoped ? "group_type:" : "name:";
        const attributePrefix = this.projectOrOrgScoped ? "attribute:" : "name:";
        for (const gt of groupTypes) {
          items.push([groupTypePrefix + gt.id, gt.name, _4("Contexts")]);
        }
        for (const attr of attributes) {
          items.push([attributePrefix + attr.id, attr.name, _4("Fields")]);
        }
        items.push(["models", _4("Card type"), _4("Other")]);
        items.push(["state", _4("State"), _4("Other")]);
        if (this.portfolioScoped || !this.projectScoped) {
          items.push(["project", _4("Workspace"), _4("Other")]);
          items.push(["team", _4("Team"), _4("Other")]);
          if (!this.portfolioScoped && !this.orgScoped) {
            items.push(["organization", _4("Organization"), _4("Other")]);
          }
        }
        this.items = items;
      }).catch((r3) => {
        this.items = [];
        return this.$q.resolve();
      });
    }
    fetchGroupBy() {
      if (this.projectOrOrgScoped) {
        return this.$q.all([
          (() => {
            if (this.options.project) {
              return loadAllGroupTypesForProject(this.options.project).then(() => {
                return cardGroupTypeStore.scopedByEnabled(this.options.project, false).query();
              });
            }
            if (this.options.org) {
              return loadAllGroupTypesForOrg(this.options.org).then(() => {
                return cardGroupTypeStore.scopedByOrg(this.options.org, false).query();
              });
            }
            return Promise.reject();
          })(),
          (() => {
            const attrTypes = attributeTypeRegistry.filterSupporting("groupable").map((a3) => a3.name);
            if (this.options.project) {
              return loadAllEnabledModelsForProject(this.options.project).then(() => {
                return cardModelStore.scopedByEnabled(this.options.project).getAttributesFromModels({ type: (t3) => attrTypes.includes(t3) });
              });
            }
            if (this.options.org) {
              return loadAllModelsForOrg(this.options.project).then(() => {
                return cardModelStore.scopedByOrg(this.options.project).getAttributesFromModels({ type: (t3) => attrTypes.includes(t3) });
              });
            }
            return Promise.reject();
          })()
        ]);
      }
      if (this.options.filter_scopes || this.options.filter) {
        return this.$q.when(fetchGroupByChoices(
          this.options.filter,
          this.options.filter_scopes,
          { ignoreErrorHandlers: true }
        ), (choices) => {
          return choices.reduce((accu, choice) => {
            const item = { "id": choice.id, "name": choice.id };
            if (choice.types.includes("context")) {
              accu[0].push(item);
            } else {
              accu[1].push(item);
            }
            return accu;
          }, [[], []]);
        });
      }
      return this.$q.reject();
    }
  }
});
angular_default.module("kantree").component("optionsWidgetGroupByGroups", {
  template: `
    <options-widget-select ng-model="$ctrl.value" ng-change="$ctrl.setViewValue()"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled || !$ctrl.groupById || $ctrl.items.length === 0" multiple="true"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshItems();
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      const filterOrFilterScopesChanged = optionsChanged && ((changes.options.previousValue || {}).filter !== (this.options || {}).filter || (changes.options.previousValue || {}).filter_scopes !== (this.options || {}).filter_scopes);
      const groupByChanged = optionsChanged && this.options.depends_on && (this.options || {}).depends_on_value !== (changes.options.previousValue || {}).depends_on_value;
      const cardOrProjectChanged = optionsChanged && ((changes.options.previousValue || {}).card !== (this.options || {}).card || (changes.options.previousValue || {}).project !== (this.options || {}).project);
      if (cardOrProjectChanged || filterOrFilterScopesChanged || groupByChanged) {
        this.refreshItems();
      }
    }
    get groupById() {
      return this.options.depends_on ? this.options.depends_on_value : null;
    }
    get projectScoped() {
      return !!this.options.project;
    }
    get portfolioScoped() {
      return this.options.filter_scopes?.[0]?.[0] === "portfolio";
    }
    get orgScoped() {
      return !!this.options.org;
    }
    get projectOrOrgScoped() {
      return this.projectScoped || this.orgScoped;
    }
    refreshItems() {
      const parent = this.options.card || (this.options.project || {}).top_level_card;
      const project = this.options.project || projectStore.tryGet((this.options.card || {}).project_id);
      const noGroupBy = (name2) => ["__empty__", _4("(No {empty_dimension})", { empty_dimension: name2 }), name2];
      if (!this.groupById) {
        this.items = [];
        return;
      }
      if (this.groupById === "state") {
        this.items = cardStateStore.getBuiltinStates().map((state) => [state.id, state.label, _4("State")]);
        return;
      }
      if (this.groupById === "models" && this.projectScoped) {
        this.items = [noGroupBy(_4("Card type"))].concat(
          (project ? cardModelStore.scopedByEnabled(project).query({ base_model_id: query_exports.isUndefined() }, { sortBy: "name" }) : []).map((model) => {
            return [model.id, model.name, _4("Card type")];
          })
        );
        return;
      }
      if (parent) {
        if (this.groupById.includes("attribute:", 0)) {
          const attr = cardModelStore.getAttribute(parseInt(this.groupById.replace("attribute:", ""), 10));
          if (attr.type === "group_type") {
            const gt = cardGroupTypeStore.tryGet(attr.group_type_id);
            if (gt) {
              const groups = cardGroupStore.scopedByType(gt, parent, false).query();
              this.items = [noGroupBy(gt.name)].concat(groups.map((g3) => [g3.id, g3.title, gt.name]));
              return;
            }
          } else {
            this.$q.when(getSelectChoices(new OptionsWidgetAttributeGroup([attr], project || null), attr, parent), (choices) => {
              const attrType = attributeTypeRegistry.get(attr.type);
              if (attrType.groupByChoiceFormatter) {
                this.items = choices.map((choice) => attrType.groupByChoiceFormatter(choice));
              } else {
                this.items = choices;
              }
              this.items = [noGroupBy(attr.name)].concat(this.items.map((item) => item.concat([attr.name])));
            });
            return;
          }
        }
        if (this.groupById.includes("group_type:", 0)) {
          const gt = cardGroupTypeStore.tryGet(parseInt(this.groupById.replace("group_type:", ""), 10));
          if (gt) {
            const groups = cardGroupStore.scopedByType(gt, parent, false).query();
            this.items = [noGroupBy(gt.name)].concat(groups.map((g3) => [g3.id, g3.title, gt.name]));
            return;
          }
        }
      }
      if (this.options.filter_scopes && this.options.filter_scopes.length > 0) {
        const groupByName = this.groupById.replace("name:", "");
        if (groupByName) {
          this.$q.when(fetchGroupByGroups(
            { id: groupByName },
            this.options.filter,
            this.options.filter_scopes,
            { ignoreErrorHandlers: true }
          ), (groups) => {
            this.items = (this.groupById === "project" ? [] : [noGroupBy(groupByName)]).concat(groups.map((groupName) => [groupName, groupName, groupByName]));
          });
        } else {
          this.items = [];
        }
        return;
      }
    }
    setViewValue() {
      this.ngModel.$setViewValue(this.value);
    }
  }
});
angular_default.module("kantree").component("optionsWidgetViz", {
  template: `
    <div ng-repeat="item in $ctrl.items track by item[0]" ng-class="{'selected': $ctrl.value === item[0]}"
      ng-click="$ctrl.setViewValue(item)" ng-disabled="$ctrl.isDisabled || !$ctrl.value && item !== $ctrl.items[0] || item === $ctrl.items[0] && !!$ctrl.value">
      <span>{{item[1]}}</span>
    </div>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.items = [...this.options.items || []];
      this.items.unshift([null, _4("Number")]);
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
    setViewValue(item) {
      if (this.isDisabled || item === this.items[0] && !!this.value || item !== this.items[0] && !this.value) return;
      this.ngModel.$setViewValue(item[0]);
    }
  }
});

// public/app/ui/editors/options-editor/widgets/refs.js
angular_default.module("kantree").component("optionsWidgetGroupType", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.setViewValue()"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshItems();
    }
    $onChanges(changes) {
      const filterOrFilterScopesChanged = changes.options && !changes.options.isFirstChange() && ((changes.options.previousValue || {}).filter !== (this.options || {}).filter || (changes.options.previousValue || {}).filter_scopes !== (this.options || {}).filter_scopes);
      if (filterOrFilterScopesChanged) {
        this.refreshItems();
      }
    }
    refreshItems() {
      this.$q.when((() => {
        if (this.options.filter_scopes || this.options.filter) {
          return fetchGroupByChoices(this.options.filter, this.options.filter_scopes).then((choices) => {
            return choices.filter((choice) => choice.types.some((type) => type === "context" || type === "group_type")).map((choice) => {
              return { "id": choice.id, "name": choice.id };
            });
          });
        }
        if (this.options.project) {
          return loadAllGroupTypesForProject(this.options.project).then(() => {
            return cardGroupTypeStore.scopedByEnabled(this.options.project, true).query();
          });
        }
        if (this.options.org) {
          return loadAllGroupTypesForOrg(this.options.org, () => {
            return cardGroupTypeStore.scopedByOrg(this.options.org, true).query();
          });
        }
        return this.$q.reject();
      })()).then((groupTypes) => {
        this.items = groupTypes.map((gt) => [gt.id, gt.name, _4("Group types")]);
      }).catch((r3) => {
        this.items = [];
        return this.$q.resolve();
      });
    }
    setViewValue() {
      if (!this.value) {
        this.ngModel.$setViewValue(this.value);
      } else {
        if (this.options.filter_scopes || this.options.filter) {
          this.ngModel.$setViewValue({ "name": this.value.name });
        } else {
          this.ngModel.$setViewValue(this.value);
        }
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetGroup", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.setViewValue()"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshItems();
    }
    $onChanges(changes) {
      const filterOrFilterScopesChanged = changes.options && !changes.options.isFirstChange() && ((changes.options.previousValue || {}).filter !== (this.options || {}).filter || (changes.options.previousValue || {}).filter_scopes !== (this.options || {}).filter_scopes);
      const dependsOnOptionChanged = changes.options && !changes.options.isFirstChange() && this.options.depends_on && this.options.depends_on_value !== changes.options.previousValue.depends_on_value;
      if (filterOrFilterScopesChanged || dependsOnOptionChanged) {
        this.refreshItems();
      }
    }
    refreshItems() {
      if (this.options.card || this.options.project) {
        const parent = this.options.card ? this.options.card : this.options.project.top_level_card;
        if (this.options.depends_on) {
          const gt = this.options.depends_on_value ? cardGroupTypeStore.tryGet(parseInt(this.options.depends_on_value.id, 10)) : null;
          if (gt) {
            const groups = cardGroupStore.scopedByType(gt, parent, false).query();
            this.items = groups.map((g3) => [g3.id, g3.title, gt.name]);
          } else {
            this.items = [];
          }
        } else {
          const groups = cardGroupStore.scopedByAvailableForChildren(parent).query();
          this.items = groups.map((g3) => [g3.id, g3.title, cardGroupTypeStore.get(g3.type_id).name]);
        }
      } else if (this.options.filter_scopes && this.options.filter_scopes.length > 0) {
        this.$q.when(api_default.search.list_groups.get({ filter_scopes: filterScopesToString(this.options.filter_scopes) }), (gt) => {
          if (!!this.options.depends_on) {
            if (gt[this.options.depends_on_value?.name]) {
              this.items = gt[this.options.depends_on_value.name].map((groupName) => [groupName, groupName, this.options.depends_on_value.name]);
            } else {
              this.items = [];
            }
          } else {
            this.items = Object.keys(gt).reduce((accu, gtName) => {
              accu.push(...gt[gtName].map((groupName) => [groupName, groupName, gtName]));
              return accu;
            }, []);
          }
        });
      }
    }
    setViewValue() {
      if (!this.value) {
        this.ngModel.$setViewValue(this.value);
      } else {
        if (this.options.filter_scopes || this.options.filter) {
          this.ngModel.$setViewValue({ "name": this.value.name });
        } else {
          this.ngModel.$setViewValue(this.value);
        }
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetLogType", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      if (this.options.project) {
        this.$q.when(loadAllLogTypes(this.options.project), () => {
          const logTypes = projectLogTypeStore.scopedByProject(this.options.project).query();
          this.items = logTypes.map((lt) => [lt.id, lt.name, _4("Categories")]);
        });
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetRequestForm", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      if (this.options.project) {
        this.$q.when(loadAllRequestFormsForProject(this.options.project), (forms) => {
          this.items = forms.map((f3) => [f3.id, f3.name, _4("Forms")]);
        });
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetMembers", {
  template: `
    <ui-select multiple ng-model="$ctrl.value" on-remove="$ctrl.update()" on-select="$ctrl.update()">
      <ui-select-match>@{{$item.username}}</ui-select-match>
      <ui-select-choices repeat="item.id as item in ($ctrl.items | filter: $select.search)">@{{item.username}}</ui-select-choices>
    </ui-select>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      if (this.options.project) {
        this.$q.when(api_default.project_members.list_members.get({ project_id: this.options.project.id }), (members) => {
          this.items = members.map((m3) => m3.user);
        });
      }
    }
    update() {
      this.ngModel.$setViewValue(this.value);
    }
  }
});
angular_default.module("kantree").component("optionsWidgetAutomationRule", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled" allow-unknown-value="false"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.refreshItems();
    }
    $onChanges(changes) {
      const dependsOnOptionChanged = changes.options && !changes.options.isFirstChange() && this.options.depends_on && this.options.depends_on_value !== changes.options.previousValue.depends_on_value;
      if (dependsOnOptionChanged) {
        this.refreshItems();
        this.ngModel.$setViewValue(null);
      }
    }
    get project() {
      if (this.options.depends_on) {
        return this.options.depends_on_value ? projectStore.tryGet(this.options.depends_on_value) : this.options.project;
      }
      return this.options.project;
    }
    refreshItems() {
      const project = this.project;
      if (!project) {
        this.items = [];
        return;
      }
      this.$q.all([
        loadAutomationRulesForProject(project),
        loadAvailableAutomationEvents()
      ]).then(([rules, eventTypes]) => {
        const triggerEvents = eventTypes.filter((t3) => t3.trigger_only).map((t3) => t3.name);
        this.items = rules.filter((r3) => !this.options.trigger_only || triggerEvents.includes(r3.trigger_event)).filter((r3) => !this.options.exposed_only || (this.options.project.id === project.id || r3.exposed)).map((r3) => [r3.id, r3.name, _4("Automation rules")]);
      });
    }
  }
});
angular_default.module("kantree").component("optionsWidgetCard", {
  template: `
    <p class="form-control-plaintext">
      <card-selector-input ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
        card="$ctrl.card" is-disabled="$ctrl.isDisabled" is-required="$ctrl.isRequired" ></card-selector-input>
    </p>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      if (this.options.card || this.options.project) {
        this.card = this.options.card || this.options.project.top_level_card;
      }
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        if (this.options.card || this.options.project) {
          this.card = this.options.card || this.options.project.top_level_card;
        }
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetCardTarget", {
  template: `
    <p class="form-control-plaintext">
      <card-target-input ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
        card="$ctrl.card" is-disabled="$ctrl.isDisabled" is-required="$ctrl.isRequired" ></card-target-input>
    </p>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      if (this.options.card || this.options.project) {
        this.card = this.options.card || this.options.project.top_level_card;
      }
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        if (this.options.card || this.options.project) {
          this.card = this.options.card || this.options.project.top_level_card;
        }
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetProject", {
  template: `
    <user-project-selector-btn class="form-select project-selector-btn"
      selected-projects="$ctrl.value"
      is-multiple="$ctrl.options.multiple"
      is-disabled="$ctrl.isDisabled"
      on-change="$ctrl.saveProject($projects)"
      empty-label="{{$ctrl.emptyLabel}}"
    ></user-project-selector-btn>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.emptyLabel = this.options.empty_fallback === "current" ? _4("Current workspace") : _4("Any workspace");
      this.ngModel.$render = () => {
        let viewValue = this.ngModel.$viewValue;
        if (viewValue && !this.options.multiple) {
          viewValue = [viewValue];
        }
        this.value = (viewValue || []).map((id) => projectStore.tryGet(id)).filter(Boolean);
      };
    }
    saveProject = (projects) => {
      if (!projects.length) {
        if (this.options.empty_fallback === "current") {
          projects = [this.options.project];
        }
        this.ngModel.$setViewValue(this.options.multiple ? projects : projects[0]?.id);
      } else if (this.options.multiple) {
        this.ngModel.$setViewValue(projects.map((p4) => p4.id));
      } else {
        this.ngModel.$setViewValue(projects[0]?.id);
      }
    };
  }
});
angular_default.module("kantree").component("optionsWidgetOrgs", {
  template: `
    <options-widget-menu ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      options="$ctrl.options" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-menu>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["orgSelectorMenu"];
    $onInit() {
      this.options = { ...this.options };
      this.formatOptions();
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
        this.options.buttonLabel = this.buttonLabel;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
        this.options.buttonLabel = this.buttonLabel;
      });
    }
    $onChanges(changes) {
      const optionsChanged = changes.options && !changes.options.isFirstChange();
      if (optionsChanged) {
        this.options = { ...this.options };
        this.formatOptions();
      }
    }
    formatOptions() {
      this.options.withCaret = true;
      this.options.dropConfig = this.options.dropConfig || { classes: "drop-theme-menu" };
      this.options.buttonLabel = this.buttonLabel;
      this.options.menu = this.menu;
    }
    get buttonLabel() {
      if (!this.value || !this.value.org) {
        if (this.options.withTeams) {
          return _4("No team nor organization selected");
        }
        return _4("No organization selected");
      }
      if (this.value.org.type === "user") {
        return !currentUser2.can_create_private_projects ? _4("Your public workspaces") : _4("Your workspaces");
      }
      return this.value.org.name + (this.value.team ? " / " + this.value.team.name : "");
    }
    get menu() {
      return {
        build: (selected, setValue2) => this.$orgSelectorMenu.getMenu({
          selected,
          org: this.options.org,
          withTeams: this.options.withTeams,
          select: (newVal) => setValue2(newVal)
        }),
        parseNewValue: (newVal, oldVal) => newVal ? { ...newVal } : {}
      };
    }
  }
});
angular_default.module("kantree").component("optionsWidgetModel", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl._isDisabled"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push((e3) => {
        this.value = this.ngModel.$viewValue;
      });
    }
    $onChanges(changes) {
      if (changes.options.currentValue?.[this.projectOptionKey]) {
        const project = changes.options.currentValue?.[this.projectOptionKey];
        this.$q.when(loadAllEnabledModelsForProject({ id: project?.id ?? project }), (models) => {
          this.items = models.map((m3) => [m3.id, m3.name, _4("Card types")]);
        });
      }
    }
    get projectOptionKey() {
      return this.options.depends_on ? "depends_on_value" : "project";
    }
    get _isDisabled() {
      return this.isDisabled || !this.options?.[this.projectOptionKey];
    }
  }
});
angular_default.module("kantree").component("optionsWidgetProjectExportTemplate", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      if (this.options.project) {
        this.$q.when(api_default.project_export_templates.list_templates.get({ project_id: this.options.project.id }), (templates) => {
          this.items = templates.map((t3) => [t3.id, t3.name, _4("Export templates")]);
        });
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetRoles", {
  template: `
    <options-widget-select-ref ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled" multiple="true"
      placeholder="{{$ctrl.placeholder}}"></options-widget-select-ref>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.items = [];
      this.placeholder = this.options?.placeholder || null;
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      if (this.options.project) {
        this.$q.when(loadAllRolesForProject(this.options.project), (roles) => {
          this.items = roles.map((r3) => [r3.id, r3.name, _4("Role")]);
        });
      }
    }
  }
});

// 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((s3) => s3 ? parseInt(s3, 36) : 1);
  for (let i3 = 0, n4 = 0; i3 < numbers.length; i3++)
    (i3 % 2 ? rangeTo : rangeFrom).push(n4 = n4 + numbers[i3]);
})();
function isExtendingChar(code2) {
  if (code2 < 768) return false;
  for (let from2 = 0, to = rangeFrom.length; ; ) {
    let mid = from2 + to >> 1;
    if (code2 < rangeFrom[mid]) to = mid;
    else if (code2 >= rangeTo[mid]) from2 = mid + 1;
    else return true;
    if (from2 == to) return false;
  }
}
function isRegionalIndicator(code2) {
  return code2 >= 127462 && code2 <= 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, i3 = pos - 2;
      while (i3 >= 0 && isRegionalIndicator(codePointAt(str, i3))) {
        countBefore++;
        i3 -= 2;
      }
      if (countBefore % 2 == 0) break;
      else pos += 2;
    } else {
      break;
    }
  }
  return pos;
}
function prevClusterBreak(str, pos, includeExtending) {
  while (pos > 0) {
    let found2 = nextClusterBreak(str, pos - 2, includeExtending);
    if (found2 < pos) return found2;
    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(code2) {
  return code2 < 65536 ? 1 : 2;
}

// node_modules/@codemirror/state/dist/index.js
var Text = 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(n4) {
    if (n4 < 1 || n4 > this.lines)
      throw new RangeError(`Invalid line number ${n4} in ${this.lines}-line document`);
    return this.lineInner(n4, true, 1, 0);
  }
  /**
  Replace a range of the text with the given content.
  */
  replace(from2, to, text3) {
    [from2, to] = clip(this, from2, to);
    let parts = [];
    this.decompose(
      0,
      from2,
      parts,
      2
      /* Open.To */
    );
    if (text3.length)
      text3.decompose(
        0,
        text3.length,
        parts,
        1 | 2
        /* Open.To */
      );
    this.decompose(
      to,
      this.length,
      parts,
      1
      /* Open.From */
    );
    return TextNode2.from(parts, this.length - (to - from2) + text3.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(from2, to = this.length) {
    [from2, to] = clip(this, from2, to);
    let parts = [];
    this.decompose(from2, to, parts, 0);
    return TextNode2.from(parts, to - from2);
  }
  /**
  Test whether this text is equal to another instance.
  */
  eq(other) {
    if (other == this)
      return true;
    if (other.length != this.length || other.lines != this.lines)
      return false;
    let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
    let a3 = new RawTextCursor(this), b3 = new RawTextCursor(other);
    for (let skip3 = start, pos = start; ; ) {
      a3.next(skip3);
      b3.next(skip3);
      skip3 = 0;
      if (a3.lineBreak != b3.lineBreak || a3.done != b3.done || a3.value != b3.value)
        return false;
      pos += a3.value.length;
      if (a3.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(from2, to = this.length) {
    return new PartialTextCursor(this, from2, 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(from2, to) {
    let inner;
    if (from2 == null) {
      inner = this.iter();
    } else {
      if (to == null)
        to = this.lines + 1;
      let start = this.line(from2).from;
      inner = this.iterRange(start, Math.max(start, 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(text3) {
    if (text3.length == 0)
      throw new RangeError("A document must have at least one line");
    if (text3.length == 1 && !text3[0])
      return _Text.empty;
    return text3.length <= 32 ? new TextLeaf(text3) : TextNode2.from(TextLeaf.split(text3, []));
  }
};
var TextLeaf = class _TextLeaf extends Text {
  constructor(text3, length = textLength(text3)) {
    super();
    this.text = text3;
    this.length = length;
  }
  get lines() {
    return this.text.length;
  }
  get children() {
    return null;
  }
  lineInner(target, isLine, line, offset) {
    for (let i3 = 0; ; i3++) {
      let string3 = this.text[i3], end = offset + string3.length;
      if ((isLine ? line : end) >= target)
        return new Line(offset, end, line, string3);
      offset = end + 1;
      line++;
    }
  }
  decompose(from2, to, target, open) {
    let text3 = from2 <= 0 && to >= this.length ? this : new _TextLeaf(sliceText(this.text, from2, to), Math.min(to, this.length) - Math.max(0, from2));
    if (open & 1) {
      let prev = target.pop();
      let joined = appendText(text3.text, prev.text.slice(), 0, text3.length);
      if (joined.length <= 32) {
        target.push(new _TextLeaf(joined, prev.length + text3.length));
      } else {
        let mid = joined.length >> 1;
        target.push(new _TextLeaf(joined.slice(0, mid)), new _TextLeaf(joined.slice(mid)));
      }
    } else {
      target.push(text3);
    }
  }
  replace(from2, to, text3) {
    if (!(text3 instanceof _TextLeaf))
      return super.replace(from2, to, text3);
    [from2, to] = clip(this, from2, to);
    let lines = appendText(this.text, appendText(text3.text, sliceText(this.text, 0, from2)), to);
    let newLen = this.length + text3.length - (to - from2);
    if (lines.length <= 32)
      return new _TextLeaf(lines, newLen);
    return TextNode2.from(_TextLeaf.split(lines, []), newLen);
  }
  sliceString(from2, to = this.length, lineSep = "\n") {
    [from2, to] = clip(this, from2, to);
    let result2 = "";
    for (let pos = 0, i3 = 0; pos <= to && i3 < this.text.length; i3++) {
      let line = this.text[i3], end = pos + line.length;
      if (pos > from2 && i3)
        result2 += lineSep;
      if (from2 < end && to > pos)
        result2 += line.slice(Math.max(0, from2 - pos), to - pos);
      pos = end + 1;
    }
    return result2;
  }
  flatten(target) {
    for (let line of this.text)
      target.push(line);
  }
  scanIdentical() {
    return 0;
  }
  static split(text3, target) {
    let part = [], len = -1;
    for (let line of text3) {
      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 TextNode2 = class _TextNode extends Text {
  constructor(children2, length) {
    super();
    this.children = children2;
    this.length = length;
    this.lines = 0;
    for (let child of children2)
      this.lines += child.lines;
  }
  lineInner(target, isLine, line, offset) {
    for (let i3 = 0; ; i3++) {
      let child = this.children[i3], end = offset + child.length, endLine = line + child.lines - 1;
      if ((isLine ? endLine : end) >= target)
        return child.lineInner(target, isLine, line, offset);
      offset = end + 1;
      line = endLine + 1;
    }
  }
  decompose(from2, to, target, open) {
    for (let i3 = 0, pos = 0; pos <= to && i3 < this.children.length; i3++) {
      let child = this.children[i3], end = pos + child.length;
      if (from2 <= end && to >= pos) {
        let childOpen = open & ((pos <= from2 ? 1 : 0) | (end >= to ? 2 : 0));
        if (pos >= from2 && end <= to && !childOpen)
          target.push(child);
        else
          child.decompose(from2 - pos, to - pos, target, childOpen);
      }
      pos = end + 1;
    }
  }
  replace(from2, to, text3) {
    [from2, to] = clip(this, from2, to);
    if (text3.lines < this.lines)
      for (let i3 = 0, pos = 0; i3 < this.children.length; i3++) {
        let child = this.children[i3], end = pos + child.length;
        if (from2 >= pos && to <= end) {
          let updated = child.replace(from2 - pos, to - pos, text3);
          let totalLines = this.lines - child.lines + updated.lines;
          if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) {
            let copy2 = this.children.slice();
            copy2[i3] = updated;
            return new _TextNode(copy2, this.length - (to - from2) + text3.length);
          }
          return super.replace(pos, end, updated);
        }
        pos = end + 1;
      }
    return super.replace(from2, to, text3);
  }
  sliceString(from2, to = this.length, lineSep = "\n") {
    [from2, to] = clip(this, from2, to);
    let result2 = "";
    for (let i3 = 0, pos = 0; i3 < this.children.length && pos <= to; i3++) {
      let child = this.children[i3], end = pos + child.length;
      if (pos > from2 && i3)
        result2 += lineSep;
      if (from2 < end && to > pos)
        result2 += child.sliceString(from2 - pos, to - pos, lineSep);
      pos = end + 1;
    }
    return result2;
  }
  flatten(target) {
    for (let child of this.children)
      child.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((l3, ch) => l3 + 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 chunk2 = Math.max(
      32,
      lines >> 5
      /* Tree.BranchShift */
    ), maxChunk = chunk2 << 1, minChunk = chunk2 >> 1;
    let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
    function add4(child) {
      let last3;
      if (child.lines > maxChunk && child instanceof _TextNode) {
        for (let node of child.children)
          add4(node);
      } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
        flush();
        chunked.push(child);
      } else if (child instanceof TextLeaf && currentLines && (last3 = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last3.lines <= 32) {
        currentLines += child.lines;
        currentLen += child.length + 1;
        currentChunk[currentChunk.length - 1] = new TextLeaf(last3.text.concat(child.text), last3.length + 1 + child.length);
      } else {
        if (currentLines + child.lines > chunk2)
          flush();
        currentLines += child.lines;
        currentLen += child.length + 1;
        currentChunk.push(child);
      }
    }
    function flush() {
      if (currentLines == 0)
        return;
      chunked.push(currentChunk.length == 1 ? currentChunk[0] : _TextNode.from(currentChunk, currentLen));
      currentLen = -1;
      currentLines = currentChunk.length = 0;
    }
    for (let child of children2)
      add4(child);
    flush();
    return chunked.length == 1 ? chunked[0] : new _TextNode(chunked, length);
  }
};
Text.empty = /* @__PURE__ */ new TextLeaf([""], 0);
function textLength(text3) {
  let length = -1;
  for (let line of text3)
    length += line.length + 1;
  return length;
}
function appendText(text3, target, from2 = 0, to = 1e9) {
  for (let pos = 0, i3 = 0, first2 = true; i3 < text3.length && pos <= to; i3++) {
    let line = text3[i3], end = pos + line.length;
    if (end >= from2) {
      if (end > to)
        line = line.slice(0, to - pos);
      if (pos < from2)
        line = line.slice(from2 - pos);
      if (first2) {
        target[target.length - 1] += line;
        first2 = false;
      } else
        target.push(line);
    }
    pos = end + 1;
  }
  return target;
}
function sliceText(text3, from2, to) {
  return appendText(text3, [""], from2, to);
}
var RawTextCursor = class {
  constructor(text3, dir = 1) {
    this.dir = dir;
    this.done = false;
    this.lineBreak = false;
    this.value = "";
    this.nodes = [text3];
    this.offsets = [dir > 0 ? 1 : (text3 instanceof TextLeaf ? text3.text.length : text3.children.length) << 1];
  }
  nextInner(skip3, dir) {
    this.done = this.lineBreak = false;
    for (; ; ) {
      let last3 = this.nodes.length - 1;
      let top2 = this.nodes[last3], offsetValue = this.offsets[last3], offset = offsetValue >> 1;
      let size4 = top2 instanceof TextLeaf ? top2.text.length : top2.children.length;
      if (offset == (dir > 0 ? size4 : 0)) {
        if (last3 == 0) {
          this.done = true;
          this.value = "";
          return this;
        }
        if (dir > 0)
          this.offsets[last3 - 1]++;
        this.nodes.pop();
        this.offsets.pop();
      } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
        this.offsets[last3] += dir;
        if (skip3 == 0) {
          this.lineBreak = true;
          this.value = "\n";
          return this;
        }
        skip3--;
      } else if (top2 instanceof TextLeaf) {
        let next2 = top2.text[offset + (dir < 0 ? -1 : 0)];
        this.offsets[last3] += dir;
        if (next2.length > Math.max(0, skip3)) {
          this.value = skip3 == 0 ? next2 : dir > 0 ? next2.slice(skip3) : next2.slice(0, next2.length - skip3);
          return this;
        }
        skip3 -= next2.length;
      } else {
        let next2 = top2.children[offset + (dir < 0 ? -1 : 0)];
        if (skip3 > next2.length) {
          skip3 -= next2.length;
          this.offsets[last3] += dir;
        } else {
          if (dir < 0)
            this.offsets[last3]--;
          this.nodes.push(next2);
          this.offsets.push(dir > 0 ? 1 : (next2 instanceof TextLeaf ? next2.text.length : next2.children.length) << 1);
        }
      }
    }
  }
  next(skip3 = 0) {
    if (skip3 < 0) {
      this.nextInner(-skip3, -this.dir);
      skip3 = this.value.length;
    }
    return this.nextInner(skip3, this.dir);
  }
};
var PartialTextCursor = class {
  constructor(text3, start, end) {
    this.value = "";
    this.done = false;
    this.cursor = new RawTextCursor(text3, start > end ? -1 : 1);
    this.pos = start > end ? text3.length : 0;
    this.from = Math.min(start, end);
    this.to = Math.max(start, end);
  }
  nextInner(skip3, dir) {
    if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
      this.value = "";
      this.done = true;
      return this;
    }
    skip3 += 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 (skip3 > limit)
      skip3 = limit;
    limit -= skip3;
    let { value: value2 } = this.cursor.next(skip3);
    this.pos += (value2.length + skip3) * dir;
    this.value = value2.length <= limit ? value2 : dir < 0 ? value2.slice(value2.length - limit) : value2.slice(0, limit);
    this.done = !this.value;
    return this;
  }
  next(skip3 = 0) {
    if (skip3 < 0)
      skip3 = Math.max(skip3, this.from - this.pos);
    else if (skip3 > 0)
      skip3 = Math.min(skip3, this.to - this.pos);
    return this.nextInner(skip3, 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(skip3 = 0) {
    let { done, lineBreak, value: value2 } = this.inner.next(skip3);
    if (done && this.afterBreak) {
      this.value = "";
      this.afterBreak = false;
    } else if (done) {
      this.done = true;
      this.value = "";
    } else if (lineBreak) {
      if (this.afterBreak) {
        this.value = "";
      } else {
        this.afterBreak = true;
        this.next();
      }
    } else {
      this.value = value2;
      this.afterBreak = false;
    }
    return this;
  }
  get lineBreak() {
    return false;
  }
};
if (typeof Symbol != "undefined") {
  Text.prototype[Symbol.iterator] = function() {
    return this.iter();
  };
  RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() {
    return this;
  };
}
var Line = class {
  /**
  @internal
  */
  constructor(from2, to, number3, text3) {
    this.from = from2;
    this.to = to;
    this.number = number3;
    this.text = text3;
  }
  /**
  The length of the line (not including any line break after it).
  */
  get length() {
    return this.to - this.from;
  }
};
function clip(text3, from2, to) {
  from2 = Math.max(0, Math.min(text3.length, from2));
  return [from2, Math.max(from2, Math.min(text3.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(code2) {
  if (code2 <= 65535)
    return String.fromCharCode(code2);
  code2 -= 65536;
  return String.fromCharCode((code2 >> 10) + 55296, (code2 & 1023) + 56320);
}
function codePointSize2(code2) {
  return code2 < 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 result2 = 0;
    for (let i3 = 0; i3 < this.sections.length; i3 += 2)
      result2 += this.sections[i3];
    return result2;
  }
  /**
  The length of the document after the change.
  */
  get newLength() {
    let result2 = 0;
    for (let i3 = 0; i3 < this.sections.length; i3 += 2) {
      let ins = this.sections[i3 + 1];
      result2 += ins < 0 ? this.sections[i3] : ins;
    }
    return result2;
  }
  /**
  False when there are actual changes in this set.
  */
  get empty() {
    return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
  }
  /**
  Iterate over the unchanged parts left by these changes. `posA`
  provides the position of the range in the old document, `posB`
  the new position in the changed document.
  */
  iterGaps(f3) {
    for (let i3 = 0, posA = 0, posB = 0; i3 < this.sections.length; ) {
      let len = this.sections[i3++], ins = this.sections[i3++];
      if (ins < 0) {
        f3(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(f3, individual = false) {
    iterChanges(this, f3, individual);
  }
  /**
  Get a description of the inverted form of these changes.
  */
  get invertedDesc() {
    let sections = [];
    for (let i3 = 0; i3 < this.sections.length; ) {
      let len = this.sections[i3++], ins = this.sections[i3++];
      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, before2 = false) {
    return other.empty ? this : mapSet(this, other, before2);
  }
  mapPos(pos, assoc = -1, mode = MapMode.Simple) {
    let posA = 0, posB = 0;
    for (let i3 = 0; i3 < this.sections.length; ) {
      let len = this.sections[i3++], ins = this.sections[i3++], 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(from2, to = from2) {
    for (let i3 = 0, pos = 0; i3 < this.sections.length && pos <= to; ) {
      let len = this.sections[i3++], ins = this.sections[i3++], end = pos + len;
      if (ins >= 0 && pos <= to && end >= from2)
        return pos < from2 && end > to ? "cover" : true;
      pos = end;
    }
    return false;
  }
  /**
  @internal
  */
  toString() {
    let result2 = "";
    for (let i3 = 0; i3 < this.sections.length; ) {
      let len = this.sections[i3++], ins = this.sections[i3++];
      result2 += (result2 ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
    }
    return result2;
  }
  /**
  Serialize this change desc to a JSON-representable value.
  */
  toJSON() {
    return this.sections;
  }
  /**
  Create a change desc from its JSON representation (as produced
  by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
  */
  static fromJSON(json2) {
    if (!Array.isArray(json2) || json2.length % 2 || json2.some((a3) => typeof a3 != "number"))
      throw new RangeError("Invalid JSON representation of ChangeDesc");
    return new _ChangeDesc(json2);
  }
  /**
  @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(doc4) {
    if (this.length != doc4.length)
      throw new RangeError("Applying change set to a document with the wrong length");
    iterChanges(this, (fromA, toA, fromB, _toB, text3) => doc4 = doc4.replace(fromB, fromB + (toA - fromA), text3), false);
    return doc4;
  }
  mapDesc(other, before2 = false) {
    return mapSet(this, other, before2, 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(doc4) {
    let sections = this.sections.slice(), inserted = [];
    for (let i3 = 0, pos = 0; i3 < sections.length; i3 += 2) {
      let len = sections[i3], ins = sections[i3 + 1];
      if (ins >= 0) {
        sections[i3] = ins;
        sections[i3 + 1] = len;
        let index2 = i3 >> 1;
        while (inserted.length < index2)
          inserted.push(Text.empty);
        inserted.push(len ? doc4.slice(pos, pos + len) : Text.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, before2 = false) {
    return other.empty ? this : mapSet(this, other, before2, 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(f3, individual = false) {
    iterChanges(this, f3, 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 i3 = 0, pos = 0; ; ) {
      let next2 = i3 == ranges.length ? 1e9 : ranges[i3++];
      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[i3++];
      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 parts = [];
    for (let i3 = 0; i3 < this.sections.length; i3 += 2) {
      let len = this.sections[i3], ins = this.sections[i3 + 1];
      if (ins < 0)
        parts.push(len);
      else if (ins == 0)
        parts.push([len]);
      else
        parts.push([len].concat(this.inserted[i3 >> 1].toJSON()));
    }
    return parts;
  }
  /**
  Create a change set for the given changes, for a document of the
  given length, using `lineSep` as line separator.
  */
  static of(changes, length, lineSep) {
    let sections = [], inserted = [], 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 process3(spec) {
      if (Array.isArray(spec)) {
        for (let sub of spec)
          process3(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: from2, to = from2, insert: insert4 } = spec;
        if (from2 > to || from2 < 0 || to > length)
          throw new RangeError(`Invalid change range ${from2} to ${to} (in doc of length ${length})`);
        let insText = !insert4 ? Text.empty : typeof insert4 == "string" ? Text.of(insert4.split(lineSep || DefaultSplit)) : insert4;
        let insLen = insText.length;
        if (from2 == to && insLen == 0)
          return;
        if (from2 < pos)
          flush();
        if (from2 > pos)
          addSection(sections, from2 - pos, -1);
        addSection(sections, to - from2, insLen);
        addInsert(inserted, sections, insText);
        pos = to;
      }
    }
    process3(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(json2) {
    if (!Array.isArray(json2))
      throw new RangeError("Invalid JSON representation of ChangeSet");
    let sections = [], inserted = [];
    for (let i3 = 0; i3 < json2.length; i3++) {
      let part = json2[i3];
      if (typeof part == "number") {
        sections.push(part, -1);
      } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e3, i4) => i4 && typeof e3 != "string")) {
        throw new RangeError("Invalid JSON representation of ChangeSet");
      } else if (part.length == 1) {
        sections.push(part[0], 0);
      } else {
        while (inserted.length < i3)
          inserted.push(Text.empty);
        inserted[i3] = Text.of(part.slice(1));
        sections.push(part[0], inserted[i3].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 last3 = sections.length - 2;
  if (last3 >= 0 && ins <= 0 && ins == sections[last3 + 1])
    sections[last3] += len;
  else if (last3 >= 0 && len == 0 && sections[last3] == 0)
    sections[last3 + 1] += ins;
  else if (forceJoin) {
    sections[last3] += len;
    sections[last3 + 1] += ins;
  } else
    sections.push(len, ins);
}
function addInsert(values2, sections, value2) {
  if (value2.length == 0)
    return;
  let index2 = sections.length - 2 >> 1;
  if (index2 < values2.length) {
    values2[values2.length - 1] = values2[values2.length - 1].append(value2);
  } else {
    while (values2.length < index2)
      values2.push(Text.empty);
    values2.push(value2);
  }
}
function iterChanges(desc, f3, individual) {
  let inserted = desc.inserted;
  for (let posA = 0, posB = 0, i3 = 0; i3 < desc.sections.length; ) {
    let len = desc.sections[i3++], ins = desc.sections[i3++];
    if (ins < 0) {
      posA += len;
      posB += len;
    } else {
      let endA = posA, endB = posB, text3 = Text.empty;
      for (; ; ) {
        endA += len;
        endB += ins;
        if (ins && inserted)
          text3 = text3.append(inserted[i3 - 2 >> 1]);
        if (individual || i3 == desc.sections.length || desc.sections[i3 + 1] < 0)
          break;
        len = desc.sections[i3++];
        ins = desc.sections[i3++];
      }
      f3(posA, endA, posB, endB, text3);
      posA = endA;
      posB = endB;
    }
  }
}
function mapSet(setA, setB, before2, mkSet = false) {
  let sections = [], insert4 = mkSet ? [] : null;
  let a3 = new SectionIter(setA), b3 = new SectionIter(setB);
  for (let inserted = -1; ; ) {
    if (a3.done && b3.len || b3.done && a3.len) {
      throw new Error("Mismatched change set lengths");
    } else if (a3.ins == -1 && b3.ins == -1) {
      let len = Math.min(a3.len, b3.len);
      addSection(sections, len, -1);
      a3.forward(len);
      b3.forward(len);
    } else if (b3.ins >= 0 && (a3.ins < 0 || inserted == a3.i || a3.off == 0 && (b3.len < a3.len || b3.len == a3.len && !before2))) {
      let len = b3.len;
      addSection(sections, b3.ins, -1);
      while (len) {
        let piece = Math.min(a3.len, len);
        if (a3.ins >= 0 && inserted < a3.i && a3.len <= piece) {
          addSection(sections, 0, a3.ins);
          if (insert4)
            addInsert(insert4, sections, a3.text);
          inserted = a3.i;
        }
        a3.forward(piece);
        len -= piece;
      }
      b3.next();
    } else if (a3.ins >= 0) {
      let len = 0, left = a3.len;
      while (left) {
        if (b3.ins == -1) {
          let piece = Math.min(left, b3.len);
          len += piece;
          left -= piece;
          b3.forward(piece);
        } else if (b3.ins == 0 && b3.len < left) {
          left -= b3.len;
          b3.next();
        } else {
          break;
        }
      }
      addSection(sections, len, inserted < a3.i ? a3.ins : 0);
      if (insert4 && inserted < a3.i)
        addInsert(insert4, sections, a3.text);
      inserted = a3.i;
      a3.forward(a3.len - left);
    } else if (a3.done && b3.done) {
      return insert4 ? ChangeSet.createSet(sections, insert4) : ChangeDesc.create(sections);
    } else {
      throw new Error("Mismatched change set lengths");
    }
  }
}
function composeSets(setA, setB, mkSet = false) {
  let sections = [];
  let insert4 = mkSet ? [] : null;
  let a3 = new SectionIter(setA), b3 = new SectionIter(setB);
  for (let open = false; ; ) {
    if (a3.done && b3.done) {
      return insert4 ? ChangeSet.createSet(sections, insert4) : ChangeDesc.create(sections);
    } else if (a3.ins == 0) {
      addSection(sections, a3.len, 0, open);
      a3.next();
    } else if (b3.len == 0 && !b3.done) {
      addSection(sections, 0, b3.ins, open);
      if (insert4)
        addInsert(insert4, sections, b3.text);
      b3.next();
    } else if (a3.done || b3.done) {
      throw new Error("Mismatched change set lengths");
    } else {
      let len = Math.min(a3.len2, b3.len), sectionLen = sections.length;
      if (a3.ins == -1) {
        let insB = b3.ins == -1 ? -1 : b3.off ? 0 : b3.ins;
        addSection(sections, len, insB, open);
        if (insert4 && insB)
          addInsert(insert4, sections, b3.text);
      } else if (b3.ins == -1) {
        addSection(sections, a3.off ? 0 : a3.len, len, open);
        if (insert4)
          addInsert(insert4, sections, a3.textBit(len));
      } else {
        addSection(sections, a3.off ? 0 : a3.len, b3.off ? 0 : b3.ins, open);
        if (insert4 && !b3.off)
          addInsert(insert4, sections, b3.text);
      }
      open = (a3.ins > len || b3.ins >= 0 && b3.len > len) && (open || sections.length > sectionLen);
      a3.forward2(len);
      b3.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, index2 = this.i - 2 >> 1;
    return index2 >= inserted.length ? Text.empty : inserted[index2];
  }
  textBit(len) {
    let { inserted } = this.set, index2 = this.i - 2 >> 1;
    return index2 >= inserted.length && !len ? Text.empty : inserted[index2].slice(this.off, len == null ? void 0 : this.off + len);
  }
  forward(len) {
    if (len == this.len)
      this.next();
    else {
      this.len -= len;
      this.off += len;
    }
  }
  forward2(len) {
    if (this.ins == -1)
      this.forward(len);
    else if (len == this.ins)
      this.next();
    else {
      this.ins -= len;
      this.off += len;
    }
  }
};
var SelectionRange2 = class _SelectionRange {
  constructor(from2, to, flags) {
    this.from = from2;
    this.to = to;
    this.flags = flags;
  }
  /**
  The anchor of the range—the side that doesn't move when you
  extend it.
  */
  get anchor() {
    return this.flags & 32 ? this.to : this.from;
  }
  /**
  The head of the range, which is moved when the range is
  [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
  */
  get head() {
    return this.flags & 32 ? this.from : this.to;
  }
  /**
  True when `anchor` and `head` are at the same position.
  */
  get empty() {
    return this.from == this.to;
  }
  /**
  If this is a cursor that is explicitly associated with the
  character on one of its sides, this returns the side. -1 means
  the character before its position, 1 the character after, and 0
  means no association.
  */
  get assoc() {
    return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0;
  }
  /**
  The bidirectional text level associated with this cursor, if
  any.
  */
  get bidiLevel() {
    let level = this.flags & 7;
    return level == 7 ? null : level;
  }
  /**
  The goal column (stored vertical offset) associated with a
  cursor. This is used to preserve the vertical position when
  [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
  lines of different length.
  */
  get goalColumn() {
    let value2 = this.flags >> 6;
    return value2 == 16777215 ? void 0 : value2;
  }
  /**
  Map this range through a change, producing a valid range in the
  updated document.
  */
  map(change, assoc = -1) {
    let from2, to;
    if (this.empty) {
      from2 = to = change.mapPos(this.from, assoc);
    } else {
      from2 = change.mapPos(this.from, 1);
      to = change.mapPos(this.to, -1);
    }
    return from2 == this.from && to == this.to ? this : new _SelectionRange(from2, to, this.flags);
  }
  /**
  Extend this range to cover at least `from` to `to`.
  */
  extend(from2, to = from2) {
    if (from2 <= this.anchor && to >= this.anchor)
      return EditorSelection.range(from2, to);
    let head2 = Math.abs(from2 - this.anchor) > Math.abs(to - this.anchor) ? from2 : 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 && this.goalColumn == other.goalColumn && (!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(json2) {
    if (!json2 || typeof json2.anchor != "number" || typeof json2.head != "number")
      throw new RangeError("Invalid JSON representation for SelectionRange");
    return EditorSelection.range(json2.anchor, json2.head);
  }
  /**
  @internal
  */
  static create(from2, to, flags) {
    return new _SelectionRange(from2, to, flags);
  }
};
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((r3) => r3.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 i3 = 0; i3 < this.ranges.length; i3++)
      if (!this.ranges[i3].eq(other.ranges[i3], 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, main2 = true) {
    return _EditorSelection.create([range2].concat(this.ranges), main2 ? 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((r3) => r3.toJSON()), main: this.mainIndex };
  }
  /**
  Create a selection from a JSON representation.
  */
  static fromJSON(json2) {
    if (!json2 || !Array.isArray(json2.ranges) || typeof json2.main != "number" || json2.main >= json2.ranges.length)
      throw new RangeError("Invalid JSON representation for EditorSelection");
    return new _EditorSelection(json2.ranges.map((r3) => SelectionRange2.fromJSON(r3)), json2.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, i3 = 0; i3 < ranges.length; i3++) {
      let range2 = ranges[i3];
      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 SelectionRange2.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 flags = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
    return head2 < anchor ? SelectionRange2.create(head2, anchor, 32 | 16 | flags) : SelectionRange2.create(anchor, head2, (head2 > anchor ? 8 : 0) | flags);
  }
  /**
  @internal
  */
  static normalized(ranges, mainIndex = 0) {
    let main2 = ranges[mainIndex];
    ranges.sort((a3, b3) => a3.from - b3.from);
    mainIndex = ranges.indexOf(main2);
    for (let i3 = 1; i3 < ranges.length; i3++) {
      let range2 = ranges[i3], prev = ranges[i3 - 1];
      if (range2.empty ? range2.from <= prev.to : range2.from < prev.to) {
        let from2 = prev.from, to = Math.max(range2.to, prev.to);
        if (i3 <= mainIndex)
          mainIndex--;
        ranges.splice(--i3, 2, range2.anchor > range2.head ? _EditorSelection.range(to, from2) : _EditorSelection.range(from2, to));
      }
    }
    return new _EditorSelection(ranges, mainIndex);
  }
};
function checkSelection(selection, docLength) {
  for (let range2 of selection.ranges)
    if (range2.to > docLength)
      throw new RangeError("Selection points outside of document");
}
var nextID = 0;
var Facet = class _Facet {
  constructor(combine, compareInput, compare4, isStatic, enables) {
    this.combine = combine;
    this.compareInput = compareInput;
    this.compare = compare4;
    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(config3 = {}) {
    return new _Facet(config3.combine || ((a3) => a3), config3.compareInput || ((a3, b3) => a3 === b3), config3.compare || (!config3.combine ? sameArray : (a3, b3) => a3 === b3), !!config3.static, config3.enables);
  }
  /**
  Returns an extension that adds the given value to this facet.
  */
  of(value2) {
    return new FacetProvider([], this, 0, value2);
  }
  /**
  Create an extension that computes a value for the facet from a
  state. You must take care to declare the parts of the state that
  this value depends on, since your function is only called again
  for a new state when one of those parts changed.
  
  In cases where your value depends only on a single field, you'll
  want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
  */
  compute(deps, get7) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 1, get7);
  }
  /**
  Create an extension that computes zero or more values for this
  facet from a state.
  */
  computeN(deps, get7) {
    if (this.isStatic)
      throw new Error("Can't compute a static facet");
    return new FacetProvider(deps, this, 2, get7);
  }
  from(field2, get7) {
    if (!get7)
      get7 = (x3) => x3;
    return this.compute([field2], (state) => get7(state.field(field2)));
  }
};
function sameArray(a3, b3) {
  return a3 == b3 || a3.length == b3.length && a3.every((e3, i3) => e3 === b3[i3]);
}
var FacetProvider = class {
  constructor(dependencies, facet, type, value2) {
    this.dependencies = dependencies;
    this.facet = facet;
    this.type = type;
    this.value = value2;
    this.id = nextID++;
  }
  dynamicSlot(addresses) {
    var _a4;
    let getter = this.value;
    let compare4 = this.facet.compareInput;
    let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2;
    let depDoc = false, depSel = false, depAddrs = [];
    for (let dep of this.dependencies) {
      if (dep == "doc")
        depDoc = true;
      else if (dep == "selection")
        depSel = true;
      else if ((((_a4 = addresses[dep.id]) !== null && _a4 !== void 0 ? _a4 : 1) & 1) == 0)
        depAddrs.push(addresses[dep.id]);
    }
    return {
      create(state) {
        state.values[idx] = getter(state);
        return 1;
      },
      update(state, tr2) {
        if (depDoc && tr2.docChanged || depSel && (tr2.docChanged || tr2.selection) || ensureAll(state, depAddrs)) {
          let newVal = getter(state);
          if (multi ? !compareArray(newVal, state.values[idx], compare4) : !compare4(newVal, state.values[idx])) {
            state.values[idx] = newVal;
            return 1;
          }
        }
        return 0;
      },
      reconfigure: (state, oldState) => {
        let newVal, oldAddr = oldState.config.address[id];
        if (oldAddr != null) {
          let oldVal = getAddr(oldState, oldAddr);
          if (this.dependencies.every((dep) => {
            return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
          }) || (multi ? compareArray(newVal = getter(state), oldVal, compare4) : compare4(newVal = getter(state), oldVal))) {
            state.values[idx] = oldVal;
            return 0;
          }
        } else {
          newVal = getter(state);
        }
        state.values[idx] = newVal;
        return 1;
      }
    };
  }
};
function compareArray(a3, b3, compare4) {
  if (a3.length != b3.length)
    return false;
  for (let i3 = 0; i3 < a3.length; i3++)
    if (!compare4(a3[i3], b3[i3]))
      return false;
  return true;
}
function ensureAll(state, addrs) {
  let changed = false;
  for (let addr of addrs)
    if (ensureAddr(state, addr) & 1)
      changed = true;
  return changed;
}
function dynamicFacetSlot(addresses, facet, providers) {
  let providerAddrs = providers.map((p4) => addresses[p4.id]);
  let providerTypes = providers.map((p4) => p4.type);
  let dynamic = providerAddrs.filter((p4) => !(p4 & 1));
  let idx = addresses[facet.id] >> 1;
  function get7(state) {
    let values2 = [];
    for (let i3 = 0; i3 < providerAddrs.length; i3++) {
      let value2 = getAddr(state, providerAddrs[i3]);
      if (providerTypes[i3] == 2)
        for (let val of value2)
          values2.push(val);
      else
        values2.push(value2);
    }
    return facet.combine(values2);
  }
  return {
    create(state) {
      for (let addr of providerAddrs)
        ensureAddr(state, addr);
      state.values[idx] = get7(state);
      return 1;
    },
    update(state, tr2) {
      if (!ensureAll(state, dynamic))
        return 0;
      let value2 = get7(state);
      if (facet.compare(value2, state.values[idx]))
        return 0;
      state.values[idx] = value2;
      return 1;
    },
    reconfigure(state, oldState) {
      let depChanged = ensureAll(state, providerAddrs);
      let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
      if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
        state.values[idx] = oldValue;
        return 0;
      }
      let value2 = get7(state);
      if (facet.compare(value2, oldValue)) {
        state.values[idx] = oldValue;
        return 0;
      }
      state.values[idx] = value2;
      return 1;
    }
  };
}
var initField = /* @__PURE__ */ Facet.define({ static: true });
var StateField = class _StateField {
  constructor(id, createF, updateF, compareF, spec) {
    this.id = id;
    this.createF = createF;
    this.updateF = updateF;
    this.compareF = compareF;
    this.spec = spec;
    this.provides = void 0;
  }
  /**
  Define a state field.
  */
  static define(config3) {
    let field2 = new _StateField(nextID++, config3.create, config3.update, config3.compare || ((a3, b3) => a3 === b3), config3);
    if (config3.provide)
      field2.provides = config3.provide(field2);
    return field2;
  }
  create(state) {
    let init = state.facet(initField).find((i3) => i3.field == this);
    return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
  }
  /**
  @internal
  */
  slot(addresses) {
    let idx = addresses[this.id] >> 1;
    return {
      create: (state) => {
        state.values[idx] = this.create(state);
        return 1;
      },
      update: (state, tr2) => {
        let oldVal = state.values[idx];
        let value2 = this.updateF(oldVal, tr2);
        if (this.compareF(oldVal, value2))
          return 0;
        state.values[idx] = value2;
        return 1;
      },
      reconfigure: (state, oldState) => {
        let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;
        if ((reInit = init.find((i3) => i3.field == this)) && reInit != oldInit.find((i3) => i3.field == this)) {
          state.values[idx] = reInit.create(state);
          return 1;
        }
        if (oldState.config.address[this.id] != null) {
          state.values[idx] = oldState.field(this);
          return 0;
        }
        state.values[idx] = this.create(state);
        return 1;
      }
    };
  }
  /**
  Returns an extension that enables this field and overrides the
  way it is initialized. Can be useful when you need to provide a
  non-default starting value for the field.
  */
  init(create6) {
    return [this, initField.of({ field: this, create: create6 })];
  }
  /**
  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(value2) {
  return (ext) => new PrecExtension(ext, value2);
}
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(ext) {
    return new CompartmentInstance(this, ext);
  }
  /**
  Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
  reconfigures this compartment.
  */
  reconfigure(content2) {
    return _Compartment.reconfigure.of({ compartment: this, extension: content2 });
  }
  /**
  Get the current content of the compartment in the state, or
  `undefined` if it isn't present.
  */
  get(state) {
    return state.config.compartments.get(this);
  }
};
var CompartmentInstance = class {
  constructor(compartment, inner) {
    this.compartment = compartment;
    this.inner = inner;
  }
};
var Configuration2 = class _Configuration {
  constructor(base3, compartments, dynamicSlots, address, staticValues, facets) {
    this.base = base3;
    this.compartments = compartments;
    this.dynamicSlots = dynamicSlots;
    this.address = address;
    this.staticValues = staticValues;
    this.facets = facets;
    this.statusTemplate = [];
    while (this.statusTemplate.length < dynamicSlots.length)
      this.statusTemplate.push(
        0
        /* SlotStatus.Unresolved */
      );
  }
  staticFacet(facet) {
    let addr = this.address[facet.id];
    return addr == null ? facet.default : this.staticValues[addr >> 1];
  }
  static resolve(base3, compartments, oldState) {
    let fields2 = [];
    let facets = /* @__PURE__ */ Object.create(null);
    let newCompartments = /* @__PURE__ */ new Map();
    for (let ext of flatten3(base3, compartments, newCompartments)) {
      if (ext instanceof StateField)
        fields2.push(ext);
      else
        (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
    }
    let address = /* @__PURE__ */ Object.create(null);
    let staticValues = [];
    let dynamicSlots = [];
    for (let field2 of fields2) {
      address[field2.id] = dynamicSlots.length << 1;
      dynamicSlots.push((a3) => field2.slot(a3));
    }
    let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
    for (let id in facets) {
      let providers = facets[id], facet = providers[0].facet;
      let oldProviders = oldFacets && oldFacets[id] || [];
      if (providers.every(
        (p4) => p4.type == 0
        /* Provider.Static */
      )) {
        address[facet.id] = staticValues.length << 1 | 1;
        if (sameArray(oldProviders, providers)) {
          staticValues.push(oldState.facet(facet));
        } else {
          let value2 = facet.combine(providers.map((p4) => p4.value));
          staticValues.push(oldState && facet.compare(value2, oldState.facet(facet)) ? oldState.facet(facet) : value2);
        }
      } else {
        for (let p4 of providers) {
          if (p4.type == 0) {
            address[p4.id] = staticValues.length << 1 | 1;
            staticValues.push(p4.value);
          } else {
            address[p4.id] = dynamicSlots.length << 1;
            dynamicSlots.push((a3) => p4.dynamicSlot(a3));
          }
        }
        address[facet.id] = dynamicSlots.length << 1;
        dynamicSlots.push((a3) => dynamicFacetSlot(a3, facet, providers));
      }
    }
    let dynamic = dynamicSlots.map((f3) => f3(address));
    return new _Configuration(base3, newCompartments, dynamic, address, staticValues, facets);
  }
};
function flatten3(extension, compartments, newCompartments) {
  let result2 = [[], [], [], [], []];
  let seen = /* @__PURE__ */ new Map();
  function inner(ext, prec2) {
    let known = seen.get(ext);
    if (known != null) {
      if (known <= prec2)
        return;
      let found2 = result2[known].indexOf(ext);
      if (found2 > -1)
        result2[known].splice(found2, 1);
      if (ext instanceof CompartmentInstance)
        newCompartments.delete(ext.compartment);
    }
    seen.set(ext, prec2);
    if (Array.isArray(ext)) {
      for (let e3 of ext)
        inner(e3, prec2);
    } else if (ext instanceof CompartmentInstance) {
      if (newCompartments.has(ext.compartment))
        throw new RangeError(`Duplicate use of compartment in extensions`);
      let content2 = compartments.get(ext.compartment) || ext.inner;
      newCompartments.set(ext.compartment, content2);
      inner(content2, prec2);
    } else if (ext instanceof PrecExtension) {
      inner(ext.inner, ext.prec);
    } else if (ext instanceof StateField) {
      result2[prec2].push(ext);
      if (ext.provides)
        inner(ext.provides, prec2);
    } else if (ext instanceof FacetProvider) {
      result2[prec2].push(ext);
      if (ext.facet.extensions)
        inner(ext.facet.extensions, Prec_.default);
    } else {
      let content2 = ext.extension;
      if (!content2)
        throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
      inner(content2, prec2);
    }
  }
  inner(extension, Prec_.default);
  return result2.reduce((a3, b3) => a3.concat(b3));
}
function ensureAddr(state, addr) {
  if (addr & 1)
    return 2;
  let idx = addr >> 1;
  let status = state.status[idx];
  if (status == 4)
    throw new Error("Cyclic dependency between fields and/or facets");
  if (status & 2)
    return status;
  state.status[idx] = 4;
  let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
  return state.status[idx] = 2 | changed;
}
function getAddr(state, addr) {
  return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
}
var languageData = /* @__PURE__ */ Facet.define();
var allowMultipleSelections = /* @__PURE__ */ Facet.define({
  combine: (values2) => values2.some((v3) => v3),
  static: true
});
var lineSeparator = /* @__PURE__ */ Facet.define({
  combine: (values2) => values2.length ? values2[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: (values2) => values2.length ? values2[0] : false
});
var Annotation = class {
  /**
  @internal
  */
  constructor(type, value2) {
    this.type = type;
    this.value = value2;
  }
  /**
  Define a new type of annotation.
  */
  static define() {
    return new AnnotationType();
  }
};
var AnnotationType = class {
  /**
  Create an instance of this annotation.
  */
  of(value2) {
    return new Annotation(this, value2);
  }
};
var StateEffectType = class {
  /**
  @internal
  */
  constructor(map5) {
    this.map = map5;
  }
  /**
  Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
  type.
  */
  of(value2) {
    return new StateEffect(this, value2);
  }
};
var StateEffect = class _StateEffect {
  /**
  @internal
  */
  constructor(type, value2) {
    this.type = type;
    this.value = value2;
  }
  /**
  Map this effect through a position mapping. Will return
  `undefined` when that ends up deleting the effect.
  */
  map(mapping) {
    let mapped = this.type.map(this.value, mapping);
    return mapped === void 0 ? void 0 : mapped == this.value ? this : new _StateEffect(this.type, mapped);
  }
  /**
  Tells you whether this effect object is of a given
  [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
  */
  is(type) {
    return this.type == type;
  }
  /**
  Define a new effect type. The type parameter indicates the type
  of values that his effect holds. It should be a type that
  doesn't include `undefined`, since that is used in
  [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
  removed.
  */
  static define(spec = {}) {
    return new StateEffectType(spec.map || ((v3) => v3));
  }
  /**
  Map an array of effects through a change set.
  */
  static mapEffects(effects, mapping) {
    if (!effects.length)
      return effects;
    let result2 = [];
    for (let effect2 of effects) {
      let mapped = effect2.map(mapping);
      if (mapped)
        result2.push(mapped);
    }
    return result2;
  }
};
StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
var Transaction2 = class _Transaction {
  constructor(startState, changes, selection, effects, annotations, scrollIntoView3) {
    this.startState = startState;
    this.changes = changes;
    this.selection = selection;
    this.effects = effects;
    this.annotations = annotations;
    this.scrollIntoView = scrollIntoView3;
    this._doc = null;
    this._state = null;
    if (selection)
      checkSelection(selection, changes.newLength);
    if (!annotations.some((a3) => a3.type == _Transaction.time))
      this.annotations = annotations.concat(_Transaction.time.of(Date.now()));
  }
  /**
  @internal
  */
  static create(startState, changes, selection, effects, annotations, scrollIntoView3) {
    return new _Transaction(startState, changes, selection, 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 e3 = this.annotation(_Transaction.userEvent);
    return !!(e3 && (e3 == event2 || e3.length > event2.length && e3.slice(0, event2.length) == event2 && e3[event2.length] == "."));
  }
};
Transaction2.time = /* @__PURE__ */ Annotation.define();
Transaction2.userEvent = /* @__PURE__ */ Annotation.define();
Transaction2.addToHistory = /* @__PURE__ */ Annotation.define();
Transaction2.remote = /* @__PURE__ */ Annotation.define();
function joinRanges(a3, b3) {
  let result2 = [];
  for (let iA = 0, iB = 0; ; ) {
    let from2, to;
    if (iA < a3.length && (iB == b3.length || b3[iB] >= a3[iA])) {
      from2 = a3[iA++];
      to = a3[iA++];
    } else if (iB < b3.length) {
      from2 = b3[iB++];
      to = b3[iB++];
    } else
      return result2;
    if (!result2.length || result2[result2.length - 1] < from2)
      result2.push(from2, to);
    else if (result2[result2.length - 1] < to)
      result2[result2.length - 1] = to;
  }
}
function mergeTransaction(a3, b3, sequential) {
  var _a4;
  let mapForA, mapForB, changes;
  if (sequential) {
    mapForA = b3.changes;
    mapForB = ChangeSet.empty(b3.changes.length);
    changes = a3.changes.compose(b3.changes);
  } else {
    mapForA = b3.changes.map(a3.changes);
    mapForB = a3.changes.mapDesc(b3.changes, true);
    changes = a3.changes.compose(mapForA);
  }
  return {
    changes,
    selection: b3.selection ? b3.selection.map(mapForB) : (_a4 = a3.selection) === null || _a4 === void 0 ? void 0 : _a4.map(mapForA),
    effects: StateEffect.mapEffects(a3.effects, mapForA).concat(StateEffect.mapEffects(b3.effects, mapForB)),
    annotations: a3.annotations.length ? a3.annotations.concat(b3.annotations) : b3.annotations,
    scrollIntoView: a3.scrollIntoView || b3.scrollIntoView
  };
}
function resolveTransactionInner(state, spec, docSize) {
  let sel = spec.selection, annotations = asArray3(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, state.facet(lineSeparator)),
    selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
    effects: asArray3(spec.effects),
    annotations,
    scrollIntoView: !!spec.scrollIntoView
  };
}
function resolveTransaction(state, specs, filter4) {
  let s3 = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
  if (specs.length && specs[0].filter === false)
    filter4 = false;
  for (let i3 = 1; i3 < specs.length; i3++) {
    if (specs[i3].filter === false)
      filter4 = false;
    let seq2 = !!specs[i3].sequential;
    s3 = mergeTransaction(s3, resolveTransactionInner(state, specs[i3], seq2 ? s3.changes.newLength : state.doc.length), seq2);
  }
  let tr2 = Transaction2.create(state, s3.changes, s3.selection, s3.effects, s3.annotations, s3.scrollIntoView);
  return extendTransaction(filter4 ? filterTransaction(tr2) : tr2);
}
function filterTransaction(tr2) {
  let state = tr2.startState;
  let result2 = true;
  for (let filter4 of state.facet(changeFilter)) {
    let value2 = filter4(tr2);
    if (value2 === false) {
      result2 = false;
      break;
    }
    if (Array.isArray(value2))
      result2 = result2 === true ? value2 : joinRanges(result2, value2);
  }
  if (result2 !== true) {
    let changes, back;
    if (result2 === false) {
      back = tr2.changes.invertedDesc;
      changes = ChangeSet.empty(state.doc.length);
    } else {
      let filtered = tr2.changes.filter(result2);
      changes = filtered.changes;
      back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
    }
    tr2 = Transaction2.create(state, changes, tr2.selection && tr2.selection.map(back), StateEffect.mapEffects(tr2.effects, back), tr2.annotations, tr2.scrollIntoView);
  }
  let filters = state.facet(transactionFilter);
  for (let i3 = filters.length - 1; i3 >= 0; i3--) {
    let filtered = filters[i3](tr2);
    if (filtered instanceof Transaction2)
      tr2 = filtered;
    else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction2)
      tr2 = filtered[0];
    else
      tr2 = resolveTransaction(state, asArray3(filtered), false);
  }
  return tr2;
}
function extendTransaction(tr2) {
  let state = tr2.startState, extenders = state.facet(transactionExtender), spec = tr2;
  for (let i3 = extenders.length - 1; i3 >= 0; i3--) {
    let extension = extenders[i3](tr2);
    if (extension && Object.keys(extension).length)
      spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr2.changes.newLength), true);
  }
  return spec == tr2 ? tr2 : Transaction2.create(state, tr2.changes, tr2.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
var none = [];
function asArray3(value2) {
  return value2 == null ? none : Array.isArray(value2) ? value2 : [value2];
}
var CharCategory = /* @__PURE__ */ function(CharCategory2) {
  CharCategory2[CharCategory2["Word"] = 0] = "Word";
  CharCategory2[CharCategory2["Space"] = 1] = "Space";
  CharCategory2[CharCategory2["Other"] = 2] = "Other";
  return CharCategory2;
}(CharCategory || (CharCategory = {}));
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 (_5) {
}
function hasWordChar(str) {
  if (wordChar)
    return wordChar.test(str);
  for (let i3 = 0; i3 < str.length; i3++) {
    let ch = str[i3];
    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 i3 = 0; i3 < wordChars.length; i3++)
      if (char.indexOf(wordChars[i3]) > -1)
        return CharCategory.Word;
    return CharCategory.Other;
  };
}
var EditorState2 = class _EditorState {
  constructor(config3, doc4, selection, values2, computeSlot, tr2) {
    this.config = config3;
    this.doc = doc4;
    this.selection = selection;
    this.values = values2;
    this.status = config3.statusTemplate.slice();
    this.computeSlot = computeSlot;
    if (tr2)
      tr2._state = this;
    for (let i3 = 0; i3 < this.config.dynamicSlots.length; i3++)
      ensureAddr(this, i3 << 1);
    this.computeSlot = null;
  }
  field(field2, require2 = true) {
    let addr = this.config.address[field2.id];
    if (addr == null) {
      if (require2)
        throw new RangeError("Field is not present in this state");
      return void 0;
    }
    ensureAddr(this, addr);
    return getAddr(this, addr);
  }
  /**
  Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
  state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
  can be passed. Unless
  [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
  [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
  are assumed to start in the _current_ document (not the document
  produced by previous specs), and its
  [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
  [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
  to the document created by its _own_ changes. The resulting
  transaction contains the combined effect of all the different
  specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
  specs take precedence over earlier ones.
  */
  update(...specs) {
    return resolveTransaction(this, specs, true);
  }
  /**
  @internal
  */
  applyTransaction(tr2) {
    let conf = this.config, { base: base3, compartments } = conf;
    for (let effect2 of tr2.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;
        base3 = effect2.value;
      } else if (effect2.is(StateEffect.appendConfig)) {
        conf = null;
        base3 = asArray3(base3).concat(effect2.value);
      }
    }
    let startValues;
    if (!conf) {
      conf = Configuration2.resolve(base3, compartments, this);
      let intermediateState = new _EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
      startValues = intermediateState.values;
    } else {
      startValues = tr2.startState.values.slice();
    }
    let selection = tr2.startState.facet(allowMultipleSelections) ? tr2.newSelection : tr2.newSelection.asSingle();
    new _EditorState(conf, tr2.newDoc, selection, startValues, (state, slot) => slot.update(state, tr2), tr2);
  }
  /**
  Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
  replaces every selection range with the given content.
  */
  replaceSelection(text3) {
    if (typeof text3 == "string")
      text3 = this.toText(text3);
    return this.changeByRange((range2) => ({
      changes: { from: range2.from, to: range2.to, insert: text3 },
      range: EditorSelection.cursor(range2.from + text3.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(f3) {
    let sel = this.selection;
    let result1 = f3(sel.ranges[0]);
    let changes = this.changes(result1.changes), ranges = [result1.range];
    let effects = asArray3(result1.effects);
    for (let i3 = 1; i3 < sel.ranges.length; i3++) {
      let result2 = f3(sel.ranges[i3]);
      let newChanges = this.changes(result2.changes), newMapped = newChanges.map(changes);
      for (let j = 0; j < i3; j++)
        ranges[j] = ranges[j].map(newMapped);
      let mapBy = changes.mapDesc(newChanges, true);
      ranges.push(result2.range.map(mapBy));
      changes = changes.compose(newMapped);
      effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray3(result2.effects), mapBy));
    }
    return {
      changes,
      selection: EditorSelection.create(ranges, sel.mainIndex),
      effects
    };
  }
  /**
  Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
  description, taking the state's document length and line
  separator into account.
  */
  changes(spec = []) {
    if (spec instanceof ChangeSet)
      return spec;
    return ChangeSet.of(spec, this.doc.length, this.facet(_EditorState.lineSeparator));
  }
  /**
  Using the state's [line
  separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
  [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
  */
  toText(string3) {
    return Text.of(string3.split(this.facet(_EditorState.lineSeparator) || DefaultSplit));
  }
  /**
  Return the given range of the document as a string.
  */
  sliceDoc(from2 = 0, to = this.doc.length) {
    return this.doc.sliceString(from2, to, this.lineBreak);
  }
  /**
  Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
  */
  facet(facet) {
    let addr = this.config.address[facet.id];
    if (addr == null)
      return facet.default;
    ensureAddr(this, addr);
    return getAddr(this, addr);
  }
  /**
  Convert this state to a JSON-serializable object. When custom
  fields should be serialized, you can pass them in as an object
  mapping property names (in the resulting object, which should
  not use `doc` or `selection`) to fields.
  */
  toJSON(fields2) {
    let result2 = {
      doc: this.sliceDoc(),
      selection: this.selection.toJSON()
    };
    if (fields2)
      for (let prop2 in fields2) {
        let value2 = fields2[prop2];
        if (value2 instanceof StateField && this.config.address[value2.id] != null)
          result2[prop2] = value2.spec.toJSON(this.field(fields2[prop2]), this);
      }
    return result2;
  }
  /**
  Deserialize a state from its JSON representation. When custom
  fields should be deserialized, pass the same object you passed
  to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
  third argument.
  */
  static fromJSON(json2, config3 = {}, fields2) {
    if (!json2 || typeof json2.doc != "string")
      throw new RangeError("Invalid JSON representation for EditorState");
    let fieldInit = [];
    if (fields2)
      for (let prop2 in fields2) {
        if (Object.prototype.hasOwnProperty.call(json2, prop2)) {
          let field2 = fields2[prop2], value2 = json2[prop2];
          fieldInit.push(field2.init((state) => field2.spec.fromJSON(value2, state)));
        }
      }
    return _EditorState.create({
      doc: json2.doc,
      selection: EditorSelection.fromJSON(json2.selection),
      extensions: config3.extensions ? fieldInit.concat([config3.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(config3 = {}) {
    let configuration = Configuration2.resolve(config3.extensions || [], /* @__PURE__ */ new Map());
    let doc4 = config3.doc instanceof Text ? config3.doc : Text.of((config3.doc || "").split(configuration.staticFacet(_EditorState.lineSeparator) || DefaultSplit));
    let selection = !config3.selection ? EditorSelection.single(0) : config3.selection instanceof EditorSelection ? config3.selection : EditorSelection.single(config3.selection.anchor, config3.selection.head);
    checkSelection(selection, doc4.length);
    if (!configuration.staticFacet(allowMultipleSelections))
      selection = selection.asSingle();
    return new _EditorState(configuration, doc4, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
  }
  /**
  The size (in columns) of a tab in the document, determined by
  the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
  */
  get tabSize() {
    return this.facet(_EditorState.tabSize);
  }
  /**
  Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
  string for this state.
  */
  get lineBreak() {
    return this.facet(_EditorState.lineSeparator) || "\n";
  }
  /**
  Returns true when the editor is
  [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
  */
  get readOnly() {
    return this.facet(readOnly);
  }
  /**
  Look up a translation for the given phrase (via the
  [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
  original string if no translation is found.
  
  If additional arguments are passed, they will be inserted in
  place of markers like `$1` (for the first value) and `$2`, etc.
  A single `$` is equivalent to `$1`, and `$$` will produce a
  literal dollar sign.
  */
  phrase(phrase2, ...insert4) {
    for (let map5 of this.facet(_EditorState.phrases))
      if (Object.prototype.hasOwnProperty.call(map5, phrase2)) {
        phrase2 = map5[phrase2];
        break;
      }
    if (insert4.length)
      phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m3, i3) => {
        if (i3 == "$")
          return "$";
        let n4 = +(i3 || 1);
        return !n4 || n4 > insert4.length ? m3 : insert4[n4 - 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(name2, pos, side = -1) {
    let values2 = [];
    for (let provider of this.facet(languageData)) {
      for (let result2 of provider(this, pos, side)) {
        if (Object.prototype.hasOwnProperty.call(result2, name2))
          values2.push(result2[name2]);
      }
    }
    return values2;
  }
  /**
  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) {
    let chars = this.languageDataAt("wordChars", at);
    return makeCategorizer(chars.length ? chars[0] : "");
  }
  /**
  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: text3, from: from2, length } = this.doc.lineAt(pos);
    let cat = this.charCategorizer(pos);
    let start = pos - from2, end = pos - from2;
    while (start > 0) {
      let prev = findClusterBreak2(text3, start, false);
      if (cat(text3.slice(prev, start)) != CharCategory.Word)
        break;
      start = prev;
    }
    while (end < length) {
      let next2 = findClusterBreak2(text3, end);
      if (cat(text3.slice(end, next2)) != CharCategory.Word)
        break;
      end = next2;
    }
    return start == end ? null : EditorSelection.range(start + from2, end + from2);
  }
};
EditorState2.allowMultipleSelections = allowMultipleSelections;
EditorState2.tabSize = /* @__PURE__ */ Facet.define({
  combine: (values2) => values2.length ? values2[0] : 4
});
EditorState2.lineSeparator = lineSeparator;
EditorState2.readOnly = readOnly;
EditorState2.phrases = /* @__PURE__ */ Facet.define({
  compare(a3, b3) {
    let kA = Object.keys(a3), kB = Object.keys(b3);
    return kA.length == kB.length && kA.every((k2) => a3[k2] == b3[k2]);
  }
});
EditorState2.languageData = languageData;
EditorState2.changeFilter = changeFilter;
EditorState2.transactionFilter = transactionFilter;
EditorState2.transactionExtender = transactionExtender;
Compartment.reconfigure = /* @__PURE__ */ StateEffect.define();
function combineConfig(configs, defaults5, combine = {}) {
  let result2 = {};
  for (let config3 of configs)
    for (let key2 of Object.keys(config3)) {
      let value2 = config3[key2], current = result2[key2];
      if (current === void 0)
        result2[key2] = value2;
      else if (current === value2 || value2 === void 0) ;
      else if (Object.hasOwnProperty.call(combine, key2))
        result2[key2] = combine[key2](current, value2);
      else
        throw new Error("Config merge conflict for field " + key2);
    }
  for (let key2 in defaults5)
    if (result2[key2] === void 0)
      result2[key2] = defaults5[key2];
  return result2;
}
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(from2, to = from2) {
    return Range.create(from2, to, this);
  }
};
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
RangeValue.prototype.point = false;
RangeValue.prototype.mapMode = MapMode.TrackDel;
function cmpVal(a3, b3) {
  return a3 == b3 || a3.constructor == b3.constructor && a3.eq(b3);
}
var Range = class _Range {
  constructor(from2, to, value2) {
    this.from = from2;
    this.to = to;
    this.value = value2;
  }
  /**
  @internal
  */
  static create(from2, to, value2) {
    return new _Range(from2, to, value2);
  }
};
function cmpRange(a3, b3) {
  return a3.from - b3.from || a3.value.startSide - b3.value.startSide;
}
var Chunk = class _Chunk {
  constructor(from2, to, value2, maxPoint) {
    this.from = from2;
    this.to = to;
    this.value = value2;
    this.maxPoint = maxPoint;
  }
  get length() {
    return this.to[this.to.length - 1];
  }
  // Find the index of the given position and side. Use the ranges'
  // `from` pos when `end == false`, `to` when `end == true`.
  findIndex(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, from2, to, f3) {
    for (let i3 = this.findIndex(from2, -1e9, true), e3 = this.findIndex(to, 1e9, false, i3); i3 < e3; i3++)
      if (f3(this.from[i3] + offset, this.to[i3] + offset, this.value[i3]) === false)
        return false;
  }
  map(offset, changes) {
    let value2 = [], from2 = [], to = [], newPos = -1, maxPoint = -1;
    for (let i3 = 0; i3 < this.value.length; i3++) {
      let val = this.value[i3], curFrom = this.from[i3] + offset, curTo = this.to[i3] + offset, newFrom, newTo;
      if (curFrom == curTo) {
        let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
        if (mapped == null)
          continue;
        newFrom = newTo = mapped;
        if (val.startSide != val.endSide) {
          newTo = changes.mapPos(curFrom, val.endSide);
          if (newTo < newFrom)
            continue;
        }
      } else {
        newFrom = changes.mapPos(curFrom, val.startSide);
        newTo = changes.mapPos(curTo, val.endSide);
        if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
          continue;
      }
      if ((newTo - newFrom || val.endSide - val.startSide) < 0)
        continue;
      if (newPos < 0)
        newPos = newFrom;
      if (val.point)
        maxPoint = Math.max(maxPoint, newTo - newFrom);
      value2.push(val);
      from2.push(newFrom - newPos);
      to.push(newTo - newPos);
    }
    return { mapped: value2.length ? new _Chunk(from2, to, value2, maxPoint) : null, pos: newPos };
  }
};
var RangeSet = class _RangeSet {
  constructor(chunkPos, chunk2, nextLayer, maxPoint) {
    this.chunkPos = chunkPos;
    this.chunk = chunk2;
    this.nextLayer = nextLayer;
    this.maxPoint = maxPoint;
  }
  /**
  @internal
  */
  static create(chunkPos, chunk2, nextLayer, maxPoint) {
    return new _RangeSet(chunkPos, chunk2, nextLayer, maxPoint);
  }
  /**
  @internal
  */
  get length() {
    let last3 = this.chunk.length - 1;
    return last3 < 0 ? 0 : Math.max(this.chunkEnd(last3), this.nextLayer.length);
  }
  /**
  The number of ranges in the set.
  */
  get size() {
    if (this.isEmpty)
      return 0;
    let size4 = this.nextLayer.size;
    for (let chunk2 of this.chunk)
      size4 += chunk2.value.length;
    return size4;
  }
  /**
  @internal
  */
  chunkEnd(index2) {
    return this.chunkPos[index2] + this.chunk[index2].length;
  }
  /**
  Update the range set, optionally adding new ranges or filtering
  out existing ones.
  
  (Note: The type parameter is just there as a kludge to work
  around TypeScript variance issues that prevented `RangeSet<X>`
  from being a subtype of `RangeSet<Y>` when `X` is a subtype of
  `Y`.)
  */
  update(updateSpec) {
    let { add: add4 = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
    let filter4 = updateSpec.filter;
    if (add4.length == 0 && !filter4)
      return this;
    if (sort)
      add4 = add4.slice().sort(cmpRange);
    if (this.isEmpty)
      return add4.length ? _RangeSet.of(add4) : this;
    let cur2 = new LayerCursor(this, null, -1).goto(0), i3 = 0, spill = [];
    let builder = new RangeSetBuilder();
    while (cur2.value || i3 < add4.length) {
      if (i3 < add4.length && (cur2.from - add4[i3].from || cur2.startSide - add4[i3].value.startSide) >= 0) {
        let range2 = add4[i3++];
        if (!builder.addInner(range2.from, range2.to, range2.value))
          spill.push(range2);
      } else if (cur2.rangeIndex == 1 && cur2.chunkIndex < this.chunk.length && (i3 == add4.length || this.chunkEnd(cur2.chunkIndex) < add4[i3].from) && (!filter4 || filterFrom > this.chunkEnd(cur2.chunkIndex) || filterTo < this.chunkPos[cur2.chunkIndex]) && builder.addChunk(this.chunkPos[cur2.chunkIndex], this.chunk[cur2.chunkIndex])) {
        cur2.nextChunk();
      } else {
        if (!filter4 || filterFrom > cur2.to || filterTo < cur2.from || filter4(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: filter4, 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 i3 = 0; i3 < this.chunk.length; i3++) {
      let start = this.chunkPos[i3], chunk2 = this.chunk[i3];
      let touch = changes.touchesRange(start, start + chunk2.length);
      if (touch === false) {
        maxPoint = Math.max(maxPoint, chunk2.maxPoint);
        chunks.push(chunk2);
        chunkPos.push(changes.mapPos(start));
      } else if (touch === true) {
        let { mapped, pos } = chunk2.map(start, 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(from2, to, f3) {
    if (this.isEmpty)
      return;
    for (let i3 = 0; i3 < this.chunk.length; i3++) {
      let start = this.chunkPos[i3], chunk2 = this.chunk[i3];
      if (to >= start && from2 <= start + chunk2.length && chunk2.between(start, from2 - start, to - start, f3) === false)
        return;
    }
    this.nextLayer.between(from2, to, f3);
  }
  /**
  Iterate over the ranges in this set, in order, including all
  ranges that end at or after `from`.
  */
  iter(from2 = 0) {
    return HeapCursor.from([this]).goto(from2);
  }
  /**
  @internal
  */
  get isEmpty() {
    return this.nextLayer == this;
  }
  /**
  Iterate over the ranges in a collection of sets, in order,
  starting from `from`.
  */
  static iter(sets, from2 = 0) {
    return HeapCursor.from(sets).goto(from2);
  }
  /**
  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 a3 = oldSets.filter((set4) => set4.maxPoint > 0 || !set4.isEmpty && set4.maxPoint >= minPointSize);
    let b3 = newSets.filter((set4) => set4.maxPoint > 0 || !set4.isEmpty && set4.maxPoint >= minPointSize);
    let sharedChunks = findSharedChunks(a3, b3, textDiff);
    let sideA = new SpanCursor(a3, sharedChunks, minPointSize);
    let sideB = new SpanCursor(b3, sharedChunks, minPointSize);
    textDiff.iterGaps((fromA, fromB, length) => compare3(sideA, fromA, sideB, fromB, length, comparator));
    if (textDiff.empty && textDiff.length == 0)
      compare3(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, from2 = 0, to) {
    if (to == null)
      to = 1e9 - 1;
    let a3 = oldSets.filter((set4) => !set4.isEmpty && newSets.indexOf(set4) < 0);
    let b3 = newSets.filter((set4) => !set4.isEmpty && oldSets.indexOf(set4) < 0);
    if (a3.length != b3.length)
      return false;
    if (!a3.length)
      return true;
    let sharedChunks = findSharedChunks(a3, b3);
    let sideA = new SpanCursor(a3, sharedChunks, 0).goto(from2), sideB = new SpanCursor(b3, sharedChunks, 0).goto(from2);
    for (; ; ) {
      if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !cmpVal(sideA.point, 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, from2, to, iterator, minPointSize = -1) {
    let cursor = new SpanCursor(sets, null, minPointSize).goto(from2), pos = from2;
    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 < from2 ? 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, sort = false) {
    let build = new RangeSetBuilder();
    for (let range2 of ranges instanceof Range ? [ranges] : sort ? 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 result2 = sets[sets.length - 1];
    for (let i3 = sets.length - 2; i3 >= 0; i3--) {
      for (let layer2 = sets[i3]; layer2 != _RangeSet.empty; layer2 = layer2.nextLayer)
        result2 = new _RangeSet(layer2.chunkPos, layer2.chunk, result2, Math.max(layer2.maxPoint, result2.maxPoint));
    }
    return result2;
  }
};
RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1);
function lazySort(ranges) {
  if (ranges.length > 1)
    for (let prev = ranges[0], i3 = 1; i3 < ranges.length; i3++) {
      let cur2 = ranges[i3];
      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(from2, to, value2) {
    if (!this.addInner(from2, to, value2))
      (this.nextLayer || (this.nextLayer = new _RangeSetBuilder())).add(from2, to, value2);
  }
  /**
  @internal
  */
  addInner(from2, to, value2) {
    let diff = from2 - this.lastTo || value2.startSide - this.last.endSide;
    if (diff <= 0 && (from2 - this.lastFrom || value2.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 = from2;
    this.from.push(from2 - this.chunkStart);
    this.to.push(to - this.chunkStart);
    this.last = value2;
    this.lastFrom = from2;
    this.lastTo = to;
    this.value.push(value2);
    if (value2.point)
      this.maxPoint = Math.max(this.maxPoint, to - from2);
    return true;
  }
  /**
  @internal
  */
  addChunk(from2, chunk2) {
    if ((from2 - this.lastTo || chunk2.value[0].startSide - this.last.endSide) < 0)
      return false;
    if (this.from.length)
      this.finishChunk(true);
    this.setMaxPoint = Math.max(this.setMaxPoint, chunk2.maxPoint);
    this.chunks.push(chunk2);
    this.chunkPos.push(from2);
    let last3 = chunk2.value.length - 1;
    this.last = chunk2.value[last3];
    this.lastFrom = chunk2.from[last3] + from2;
    this.lastTo = chunk2.to[last3] + from2;
    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 result2 = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next2) : next2, this.setMaxPoint);
    this.from = null;
    return result2;
  }
};
function findSharedChunks(a3, b3, textDiff) {
  let inA = /* @__PURE__ */ new Map();
  for (let set4 of a3)
    for (let i3 = 0; i3 < set4.chunk.length; i3++)
      if (set4.chunk[i3].maxPoint <= 0)
        inA.set(set4.chunk[i3], set4.chunkPos[i3]);
  let shared = /* @__PURE__ */ new Set();
  for (let set4 of b3)
    for (let i3 = 0; i3 < set4.chunk.length; i3++) {
      let known = inA.get(set4.chunk[i3]);
      if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set4.chunkPos[i3] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set4.chunk[i3].length)))
        shared.add(set4.chunk[i3]);
    }
  return shared;
}
var LayerCursor = class {
  constructor(layer2, skip3, minPoint, rank = 0) {
    this.layer = layer2;
    this.skip = skip3;
    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], chunk2 = this.layer.chunk[this.chunkIndex];
        let from2 = chunkPos + chunk2.from[this.rangeIndex];
        this.from = from2;
        this.to = chunkPos + chunk2.to[this.rangeIndex];
        this.value = chunk2.value[this.rangeIndex];
        this.setRangeIndex(this.rangeIndex + 1);
        if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
          break;
      }
    }
  }
  setRangeIndex(index2) {
    if (index2 == this.layer.chunk[this.chunkIndex].value.length) {
      this.chunkIndex++;
      if (this.skip) {
        while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
          this.chunkIndex++;
      }
      this.rangeIndex = 0;
    } else {
      this.rangeIndex = index2;
    }
  }
  nextChunk() {
    this.chunkIndex++;
    this.rangeIndex = 0;
    this.next();
  }
  compare(other) {
    return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
  }
};
var HeapCursor = class _HeapCursor {
  constructor(heap) {
    this.heap = heap;
  }
  static from(sets, skip3 = null, minPoint = -1) {
    let heap = [];
    for (let i3 = 0; i3 < sets.length; i3++) {
      for (let cur2 = sets[i3]; !cur2.isEmpty; cur2 = cur2.nextLayer) {
        if (cur2.maxPoint >= minPoint)
          heap.push(new LayerCursor(cur2, skip3, minPoint, i3));
      }
    }
    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 i3 = this.heap.length >> 1; i3 >= 0; i3--)
      heapBubble(this.heap, i3);
    this.next();
    return this;
  }
  forward(pos, side) {
    for (let cur2 of this.heap)
      cur2.forward(pos, side);
    for (let i3 = this.heap.length >> 1; i3 >= 0; i3--)
      heapBubble(this.heap, i3);
    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 top2 = this.heap[0];
      this.from = top2.from;
      this.to = top2.to;
      this.value = top2.value;
      this.rank = top2.rank;
      if (top2.value)
        top2.next();
      heapBubble(this.heap, 0);
    }
  }
};
function heapBubble(heap, index2) {
  for (let cur2 = heap[index2]; ; ) {
    let childIndex = (index2 << 1) + 1;
    if (childIndex >= heap.length)
      break;
    let child = heap[childIndex];
    if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
      child = heap[childIndex + 1];
      childIndex++;
    }
    if (cur2.compare(child) < 0)
      break;
    heap[childIndex] = cur2;
    heap[index2] = child;
    index2 = childIndex;
  }
}
var SpanCursor = class {
  constructor(sets, skip3, 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, skip3, 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(index2) {
    remove(this.active, index2);
    remove(this.activeTo, index2);
    remove(this.activeRank, index2);
    this.minActive = findMinIndex(this.active, this.activeTo);
  }
  addActive(trackOpen) {
    let i3 = 0, { value: value2, to, rank } = this.cursor;
    while (i3 < this.activeRank.length && (rank - this.activeRank[i3] || to - this.activeTo[i3]) > 0)
      i3++;
    insert2(this.active, i3, value2);
    insert2(this.activeTo, i3, to);
    insert2(this.activeRank, i3, rank);
    if (trackOpen)
      insert2(trackOpen, i3, 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 from2 = this.to, wasPoint = this.point;
    this.point = null;
    let trackOpen = this.openStart < 0 ? [] : null;
    for (; ; ) {
      let a3 = this.minActive;
      if (a3 > -1 && (this.activeTo[a3] - this.cursor.from || this.active[a3].endSide - this.cursor.startSide) < 0) {
        if (this.activeTo[a3] > from2) {
          this.to = this.activeTo[a3];
          this.endSide = this.active[a3].endSide;
          break;
        }
        this.removeActive(a3);
        if (trackOpen)
          remove(trackOpen, a3);
      } else if (!this.cursor.value) {
        this.to = this.endSide = 1e9;
        break;
      } else if (this.cursor.from > from2) {
        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 i3 = trackOpen.length - 1; i3 >= 0 && trackOpen[i3] < from2; i3--)
        this.openStart++;
    }
  }
  activeForPoint(to) {
    if (!this.active.length)
      return this.active;
    let active = [];
    for (let i3 = this.active.length - 1; i3 >= 0; i3--) {
      if (this.activeRank[i3] < this.pointRank)
        break;
      if (this.activeTo[i3] > to || this.activeTo[i3] == to && this.active[i3].endSide >= this.point.endSide)
        active.push(this.active[i3]);
    }
    return active.reverse();
  }
  openEnd(to) {
    let open = 0;
    for (let i3 = this.activeTo.length - 1; i3 >= 0 && this.activeTo[i3] > to; i3--)
      open++;
    return open;
  }
};
function compare3(a3, startA, b3, startB, length, comparator) {
  a3.goto(startA);
  b3.goto(startB);
  let endB = startB + length;
  let pos = startB, dPos = startB - startA;
  let bounds = !!comparator.boundChange;
  for (let boundChange = false; ; ) {
    let dEnd = a3.to + dPos - b3.to, diff = dEnd || a3.endSide - b3.endSide;
    let end = diff < 0 ? a3.to + dPos : b3.to, clipEnd = Math.min(end, endB);
    let point = a3.point || b3.point;
    if (point) {
      if (!(a3.point && b3.point && cmpVal(a3.point, b3.point) && sameValues(a3.activeForPoint(a3.to), b3.activeForPoint(b3.to))))
        comparator.comparePoint(pos, clipEnd, a3.point, b3.point);
      boundChange = false;
    } else {
      if (boundChange)
        comparator.boundChange(pos);
      if (clipEnd > pos && !sameValues(a3.active, b3.active))
        comparator.compareRange(pos, clipEnd, a3.active, b3.active);
      if (bounds && clipEnd < endB && (dEnd || a3.openEnd(end) != b3.openEnd(end)))
        boundChange = true;
    }
    if (end > endB)
      break;
    pos = end;
    if (diff <= 0)
      a3.next();
    if (diff >= 0)
      b3.next();
  }
}
function sameValues(a3, b3) {
  if (a3.length != b3.length)
    return false;
  for (let i3 = 0; i3 < a3.length; i3++)
    if (a3[i3] != b3[i3] && !cmpVal(a3[i3], b3[i3]))
      return false;
  return true;
}
function remove(array, index2) {
  for (let i3 = index2, e3 = array.length - 1; i3 < e3; i3++)
    array[i3] = array[i3 + 1];
  array.pop();
}
function insert2(array, index2, value2) {
  for (let i3 = array.length - 1; i3 >= index2; i3--)
    array[i3 + 1] = array[i3];
  array[index2] = value2;
}
function findMinIndex(value2, array) {
  let found2 = -1, foundPos = 1e9;
  for (let i3 = 0; i3 < array.length; i3++)
    if ((array[i3] - foundPos || value2[i3].endSide - value2[found2].endSide) < 0) {
      found2 = i3;
      foundPos = array[i3];
    }
  return found2;
}
function countColumn(string3, tabSize, to = string3.length) {
  let n4 = 0;
  for (let i3 = 0; i3 < to && i3 < string3.length; ) {
    if (string3.charCodeAt(i3) == 9) {
      n4 += tabSize - n4 % tabSize;
      i3++;
    } else {
      n4++;
      i3 = findClusterBreak2(string3, i3);
    }
  }
  return n4;
}
function findColumn(string3, col, tabSize, strict) {
  for (let i3 = 0, n4 = 0; ; ) {
    if (n4 >= col)
      return i3;
    if (i3 == string3.length)
      break;
    n4 += string3.charCodeAt(i3) == 9 ? tabSize - n4 % tabSize : 1;
    i3 = findClusterBreak2(string3, i3);
  }
  return strict === true ? -1 : string3.length;
}

// node_modules/style-mod/src/style-mod.js
var C2 = "\u037C";
var COUNT = typeof Symbol == "undefined" ? "__" + C2 : Symbol.for(C2);
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, options2) {
    this.rules = [];
    let { finish } = options2 || {};
    function splitSelector(selector) {
      return /^@/.test(selector) ? [selector] : selector.split(/,\s*/);
    }
    function render3(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 value2 = spec2[prop2];
        if (/&/.test(prop2)) {
          render3(
            prop2.split(/,\s*/).map((part) => selectors.map((sel) => part.replace(/&/, sel))).reduce((a3, b3) => a3.concat(b3)),
            value2,
            target
          );
        } else if (value2 && typeof value2 == "object") {
          if (!isAt) throw new RangeError("The value of a property (" + prop2 + ") should be a primitive value.");
          render3(splitSelector(prop2), value2, local, keyframes);
        } else if (value2 != null) {
          local.push(prop2.replace(/_.*/, "").replace(/[A-Z]/g, (l3) => "-" + l3.toLowerCase()) + ": " + value2 + ";");
        }
      }
      if (local.length || keyframes) {
        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}");
      }
    }
    for (let prop2 in spec) render3(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 id = top[COUNT] || 1;
    top[COUNT] = id + 1;
    return C2 + id.toString(36);
  }
  // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
  //
  // Mount the given set of modules in the given DOM root, which ensures
  // that the CSS rules defined by the module are available in that
  // context.
  //
  // Rules are only added to the document once per root.
  //
  // Rule order will follow the order of the modules, so that rules from
  // modules later in the array take precedence of those from earlier
  // modules. If you call this function multiple times for the same root
  // in a way that changes the order of already mounted modules, the old
  // order will be changed.
  //
  // If a Content Security Policy nonce is provided, it is added to
  // the `<style>` tag generated by the library.
  static mount(root3, modules, options2) {
    let set4 = root3[SET], nonce = options2 && options2.nonce;
    if (!set4) set4 = new StyleSet(root3, nonce);
    else if (nonce) set4.setNonce(nonce);
    set4.mount(Array.isArray(modules) ? modules : [modules], root3);
  }
};
var adoptedSet = /* @__PURE__ */ new Map();
var StyleSet = class {
  constructor(root3, nonce) {
    let doc4 = root3.ownerDocument || root3, win = doc4.defaultView;
    if (!root3.head && root3.adoptedStyleSheets && win.CSSStyleSheet) {
      let adopted = adoptedSet.get(doc4);
      if (adopted) return root3[SET] = adopted;
      this.sheet = new win.CSSStyleSheet();
      adoptedSet.set(doc4, this);
    } else {
      this.styleTag = doc4.createElement("style");
      if (nonce) this.styleTag.setAttribute("nonce", nonce);
    }
    this.modules = [];
    root3[SET] = this;
  }
  mount(modules, root3) {
    let sheet = this.sheet;
    let pos = 0, j = 0;
    for (let i3 = 0; i3 < modules.length; i3++) {
      let mod = modules[i3], index2 = this.modules.indexOf(mod);
      if (index2 < j && index2 > -1) {
        this.modules.splice(index2, 1);
        j--;
        index2 = -1;
      }
      if (index2 == -1) {
        this.modules.splice(j++, 0, mod);
        if (sheet) for (let k2 = 0; k2 < mod.rules.length; k2++)
          sheet.insertRule(mod.rules[k2], pos++);
      } else {
        while (j < index2) pos += this.modules[j++].rules.length;
        pos += mod.rules.length;
        j++;
      }
    }
    if (sheet) {
      if (root3.adoptedStyleSheets.indexOf(this.sheet) < 0)
        root3.adoptedStyleSheets = [this.sheet, ...root3.adoptedStyleSheets];
    } else {
      let text3 = "";
      for (let i3 = 0; i3 < this.modules.length; i3++)
        text3 += this.modules[i3].getRules() + "\n";
      this.styleTag.textContent = text3;
      let target = root3.head || root3;
      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.es.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 chrome = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
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);
var brokenModifierNames = mac || chrome && +chrome[1] < 57;
for (i3 = 0; i3 < 10; i3++) base[48 + i3] = base[96 + i3] = String(i3);
var i3;
for (i3 = 1; i3 <= 24; i3++) base[i3 + 111] = "F" + i3;
var i3;
for (i3 = 65; i3 <= 90; i3++) {
  base[i3] = String.fromCharCode(i3 + 32);
  shift[i3] = String.fromCharCode(i3);
}
var i3;
for (code2 in base) if (!shift.hasOwnProperty(code2)) shift[code2] = base[code2];
var code2;
function keyName(event2) {
  var ignoreKey = brokenModifierNames && (event2.ctrlKey || event2.altKey || event2.metaKey) || ie && event2.shiftKey && event2.key && event2.key.length == 1 || event2.key == "Unidentified";
  var name2 = !ignoreKey && event2.key || (event2.shiftKey ? shift : base)[event2.keyCode] || event2.key || "Unidentified";
  if (name2 == "Esc") name2 = "Escape";
  if (name2 == "Del") name2 = "Delete";
  if (name2 == "Left") name2 = "ArrowLeft";
  if (name2 == "Up") name2 = "ArrowUp";
  if (name2 == "Right") name2 = "ArrowRight";
  if (name2 == "Down") name2 = "ArrowDown";
  return name2;
}

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

// node_modules/@codemirror/view/dist/index.js
var nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
var doc2 = 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 gecko2 = !ie2 && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
var chrome2 = !ie2 && /* @__PURE__ */ /Chrome\/(\d+)/.exec(nav.userAgent);
var webkit = "webkitFontSmoothing" in doc2.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 ? doc2.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
  gecko: gecko2,
  gecko_version: gecko2 ? +(/* @__PURE__ */ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  chrome: !!chrome2,
  chrome_version: chrome2 ? +chrome2[1] : 0,
  ios,
  android: /* @__PURE__ */ /Android\b/.test(nav.userAgent),
  webkit,
  webkit_version: webkit ? +(/* @__PURE__ */ /\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  safari,
  safari_version: safari ? +(/* @__PURE__ */ /\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  tabSize: doc2.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
};
function combineAttrs(source, target) {
  for (let name2 in source) {
    if (name2 == "class" && target.class)
      target.class += " " + source.class;
    else if (name2 == "style" && target.style)
      target.style += ";" + source.style;
    else
      target[name2] = source[name2];
  }
  return target;
}
var noAttrs = /* @__PURE__ */ Object.create(null);
function attrsEq(a3, b3, ignore) {
  if (a3 == b3)
    return true;
  if (!a3)
    a3 = noAttrs;
  if (!b3)
    b3 = noAttrs;
  let keysA = Object.keys(a3), keysB = Object.keys(b3);
  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 || a3[key2] !== b3[key2]))
      return false;
  }
  return true;
}
function setAttrs(dom, attrs2) {
  for (let i3 = dom.attributes.length - 1; i3 >= 0; i3--) {
    let name2 = dom.attributes[i3].name;
    if (attrs2[name2] == null)
      dom.removeAttribute(name2);
  }
  for (let name2 in attrs2) {
    let value2 = attrs2[name2];
    if (name2 == "style")
      dom.style.cssText = value2;
    else if (dom.getAttribute(name2) != value2)
      dom.setAttribute(name2, value2);
  }
}
function updateAttrs(dom, prev, attrs2) {
  let changed = false;
  if (prev) {
    for (let name2 in prev)
      if (!(attrs2 && name2 in attrs2)) {
        changed = true;
        if (name2 == "style")
          dom.style.cssText = "";
        else
          dom.removeAttribute(name2);
      }
  }
  if (attrs2) {
    for (let name2 in attrs2)
      if (!(prev && prev[name2] == attrs2[name2])) {
        changed = true;
        if (name2 == "style")
          dom.style.cssText = attrs2[name2];
        else
          dom.setAttribute(name2, attrs2[name2]);
      }
  }
  return changed;
}
function getAttrs(dom) {
  let attrs2 = /* @__PURE__ */ Object.create(null);
  for (let i3 = 0; i3 < dom.attributes.length; i3++) {
    let attr = dom.attributes[i3];
    attrs2[attr.name] = attr.value;
  }
  return attrs2;
}
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)), block3 = !!spec.block;
    side += block3 && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
    return new PointDecoration(spec, side, side, block3, spec.widget || null, false);
  }
  /**
  Create a replace decoration which replaces the given range with
  a widget, or simply hides it.
  */
  static replace(spec) {
    let block3 = !!spec.block, startSide, endSide;
    if (spec.isBlockGap) {
      startSide = -5e8;
      endSide = 4e8;
    } else {
      let { start, end } = getInclusive(spec, block3);
      startSide = (start ? block3 ? -3e8 : -1 : 5e8) - 1;
      endSide = (end ? block3 ? 2e8 : 1 : -6e8) + 1;
    }
    return new PointDecoration(spec, startSide, endSide, block3, spec.widget || null, true);
  }
  /**
  Create a line decoration, which can add DOM attributes to the
  line starting at the given position.
  */
  static line(spec) {
    return new LineDecoration(spec);
  }
  /**
  Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
  decorated range or ranges. If the ranges aren't already sorted,
  pass `true` for `sort` to make the library sort them for you.
  */
  static set(of, sort = false) {
    return RangeSet.of(of, sort);
  }
  /**
  @internal
  */
  hasHeight() {
    return this.widget ? this.widget.estimatedHeight > -1 : false;
  }
};
Decoration.none = RangeSet.empty;
var MarkDecoration = class _MarkDecoration extends Decoration {
  constructor(spec) {
    let { start, end } = getInclusive(spec);
    super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec);
    this.tagName = spec.tagName || "span";
    this.attrs = spec.class && spec.attributes ? combineAttrs(spec.attributes, { class: spec.class }) : spec.class ? { class: spec.class } : spec.attributes || noAttrs;
  }
  eq(other) {
    return this == other || other instanceof _MarkDecoration && this.tagName == other.tagName && attrsEq(this.attrs, other.attrs);
  }
  range(from2, to = from2) {
    if (from2 >= to)
      throw new RangeError("Mark decorations may not be empty");
    return super.range(from2, 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(from2, to = from2) {
    if (to != from2)
      throw new RangeError("Line decoration ranges must be zero-length");
    return super.range(from2, to);
  }
};
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
LineDecoration.prototype.point = true;
var PointDecoration = class _PointDecoration extends Decoration {
  constructor(spec, startSide, endSide, block3, widget, isReplace) {
    super(startSide, endSide, widget, spec);
    this.block = block3;
    this.isReplace = isReplace;
    this.mapMode = !block3 ? 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(from2, to = from2) {
    if (this.isReplace && (from2 > to || from2 == to && this.startSide > 0 && this.endSide <= 0))
      throw new RangeError("Invalid range for replacement decoration");
    if (!this.isReplace && to != from2)
      throw new RangeError("Widget decorations can only have zero-length ranges");
    return super.range(from2, to);
  }
};
PointDecoration.prototype.point = true;
function getInclusive(spec, block3 = false) {
  let { inclusiveStart: start, inclusiveEnd: end } = spec;
  if (start == null)
    start = spec.inclusive;
  if (end == null)
    end = spec.inclusive;
  return { start: start !== null && start !== void 0 ? start : block3, end: end !== null && end !== void 0 ? end : block3 };
}
function widgetsEq(a3, b3) {
  return a3 == b3 || !!(a3 && b3 && a3.compare(b3));
}
function addRange2(from2, to, ranges, margin = 0) {
  let last3 = ranges.length - 1;
  if (last3 >= 0 && ranges[last3] + margin >= from2)
    ranges[last3] = Math.max(ranges[last3], to);
  else
    ranges.push(from2, to);
}
var BlockWrapper = class _BlockWrapper extends RangeValue {
  constructor(tagName, attributes) {
    super();
    this.tagName = tagName;
    this.attributes = attributes;
  }
  eq(other) {
    return other == this || other instanceof _BlockWrapper && this.tagName == other.tagName && attrsEq(this.attributes, other.attributes);
  }
  /**
  Create a block wrapper object with the given tag name and
  attributes.
  */
  static create(spec) {
    return new _BlockWrapper(spec.tagName, spec.attributes || noAttrs);
  }
  /**
  Create a range set from the given block wrapper ranges.
  */
  static set(of, sort = false) {
    return RangeSet.of(of, sort);
  }
};
BlockWrapper.prototype.startSide = BlockWrapper.prototype.endSide = -1;
function getSelection2(root3) {
  let target;
  if (root3.nodeType == 11) {
    target = root3.getSelection ? root3 : root3.ownerDocument;
  } else {
    target = root3;
  }
  return target.getSelection();
}
function contains3(dom, node) {
  return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function hasSelection(dom, selection) {
  if (!selection.anchorNode)
    return false;
  try {
    return contains3(dom, selection.anchorNode);
  } catch (_5) {
    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 index2 = 0; ; index2++) {
    node = node.previousSibling;
    if (!node)
      return index2;
  }
}
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 parent = node.parentNode;
      if (!parent || parent.nodeType != 1)
        return false;
      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent;
    } 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, left) {
  let x3 = left ? rect.left : rect.right;
  return { left: x3, right: x3, 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, x3, y3, xMargin, yMargin, ltr) {
  let doc4 = dom.ownerDocument, win = doc4.defaultView || window;
  for (let cur2 = dom, stop = false; cur2 && !stop; ) {
    if (cur2.nodeType == 1) {
      let bounding, top2 = cur2 == doc4.body;
      let scaleX = 1, scaleY = 1;
      if (top2) {
        bounding = windowRect(win);
      } else {
        if (/^(fixed|sticky)$/.test(getComputedStyle(cur2).position))
          stop = true;
        if (cur2.scrollHeight <= cur2.clientHeight && cur2.scrollWidth <= cur2.clientWidth) {
          cur2 = cur2.assignedSlot || cur2.parentNode;
          continue;
        }
        let rect2 = cur2.getBoundingClientRect();
        ({ scaleX, scaleY } = getScale(cur2, rect2));
        bounding = {
          left: rect2.left,
          right: rect2.left + cur2.clientWidth * scaleX,
          top: rect2.top,
          bottom: rect2.top + cur2.clientHeight * scaleY
        };
      }
      let moveX = 0, moveY = 0;
      if (y3 == "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 = y3 == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y3 == "start" || y3 == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin;
        moveY = targetTop - bounding.top;
      }
      if (x3 == "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 = x3 == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x3 == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin;
        moveX = targetLeft - bounding.left;
      }
      if (moveX || moveY) {
        if (top2) {
          win.scrollBy(moveX, moveY);
        } else {
          let movedX = 0, movedY = 0;
          if (moveY) {
            let start = cur2.scrollTop;
            cur2.scrollTop += moveY / scaleY;
            movedY = (cur2.scrollTop - start) * scaleY;
          }
          if (moveX) {
            let start = cur2.scrollLeft;
            cur2.scrollLeft += moveX / scaleX;
            movedX = (cur2.scrollLeft - start) * scaleX;
          }
          rect = {
            left: rect.left - movedX,
            top: rect.top - movedY,
            right: rect.right - movedX,
            bottom: rect.bottom - movedY
          };
          if (movedX && Math.abs(movedX - moveX) < 1)
            x3 = "nearest";
          if (movedY && Math.abs(movedY - moveY) < 1)
            y3 = "nearest";
        }
      }
      if (top2)
        break;
      if (rect.top < bounding.top || rect.bottom > bounding.bottom || rect.left < bounding.left || rect.right > bounding.right)
        rect = {
          left: Math.max(rect.left, bounding.left),
          right: Math.min(rect.right, bounding.right),
          top: Math.max(rect.top, bounding.top),
          bottom: Math.min(rect.bottom, bounding.bottom)
        };
      cur2 = cur2.assignedSlot || cur2.parentNode;
    } else if (cur2.nodeType == 11) {
      cur2 = cur2.host;
    } else {
      break;
    }
  }
}
function scrollableParents(dom) {
  let doc4 = dom.ownerDocument, x3, y3;
  for (let cur2 = dom.parentNode; cur2; ) {
    if (cur2 == doc4.body || x3 && y3) {
      break;
    } else if (cur2.nodeType == 1) {
      if (!y3 && cur2.scrollHeight > cur2.clientHeight)
        y3 = cur2;
      if (!x3 && cur2.scrollWidth > cur2.clientWidth)
        x3 = cur2;
      cur2 = cur2.assignedSlot || cur2.parentNode;
    } else if (cur2.nodeType == 11) {
      cur2 = cur2.host;
    } else {
      break;
    }
  }
  return { x: x3, y: y3 };
}
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;
if (browser.safari && browser.safari_version >= 26)
  preventScrollSupported = false;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stack = [];
  for (let cur2 = dom; cur2; cur2 = cur2.parentNode) {
    stack.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 i3 = 0; i3 < stack.length; ) {
      let elt = stack[i3++], top2 = stack[i3++], left = stack[i3++];
      if (elt.scrollTop != top2)
        elt.scrollTop = top2;
      if (elt.scrollLeft != left)
        elt.scrollLeft = left;
    }
  }
}
var scratchRange;
function textRange(node, from2, to = from2) {
  let range2 = scratchRange || (scratchRange = document.createRange());
  range2.setEnd(node, to);
  range2.setStart(node, from2);
  return range2;
}
function dispatchKey(elt, name2, code2, mods) {
  let options2 = { key: name2, code: name2, keyCode: code2, which: code2, cancelable: true };
  if (mods)
    ({ altKey: options2.altKey, ctrlKey: options2.ctrlKey, shiftKey: options2.shiftKey, metaKey: options2.metaKey } = mods);
  let down = new KeyboardEvent("keydown", options2);
  down.synthetic = true;
  elt.dispatchEvent(down);
  let up = new KeyboardEvent("keyup", options2);
  up.synthetic = true;
  elt.dispatchEvent(up);
  return down.defaultPrevented || up.defaultPrevented;
}
function getRoot(node) {
  while (node) {
    if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
      return node;
    node = node.assignedSlot || node.parentNode;
  }
  return null;
}
function atElementStart(doc4, selection) {
  let node = selection.focusNode, offset = selection.focusOffset;
  if (!node || selection.anchorNode != node || selection.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 == doc4) {
      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 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 result2 = [];
  for (let i3 = 0; i3 < str.length; i3++)
    result2.push(1 << +str[i3]);
  return result2;
}
var LowTypes = /* @__PURE__ */ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
var ArabicTypes = /* @__PURE__ */ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
var Brackets = /* @__PURE__ */ Object.create(null);
var BracketStack = [];
for (let p4 of ["()", "[]", "{}"]) {
  let l3 = /* @__PURE__ */ p4.charCodeAt(0), r3 = /* @__PURE__ */ p4.charCodeAt(1);
  Brackets[l3] = r3;
  Brackets[r3] = -l3;
}
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(from2, to, level) {
    this.from = from2;
    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(order2, index2, level, assoc) {
    let maybe = -1;
    for (let i3 = 0; i3 < order2.length; i3++) {
      let span = order2[i3];
      if (span.from <= index2 && span.to >= index2) {
        if (span.level == level)
          return i3;
        if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index2 : span.to > index2 : order2[maybe].level > span.level))
          maybe = i3;
      }
    }
    if (maybe < 0)
      throw new RangeError("Index out of range");
    return maybe;
  }
};
function isolatesEq(a3, b3) {
  if (a3.length != b3.length)
    return false;
  for (let i3 = 0; i3 < a3.length; i3++) {
    let iA = a3[i3], iB = b3[i3];
    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 from2 = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    let prevType = iI ? 256 : outerType;
    for (let i3 = from2, prev = prevType, prevStrong = prevType; i3 < to; i3++) {
      let type = charType(line.charCodeAt(i3));
      if (type == 512)
        type = prev;
      else if (type == 8 && prevStrong == 4)
        type = 16;
      types[i3] = type == 4 ? 2 : type;
      if (type & 7)
        prevStrong = type;
      prev = type;
    }
    for (let i3 = from2, prev = prevType, prevStrong = prevType; i3 < to; i3++) {
      let type = types[i3];
      if (type == 128) {
        if (i3 < to - 1 && prev == types[i3 + 1] && prev & 24)
          type = types[i3] = prev;
        else
          types[i3] = 256;
      } else if (type == 64) {
        let end = i3 + 1;
        while (end < to && types[end] == 64)
          end++;
        let replace4 = i3 && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
        for (let j = i3; j < end; j++)
          types[j] = replace4;
        i3 = end - 1;
      } else if (type == 8 && prevStrong == 1) {
        types[i3] = 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, context = 0; iI <= isolates.length; iI++) {
    let from2 = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i3 = from2, ch, br, type; i3 < to; i3++) {
      if (br = Brackets[ch = line.charCodeAt(i3)]) {
        if (br < 0) {
          for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
            if (BracketStack[sJ + 1] == -br) {
              let flags = BracketStack[sJ + 2];
              let type2 = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
              if (type2)
                types[i3] = types[BracketStack[sJ]] = type2;
              sI = sJ;
              break;
            }
          }
        } else if (BracketStack.length == 189) {
          break;
        } else {
          BracketStack[sI++] = i3;
          BracketStack[sI++] = ch;
          BracketStack[sI++] = context;
        }
      } else if ((type = types[i3]) == 2 || type == 1) {
        let embed = type == outerType;
        context = embed ? 0 : 1;
        for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
          let cur2 = BracketStack[sJ + 2];
          if (cur2 & 2)
            break;
          if (embed) {
            BracketStack[sJ + 2] |= 2;
          } else {
            if (cur2 & 4)
              break;
            BracketStack[sJ + 2] |= 4;
          }
        }
      }
    }
  }
}
function processNeutrals(rFrom, rTo, isolates, outerType) {
  for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
    let from2 = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
    for (let i3 = from2; i3 < to; ) {
      let type = types[i3];
      if (type == 256) {
        let end = i3 + 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 replace4 = beforeL == afterL ? beforeL ? 1 : 2 : outerType;
        for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i3; ) {
          if (j == fromJ) {
            j = isolates[--jI].from;
            fromJ = jI ? isolates[jI - 1].to : rFrom;
          }
          types[--j] = replace4;
        }
        i3 = end;
      } else {
        prev = type;
        i3++;
      }
    }
  }
}
function emitSpans(line, from2, to, level, baseLevel, isolates, order2) {
  let ourType = level % 2 ? 2 : 1;
  if (level % 2 == baseLevel % 2) {
    for (let iCh = from2, 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)
              order2.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, order2);
            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, order2);
      else if (iCh < iScan)
        order2.push(new BidiSpan(iCh, iScan, localLevel));
      iCh = iScan;
    }
  } else {
    for (let iCh = to, iI = isolates.length; iCh > from2; ) {
      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 == from2)
                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)
              order2.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, order2);
            iCh = iso.from;
          }
          iScan = iso.from;
        } else if (iScan == from2 || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
          break;
        } else {
          iScan--;
        }
      }
      if (recurse)
        emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order2);
      else if (iScan < iCh)
        order2.push(new BidiSpan(iScan, iCh, localLevel));
      iCh = iScan;
    }
  }
}
function computeSectionOrder(line, level, baseLevel, isolates, from2, to, order2) {
  let outerType = level % 2 ? 2 : 1;
  computeCharTypes(line, from2, to, isolates, outerType);
  processBracketPairs(line, from2, to, isolates, outerType);
  processNeutrals(from2, to, isolates, outerType);
  emitSpans(line, from2, to, level, baseLevel, isolates, order2);
}
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 order2 = [], level = direction == LTR ? 0 : 1;
  computeSectionOrder(line, level, level, isolates, 0, line.length, order2);
  return order2;
}
function trivialOrder(length) {
  return [new BidiSpan(0, length, 0)];
}
var movedOver = "";
function moveVisually(line, order2, dir, start, forward) {
  var _a4;
  let startIndex = start.head - line.from;
  let spanI = BidiSpan.find(order2, startIndex, (_a4 = start.bidiLevel) !== null && _a4 !== void 0 ? _a4 : -1, start.assoc);
  let span = order2[spanI], spanEnd = span.side(forward, dir);
  if (startIndex == spanEnd) {
    let nextI = spanI += forward ? 1 : -1;
    if (nextI < 0 || nextI >= order2.length)
      return null;
    span = order2[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 ? order2.length - 1 : 0) ? null : order2[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(text3, from2, to) {
  for (let i3 = from2; i3 < to; i3++) {
    let type = charType(text3.charCodeAt(i3));
    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: (values2) => values2.some((x3) => x3)
});
var nativeSelectionHidden = /* @__PURE__ */ Facet.define({
  combine: (values2) => values2.some((x3) => x3)
});
var scrollHandler = /* @__PURE__ */ Facet.define();
var ScrollTarget = class _ScrollTarget {
  constructor(range2, y3 = "nearest", x3 = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
    this.range = range2;
    this.y = y3;
    this.x = x3;
    this.yMargin = yMargin;
    this.xMargin = xMargin;
    this.isSnapshot = isSnapshot;
  }
  map(changes) {
    return changes.empty ? this : new _ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
  clip(state) {
    return this.range.to <= state.doc.length ? this : new _ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
  }
};
var scrollIntoView = /* @__PURE__ */ StateEffect.define({ map: (t3, ch) => t3.map(ch) });
var setEditContextFormatting = /* @__PURE__ */ StateEffect.define();
function logException(state, exception, context) {
  let handler = state.facet(exceptionSink);
  if (handler.length)
    handler[0](exception);
  else if (window.onerror && window.onerror(String(exception), context, void 0, void 0, exception)) ;
  else if (context)
    console.error(context + ":", exception);
  else
    console.error(exception);
}
var editable = /* @__PURE__ */ Facet.define({ combine: (values2) => values2.length ? values2[0] : true });
var nextPluginID = 0;
var viewPlugin = /* @__PURE__ */ Facet.define({
  combine(plugins) {
    return plugins.filter((p4, i3) => {
      for (let j = 0; j < i3; j++)
        if (plugins[j].plugin == p4.plugin)
          return false;
      return true;
    });
  }
});
var ViewPlugin = class _ViewPlugin {
  constructor(id, create6, domEventHandlers, domEventObservers, buildExtensions) {
    this.id = id;
    this.create = create6;
    this.domEventHandlers = domEventHandlers;
    this.domEventObservers = domEventObservers;
    this.baseExtensions = buildExtensions(this);
    this.extension = this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg: void 0 }));
  }
  /**
  Create an extension for this plugin with the given argument.
  */
  of(arg) {
    return this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg }));
  }
  /**
  Define a plugin from a constructor function that creates the
  plugin's value, given an editor view.
  */
  static define(create6, spec) {
    const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
    return new _ViewPlugin(nextPluginID++, create6, eventHandlers, eventObservers, (plugin) => {
      let ext = [];
      if (deco)
        ext.push(decorations.of((view) => {
          let pluginInst = view.plugin(plugin);
          return pluginInst ? deco(pluginInst) : Decoration.none;
        }));
      if (provide)
        ext.push(provide(plugin));
      return ext;
    });
  }
  /**
  Create a plugin for a class whose constructor takes a single
  editor view as argument.
  */
  static fromClass(cls, spec) {
    return _ViewPlugin.define((view, arg) => new cls(view, arg), spec);
  }
};
var PluginInstance = class {
  constructor(spec) {
    this.spec = spec;
    this.mustUpdate = null;
    this.value = null;
  }
  get plugin() {
    return this.spec && this.spec.plugin;
  }
  update(view) {
    if (!this.value) {
      if (this.spec) {
        try {
          this.value = this.spec.plugin.create(view, this.spec.arg);
        } catch (e3) {
          logException(view.state, e3, "CodeMirror plugin crashed");
          this.deactivate();
        }
      }
    } else if (this.mustUpdate) {
      let update2 = this.mustUpdate;
      this.mustUpdate = null;
      if (this.value.update) {
        try {
          this.value.update(update2);
        } catch (e3) {
          logException(update2.state, e3, "CodeMirror plugin crashed");
          if (this.value.destroy)
            try {
              this.value.destroy();
            } catch (_5) {
            }
          this.deactivate();
        }
      }
    }
    return this;
  }
  destroy(view) {
    var _a4;
    if ((_a4 = this.value) === null || _a4 === void 0 ? void 0 : _a4.destroy) {
      try {
        this.value.destroy();
      } catch (e3) {
        logException(view.state, e3, "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 blockWrappers = /* @__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((i3) => i3 instanceof Function ? i3(view) : i3);
  let result2 = [];
  RangeSet.spans(sets, line.from, line.to, {
    point() {
    },
    span(fromDoc, toDoc, active, open) {
      let from2 = fromDoc - line.from, to = toDoc - line.from;
      let level = result2;
      for (let i3 = active.length - 1; i3 >= 0; i3--, open--) {
        let direction = active[i3].spec.bidiIsolate, update2;
        if (direction == null)
          direction = autoDirection(line.text, from2, to);
        if (open > 0 && level.length && (update2 = level[level.length - 1]).to == from2 && update2.direction == direction) {
          update2.to = to;
          level = update2.inner;
        } else {
          let add4 = { from: from2, to, direction, inner: [] };
          level.push(add4);
          level = add4.inner;
        }
      }
    }
  });
  return result2;
}
var scrollMargins = /* @__PURE__ */ Facet.define();
function getScrollMargins(view) {
  let left = 0, right = 0, top2 = 0, bottom = 0;
  for (let source of view.state.facet(scrollMargins)) {
    let m3 = source(view);
    if (m3) {
      if (m3.left != null)
        left = Math.max(left, m3.left);
      if (m3.right != null)
        right = Math.max(right, m3.right);
      if (m3.top != null)
        top2 = Math.max(top2, m3.top);
      if (m3.bottom != null)
        bottom = Math.max(bottom, m3.bottom);
    }
  }
  return { left, right, top: top2, bottom };
}
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 i3 = set4.length, me = this;
    for (; i3 > 0; i3--) {
      let range2 = set4[i3 - 1];
      if (range2.fromA > me.toA)
        continue;
      if (range2.toA < me.fromA)
        break;
      me = me.join(range2);
      set4.splice(i3 - 1, 1);
    }
    set4.splice(i3, 0, me);
    return set4;
  }
  // Extend a set to cover all the content in `ranges`, which is a
  // flat array with each pair of numbers representing fromB/toB
  // positions. These pairs are generated in unchanged ranges, so the
  // offset between doc A and doc B is the same for their start and
  // end points.
  static extendWithRanges(diff, ranges) {
    if (ranges.length == 0)
      return diff;
    let result2 = [];
    for (let dI = 0, rI = 0, off = 0; ; ) {
      let nextD = dI < diff.length ? diff[dI].fromB : 1e9;
      let nextR = rI < ranges.length ? ranges[rI] : 1e9;
      let fromB = Math.min(nextD, nextR);
      if (fromB == 1e9)
        break;
      let fromA = fromB + off, toB = fromB, toA = fromA;
      for (; ; ) {
        if (rI < ranges.length && ranges[rI] <= toB) {
          let end = ranges[rI + 1];
          rI += 2;
          toB = Math.max(toB, end);
          for (let i3 = dI; i3 < diff.length && diff[i3].fromB <= toB; i3++)
            off = diff[i3].toA - diff[i3].toB;
          toA = Math.max(toA, end + off);
        } else if (dI < diff.length && diff[dI].fromB <= toB) {
          let next2 = diff[dI++];
          toB = Math.max(toB, next2.toB);
          toA = Math.max(toA, next2.toA);
          off = next2.toA - next2.toB;
        } else {
          break;
        }
      }
      result2.push(new _ChangedRange(fromA, toA, fromB, toB));
    }
    return result2;
  }
};
var ViewUpdate = class _ViewUpdate {
  constructor(view, state, transactions) {
    this.view = view;
    this.state = state;
    this.transactions = transactions;
    this.flags = 0;
    this.startState = view.state;
    this.changes = ChangeSet.empty(this.startState.doc.length);
    for (let tr2 of transactions)
      this.changes = this.changes.compose(tr2.changes);
    let changedRanges = [];
    this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
    this.changedRanges = changedRanges;
  }
  /**
  @internal
  */
  static create(view, state, transactions) {
    return new _ViewUpdate(view, state, transactions);
  }
  /**
  Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
  [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
  update.
  */
  get viewportChanged() {
    return (this.flags & 4) > 0;
  }
  /**
  Returns true when
  [`viewportChanged`](https://codemirror.net/6/docs/ref/#view.ViewUpdate.viewportChanged) is true
  and the viewport change is not just the result of mapping it in
  response to document changes.
  */
  get viewportMoved() {
    return (this.flags & 8) > 0;
  }
  /**
  Indicates whether the height of a block element in the editor
  changed in this update.
  */
  get heightChanged() {
    return (this.flags & 2) > 0;
  }
  /**
  Returns true when the document was modified or the size of the
  editor, or elements within the editor, changed.
  */
  get geometryChanged() {
    return this.docChanged || (this.flags & (16 | 2)) > 0;
  }
  /**
  True when this update indicates a focus change.
  */
  get focusChanged() {
    return (this.flags & 1) > 0;
  }
  /**
  Whether the document changed in this update.
  */
  get docChanged() {
    return !this.changes.empty;
  }
  /**
  Whether the selection was explicitly set in this update.
  */
  get selectionSet() {
    return this.transactions.some((tr2) => tr2.selection);
  }
  /**
  @internal
  */
  get empty() {
    return this.flags == 0 && this.transactions.length == 0;
  }
};
var noChildren = [];
var Tile = class {
  constructor(dom, length, flags = 0) {
    this.dom = dom;
    this.length = length;
    this.flags = flags;
    this.parent = null;
    dom.cmTile = this;
  }
  get breakAfter() {
    return this.flags & 1;
  }
  get children() {
    return noChildren;
  }
  isWidget() {
    return false;
  }
  get isHidden() {
    return false;
  }
  isComposite() {
    return false;
  }
  isLine() {
    return false;
  }
  isText() {
    return false;
  }
  isBlock() {
    return false;
  }
  get domAttrs() {
    return null;
  }
  sync(track) {
    this.flags |= 2;
    if (this.flags & 4) {
      this.flags &= ~4;
      let attrs2 = this.domAttrs;
      if (attrs2)
        setAttrs(this.dom, attrs2);
    }
  }
  toString() {
    return this.constructor.name + (this.children.length ? `(${this.children})` : "") + (this.breakAfter ? "#" : "");
  }
  destroy() {
    this.parent = null;
  }
  setDOM(dom) {
    this.dom = dom;
    dom.cmTile = this;
  }
  get posAtStart() {
    return this.parent ? this.parent.posBefore(this) : 0;
  }
  get posAtEnd() {
    return this.posAtStart + this.length;
  }
  posBefore(tile, start = this.posAtStart) {
    let pos = start;
    for (let child of this.children) {
      if (child == tile)
        return pos;
      pos += child.length + child.breakAfter;
    }
    throw new RangeError("Invalid child in posBefore");
  }
  posAfter(tile) {
    return this.posBefore(tile) + tile.length;
  }
  covers(side) {
    return true;
  }
  coordsIn(pos, side) {
    return null;
  }
  domPosFor(off, side) {
    let index2 = domIndex(this.dom);
    let after2 = this.length ? off > 0 : side > 0;
    return new DOMPos(this.parent.dom, index2 + (after2 ? 1 : 0), off == 0 || off == this.length);
  }
  markDirty(attrs2) {
    this.flags &= ~2;
    if (attrs2)
      this.flags |= 4;
    if (this.parent && this.parent.flags & 2)
      this.parent.markDirty(false);
  }
  get overrideDOMText() {
    return null;
  }
  get root() {
    for (let t3 = this; t3; t3 = t3.parent)
      if (t3 instanceof DocTile)
        return t3;
    return null;
  }
  static get(dom) {
    return dom.cmTile;
  }
};
var CompositeTile = class extends Tile {
  constructor(dom) {
    super(dom, 0);
    this._children = [];
  }
  isComposite() {
    return true;
  }
  get children() {
    return this._children;
  }
  get lastChild() {
    return this.children.length ? this.children[this.children.length - 1] : null;
  }
  append(child) {
    this.children.push(child);
    child.parent = this;
  }
  sync(track) {
    if (this.flags & 2)
      return;
    super.sync(track);
    let parent = this.dom, prev = null, next2;
    let tracking = (track === null || track === void 0 ? void 0 : track.node) == parent ? track : null;
    let length = 0;
    for (let child of this.children) {
      child.sync(track);
      length += child.length + child.breakAfter;
      next2 = prev ? prev.nextSibling : parent.firstChild;
      if (tracking && next2 != child.dom)
        tracking.written = true;
      if (child.dom.parentNode == parent) {
        while (next2 && next2 != child.dom)
          next2 = rm$1(next2);
      } else {
        parent.insertBefore(child.dom, next2);
      }
      prev = child.dom;
    }
    next2 = prev ? prev.nextSibling : parent.firstChild;
    if (tracking && next2)
      tracking.written = true;
    while (next2)
      next2 = rm$1(next2);
    this.length = length;
  }
};
function rm$1(dom) {
  let next2 = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next2;
}
var DocTile = class extends CompositeTile {
  constructor(view, dom) {
    super(dom);
    this.view = view;
  }
  owns(tile) {
    for (; tile; tile = tile.parent)
      if (tile == this)
        return true;
    return false;
  }
  isBlock() {
    return true;
  }
  nearest(dom) {
    for (; ; ) {
      if (!dom)
        return null;
      let tile = Tile.get(dom);
      if (tile && this.owns(tile))
        return tile;
      dom = dom.parentNode;
    }
  }
  blockTiles(f3) {
    for (let stack = [], cur2 = this, i3 = 0, pos = 0; ; ) {
      if (i3 == cur2.children.length) {
        if (!stack.length)
          return;
        cur2 = cur2.parent;
        if (cur2.breakAfter)
          pos++;
        i3 = stack.pop();
      } else {
        let next2 = cur2.children[i3++];
        if (next2 instanceof BlockWrapperTile) {
          stack.push(i3);
          cur2 = next2;
          i3 = 0;
        } else {
          let end = pos + next2.length;
          let result2 = f3(next2, pos);
          if (result2 !== void 0)
            return result2;
          pos = end + next2.breakAfter;
        }
      }
    }
  }
  // Find the block at the given position. If side < -1, make sure to
  // stay before block widgets at that position, if side > 1, after
  // such widgets (used for selection drawing, which needs to be able
  // to get coordinates for positions that aren't valid cursor positions).
  resolveBlock(pos, side) {
    let before2, beforeOff = -1, after2, afterOff = -1;
    this.blockTiles((tile, off) => {
      let end = off + tile.length;
      if (pos >= off && pos <= end) {
        if (tile.isWidget() && side >= -1 && side <= 1) {
          if (tile.flags & 32)
            return true;
          if (tile.flags & 16)
            before2 = void 0;
        }
        if ((off < pos || pos == end && (side < -1 ? tile.length : tile.covers(1))) && (!before2 || !tile.isWidget() && before2.isWidget())) {
          before2 = tile;
          beforeOff = pos - off;
        }
        if ((end > pos || pos == off && (side > 1 ? tile.length : tile.covers(-1))) && (!after2 || !tile.isWidget() && after2.isWidget())) {
          after2 = tile;
          afterOff = pos - off;
        }
      }
    });
    if (!before2 && !after2)
      throw new Error("No tile at position " + pos);
    return before2 && side < 0 || !after2 ? { tile: before2, offset: beforeOff } : { tile: after2, offset: afterOff };
  }
};
var BlockWrapperTile = class _BlockWrapperTile extends CompositeTile {
  constructor(dom, wrapper) {
    super(dom);
    this.wrapper = wrapper;
  }
  isBlock() {
    return true;
  }
  covers(side) {
    if (!this.children.length)
      return false;
    return side < 0 ? this.children[0].covers(-1) : this.lastChild.covers(1);
  }
  get domAttrs() {
    return this.wrapper.attributes;
  }
  static of(wrapper, dom) {
    let tile = new _BlockWrapperTile(dom || document.createElement(wrapper.tagName), wrapper);
    if (!dom)
      tile.flags |= 4;
    return tile;
  }
};
var LineTile = class _LineTile extends CompositeTile {
  constructor(dom, attrs2) {
    super(dom);
    this.attrs = attrs2;
  }
  isLine() {
    return true;
  }
  static start(attrs2, dom, keepAttrs) {
    let line = new _LineTile(dom || document.createElement("div"), attrs2);
    if (!dom || !keepAttrs)
      line.flags |= 4;
    return line;
  }
  get domAttrs() {
    return this.attrs;
  }
  // Find the tile associated with a given position in this line.
  resolveInline(pos, side, forCoords) {
    let before2 = null, beforeOff = -1, after2 = null, afterOff = -1;
    function scan(tile, pos2) {
      for (let i3 = 0, off = 0; i3 < tile.children.length && off <= pos2; i3++) {
        let child = tile.children[i3], end = off + child.length;
        if (end >= pos2) {
          if (child.isComposite()) {
            scan(child, pos2 - off);
          } else if ((!after2 || after2.isHidden && (side > 0 || forCoords && onSameLine(after2, child))) && (end > pos2 || child.flags & 32)) {
            after2 = child;
            afterOff = pos2 - off;
          } else if (off < pos2 || child.flags & 16 && !child.isHidden) {
            before2 = child;
            beforeOff = pos2 - off;
          }
        }
        off = end;
      }
    }
    scan(this, pos);
    let target = (side < 0 ? before2 : after2) || before2 || after2;
    return target ? { tile: target, offset: target == before2 ? beforeOff : afterOff } : null;
  }
  coordsIn(pos, side) {
    let found2 = this.resolveInline(pos, side, true);
    if (!found2)
      return fallbackRect(this);
    return found2.tile.coordsIn(Math.max(0, found2.offset), side);
  }
  domIn(pos, side) {
    let found2 = this.resolveInline(pos, side);
    if (found2) {
      let { tile, offset } = found2;
      if (this.dom.contains(tile.dom)) {
        if (tile.isText())
          return new DOMPos(tile.dom, Math.min(tile.dom.nodeValue.length, offset));
        return tile.domPosFor(offset, tile.flags & 16 ? 1 : tile.flags & 32 ? -1 : side);
      }
      let parent = found2.tile.parent, saw = false;
      for (let ch of parent.children) {
        if (saw)
          return new DOMPos(ch.dom, 0);
        if (ch == found2.tile) {
          saw = true;
        }
      }
    }
    return new DOMPos(this.dom, 0);
  }
};
function fallbackRect(tile) {
  let last3 = tile.dom.lastChild;
  if (!last3)
    return tile.dom.getBoundingClientRect();
  let rects = clientRectsFor(last3);
  return rects[rects.length - 1] || null;
}
function onSameLine(a3, b3) {
  let posA = a3.coordsIn(0, 1), posB = b3.coordsIn(0, 1);
  return posA && posB && posB.top < posA.bottom;
}
var MarkTile = class _MarkTile extends CompositeTile {
  constructor(dom, mark2) {
    super(dom);
    this.mark = mark2;
  }
  get domAttrs() {
    return this.mark.attrs;
  }
  static of(mark2, dom) {
    let tile = new _MarkTile(dom || document.createElement(mark2.tagName), mark2);
    if (!dom)
      tile.flags |= 4;
    return tile;
  }
};
var TextTile = class _TextTile extends Tile {
  constructor(dom, text3) {
    super(dom, text3.length);
    this.text = text3;
  }
  sync(track) {
    if (this.flags & 2)
      return;
    super.sync(track);
    if (this.dom.nodeValue != this.text) {
      if (track && track.node == this.dom)
        track.written = true;
      this.dom.nodeValue = this.text;
    }
  }
  isText() {
    return true;
  }
  toString() {
    return JSON.stringify(this.text);
  }
  coordsIn(pos, side) {
    let length = this.dom.nodeValue.length;
    if (pos > length)
      pos = length;
    let from2 = pos, to = pos, flatten4 = 0;
    if (pos == 0 && side < 0 || pos == length && side >= 0) {
      if (!(browser.chrome || browser.gecko)) {
        if (pos) {
          from2--;
          flatten4 = 1;
        } else if (to < length) {
          to++;
          flatten4 = -1;
        }
      }
    } else {
      if (side < 0)
        from2--;
      else if (to < length)
        to++;
    }
    let rects = textRange(this.dom, from2, to).getClientRects();
    if (!rects.length)
      return null;
    let rect = rects[(flatten4 ? flatten4 < 0 : side >= 0) ? 0 : rects.length - 1];
    if (browser.safari && !flatten4 && rect.width == 0)
      rect = Array.prototype.find.call(rects, (r3) => r3.width) || rect;
    return flatten4 ? flattenRect(rect, flatten4 < 0) : rect || null;
  }
  static of(text3, dom) {
    let tile = new _TextTile(dom || document.createTextNode(text3), text3);
    if (!dom)
      tile.flags |= 2;
    return tile;
  }
};
var WidgetTile = class _WidgetTile extends Tile {
  constructor(dom, length, widget, flags) {
    super(dom, length, flags);
    this.widget = widget;
  }
  isWidget() {
    return true;
  }
  get isHidden() {
    return this.widget.isHidden;
  }
  covers(side) {
    if (this.flags & 48)
      return false;
    return (this.flags & (side < 0 ? 64 : 128)) > 0;
  }
  coordsIn(pos, side) {
    return this.coordsInWidget(pos, side, false);
  }
  coordsInWidget(pos, side, block3) {
    let custom = this.widget.coordsAt(this.dom, pos, side);
    if (custom)
      return custom;
    if (block3) {
      return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 0 : side <= 0);
    } else {
      let rects = this.dom.getClientRects(), rect = null;
      if (!rects.length)
        return null;
      let fromBack = this.flags & 16 ? true : this.flags & 32 ? false : pos > 0;
      for (let i3 = fromBack ? rects.length - 1 : 0; ; i3 += fromBack ? -1 : 1) {
        rect = rects[i3];
        if (pos > 0 ? i3 == 0 : i3 == rects.length - 1 || rect.top < rect.bottom)
          break;
      }
      return flattenRect(rect, !fromBack);
    }
  }
  get overrideDOMText() {
    if (!this.length)
      return Text.empty;
    let { root: root3 } = this;
    if (!root3)
      return Text.empty;
    let start = this.posAtStart;
    return root3.view.state.doc.slice(start, start + this.length);
  }
  destroy() {
    super.destroy();
    this.widget.destroy(this.dom);
  }
  static of(widget, view, length, flags, dom) {
    if (!dom) {
      dom = widget.toDOM(view);
      if (!widget.editable)
        dom.contentEditable = "false";
    }
    return new _WidgetTile(dom, length, widget, flags);
  }
};
var WidgetBufferTile = class extends Tile {
  constructor(flags) {
    let img = document.createElement("img");
    img.className = "cm-widgetBuffer";
    img.setAttribute("aria-hidden", "true");
    super(img, 0, flags);
  }
  get isHidden() {
    return true;
  }
  get overrideDOMText() {
    return Text.empty;
  }
  coordsIn(pos) {
    return this.dom.getBoundingClientRect();
  }
};
var TilePointer = class {
  constructor(top2) {
    this.index = 0;
    this.beforeBreak = false;
    this.parents = [];
    this.tile = top2;
  }
  // Advance by the given distance. If side is -1, stop leaving or
  // entering tiles, or skipping zero-length tiles, once the distance
  // has been traversed. When side is 1, leave, enter, or skip
  // everything at the end position.
  advance(dist2, side, walker) {
    let { tile, index: index2, beforeBreak, parents } = this;
    while (dist2 || side > 0) {
      if (!tile.isComposite()) {
        if (index2 == tile.length) {
          beforeBreak = !!tile.breakAfter;
          ({ tile, index: index2 } = parents.pop());
          index2++;
        } else if (!dist2) {
          break;
        } else {
          let take = Math.min(dist2, tile.length - index2);
          if (walker)
            walker.skip(tile, index2, index2 + take);
          dist2 -= take;
          index2 += take;
        }
      } else if (beforeBreak) {
        if (!dist2)
          break;
        if (walker)
          walker.break();
        dist2--;
        beforeBreak = false;
      } else if (index2 == tile.children.length) {
        if (!dist2 && !parents.length)
          break;
        if (walker)
          walker.leave(tile);
        beforeBreak = !!tile.breakAfter;
        ({ tile, index: index2 } = parents.pop());
        index2++;
      } else {
        let next2 = tile.children[index2], brk = next2.breakAfter;
        if ((side > 0 ? next2.length <= dist2 : next2.length < dist2) && (!walker || walker.skip(next2, 0, next2.length) !== false || !next2.isComposite)) {
          beforeBreak = !!brk;
          index2++;
          dist2 -= next2.length;
        } else {
          parents.push({ tile, index: index2 });
          tile = next2;
          index2 = 0;
          if (walker && next2.isComposite())
            walker.enter(next2);
        }
      }
    }
    this.tile = tile;
    this.index = index2;
    this.beforeBreak = beforeBreak;
    return this;
  }
  get root() {
    return this.parents.length ? this.parents[0].tile : this.tile;
  }
};
var OpenWrapper = class {
  constructor(from2, to, wrapper, rank) {
    this.from = from2;
    this.to = to;
    this.wrapper = wrapper;
    this.rank = rank;
  }
};
var TileBuilder = class {
  constructor(cache5, root3, blockWrappers2) {
    this.cache = cache5;
    this.root = root3;
    this.blockWrappers = blockWrappers2;
    this.curLine = null;
    this.lastBlock = null;
    this.afterWidget = null;
    this.pos = 0;
    this.wrappers = [];
    this.wrapperPos = 0;
  }
  addText(text3, marks3, openStart, tile) {
    var _a4;
    this.flushBuffer();
    let parent = this.ensureMarks(marks3, openStart);
    let prev = parent.lastChild;
    if (prev && prev.isText() && !(prev.flags & 8) && prev.length + text3.length < 512) {
      this.cache.reused.set(
        prev,
        2
        /* Reused.DOM */
      );
      let tile2 = parent.children[parent.children.length - 1] = new TextTile(prev.dom, prev.text + text3);
      tile2.parent = parent;
    } else {
      parent.append(tile || TextTile.of(text3, (_a4 = this.cache.find(TextTile)) === null || _a4 === void 0 ? void 0 : _a4.dom));
    }
    this.pos += text3.length;
    this.afterWidget = null;
  }
  addComposition(composition, context) {
    let line = this.curLine;
    if (line.dom != context.line.dom) {
      line.setDOM(this.cache.reused.has(context.line) ? freeNode(context.line.dom) : context.line.dom);
      this.cache.reused.set(
        context.line,
        2
        /* Reused.DOM */
      );
    }
    let head2 = line;
    for (let i3 = context.marks.length - 1; i3 >= 0; i3--) {
      let mark2 = context.marks[i3];
      let last3 = head2.lastChild;
      if (last3 instanceof MarkTile && last3.mark.eq(mark2.mark)) {
        if (last3.dom != mark2.dom)
          last3.setDOM(freeNode(mark2.dom));
        head2 = last3;
      } else {
        if (this.cache.reused.get(mark2)) {
          let tile = Tile.get(mark2.dom);
          if (tile)
            tile.setDOM(freeNode(mark2.dom));
        }
        let nw = MarkTile.of(mark2.mark, mark2.dom);
        head2.append(nw);
        head2 = nw;
      }
      this.cache.reused.set(
        mark2,
        2
        /* Reused.DOM */
      );
    }
    let oldTile = Tile.get(composition.text);
    if (oldTile)
      this.cache.reused.set(
        oldTile,
        2
        /* Reused.DOM */
      );
    let text3 = new TextTile(composition.text, composition.text.nodeValue);
    text3.flags |= 8;
    head2.append(text3);
  }
  addInlineWidget(widget, marks3, openStart) {
    let noSpace = this.afterWidget && widget.flags & 48 && (this.afterWidget.flags & 48) == (widget.flags & 48);
    if (!noSpace)
      this.flushBuffer();
    let parent = this.ensureMarks(marks3, openStart);
    if (!noSpace && !(widget.flags & 16))
      parent.append(this.getBuffer(1));
    parent.append(widget);
    this.pos += widget.length;
    this.afterWidget = widget;
  }
  addMark(tile, marks3, openStart) {
    this.flushBuffer();
    let parent = this.ensureMarks(marks3, openStart);
    parent.append(tile);
    this.pos += tile.length;
    this.afterWidget = null;
  }
  addBlockWidget(widget) {
    this.getBlockPos().append(widget);
    this.pos += widget.length;
    this.lastBlock = widget;
    this.endLine();
  }
  continueWidget(length) {
    let widget = this.afterWidget || this.lastBlock;
    widget.length += length;
    this.pos += length;
  }
  addLineStart(attrs2, dom) {
    var _a4;
    if (!attrs2)
      attrs2 = lineBaseAttrs;
    let tile = LineTile.start(attrs2, dom || ((_a4 = this.cache.find(LineTile)) === null || _a4 === void 0 ? void 0 : _a4.dom), !!dom);
    this.getBlockPos().append(this.lastBlock = this.curLine = tile);
  }
  addLine(tile) {
    this.getBlockPos().append(tile);
    this.pos += tile.length;
    this.lastBlock = tile;
    this.endLine();
  }
  addBreak() {
    this.lastBlock.flags |= 1;
    this.endLine();
    this.pos++;
  }
  addLineStartIfNotCovered(attrs2) {
    if (!this.blockPosCovered())
      this.addLineStart(attrs2);
  }
  ensureLine(attrs2) {
    if (!this.curLine)
      this.addLineStart(attrs2);
  }
  ensureMarks(marks3, openStart) {
    var _a4;
    let parent = this.curLine;
    for (let i3 = marks3.length - 1; i3 >= 0; i3--) {
      let mark2 = marks3[i3], last3;
      if (openStart > 0 && (last3 = parent.lastChild) && last3 instanceof MarkTile && last3.mark.eq(mark2)) {
        parent = last3;
        openStart--;
      } else {
        let tile = MarkTile.of(mark2, (_a4 = this.cache.find(MarkTile, (m3) => m3.mark.eq(mark2))) === null || _a4 === void 0 ? void 0 : _a4.dom);
        parent.append(tile);
        parent = tile;
        openStart = 0;
      }
    }
    return parent;
  }
  endLine() {
    if (this.curLine) {
      this.flushBuffer();
      let last3 = this.curLine.lastChild;
      if (!last3 || !hasContent(this.curLine, false) || last3.dom.nodeName != "BR" && last3.isWidget() && !(browser.ios && hasContent(this.curLine, true)))
        this.curLine.append(this.cache.findWidget(
          BreakWidget,
          0,
          32
          /* TileFlag.After */
        ) || new WidgetTile(
          BreakWidget.toDOM(),
          0,
          BreakWidget,
          32
          /* TileFlag.After */
        ));
      this.curLine = this.afterWidget = null;
    }
  }
  updateBlockWrappers() {
    if (this.wrapperPos > this.pos + 1e4) {
      this.blockWrappers.goto(this.pos);
      this.wrappers.length = 0;
    }
    for (let i3 = this.wrappers.length - 1; i3 >= 0; i3--)
      if (this.wrappers[i3].to < this.pos)
        this.wrappers.splice(i3, 1);
    for (let cur2 = this.blockWrappers; cur2.value && cur2.from <= this.pos; cur2.next())
      if (cur2.to >= this.pos) {
        let wrap4 = new OpenWrapper(cur2.from, cur2.to, cur2.value, cur2.rank), i3 = this.wrappers.length;
        while (i3 > 0 && (this.wrappers[i3 - 1].rank - wrap4.rank || this.wrappers[i3 - 1].to - wrap4.to) < 0)
          i3--;
        this.wrappers.splice(i3, 0, wrap4);
      }
    this.wrapperPos = this.pos;
  }
  getBlockPos() {
    var _a4;
    this.updateBlockWrappers();
    let parent = this.root;
    for (let wrap4 of this.wrappers) {
      let last3 = parent.lastChild;
      if (wrap4.from < this.pos && last3 instanceof BlockWrapperTile && last3.wrapper.eq(wrap4.wrapper)) {
        parent = last3;
      } else {
        let tile = BlockWrapperTile.of(wrap4.wrapper, (_a4 = this.cache.find(BlockWrapperTile, (t3) => t3.wrapper.eq(wrap4.wrapper))) === null || _a4 === void 0 ? void 0 : _a4.dom);
        parent.append(tile);
        parent = tile;
      }
    }
    return parent;
  }
  blockPosCovered() {
    let last3 = this.lastBlock;
    return last3 != null && !last3.breakAfter && (!last3.isWidget() || (last3.flags & (32 | 128)) > 0);
  }
  getBuffer(side) {
    let flags = 2 | (side < 0 ? 16 : 32);
    let found2 = this.cache.find(
      WidgetBufferTile,
      void 0,
      1
      /* Reused.Full */
    );
    if (found2)
      found2.flags = flags;
    return found2 || new WidgetBufferTile(flags);
  }
  flushBuffer() {
    if (this.afterWidget && !(this.afterWidget.flags & 32)) {
      this.afterWidget.parent.append(this.getBuffer(-1));
      this.afterWidget = null;
    }
  }
};
var TextStream = class {
  constructor(doc4) {
    this.skipCount = 0;
    this.text = "";
    this.textOff = 0;
    this.cursor = doc4.iter();
  }
  skip(len) {
    if (this.textOff + len <= this.text.length) {
      this.textOff += len;
    } else {
      this.skipCount += len - (this.text.length - this.textOff);
      this.text = "";
      this.textOff = 0;
    }
  }
  next(maxLen) {
    if (this.textOff == this.text.length) {
      let { value: value2, lineBreak, done } = this.cursor.next(this.skipCount);
      this.skipCount = 0;
      if (done)
        throw new Error("Ran out of text content when drawing inline views");
      this.text = value2;
      let len = this.textOff = Math.min(maxLen, value2.length);
      return lineBreak ? null : value2.slice(0, len);
    }
    let end = Math.min(this.text.length, this.textOff + maxLen);
    let chars = this.text.slice(this.textOff, end);
    this.textOff = end;
    return chars;
  }
};
var buckets = [WidgetTile, LineTile, TextTile, MarkTile, WidgetBufferTile, BlockWrapperTile, DocTile];
for (let i3 = 0; i3 < buckets.length; i3++)
  buckets[i3].bucket = i3;
var TileCache = class {
  constructor(view) {
    this.view = view;
    this.buckets = buckets.map(() => []);
    this.index = buckets.map(() => 0);
    this.reused = /* @__PURE__ */ new Map();
  }
  // Put a tile in the cache.
  add(tile) {
    let i3 = tile.constructor.bucket, bucket = this.buckets[i3];
    if (bucket.length < 6)
      bucket.push(tile);
    else
      bucket[
        this.index[i3] = (this.index[i3] + 1) % 6
        /* C.Bucket */
      ] = tile;
  }
  find(cls, test2, type = 2) {
    let i3 = cls.bucket;
    let bucket = this.buckets[i3], off = this.index[i3];
    for (let j = bucket.length - 1; j >= 0; j--) {
      let index2 = (j + off) % bucket.length, tile = bucket[index2];
      if ((!test2 || test2(tile)) && !this.reused.has(tile)) {
        bucket.splice(index2, 1);
        if (index2 < off)
          this.index[i3]--;
        this.reused.set(tile, type);
        return tile;
      }
    }
    return null;
  }
  findWidget(widget, length, flags) {
    let widgets = this.buckets[0];
    if (widgets.length)
      for (let i3 = 0, pass = 0; ; i3++) {
        if (i3 == widgets.length) {
          if (pass)
            return null;
          pass = 1;
          i3 = 0;
        }
        let tile = widgets[i3];
        if (!this.reused.has(tile) && (pass == 0 ? tile.widget.compare(widget) : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view))) {
          widgets.splice(i3, 1);
          if (i3 < this.index[0])
            this.index[0]--;
          if (tile.widget == widget && tile.length == length && (tile.flags & (496 | 1)) == flags) {
            this.reused.set(
              tile,
              1
              /* Reused.Full */
            );
            return tile;
          } else {
            this.reused.set(
              tile,
              2
              /* Reused.DOM */
            );
            return new WidgetTile(tile.dom, length, widget, tile.flags & ~(496 | 1) | flags);
          }
        }
      }
  }
  reuse(tile) {
    this.reused.set(
      tile,
      1
      /* Reused.Full */
    );
    return tile;
  }
  maybeReuse(tile, type = 2) {
    if (this.reused.has(tile))
      return void 0;
    this.reused.set(tile, type);
    return tile.dom;
  }
  clear() {
    for (let i3 = 0; i3 < this.buckets.length; i3++)
      this.buckets[i3].length = this.index[i3] = 0;
  }
};
var TileUpdate = class {
  constructor(view, old, blockWrappers2, decorations3, disallowBlockEffectsFor) {
    this.view = view;
    this.decorations = decorations3;
    this.disallowBlockEffectsFor = disallowBlockEffectsFor;
    this.openWidget = false;
    this.openMarks = 0;
    this.cache = new TileCache(view);
    this.text = new TextStream(view.state.doc);
    this.builder = new TileBuilder(this.cache, new DocTile(view, view.contentDOM), RangeSet.iter(blockWrappers2));
    this.cache.reused.set(
      old,
      2
      /* Reused.DOM */
    );
    this.old = new TilePointer(old);
    this.reuseWalker = {
      skip: (tile, from2, to) => {
        this.cache.add(tile);
        if (tile.isComposite())
          return false;
      },
      enter: (tile) => this.cache.add(tile),
      leave: () => {
      },
      break: () => {
      }
    };
  }
  run(changes, composition) {
    let compositionContext = composition && this.getCompositionContext(composition.text);
    for (let posA = 0, posB = 0, i3 = 0; ; ) {
      let next2 = i3 < changes.length ? changes[i3++] : null;
      let skipA = next2 ? next2.fromA : this.old.root.length;
      if (skipA > posA) {
        let len = skipA - posA;
        this.preserve(len, !i3, !next2);
        posA = skipA;
        posB += len;
      }
      if (!next2)
        break;
      if (composition && next2.fromA <= composition.range.fromA && next2.toA >= composition.range.toA) {
        this.forward(next2.fromA, composition.range.fromA, composition.range.fromA < composition.range.toA ? 1 : -1);
        this.emit(posB, composition.range.fromB);
        this.cache.clear();
        this.builder.addComposition(composition, compositionContext);
        this.text.skip(composition.range.toB - composition.range.fromB);
        this.forward(composition.range.fromA, next2.toA);
        this.emit(composition.range.toB, next2.toB);
      } else {
        this.forward(next2.fromA, next2.toA);
        this.emit(posB, next2.toB);
      }
      posB = next2.toB;
      posA = next2.toA;
    }
    if (this.builder.curLine)
      this.builder.endLine();
    return this.builder.root;
  }
  preserve(length, incStart, incEnd) {
    let activeMarks = getMarks(this.old), openMarks = this.openMarks;
    this.old.advance(length, incEnd ? 1 : -1, {
      skip: (tile, from2, to) => {
        if (tile.isWidget()) {
          if (this.openWidget) {
            this.builder.continueWidget(to - from2);
          } else {
            let widget = to > 0 || from2 < tile.length ? WidgetTile.of(tile.widget, this.view, to - from2, tile.flags & 496, this.cache.maybeReuse(tile)) : this.cache.reuse(tile);
            if (widget.flags & 256) {
              widget.flags &= ~1;
              this.builder.addBlockWidget(widget);
            } else {
              this.builder.ensureLine(null);
              this.builder.addInlineWidget(widget, activeMarks, openMarks);
              openMarks = activeMarks.length;
            }
          }
        } else if (tile.isText()) {
          this.builder.ensureLine(null);
          if (!from2 && to == tile.length) {
            this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile));
          } else {
            this.cache.add(tile);
            this.builder.addText(tile.text.slice(from2, to), activeMarks, openMarks);
          }
          openMarks = activeMarks.length;
        } else if (tile.isLine()) {
          tile.flags &= ~1;
          this.cache.reused.set(
            tile,
            1
            /* Reused.Full */
          );
          this.builder.addLine(tile);
        } else if (tile instanceof WidgetBufferTile) {
          this.cache.add(tile);
        } else if (tile instanceof MarkTile) {
          this.builder.ensureLine(null);
          this.builder.addMark(tile, activeMarks, openMarks);
          this.cache.reused.set(
            tile,
            1
            /* Reused.Full */
          );
          openMarks = activeMarks.length;
        } else {
          return false;
        }
        this.openWidget = false;
      },
      enter: (tile) => {
        if (tile.isLine()) {
          this.builder.addLineStart(tile.attrs, this.cache.maybeReuse(tile));
        } else {
          this.cache.add(tile);
          if (tile instanceof MarkTile)
            activeMarks.unshift(tile.mark);
        }
        this.openWidget = false;
      },
      leave: (tile) => {
        if (tile.isLine()) {
          if (activeMarks.length)
            activeMarks.length = openMarks = 0;
        } else if (tile instanceof MarkTile) {
          activeMarks.shift();
          openMarks = Math.min(openMarks, activeMarks.length);
        }
      },
      break: () => {
        this.builder.addBreak();
        this.openWidget = false;
      }
    });
    this.text.skip(length);
  }
  emit(from2, to) {
    let pendingLineAttrs = null;
    let b3 = this.builder, markCount = 0;
    let openEnd = RangeSet.spans(this.decorations, from2, to, {
      point: (from3, to2, deco, active, openStart, index2) => {
        if (deco instanceof PointDecoration) {
          if (this.disallowBlockEffectsFor[index2]) {
            if (deco.block)
              throw new RangeError("Block decorations may not be specified via plugins");
            if (to2 > this.view.state.doc.lineAt(from3).to)
              throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
          }
          markCount = active.length;
          if (openStart > active.length) {
            b3.continueWidget(to2 - from3);
          } else {
            let widget = deco.widget || (deco.block ? NullWidget.block : NullWidget.inline);
            let flags = widgetFlags(deco);
            let tile = this.cache.findWidget(widget, to2 - from3, flags) || WidgetTile.of(widget, this.view, to2 - from3, flags);
            if (deco.block) {
              if (deco.startSide > 0)
                b3.addLineStartIfNotCovered(pendingLineAttrs);
              b3.addBlockWidget(tile);
            } else {
              b3.ensureLine(pendingLineAttrs);
              b3.addInlineWidget(tile, active, openStart);
            }
          }
          pendingLineAttrs = null;
        } else {
          pendingLineAttrs = addLineDeco(pendingLineAttrs, deco);
        }
        if (to2 > from3)
          this.text.skip(to2 - from3);
      },
      span: (from3, to2, active, openStart) => {
        for (let pos = from3; pos < to2; ) {
          let chars = this.text.next(Math.min(512, to2 - pos));
          if (chars == null) {
            b3.addLineStartIfNotCovered(pendingLineAttrs);
            b3.addBreak();
            pos++;
          } else {
            b3.ensureLine(pendingLineAttrs);
            b3.addText(chars, active, pos == from3 ? openStart : active.length);
            pos += chars.length;
          }
          pendingLineAttrs = null;
        }
      }
    });
    b3.addLineStartIfNotCovered(pendingLineAttrs);
    this.openWidget = openEnd > markCount;
    this.openMarks = openEnd;
  }
  forward(from2, to, side = 1) {
    if (to - from2 <= 10) {
      this.old.advance(to - from2, side, this.reuseWalker);
    } else {
      this.old.advance(5, -1, this.reuseWalker);
      this.old.advance(to - from2 - 10, -1);
      this.old.advance(5, side, this.reuseWalker);
    }
  }
  getCompositionContext(text3) {
    let marks3 = [], line = null;
    for (let parent = text3.parentNode; ; parent = parent.parentNode) {
      let tile = Tile.get(parent);
      if (parent == this.view.contentDOM)
        break;
      if (tile instanceof MarkTile)
        marks3.push(tile);
      else if (tile === null || tile === void 0 ? void 0 : tile.isLine())
        line = tile;
      else if (parent.nodeName == "DIV" && !line && parent != this.view.contentDOM)
        line = new LineTile(parent, lineBaseAttrs);
      else
        marks3.push(MarkTile.of(new MarkDecoration({ tagName: parent.nodeName.toLowerCase(), attributes: getAttrs(parent) }), parent));
    }
    return { line, marks: marks3 };
  }
};
function hasContent(tile, requireText) {
  let scan = (tile2) => {
    for (let ch of tile2.children)
      if ((requireText ? ch.isText() : ch.length) || scan(ch))
        return true;
    return false;
  };
  return scan(tile);
}
function widgetFlags(deco) {
  let flags = deco.isReplace ? (deco.startSide < 0 ? 64 : 0) | (deco.endSide > 0 ? 128 : 0) : deco.startSide > 0 ? 32 : 16;
  if (deco.block)
    flags |= 256;
  return flags;
}
var lineBaseAttrs = { class: "cm-line" };
function addLineDeco(value2, deco) {
  let attrs2 = deco.spec.attributes, cls = deco.spec.class;
  if (!attrs2 && !cls)
    return value2;
  if (!value2)
    value2 = { class: "cm-line" };
  if (attrs2)
    combineAttrs(attrs2, value2);
  if (cls)
    value2.class += " " + cls;
  return value2;
}
function getMarks(ptr) {
  let found2 = [];
  for (let i3 = ptr.parents.length; i3 > 1; i3--) {
    let tile = i3 == ptr.parents.length ? ptr.tile : ptr.parents[i3].tile;
    if (tile instanceof MarkTile)
      found2.push(tile.mark);
  }
  return found2;
}
function freeNode(node) {
  let tile = Tile.get(node);
  if (tile)
    tile.setDOM(node.cloneNode());
  return node;
}
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 BreakWidget = /* @__PURE__ */ new class extends WidgetType {
  toDOM() {
    return document.createElement("br");
  }
  get isHidden() {
    return true;
  }
  get editable() {
    return true;
  }
}();
var DocView = class {
  constructor(view) {
    this.view = view;
    this.decorations = [];
    this.blockWrappers = [];
    this.dynamicDecorationMap = [false];
    this.domChanged = null;
    this.hasComposition = null;
    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.updateDeco();
    this.tile = new DocTile(view, view.contentDOM);
    this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], null);
  }
  // Update the document view to a given state.
  update(update2) {
    var _a4;
    let changedRanges = update2.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 = update2.changes.mapPos(this.minWidthFrom, 1);
        this.minWidthTo = update2.changes.mapPos(this.minWidthTo, 1);
      }
    }
    this.updateEditContextFormatting(update2);
    let readCompositionAt = -1;
    if (this.view.inputState.composing >= 0 && !this.view.observer.editContext) {
      if ((_a4 = this.domChanged) === null || _a4 === void 0 ? void 0 : _a4.newSel)
        readCompositionAt = this.domChanged.newSel.head;
      else if (!touchesComposition(update2.changes, this.hasComposition) && !update2.selectionSet)
        readCompositionAt = update2.state.selection.main.head;
    }
    let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update2.changes, readCompositionAt) : null;
    this.domChanged = null;
    if (this.hasComposition) {
      let { from: from2, to } = this.hasComposition;
      changedRanges = new ChangedRange(from2, to, update2.changes.mapPos(from2, -1), update2.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 && update2 && update2.state.doc.lines != update2.startState.doc.lines)
      this.forceSelection = true;
    let prevDeco = this.decorations, prevWrappers = this.blockWrappers;
    this.updateDeco();
    let decoDiff = findChangedDeco(prevDeco, this.decorations, update2.changes);
    if (decoDiff.length)
      changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
    let blockDiff = findChangedWrappers(prevWrappers, this.blockWrappers, update2.changes);
    if (blockDiff.length)
      changedRanges = ChangedRange.extendWithRanges(changedRanges, blockDiff);
    if (composition && !changedRanges.some((r3) => r3.fromA <= composition.range.fromA && r3.toA >= composition.range.toA))
      changedRanges = composition.range.addToSet(changedRanges.slice());
    if (this.tile.flags & 2 && changedRanges.length == 0) {
      return false;
    } else {
      this.updateInner(changedRanges, composition);
      if (update2.transactions.length)
        this.lastUpdate = Date.now();
      return true;
    }
  }
  // Used by update and the constructor do perform the actual DOM
  // update
  updateInner(changes, composition) {
    this.view.viewState.mustMeasureContent = true;
    let { observer } = this.view;
    observer.ignore(() => {
      if (composition || changes.length) {
        let oldTile = this.tile;
        let builder = new TileUpdate(this.view, oldTile, this.blockWrappers, this.decorations, this.dynamicDecorationMap);
        this.tile = builder.run(changes, composition);
        destroyDropped(oldTile, builder.cache.reused);
      }
      this.tile.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
      this.tile.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
      let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : void 0;
      this.tile.sync(track);
      if (track && (track.written || observer.selectionRange.focusNode != track.node || !this.tile.dom.contains(track.node)))
        this.forceSelection = true;
      this.tile.dom.style.height = "";
    });
    let gaps = [];
    if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
      for (let child of this.tile.children)
        if (child.isWidget() && child.widget instanceof BlockGapWidget)
          gaps.push(child.dom);
    }
    observer.updateGaps(gaps);
  }
  updateEditContextFormatting(update2) {
    this.editContextFormatting = this.editContextFormatting.map(update2.changes);
    for (let tr2 of update2.transactions)
      for (let effect2 of tr2.effects)
        if (effect2.is(setEditContextFormatting)) {
          this.editContextFormatting = effect2.value;
        }
  }
  // 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 { dom } = this.tile;
    let activeElt = this.view.root.activeElement, focused = activeElt == dom;
    let selectionNotFocus = !focused && !(this.view.state.facet(editable) || dom.tabIndex > -1) && hasSelection(dom, this.view.observer.selectionRange) && !(activeElt && dom.contains(activeElt));
    if (!(focused || fromPointer || selectionNotFocus))
      return;
    let force = this.forceSelection;
    this.forceSelection = false;
    let main2 = this.view.state.selection.main, anchor, head2;
    if (main2.empty) {
      head2 = anchor = this.inlineDOMNearPos(main2.anchor, main2.assoc || 1);
    } else {
      head2 = this.inlineDOMNearPos(main2.head, main2.head == main2.from ? 1 : -1);
      anchor = this.inlineDOMNearPos(main2.anchor, main2.anchor == main2.from ? 1 : -1);
    }
    if (browser.gecko && main2.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, main2)) {
      this.view.observer.ignore(() => {
        if (browser.android && browser.chrome && dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, dom)) {
          dom.blur();
          dom.focus({ preventScroll: true });
        }
        let rawSel = getSelection2(this.view.root);
        if (!rawSel) ;
        else if (main2.empty) {
          if (browser.gecko) {
            let nextTo = nextToUneditable(anchor.node, anchor.offset);
            if (nextTo && nextTo != (1 | 2)) {
              let text3 = (nextTo == 1 ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
              if (text3)
                anchor = new DOMPos(text3.node, text3.offset);
            }
          }
          rawSel.collapse(anchor.node, anchor.offset);
          if (main2.bidiLevel != null && rawSel.caretBidiLevel !== void 0)
            rawSel.caretBidiLevel = main2.bidiLevel;
        } else if (rawSel.extend) {
          rawSel.collapse(anchor.node, anchor.offset);
          try {
            rawSel.extend(head2.node, head2.offset);
          } catch (_5) {
          }
        } else {
          let range2 = document.createRange();
          if (main2.anchor > main2.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 == dom) {
          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 = getSelection2(view.root);
    let { anchorNode, anchorOffset } = view.observer.selectionRange;
    if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
      return;
    let line = this.lineAt(cursor.head, cursor.assoc);
    if (!line)
      return;
    let lineStart = line.posAtStart;
    if (cursor.head == lineStart || cursor.head == lineStart + line.length)
      return;
    let before2 = this.coordsAt(cursor.head, -1), after2 = this.coordsAt(cursor.head, 1);
    if (!before2 || !after2 || before2.bottom > after2.top)
      return;
    let dom = this.domAtPos(cursor.head + cursor.assoc, 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);
  }
  posFromDOM(node, offset) {
    let tile = this.tile.nearest(node);
    if (!tile)
      return this.tile.dom.compareDocumentPosition(node) & 2 ? 0 : this.view.state.doc.length;
    let start = tile.posAtStart;
    if (tile.isComposite()) {
      let after2;
      if (node == tile.dom) {
        after2 = tile.dom.childNodes[offset];
      } else {
        let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
        for (; ; ) {
          let parent = node.parentNode;
          if (parent == tile.dom)
            break;
          if (bias == 0 && parent.firstChild != parent.lastChild) {
            if (node == parent.firstChild)
              bias = -1;
            else
              bias = 1;
          }
          node = parent;
        }
        if (bias < 0)
          after2 = node;
        else
          after2 = node.nextSibling;
      }
      if (after2 == tile.dom.firstChild)
        return start;
      while (after2 && !Tile.get(after2))
        after2 = after2.nextSibling;
      if (!after2)
        return start + tile.length;
      for (let i3 = 0, pos = start; ; i3++) {
        let child = tile.children[i3];
        if (child.dom == after2)
          return pos;
        pos += child.length + child.breakAfter;
      }
    } else if (tile.isText()) {
      return node == tile.dom ? start + offset : start + (offset ? tile.length : 0);
    } else {
      return start;
    }
  }
  domAtPos(pos, side) {
    let { tile, offset } = this.tile.resolveBlock(pos, side);
    if (tile.isWidget())
      return tile.domPosFor(pos, side);
    return tile.domIn(offset, side);
  }
  inlineDOMNearPos(pos, side) {
    let before2, beforeOff = -1, beforeBad = false;
    let after2, afterOff = -1, afterBad = false;
    this.tile.blockTiles((tile, off) => {
      if (tile.isWidget()) {
        if (tile.flags & 32 && off >= pos)
          return true;
        if (tile.flags & 16)
          beforeBad = true;
      } else {
        let end = off + tile.length;
        if (off <= pos) {
          before2 = tile;
          beforeOff = pos - off;
          beforeBad = end < pos;
        }
        if (end >= pos && !after2) {
          after2 = tile;
          afterOff = pos - off;
          afterBad = off > pos;
        }
        if (off > pos && after2)
          return true;
      }
    });
    if (!before2 && !after2)
      return this.domAtPos(pos, side);
    if (beforeBad && after2)
      before2 = null;
    else if (afterBad && before2)
      after2 = null;
    return before2 && side < 0 || !after2 ? before2.domIn(beforeOff, side) : after2.domIn(afterOff, side);
  }
  coordsAt(pos, side) {
    let { tile, offset } = this.tile.resolveBlock(pos, side);
    if (tile.isWidget()) {
      if (tile.widget instanceof BlockGapWidget)
        return null;
      return tile.coordsInWidget(offset, side, true);
    }
    return tile.coordsIn(offset, side);
  }
  lineAt(pos, side) {
    let { tile } = this.tile.resolveBlock(pos, side);
    return tile.isLine() ? tile : null;
  }
  coordsForChar(pos) {
    let { tile, offset } = this.tile.resolveBlock(pos, 1);
    if (!tile.isLine())
      return null;
    function scan(tile2, offset2) {
      if (tile2.isComposite()) {
        for (let ch of tile2.children) {
          if (ch.length >= offset2) {
            let found2 = scan(ch, offset2);
            if (found2)
              return found2;
          }
          offset2 -= ch.length;
          if (offset2 < 0)
            break;
        }
      } else if (tile2.isText() && offset2 < tile2.length) {
        let end = findClusterBreak2(tile2.text, offset2);
        if (end == offset2)
          return null;
        let rects = textRange(tile2.dom, offset2, 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;
    }
    return scan(tile, offset);
  }
  measureVisibleLineHeights(viewport) {
    let result2 = [], { from: from2, 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;
    let spaceAbove = 0;
    let scan = (tile, pos, measureBounds) => {
      for (let i3 = 0; i3 < tile.children.length; i3++) {
        if (pos > to)
          break;
        let child = tile.children[i3], end = pos + child.length;
        let childRect = child.dom.getBoundingClientRect(), { height } = childRect;
        if (measureBounds && !i3)
          spaceAbove += childRect.top - measureBounds.top;
        if (child instanceof BlockWrapperTile) {
          if (end > from2)
            scan(child, pos, childRect);
        } else if (pos >= from2) {
          if (spaceAbove > 0)
            result2.push(-spaceAbove);
          result2.push(height + spaceAbove);
          spaceAbove = 0;
          if (isWider) {
            let last3 = child.dom.lastChild;
            let rects = last3 ? clientRectsFor(last3) : [];
            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;
              }
            }
          }
        }
        if (measureBounds && i3 == tile.children.length - 1)
          spaceAbove += measureBounds.bottom - childRect.bottom;
        pos = end + child.breakAfter;
      }
    };
    scan(this.tile, 0, null);
    return result2;
  }
  textDirectionAt(pos) {
    let { tile } = this.tile.resolveBlock(pos, 1);
    return getComputedStyle(tile.dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
  }
  measureTextSize() {
    let lineMeasure = this.tile.blockTiles((tile) => {
      if (tile.isLine() && tile.children.length && tile.length <= 20) {
        let totalWidth = 0, textHeight2;
        for (let child of tile.children) {
          if (!child.isText() || /[^ -~]/.test(child.text))
            return void 0;
          let rects = clientRectsFor(child.dom);
          if (rects.length != 1)
            return void 0;
          totalWidth += rects[0].width;
          textHeight2 = rects[0].height;
        }
        if (totalWidth)
          return {
            lineHeight: tile.dom.getBoundingClientRect().height,
            charWidth: totalWidth / tile.length,
            textHeight: textHeight2
          };
      }
    });
    if (lineMeasure)
      return lineMeasure;
    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.tile.dom.appendChild(dummy);
      let rect = clientRectsFor(dummy.firstChild)[0];
      lineHeight = dummy.getBoundingClientRect().height;
      charWidth = rect && rect.width ? rect.width / 27 : 7;
      textHeight = rect && rect.height ? rect.height : lineHeight;
      dummy.remove();
    });
    return { lineHeight, charWidth, textHeight };
  }
  computeBlockGapDeco() {
    let deco = [], vs = this.view.viewState;
    for (let pos = 0, i3 = 0; ; i3++) {
      let next2 = i3 == vs.viewports.length ? null : vs.viewports[i3];
      let end = next2 ? next2.from - 1 : this.view.state.doc.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 i3 = 1;
    let allDeco = this.view.state.facet(decorations).map((d3) => {
      let dynamic = this.dynamicDecorationMap[i3++] = typeof d3 == "function";
      return dynamic ? d3(this.view) : d3;
    });
    let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d3, i4) => {
      let dynamic = typeof d3 == "function";
      if (dynamic)
        dynamicOuter = true;
      return dynamic ? d3(this.view) : d3;
    });
    if (outerDeco.length) {
      this.dynamicDecorationMap[i3++] = dynamicOuter;
      allDeco.push(RangeSet.join(outerDeco));
    }
    this.decorations = [
      this.editContextFormatting,
      ...allDeco,
      this.computeBlockGapDeco(),
      this.view.viewState.lineGapDeco
    ];
    while (i3 < this.decorations.length)
      this.dynamicDecorationMap[i3++] = false;
    this.blockWrappers = this.view.state.facet(blockWrappers).map((v3) => typeof v3 == "function" ? v3(this.view) : v3);
  }
  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 (e3) {
        logException(this.view.state, e3, "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);
  }
  lineHasWidget(pos) {
    let scan = (child) => child.isWidget() || child.children.some(scan);
    return scan(this.tile.resolveBlock(pos, 1).tile);
  }
  destroy() {
    destroyDropped(this.tile);
  }
};
function destroyDropped(tile, reused) {
  let r3 = reused === null || reused === void 0 ? void 0 : reused.get(tile);
  if (r3 != 1) {
    if (r3 == null)
      tile.destroy();
    for (let ch of tile.children)
      destroyDropped(ch, reused);
  }
}
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 tileAfter = Tile.get(textAfter.node);
    if (!tileAfter || tileAfter.isText() && tileAfter.text != textAfter.node.nodeValue) {
      textNode = textAfter;
    } else if (view.docView.lastCompositionAfterCursor) {
      let tileBefore = Tile.get(textBefore.node);
      if (!(!tileBefore || tileBefore.isText() && tileBefore.text != textBefore.node.nodeValue))
        textNode = textAfter;
    }
  }
  view.docView.lastCompositionAfterCursor = textNode != textBefore;
  if (!textNode)
    return null;
  let from2 = headPos - textNode.offset;
  return { from: from2, to: from2 + textNode.node.nodeValue.length, node: textNode.node };
}
function findCompositionRange(view, changes, headPos) {
  let found2 = findCompositionNode(view, headPos);
  if (!found2)
    return null;
  let { node: textNode, from: from2, to } = found2, text3 = textNode.nodeValue;
  if (/[\n\r]/.test(text3))
    return null;
  if (view.state.doc.sliceString(found2.from, found2.to) != text3)
    return null;
  let inv = changes.invertedDesc;
  return { range: new ChangedRange(inv.mapPos(from2), inv.mapPos(to), from2, to), text: textNode };
}
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(from2, to) {
    addRange2(from2, to, this.changes);
  }
  comparePoint(from2, to) {
    addRange2(from2, to, this.changes);
  }
  boundChange(pos) {
    addRange2(pos, pos, this.changes);
  }
};
function findChangedDeco(a3, b3, diff) {
  let comp = new DecorationComparator$1();
  RangeSet.compare(a3, b3, diff, comp);
  return comp.changes;
}
var WrapperComparator = class {
  constructor() {
    this.changes = [];
  }
  compareRange(from2, to) {
    addRange2(from2, to, this.changes);
  }
  comparePoint() {
  }
  boundChange(pos) {
    addRange2(pos, pos, this.changes);
  }
};
function findChangedWrappers(a3, b3, diff) {
  let comp = new WrapperComparator();
  RangeSet.compare(a3, b3, diff, comp);
  return comp.changes;
}
function inUneditable(node, inside) {
  for (let cur2 = node; cur2 && cur2 != inside; 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((from2, to) => {
      if (from2 < composition.to && to > composition.from)
        touched = true;
    });
  return touched;
}
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;
  }
};
function groupAt(state, pos, bias = 1) {
  let categorize = state.charCategorizer(pos);
  let line = state.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 from2 = linePos, to = linePos;
  if (bias < 0)
    from2 = findClusterBreak2(line.text, linePos, false);
  else
    to = findClusterBreak2(line.text, linePos);
  let cat = categorize(line.text.slice(from2, to));
  while (from2 > 0) {
    let prev = findClusterBreak2(line.text, from2, false);
    if (categorize(line.text.slice(prev, from2)) != cat)
      break;
    from2 = 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(from2 + line.from, to + line.from);
}
function posAtCoordsImprecise(view, contentRect, block3, x3, y3) {
  let into = Math.round((x3 - contentRect.left) * view.defaultCharacterWidth);
  if (view.lineWrapping && block3.height > view.defaultLineHeight * 1.5) {
    let textHeight = view.viewState.heightOracle.textHeight;
    let line = Math.floor((y3 - block3.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
    into += line * view.viewState.heightOracle.lineLength;
  }
  let content2 = view.state.sliceDoc(block3.from, block3.to);
  return block3.from + findColumn(content2, into, view.state.tabSize);
}
function blockAt(view, pos, side) {
  let line = view.lineBlockAt(pos);
  if (Array.isArray(line.type)) {
    let best;
    for (let l3 of line.type) {
      if (l3.from > pos)
        break;
      if (l3.to < pos)
        continue;
      if (l3.from < pos && l3.to > pos)
        return l3;
      if (!best || l3.type == BlockType.Text && (best.type != l3.type || (side < 0 ? l3.from < pos : l3.to > pos)))
        best = l3;
    }
    return best || line;
  }
  return line;
}
function moveToLineBoundary(view, start, forward, includeWrap) {
  let line = blockAt(view, start.head, start.assoc || -1);
  let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.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, start, forward, by) {
  let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
  let direction = view.textDirectionAt(line.from);
  for (let cur2 = start, 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, start) {
  let categorize = view.state.charCategorizer(pos);
  let cat = categorize(start);
  return (next2) => {
    let nextCat = categorize(next2);
    if (cat == CharCategory.Space)
      cat = nextCat;
    return cat == nextCat;
  };
}
function moveVertically(view, start, forward, distance) {
  let startPos = start.head, dir = forward ? 1 : -1;
  if (startPos == (forward ? view.state.doc.length : 0))
    return EditorSelection.cursor(startPos, start.assoc);
  let goal = start.goalColumn, startY;
  let rect = view.contentDOM.getBoundingClientRect();
  let startCoords = view.coordsAtPos(startPos, (start.empty ? start.assoc : 0) || (forward ? 1 : -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;
  let pos = posAtCoords(view, { x: resolvedGoal, y: startY + dist2 * dir }, false, dir);
  return EditorSelection.cursor(pos.pos, 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, (from2, to, value2) => {
        if (pos > from2 && pos < to) {
          let side = moved || bias || (pos - from2 < to - pos ? -1 : 1);
          pos = side < 0 ? from2 : to;
          moved = side;
        }
      });
    }
    if (!moved)
      return pos;
  }
}
function skipAtomsForSelection(atoms, sel) {
  let ranges = null;
  for (let i3 = 0; i3 < sel.ranges.length; i3++) {
    let range2 = sel.ranges[i3], updated = null;
    if (range2.empty) {
      let pos = skipAtomicRanges(atoms, range2.from, 0);
      if (pos != range2.from)
        updated = EditorSelection.cursor(pos, -1);
    } else {
      let from2 = skipAtomicRanges(atoms, range2.from, -1);
      let to = skipAtomicRanges(atoms, range2.to, 1);
      if (from2 != range2.from || to != range2.to)
        updated = EditorSelection.range(range2.from == range2.anchor ? from2 : to, range2.from == range2.head ? from2 : to);
    }
    if (updated) {
      if (!ranges)
        ranges = sel.ranges.slice();
      ranges[i3] = updated;
    }
  }
  return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
}
function skipAtoms(view, oldPos, pos) {
  let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map((f3) => f3(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
  return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
var PosAssoc = class {
  constructor(pos, assoc) {
    this.pos = pos;
    this.assoc = assoc;
  }
};
function posAtCoords(view, coords, precise, scanY) {
  let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop;
  let { x: x3, y: y3 } = coords, yOffset = y3 - docTop, block3;
  for (; ; ) {
    if (yOffset < 0)
      return new PosAssoc(0, 1);
    if (yOffset > view.viewState.docHeight)
      return new PosAssoc(view.state.doc.length, -1);
    block3 = view.elementAtHeight(yOffset);
    if (scanY == null)
      break;
    if (block3.type == BlockType.Text) {
      if (scanY < 0 ? block3.to < view.viewport.from : block3.from > view.viewport.to)
        break;
      let rect = view.docView.coordsAt(scanY < 0 ? block3.from : block3.to, scanY > 0 ? -1 : 1);
      if (rect && (scanY < 0 ? rect.top <= yOffset + docTop : rect.bottom >= yOffset + docTop))
        break;
    }
    let halfLine = view.viewState.heightOracle.textHeight / 2;
    yOffset = scanY > 0 ? block3.bottom + halfLine : block3.top - halfLine;
  }
  if (view.viewport.from >= block3.to || view.viewport.to <= block3.from) {
    if (precise)
      return null;
    if (block3.type == BlockType.Text) {
      let pos = posAtCoordsImprecise(view, content2, block3, x3, y3);
      return new PosAssoc(pos, pos == block3.from ? 1 : -1);
    }
  }
  if (block3.type != BlockType.Text)
    return yOffset < (block3.top + block3.bottom) / 2 ? new PosAssoc(block3.from, 1) : new PosAssoc(block3.to, -1);
  let line = view.docView.lineAt(block3.from, 2);
  if (!line || line.length != block3.length)
    line = view.docView.lineAt(block3.from, -2);
  return new InlineCoordsScan(view, x3, y3, view.textDirectionAt(block3.from)).scanTile(line, block3.from);
}
var InlineCoordsScan = class {
  constructor(view, x3, y3, baseDir) {
    this.view = view;
    this.x = x3;
    this.y = y3;
    this.baseDir = baseDir;
    this.line = null;
    this.spans = null;
  }
  bidiSpansAt(pos) {
    if (!this.line || this.line.from > pos || this.line.to < pos) {
      this.line = this.view.state.doc.lineAt(pos);
      this.spans = this.view.bidiSpans(this.line);
    }
    return this;
  }
  baseDirAt(pos, side) {
    let { line, spans } = this.bidiSpansAt(pos);
    let level = spans[BidiSpan.find(spans, pos - line.from, -1, side)].level;
    return level == this.baseDir;
  }
  dirAt(pos, side) {
    let { line, spans } = this.bidiSpansAt(pos);
    return spans[BidiSpan.find(spans, pos - line.from, -1, side)].dir;
  }
  // Used to short-circuit bidi tests for content with a uniform direction
  bidiIn(from2, to) {
    let { spans, line } = this.bidiSpansAt(from2);
    return spans.length > 1 || spans.length && (spans[0].level != this.baseDir || spans[0].to + line.from < to);
  }
  // Scan through the rectangles for the content of a tile with inline
  // content, looking for one that overlaps the queried position
  // vertically andis
  // closest horizontally. The caller is responsible for dividing its
  // content into N pieces, and pass an array with N+1 positions
  // (including the position after the last piece). For a text tile,
  // these will be character clusters, for a composite tile, these
  // will be child tiles.
  scan(positions, getRects) {
    let lo = 0, hi = positions.length - 1, seen = /* @__PURE__ */ new Set();
    let bidi = this.bidiIn(positions[0], positions[hi]);
    let above, below;
    let closestI = -1, closestDx = 1e9, closestRect;
    search: while (lo < hi) {
      let dist2 = hi - lo, mid = lo + hi >> 1;
      adjust: if (seen.has(mid)) {
        let scan = lo + Math.floor(Math.random() * dist2);
        for (let i3 = 0; i3 < dist2; i3++) {
          if (!seen.has(scan)) {
            mid = scan;
            break adjust;
          }
          scan++;
          if (scan == hi)
            scan = lo;
        }
        break search;
      }
      seen.add(mid);
      let rects = getRects(mid);
      if (rects)
        for (let i3 = 0; i3 < rects.length; i3++) {
          let rect = rects[i3], side = 0;
          if (rect.bottom < this.y) {
            if (!above || above.bottom < rect.bottom)
              above = rect;
            side = 1;
          } else if (rect.top > this.y) {
            if (!below || below.top > rect.top)
              below = rect;
            side = -1;
          } else {
            let off = rect.left > this.x ? this.x - rect.left : rect.right < this.x ? this.x - rect.right : 0;
            let dx = Math.abs(off);
            if (dx < closestDx) {
              closestI = mid;
              closestDx = dx;
              closestRect = rect;
            }
            if (off)
              side = off < 0 == (this.baseDir == Direction.LTR) ? -1 : 1;
          }
          if (side == -1 && (!bidi || this.baseDirAt(positions[mid], 1)))
            hi = mid;
          else if (side == 1 && (!bidi || this.baseDirAt(positions[mid + 1], -1)))
            lo = mid + 1;
        }
    }
    if (!closestRect) {
      let side = above && (!below || this.y - above.bottom < below.top - this.y) ? above : below;
      this.y = (side.top + side.bottom) / 2;
      return this.scan(positions, getRects);
    }
    let ltr = (bidi ? this.dirAt(positions[closestI], 1) : this.baseDir) == Direction.LTR;
    return {
      i: closestI,
      // Test whether x is closes to the start or end of this element
      after: this.x > (closestRect.left + closestRect.right) / 2 == ltr
    };
  }
  scanText(tile, offset) {
    let positions = [];
    for (let i3 = 0; i3 < tile.length; i3 = findClusterBreak2(tile.text, i3))
      positions.push(offset + i3);
    positions.push(offset + tile.length);
    let scan = this.scan(positions, (i3) => {
      let off = positions[i3] - offset, end = positions[i3 + 1] - offset;
      return textRange(tile.dom, off, end).getClientRects();
    });
    return scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(positions[scan.i], 1);
  }
  scanTile(tile, offset) {
    if (!tile.length)
      return new PosAssoc(offset, 1);
    if (tile.children.length == 1) {
      let child2 = tile.children[0];
      if (child2.isText())
        return this.scanText(child2, offset);
      else if (child2.isComposite())
        return this.scanTile(child2, offset);
    }
    let positions = [offset];
    for (let i3 = 0, pos2 = offset; i3 < tile.children.length; i3++)
      positions.push(pos2 += tile.children[i3].length);
    let scan = this.scan(positions, (i3) => {
      let child2 = tile.children[i3];
      if (child2.flags & 48)
        return null;
      return (child2.dom.nodeType == 1 ? child2.dom : textRange(child2.dom, 0, child2.length)).getClientRects();
    });
    let child = tile.children[scan.i], pos = positions[scan.i];
    if (child.isText())
      return this.scanText(child, pos);
    if (child.isComposite())
      return this.scanTile(child, pos);
    return scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(pos, 1);
  }
};
var LineBreakPlaceholder = "\uFFFF";
var DOMReader = class {
  constructor(points, view) {
    this.points = points;
    this.view = view;
    this.text = "";
    this.lineSeparator = view.state.facet(EditorState2.lineSeparator);
  }
  append(text3) {
    this.text += text3;
  }
  lineBreak() {
    this.text += LineBreakPlaceholder;
  }
  readRange(start, end) {
    if (!start)
      return this;
    let parent = start.parentNode;
    for (let cur2 = start; ; ) {
      this.findPointBefore(parent, cur2);
      let oldLen = this.text.length;
      this.readNode(cur2);
      let tile = Tile.get(cur2), next2 = cur2.nextSibling;
      if (next2 == end) {
        if ((tile === null || tile === void 0 ? void 0 : tile.breakAfter) && !next2 && parent != this.view.contentDOM)
          this.lineBreak();
        break;
      }
      let nextTile = Tile.get(next2);
      if ((tile && nextTile ? tile.breakAfter : (tile ? tile.breakAfter : isBlockElement(cur2)) || isBlockElement(next2) && (cur2.nodeName != "BR" || (tile === null || tile === void 0 ? void 0 : tile.isWidget())) && this.text.length > oldLen) && !isEmptyToEnd(next2, end))
        this.lineBreak();
      cur2 = next2;
    }
    this.findPointBefore(parent, end);
    return this;
  }
  readTextNode(node) {
    let text3 = node.nodeValue;
    for (let point of this.points)
      if (point.node == node)
        point.pos = this.text.length + Math.min(point.offset, text3.length);
    for (let off = 0, re2 = this.lineSeparator ? null : /\r\n?|\n/g; ; ) {
      let nextBreak = -1, breakSize = 1, m3;
      if (this.lineSeparator) {
        nextBreak = text3.indexOf(this.lineSeparator, off);
        breakSize = this.lineSeparator.length;
      } else if (m3 = re2.exec(text3)) {
        nextBreak = m3.index;
        breakSize = m3[0].length;
      }
      this.append(text3.slice(off, nextBreak < 0 ? text3.length : nextBreak));
      if (nextBreak < 0)
        break;
      this.lineBreak();
      if (breakSize > 1) {
        for (let point of this.points)
          if (point.node == node && point.pos > this.text.length)
            point.pos -= breakSize - 1;
      }
      off = nextBreak + breakSize;
    }
  }
  readNode(node) {
    let tile = Tile.get(node);
    let fromView = tile && tile.overrideDOMText;
    if (fromView != null) {
      this.findPointInside(node, fromView.length);
      for (let i3 = fromView.iter(); !i3.next().done; ) {
        if (i3.lineBreak)
          this.lineBreak();
        else
          this.append(i3.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 point of this.points)
      if (point.node == node && node.childNodes[point.offset] == next2)
        point.pos = this.text.length;
  }
  findPointInside(node, length) {
    for (let point of this.points)
      if (node.nodeType == 3 ? point.node == node : node.contains(point.node))
        point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
  }
};
function isAtEnd(parent, node, offset) {
  for (; ; ) {
    if (!node || offset < maxOffset(node))
      return false;
    if (node == parent)
      return true;
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
}
function isEmptyToEnd(node, end) {
  let widgets;
  for (; ; node = node.nextSibling) {
    if (node == end || !node)
      break;
    let view = Tile.get(node);
    if (!(view === null || view === void 0 ? void 0 : view.isWidget()))
      return false;
    if (view)
      (widgets || (widgets = [])).push(view);
  }
  if (widgets)
    for (let w3 of widgets) {
      let override2 = w3.overrideDOMText;
      if (override2 === null || override2 === void 0 ? void 0 : override2.length)
        return false;
    }
  return true;
}
var DOMPoint = class {
  constructor(node, offset) {
    this.node = node;
    this.offset = offset;
    this.pos = -1;
  }
};
var DOMChange = class {
  constructor(view, start, end, typeOver) {
    this.typeOver = typeOver;
    this.bounds = null;
    this.text = "";
    this.domChanged = start > -1;
    let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
    if (view.state.readOnly && start > -1) {
      this.newSel = null;
    } else if (start > -1 && (this.bounds = domBoundsAround(view.docView.tile, start, end, 0))) {
      let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
      let reader = new DOMReader(selPoints, view);
      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 || !contains3(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 || !contains3(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 from2 = Math.min(head2, anchor), to = Math.max(head2, anchor);
        let offFrom = vp.from - from2, offTo = vp.to - to;
        if ((offFrom == 0 || offFrom == 1 || from2 == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
          head2 = 0;
          anchor = view.state.doc.length;
        }
      }
      if (view.inputState.composing > -1 && view.state.selection.ranges.length > 1)
        this.newSel = view.state.selection.replaceRange(EditorSelection.range(anchor, head2));
      else
        this.newSel = EditorSelection.single(anchor, head2);
    }
  }
};
function domBoundsAround(tile, from2, to, offset) {
  if (tile.isComposite()) {
    let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
    for (let i3 = 0, pos = offset, prevEnd = offset; i3 < tile.children.length; i3++) {
      let child = tile.children[i3], end = pos + child.length;
      if (pos < from2 && end > to)
        return domBoundsAround(child, from2, to, pos);
      if (end >= from2 && fromI == -1) {
        fromI = i3;
        fromStart = pos;
      }
      if (pos > to && child.dom.parentNode == tile.dom) {
        toI = i3;
        toEnd = prevEnd;
        break;
      }
      prevEnd = end;
      pos = end + child.breakAfter;
    }
    return {
      from: fromStart,
      to: toEnd < 0 ? offset + tile.length : toEnd,
      startDOM: (fromI ? tile.children[fromI - 1].dom.nextSibling : null) || tile.dom.firstChild,
      endDOM: toI < tile.children.length && toI >= 0 ? tile.children[toI].dom : null
    };
  } else if (tile.isText()) {
    return { from: offset, to: offset + tile.length, startDOM: tile.dom, endDOM: tile.dom.nextSibling };
  } else {
    return null;
  }
}
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: from2, to } = domChange.bounds;
    let preferredPos = sel.from, preferredSide = null;
    if (lastKey === 8 || browser.android && domChange.text.length < to - from2) {
      preferredPos = sel.to;
      preferredSide = "end";
    }
    let diff = findDiff(view.state.doc.sliceString(from2, to, LineBreakPlaceholder), domChange.text, preferredPos - from2, 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: from2 + diff.from,
        to: from2 + diff.toA,
        insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder))
      };
    }
  } else if (newSel && (!view.hasFocus && view.state.facet(editable) || sameSelPos(newSel, sel))) {
    newSel = null;
  }
  if (!change && !newSel)
    return false;
  if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
    change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
  } else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
    if (newSel && change.insert.length == 2)
      newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
    change = { from: change.from, to: change.to, insert: Text.of([change.insert.toString().replace(".", " ")]) };
  } else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) {
    change = {
      from: sel.from,
      to: sel.to,
      insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
    };
  } else if (view.state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) && view.inputState.insertingTextAt > Date.now() - 50) {
    change = {
      from: sel.from,
      to: sel.to,
      insert: view.state.toText(view.inputState.insertingText)
    };
  } else if (browser.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
    if (newSel)
      newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
    change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
  }
  if (change) {
    return applyDOMChangeInner(view, change, newSel, lastKey);
  } else if (newSel && !sameSelPos(newSel, sel)) {
    let scrollIntoView3 = false, userEvent = "select";
    if (view.inputState.lastSelectionTime > Date.now() - 50) {
      if (view.inputState.lastSelectionOrigin == "select")
        scrollIntoView3 = true;
      userEvent = view.inputState.lastSelectionOrigin;
      if (userEvent == "select.pointer")
        newSel = skipAtomsForSelection(view.state.facet(atomicRanges).map((f3) => f3(view)), newSel);
    }
    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 text3 = 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((h3) => h3(view, change.from, change.to, text3, defaultInsert)))
    view.dispatch(defaultInsert());
  return true;
}
function applyDefaultInsert(view, change, newSel) {
  let tr2, startState = view.state, sel = startState.selection.main, inAtomic = -1;
  if (change.from == change.to && change.from < sel.from || change.from > sel.to) {
    let side = change.from < sel.from ? -1 : 1, pos = side < 0 ? sel.from : sel.to;
    let moved = skipAtomicRanges(startState.facet(atomicRanges).map((f3) => f3(view)), pos, side);
    if (change.from == moved)
      inAtomic = moved;
  }
  if (inAtomic > -1) {
    tr2 = {
      changes: change,
      selection: EditorSelection.cursor(change.from + change.insert.length, -1)
    };
  } else 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 before2 = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
    let after2 = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
    tr2 = startState.replaceSelection(view.state.toText(before2 + change.insert.sliceString(0, void 0, view.state.lineBreak) + after2));
  } 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 || view.inputState.compositionPendingChange) && change.to <= sel.to + 10 && 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;
      tr2 = startState.changeByRange((range2) => {
        if (range2.from == sel.from && range2.to == sel.to)
          return { changes, range: mainSel || range2.map(changes) };
        let to = range2.to - offset, from2 = to - replaced.length;
        if (view.state.sliceDoc(from2, 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.
        to >= compositionRange.from && from2 <= compositionRange.to)
          return { range: range2 };
        let rangeChanges = startState.changes({ from: from2, 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 {
      tr2 = {
        changes,
        selection: mainSel && startState.selection.replaceRange(mainSel)
      };
    }
  }
  let userEvent = "input.type";
  if (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
    view.inputState.compositionPendingChange = false;
    userEvent += ".compose";
    if (view.inputState.compositionFirstChange) {
      userEvent += ".start";
      view.inputState.compositionFirstChange = false;
    }
  }
  return startState.update(tr2, { userEvent, scrollIntoView: true });
}
function findDiff(a3, b3, preferredPos, preferredSide) {
  let minLen = Math.min(a3.length, b3.length);
  let from2 = 0;
  while (from2 < minLen && a3.charCodeAt(from2) == b3.charCodeAt(from2))
    from2++;
  if (from2 == minLen && a3.length == b3.length)
    return null;
  let toA = a3.length, toB = b3.length;
  while (toA > 0 && toB > 0 && a3.charCodeAt(toA - 1) == b3.charCodeAt(toB - 1)) {
    toA--;
    toB--;
  }
  if (preferredSide == "end") {
    let adjust = Math.max(0, from2 - Math.min(toA, toB));
    preferredPos -= toA + adjust - from2;
  }
  if (toA < from2 && a3.length < b3.length) {
    let move = preferredPos <= from2 && preferredPos >= toA ? from2 - preferredPos : 0;
    from2 -= move;
    toB = from2 + (toB - toA);
    toA = from2;
  } else if (toB < from2) {
    let move = preferredPos <= from2 && preferredPos >= toB ? from2 - preferredPos : 0;
    from2 -= move;
    toA = from2 + (toA - toB);
    toB = from2;
  }
  return { from: from2, toA, toB };
}
function selectionPoints(view) {
  let result2 = [];
  if (view.root.activeElement != view.contentDOM)
    return result2;
  let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
  if (anchorNode) {
    result2.push(new DOMPoint(anchorNode, anchorOffset));
    if (focusNode != anchorNode || focusOffset != anchorOffset)
      result2.push(new DOMPoint(focusNode, focusOffset));
  }
  return result2;
}
function selectionFromPoints(points, base3) {
  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 + base3, head2 + base3) : null;
}
function sameSelPos(selection, range2) {
  return range2.head == selection.main.head && range2.anchor == selection.main.anchor;
}
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.insertingText = "";
    this.insertingTextAt = 0;
    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 handlers3 = this.handlers[type];
    if (handlers3) {
      for (let observer of handlers3.observers)
        observer(this.view, event2);
      for (let handler of handlers3.handlers) {
        if (event2.defaultPrevented)
          break;
        if (handler(this.view, event2)) {
          event2.preventDefault();
          break;
        }
      }
    }
  }
  ensureHandlers(plugins) {
    let handlers3 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
    for (let type in handlers3)
      if (type != "scroll") {
        let passive = !handlers3[type].handlers.length;
        let exists = prev[type];
        if (exists && passive != !exists.handlers.length) {
          dom.removeEventListener(type, this.handleEvent);
          exists = null;
        }
        if (!exists)
          dom.addEventListener(type, this.handleEvent, { passive });
      }
    for (let type in prev)
      if (type != "scroll" && !handlers3[type])
        dom.removeEventListener(type, this.handleEvent);
    this.handlers = handlers3;
  }
  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 pending;
    if (browser.ios && !event2.synthetic && !event2.altKey && !event2.metaKey && ((pending = PendingKeys.find((key2) => key2.keyCode == event2.keyCode)) && !event2.ctrlKey || EmacsyPendingKeys.indexOf(event2.key) > -1 && event2.ctrlKey && !event2.shiftKey)) {
      this.pendingIOSKey = pending || 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) || event2.synthetic)
      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(update2) {
    this.view.observer.update(update2);
    if (this.mouseSelection)
      this.mouseSelection.update(update2);
    if (this.draggedContent && update2.docChanged)
      this.draggedContent = this.draggedContent.map(update2.changes);
    if (update2.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 (e3) {
      logException(view.state, e3);
    }
  };
}
function computeHandlers(plugins) {
  let result2 = /* @__PURE__ */ Object.create(null);
  function record(type) {
    return result2[type] || (result2[type] = { observers: [], handlers: [] });
  }
  for (let plugin of plugins) {
    let spec = plugin.spec, handlers3 = spec && spec.plugin.domEventHandlers, observers2 = spec && spec.plugin.domEventObservers;
    if (handlers3)
      for (let type in handlers3) {
        let f3 = handlers3[type];
        if (f3)
          record(type).handlers.push(bindHandler(plugin.value, f3));
      }
    if (observers2)
      for (let type in observers2) {
        let f3 = observers2[type];
        if (f3)
          record(type).observers.push(bindHandler(plugin.value, f3));
      }
  }
  for (let type in handlers)
    record(type).handlers.push(handlers[type]);
  for (let type in observers)
    record(type).observers.push(observers[type]);
  return result2;
}
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(a3, b3) {
  return Math.max(Math.abs(a3.clientX - b3.clientX), Math.abs(a3.clientY - b3.clientY));
}
var MouseSelection = class {
  constructor(view, startEvent, style3, mustSelect) {
    this.view = view;
    this.startEvent = startEvent;
    this.style = style3;
    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((f3) => f3(view));
    let doc4 = view.contentDOM.ownerDocument;
    doc4.addEventListener("mousemove", this.move = this.move.bind(this));
    doc4.addEventListener("mouseup", this.up = this.up.bind(this));
    this.extend = startEvent.shiftKey;
    this.multiple = view.state.facet(EditorState2.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 left = 0, top2 = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight;
    if (this.scrollParents.x)
      ({ left, right } = this.scrollParents.x.getBoundingClientRect());
    if (this.scrollParents.y)
      ({ top: top2, bottom } = this.scrollParents.y.getBoundingClientRect());
    let margins = getScrollMargins(this.view);
    if (event2.clientX - margins.left <= left + dragScrollMargin)
      sx = -dragScrollSpeed(left - event2.clientX);
    else if (event2.clientX + margins.right >= right - dragScrollMargin)
      sx = dragScrollSpeed(event2.clientX - right);
    if (event2.clientY - margins.top <= top2 + dragScrollMargin)
      sy = -dragScrollSpeed(top2 - event2.clientY);
    else if (event2.clientY + margins.bottom >= bottom - dragScrollMargin)
      sy = dragScrollSpeed(event2.clientY - bottom);
    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 doc4 = this.view.contentDOM.ownerDocument;
    doc4.removeEventListener("mousemove", this.move);
    doc4.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: x3, y: y3 } = this.scrollSpeed;
    if (x3 && this.scrollParents.x) {
      this.scrollParents.x.scrollLeft += x3;
      x3 = 0;
    }
    if (y3 && this.scrollParents.y) {
      this.scrollParents.y.scrollTop += y3;
      y3 = 0;
    }
    if (x3 || y3)
      this.view.win.scrollBy(x3, y3);
    if (this.dragging === false)
      this.select(this.lastEvent);
  }
  select(event2) {
    let { view } = this, selection = skipAtomsForSelection(this.atoms, this.style.get(event2, this.extend, this.multiple));
    if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))
      this.view.dispatch({
        selection,
        userEvent: "select.pointer"
      });
    this.mustSelect = false;
  }
  update(update2) {
    if (update2.transactions.some((tr2) => tr2.isUserEvent("input.type")))
      this.destroy();
    else if (this.style.update(update2))
      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: main2 } = view.state.selection;
  if (main2.empty)
    return false;
  let sel = getSelection2(view.root);
  if (!sel || sel.rangeCount == 0)
    return true;
  let rects = sel.getRangeAt(0).getClientRects();
  for (let i3 = 0; i3 < rects.length; i3++) {
    let rect = rects[i3];
    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, tile; node != view.contentDOM; node = node.parentNode)
    if (!node || node.nodeType == 11 || (tile = Tile.get(node)) && tile.isWidget() && !tile.isHidden && tile.widget.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 parent = view.dom.parentNode;
  if (!parent)
    return;
  let target = parent.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(state, facet, text3) {
  for (let filter4 of state.facet(facet))
    text3 = filter4(text3, state);
  return text3;
}
function doPaste(view, input) {
  input = textFilter(view.state, clipboardInputFilter, input);
  let { state } = view, changes, i3 = 1, text3 = state.toText(input);
  let byLine = text3.lines == state.selection.ranges.length;
  let linewise = lastLinewiseCopy != null && state.selection.ranges.every((r3) => r3.empty) && lastLinewiseCopy == text3.toString();
  if (linewise) {
    let lastLine = -1;
    changes = state.changeByRange((range2) => {
      let line = state.doc.lineAt(range2.from);
      if (line.from == lastLine)
        return { range: range2 };
      lastLine = line.from;
      let insert4 = state.toText((byLine ? text3.line(i3++).text : input) + state.lineBreak);
      return {
        changes: { from: line.from, insert: insert4 },
        range: EditorSelection.cursor(range2.from + insert4.length)
      };
    });
  } else if (byLine) {
    changes = state.changeByRange((range2) => {
      let line = text3.line(i3++);
      return {
        changes: { from: range2.from, to: range2.to, insert: line.text },
        range: EditorSelection.cursor(range2.from + line.length)
      };
    });
  } else {
    changes = state.replaceSelection(text3);
  }
  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, e3) => {
  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 style3 = null;
  for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
    style3 = makeStyle(view, event2);
    if (style3)
      break;
  }
  if (!style3 && event2.button == 0)
    style3 = basicMouseSelection(view, event2);
  if (style3) {
    let mustFocus = !view.hasFocus;
    view.inputState.startMouseSelection(new MouseSelection(view, event2, style3, 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;
    }
  } else {
    view.inputState.setSelectionOrigin("select.pointer");
  }
  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 = view.docView.lineAt(pos, bias), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
    let from2 = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
    if (to < view.state.doc.length && to == line.to)
      to++;
    return EditorSelection.range(from2, to);
  }
}
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 last3 = lastMouseDown, lastTime = lastMouseDownTime;
  lastMouseDown = event2;
  lastMouseDownTime = Date.now();
  return lastMouseDownCount = !last3 || lastTime > Date.now() - 400 && Math.abs(last3.clientX - event2.clientX) < 2 && Math.abs(last3.clientY - event2.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1;
}
function basicMouseSelection(view, event2) {
  let start = view.posAndSideAtCoords({ x: event2.clientX, y: event2.clientY }, false), type = getClickType(event2);
  let startSel = view.state.selection;
  return {
    update(update2) {
      if (update2.docChanged) {
        start.pos = update2.changes.mapPos(start.pos);
        startSel = startSel.map(update2.changes);
      }
    },
    get(event3, extend, multiple) {
      let cur2 = view.posAndSideAtCoords({ x: event3.clientX, y: event3.clientY }, false), removed;
      let range2 = rangeForClick(view, cur2.pos, cur2.assoc, type);
      if (start.pos != cur2.pos && !extend) {
        let startRange = rangeForClick(view, start.pos, start.assoc, type);
        let from2 = Math.min(startRange.from, range2.from), to = Math.max(startRange.to, range2.to);
        range2 = from2 < range2.from ? EditorSelection.range(from2, to) : EditorSelection.range(to, from2);
      }
      if (extend)
        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 i3 = 0; i3 < sel.ranges.length; i3++) {
    let { from: from2, to } = sel.ranges[i3];
    if (from2 <= pos && to >= pos)
      return EditorSelection.create(sel.ranges.slice(0, i3).concat(sel.ranges.slice(i3 + 1)), sel.mainIndex == i3 ? 0 : sel.mainIndex - (sel.mainIndex > i3 ? 1 : 0));
  }
  return null;
}
handlers.dragstart = (view, event2) => {
  let { selection: { main: range2 } } = view.state;
  if (event2.target.draggable) {
    let tile = view.docView.tile.nearest(event2.target);
    if (tile && tile.isWidget()) {
      let from2 = tile.posAtStart, to = from2 + tile.length;
      if (from2 >= range2.to || to <= range2.from)
        range2 = EditorSelection.range(from2, 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, text3, direct) {
  text3 = textFilter(view.state, clipboardInputFilter, text3);
  if (!text3)
    return;
  let dropPos = view.posAtCoords({ x: event2.clientX, y: event2.clientY }, false);
  let { draggedContent } = view.inputState;
  let del2 = direct && draggedContent && dragMovesSelection(view, event2) ? { from: draggedContent.from, to: draggedContent.to } : null;
  let ins = { from: dropPos, insert: text3 };
  let changes = view.state.changes(del2 ? [del2, ins] : ins);
  view.focus();
  view.dispatch({
    changes,
    selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
    userEvent: del2 ? "move.drop" : "input.drop"
  });
  view.inputState.draggedContent = null;
}
handlers.drop = (view, event2) => {
  if (!event2.dataTransfer)
    return false;
  if (view.state.readOnly)
    return true;
  let files = event2.dataTransfer.files;
  if (files && files.length) {
    let text3 = Array(files.length), read = 0;
    let finishFile = () => {
      if (++read == files.length)
        dropText(view, event2, text3.filter((s3) => s3 != null).join(view.state.lineBreak), false);
    };
    for (let i3 = 0; i3 < files.length; i3++) {
      let reader = new FileReader();
      reader.onerror = finishFile;
      reader.onload = () => {
        if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
          text3[i3] = reader.result;
        finishFile();
      };
      reader.readAsText(files[i3]);
    }
    return true;
  } else {
    let text3 = event2.dataTransfer.getData("Text");
    if (text3) {
      dropText(view, event2, text3, true);
      return true;
    }
  }
  return false;
};
handlers.paste = (view, event2) => {
  if (view.state.readOnly)
    return true;
  view.observer.flush();
  let data2 = brokenClipboardAPI ? null : event2.clipboardData;
  if (data2) {
    doPaste(view, data2.getData("text/plain") || data2.getData("text/uri-list"));
    return true;
  } else {
    capturePaste(view);
    return false;
  }
};
function captureCopy(view, text3) {
  let parent = view.dom.parentNode;
  if (!parent)
    return;
  let target = parent.appendChild(document.createElement("textarea"));
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.value = text3;
  target.focus();
  target.selectionEnd = text3.length;
  target.selectionStart = 0;
  setTimeout(() => {
    target.remove();
    view.focus();
  }, 50);
}
function copiedRange(state) {
  let content2 = [], ranges = [], linewise = false;
  for (let range2 of state.selection.ranges)
    if (!range2.empty) {
      content2.push(state.sliceDoc(range2.from, range2.to));
      ranges.push(range2);
    }
  if (!content2.length) {
    let upto = -1;
    for (let { from: from2 } of state.selection.ranges) {
      let line = state.doc.lineAt(from2);
      if (line.number > upto) {
        content2.push(line.text);
        ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
      }
      upto = line.number;
    }
    linewise = true;
  }
  return { text: textFilter(state, clipboardOutputFilter, content2.join(state.lineBreak)), ranges, linewise };
}
var lastLinewiseCopy = null;
handlers.copy = handlers.cut = (view, event2) => {
  if (!hasSelection(view.contentDOM, view.observer.selectionRange))
    return false;
  let { text: text3, ranges, linewise } = copiedRange(view.state);
  if (!text3 && !linewise)
    return false;
  lastLinewiseCopy = linewise ? text3 : null;
  if (event2.type == "cut" && !view.state.readOnly)
    view.dispatch({
      changes: ranges,
      scrollIntoView: true,
      userEvent: "delete.cut"
    });
  let data2 = brokenClipboardAPI ? null : event2.clipboardData;
  if (data2) {
    data2.clearData();
    data2.setData("text/plain", text3);
    return true;
  } else {
    captureCopy(view, text3);
    return false;
  }
};
var isFocusChange = /* @__PURE__ */ Annotation.define();
function focusChangeTransaction(state, focus2) {
  let effects = [];
  for (let getEffect of state.facet(focusChangeEffect)) {
    let effect2 = getEffect(state, focus2);
    if (effect2)
      effects.push(effect2);
  }
  return effects.length ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
}
function updateForFocusChange(view) {
  setTimeout(() => {
    let focus2 = view.hasFocus;
    if (focus2 != view.inputState.notifiedFocused) {
      let tr2 = focusChangeTransaction(view.state, focus2);
      if (tr2)
        view.dispatch(tr2);
      else
        view.update([]);
    }
  }, 10);
}
observers.focus = (view) => {
  view.inputState.lastFocusTime = Date.now();
  if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
    view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
    view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
  }
  updateForFocusChange(view);
};
observers.blur = (view) => {
  view.observer.clearSelectionRange();
  updateForFocusChange(view);
};
observers.compositionstart = observers.compositionupdate = (view) => {
  if (view.observer.editContext)
    return;
  if (view.inputState.compositionFirstChange == null)
    view.inputState.compositionFirstChange = true;
  if (view.inputState.composing < 0) {
    view.inputState.composing = 0;
  }
};
observers.compositionend = (view) => {
  if (view.observer.editContext)
    return;
  view.inputState.composing = -1;
  view.inputState.compositionEndedAt = Date.now();
  view.inputState.compositionPendingKey = true;
  view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
  view.inputState.compositionFirstChange = null;
  if (browser.chrome && browser.android) {
    view.observer.flushSoon();
  } else if (view.inputState.compositionPendingChange) {
    Promise.resolve().then(() => view.observer.flush());
  } else {
    setTimeout(() => {
      if (view.inputState.composing < 0 && view.docView.hasComposition)
        view.update([]);
    }, 50);
  }
};
observers.contextmenu = (view) => {
  view.inputState.lastContextMenu = Date.now();
};
handlers.beforeinput = (view, event2) => {
  var _a4, _b;
  if (event2.inputType == "insertText" || event2.inputType == "insertCompositionText") {
    view.inputState.insertingText = event2.data;
    view.inputState.insertingTextAt = Date.now();
  }
  if (event2.inputType == "insertReplacementText" && view.observer.editContext) {
    let text3 = (_a4 = event2.dataTransfer) === null || _a4 === void 0 ? void 0 : _a4.getData("text/plain"), ranges = event2.getTargetRanges();
    if (text3 && ranges.length) {
      let r3 = ranges[0];
      let from2 = view.posAtDOM(r3.startContainer, r3.startOffset), to = view.posAtDOM(r3.endContainer, r3.endOffset);
      applyDOMChangeInner(view, { from: from2, to, insert: view.state.toText(text3) }, null);
      return true;
    }
  }
  let pending;
  if (browser.chrome && browser.android && (pending = PendingKeys.find((key2) => key2.inputType == event2.inputType))) {
    view.observer.delayAndroidKey(pending.key, pending.keyCode);
    if (pending.key == "Backspace" || pending.key == "Delete") {
      let startViewHeight = ((_b = window.visualViewport) === null || _b === void 0 ? void 0 : _b.height) || 0;
      setTimeout(() => {
        var _a5;
        if ((((_a5 = window.visualViewport) === null || _a5 === void 0 ? void 0 : _a5.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(doc4) {
  if (!appliedFirefoxHack.has(doc4)) {
    appliedFirefoxHack.add(doc4);
    doc4.addEventListener("copy", () => {
    });
    doc4.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 = Text.empty;
    this.heightSamples = {};
    this.lineHeight = 14;
    this.charWidth = 7;
    this.textHeight = 14;
    this.lineLength = 30;
  }
  heightForGap(from2, to) {
    let lines = this.doc.lineAt(to).number - this.doc.lineAt(from2).number + 1;
    if (this.lineWrapping)
      lines += Math.max(0, Math.ceil((to - from2 - 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) / Math.max(1, this.lineLength - 5)));
    return lines * this.lineHeight;
  }
  setDoc(doc4) {
    this.doc = doc4;
    return this;
  }
  mustRefreshForWrapping(whiteSpace) {
    return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping;
  }
  mustRefreshForHeights(lineHeights) {
    let newHeight = false;
    for (let i3 = 0; i3 < lineHeights.length; i3++) {
      let h3 = lineHeights[i3];
      if (h3 < 0) {
        i3++;
      } else if (!this.heightSamples[Math.floor(h3 * 10)]) {
        newHeight = true;
        this.heightSamples[Math.floor(h3 * 10)] = true;
      }
    }
    return newHeight;
  }
  refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
    let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
    let changed = Math.abs(lineHeight - this.lineHeight) > 0.3 || this.lineWrapping != lineWrapping || Math.abs(charWidth - this.charWidth) > 0.1;
    this.lineWrapping = lineWrapping;
    this.lineHeight = lineHeight;
    this.charWidth = charWidth;
    this.textHeight = textHeight;
    this.lineLength = lineLength;
    if (changed) {
      this.heightSamples = {};
      for (let i3 = 0; i3 < knownHeights.length; i3++) {
        let h3 = knownHeights[i3];
        if (h3 < 0)
          i3++;
        else
          this.heightSamples[Math.floor(h3 * 10)] = true;
      }
    }
    return changed;
  }
};
var MeasuredHeights = class {
  constructor(from2, heights) {
    this.from = from2;
    this.heights = heights;
    this.index = 0;
  }
  get more() {
    return this.index < this.heights.length;
  }
};
var BlockInfo = class _BlockInfo {
  /**
  @internal
  */
  constructor(from2, length, top2, height, _content) {
    this.from = from2;
    this.length = length;
    this.top = top2;
    this.height = height;
    this._content = _content;
  }
  /**
  The type of element this is. When querying lines, this may be
  an array of all the blocks that make up the line.
  */
  get type() {
    return typeof this._content == "number" ? BlockType.Text : Array.isArray(this._content) ? this._content : this._content.type;
  }
  /**
  The end of the element as a document position.
  */
  get to() {
    return this.from + this.length;
  }
  /**
  The bottom position of the element.
  */
  get bottom() {
    return this.top + this.height;
  }
  /**
  If this is a widget block, this will return the widget
  associated with it.
  */
  get widget() {
    return this._content instanceof PointDecoration ? this._content.widget : null;
  }
  /**
  If this is a textblock, this holds the number of line breaks
  that appear in widgets inside the block.
  */
  get widgetLineBreaks() {
    return typeof this._content == "number" ? this._content : 0;
  }
  /**
  @internal
  */
  join(other) {
    let content2 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]);
    return new _BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content2);
  }
};
var QueryType = /* @__PURE__ */ function(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, flags = 2) {
    this.length = length;
    this.height = height;
    this.flags = flags;
  }
  get outdated() {
    return (this.flags & 2) > 0;
  }
  set outdated(value2) {
    this.flags = (value2 ? 2 : 0) | this.flags & ~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, nodes2) {
    return _HeightMap.of(nodes2);
  }
  // Again, these are base cases, and are overridden for branch and gap nodes.
  decomposeLeft(_to, result2) {
    result2.push(this);
  }
  decomposeRight(_from, result2) {
    result2.push(this);
  }
  applyChanges(decorations3, oldDoc, oracle, changes) {
    let me = this, doc4 = oracle.doc;
    for (let i3 = changes.length - 1; i3 >= 0; i3--) {
      let { fromA, toA, fromB, toB } = changes[i3];
      let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
      let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);
      toB += end.to - toA;
      toA = end.to;
      while (i3 > 0 && start.from <= changes[i3 - 1].toA) {
        fromA = changes[i3 - 1].fromA;
        fromB = changes[i3 - 1].fromB;
        i3--;
        if (fromA < start.from)
          start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);
      }
      fromB += start.from - fromA;
      fromA = start.from;
      let nodes2 = NodeBuilder.build(oracle.setDoc(doc4), decorations3, fromB, toB);
      me = replace2(me, me.replace(fromA, toA, nodes2));
    }
    return me.updateHeight(oracle, 0);
  }
  static empty() {
    return new HeightMapText(0, 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(nodes2) {
    if (nodes2.length == 1)
      return nodes2[0];
    let i3 = 0, j = nodes2.length, before2 = 0, after2 = 0;
    for (; ; ) {
      if (i3 == j) {
        if (before2 > after2 * 2) {
          let split3 = nodes2[i3 - 1];
          if (split3.break)
            nodes2.splice(--i3, 1, split3.left, null, split3.right);
          else
            nodes2.splice(--i3, 1, split3.left, split3.right);
          j += 1 + split3.break;
          before2 -= split3.size;
        } else if (after2 > before2 * 2) {
          let split3 = nodes2[j];
          if (split3.break)
            nodes2.splice(j, 1, split3.left, null, split3.right);
          else
            nodes2.splice(j, 1, split3.left, split3.right);
          j += 2 + split3.break;
          after2 -= split3.size;
        } else {
          break;
        }
      } else if (before2 < after2) {
        let next2 = nodes2[i3++];
        if (next2)
          before2 += next2.size;
      } else {
        let next2 = nodes2[--j];
        if (next2)
          after2 += next2.size;
      }
    }
    let brk = 0;
    if (nodes2[i3 - 1] == null) {
      brk = 1;
      i3--;
    } else if (nodes2[i3] == null) {
      brk = 1;
      j++;
    }
    return new HeightMapBranch(_HeightMap.of(nodes2.slice(0, i3)), brk, _HeightMap.of(nodes2.slice(j)));
  }
};
function replace2(old, val) {
  if (old == val)
    return old;
  if (old.constructor != val.constructor)
    heightChangeFlag = true;
  return val;
}
HeightMap.prototype.size = 1;
var SpaceDeco = /* @__PURE__ */ Decoration.replace({});
var HeightMapBlock = class extends HeightMap {
  constructor(length, height, deco) {
    super(length, height);
    this.deco = deco;
    this.spaceAbove = 0;
  }
  mainBlock(top2, offset) {
    return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.deco || 0);
  }
  blockAt(height, _oracle, top2, offset) {
    return this.spaceAbove && height < top2 + this.spaceAbove ? new BlockInfo(offset, 0, top2, this.spaceAbove, SpaceDeco) : this.mainBlock(top2, offset);
  }
  lineAt(_value, _type, oracle, top2, offset) {
    let main2 = this.mainBlock(top2, offset);
    return this.spaceAbove ? this.blockAt(0, oracle, top2, offset).join(main2) : main2;
  }
  forEachLine(from2, to, oracle, top2, offset, f3) {
    if (from2 <= offset + this.length && to >= offset)
      f3(this.lineAt(0, QueryType.ByPos, oracle, top2, offset));
  }
  setMeasuredHeight(measured) {
    let next2 = measured.heights[measured.index++];
    if (next2 < 0) {
      this.spaceAbove = -next2;
      next2 = measured.heights[measured.index++];
    } else {
      this.spaceAbove = 0;
    }
    this.setHeight(next2);
  }
  updateHeight(oracle, offset = 0, _force = false, measured) {
    if (measured && measured.from <= offset && measured.more)
      this.setMeasuredHeight(measured);
    this.outdated = false;
    return this;
  }
  toString() {
    return `block(${this.length})`;
  }
};
var HeightMapText = class _HeightMapText extends HeightMapBlock {
  constructor(length, height, above) {
    super(length, height, null);
    this.collapsed = 0;
    this.widgetHeight = 0;
    this.breaks = 0;
    this.spaceAbove = above;
  }
  mainBlock(top2, offset) {
    return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.breaks);
  }
  replace(_from, _to, nodes2) {
    let node = nodes2[0];
    if (nodes2.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, this.spaceAbove);
      else
        node.height = this.height;
      if (!this.outdated)
        node.outdated = false;
      return node;
    } else {
      return HeightMap.of(nodes2);
    }
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    if (measured && measured.from <= offset && measured.more) {
      this.setMeasuredHeight(measured);
    } else if (force || this.outdated) {
      this.spaceAbove = 0;
      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, top2, offset) {
    let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    if (oracle.lineWrapping) {
      let guess = offset + (height < oracle.lineHeight ? 0 : Math.round(Math.max(0, Math.min(1, (height - top2) / this.height)) * this.length));
      let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
      let lineTop = Math.max(top2, 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 - top2) / perLine)));
      let { from: from2, length } = oracle.doc.line(firstLine + line);
      return new BlockInfo(from2, length, top2 + perLine * line, perLine, 0);
    }
  }
  lineAt(value2, type, oracle, top2, offset) {
    if (type == QueryType.ByHeight)
      return this.blockAt(value2, oracle, top2, offset);
    if (type == QueryType.ByPosNoHeight) {
      let { from: from2, to } = oracle.doc.lineAt(value2);
      return new BlockInfo(from2, to - from2, 0, 0, 0);
    }
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    let line = oracle.doc.lineAt(value2), lineHeight = perLine + line.length * perChar;
    let linesAbove = line.number - firstLine;
    let lineTop = top2 + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
    return new BlockInfo(line.from, line.length, Math.max(top2, Math.min(lineTop, top2 + this.height - lineHeight)), lineHeight, 0);
  }
  forEachLine(from2, to, oracle, top2, offset, f3) {
    from2 = Math.max(from2, offset);
    to = Math.min(to, offset + this.length);
    let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
    for (let pos = from2, lineTop = top2; pos <= to; ) {
      let line = oracle.doc.lineAt(pos);
      if (pos == from2) {
        let linesAbove = line.number - firstLine;
        lineTop += perLine * linesAbove + perChar * (from2 - offset - linesAbove);
      }
      let lineHeight = perLine + perChar * line.length;
      f3(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
      lineTop += lineHeight;
      pos = line.to + 1;
    }
  }
  replace(from2, to, nodes2) {
    let after2 = this.length - to;
    if (after2 > 0) {
      let last3 = nodes2[nodes2.length - 1];
      if (last3 instanceof _HeightMapGap)
        nodes2[nodes2.length - 1] = new _HeightMapGap(last3.length + after2);
      else
        nodes2.push(null, new _HeightMapGap(after2 - 1));
    }
    if (from2 > 0) {
      let first2 = nodes2[0];
      if (first2 instanceof _HeightMapGap)
        nodes2[0] = new _HeightMapGap(from2 + first2.length);
      else
        nodes2.unshift(new _HeightMapGap(from2 - 1), null);
    }
    return HeightMap.of(nodes2);
  }
  decomposeLeft(to, result2) {
    result2.push(new _HeightMapGap(to - 1), null);
  }
  decomposeRight(from2, result2) {
    result2.push(null, new _HeightMapGap(this.length - from2 - 1));
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let end = offset + this.length;
    if (measured && measured.from <= offset + this.length && measured.more) {
      let nodes2 = [], pos = Math.max(offset, measured.from), singleHeight = -1;
      if (measured.from > offset)
        nodes2.push(new _HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
      while (pos <= end && measured.more) {
        let len = oracle.doc.lineAt(pos).length;
        if (nodes2.length)
          nodes2.push(null);
        let height = measured.heights[measured.index++], above = 0;
        if (height < 0) {
          above = -height;
          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, above);
        line.outdated = false;
        nodes2.push(line);
        pos += len + 1;
      }
      if (pos <= end)
        nodes2.push(null, new _HeightMapGap(end - pos).updateHeight(oracle, pos));
      let result2 = HeightMap.of(nodes2);
      if (singleHeight < 0 || Math.abs(result2.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
        heightChangeFlag = true;
      return replace2(this, result2);
    } else if (force || this.outdated) {
      this.setHeight(oracle.heightForGap(offset, offset + this.length));
      this.outdated = false;
    }
    return this;
  }
  toString() {
    return `gap(${this.length})`;
  }
};
var HeightMapBranch = class extends HeightMap {
  constructor(left, brk, right) {
    super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0));
    this.left = left;
    this.right = right;
    this.size = left.size + right.size;
  }
  get break() {
    return this.flags & 1;
  }
  blockAt(height, oracle, top2, offset) {
    let mid = top2 + this.left.height;
    return height < mid ? this.left.blockAt(height, oracle, top2, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
  }
  lineAt(value2, type, oracle, top2, offset) {
    let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break;
    let left = type == QueryType.ByHeight ? value2 < rightTop : value2 < rightOffset;
    let base3 = left ? this.left.lineAt(value2, type, oracle, top2, offset) : this.right.lineAt(value2, type, oracle, rightTop, rightOffset);
    if (this.break || (left ? base3.to < rightOffset : base3.from > rightOffset))
      return base3;
    let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
    if (left)
      return base3.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
    else
      return this.left.lineAt(rightOffset, subQuery, oracle, top2, offset).join(base3);
  }
  forEachLine(from2, to, oracle, top2, offset, f3) {
    let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break;
    if (this.break) {
      if (from2 < rightOffset)
        this.left.forEachLine(from2, to, oracle, top2, offset, f3);
      if (to >= rightOffset)
        this.right.forEachLine(from2, to, oracle, rightTop, rightOffset, f3);
    } else {
      let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top2, offset);
      if (from2 < mid.from)
        this.left.forEachLine(from2, mid.from - 1, oracle, top2, offset, f3);
      if (mid.to >= from2 && mid.from <= to)
        f3(mid);
      if (to > mid.to)
        this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f3);
    }
  }
  replace(from2, to, nodes2) {
    let rightStart = this.left.length + this.break;
    if (to < rightStart)
      return this.balanced(this.left.replace(from2, to, nodes2), this.right);
    if (from2 > this.left.length)
      return this.balanced(this.left, this.right.replace(from2 - rightStart, to - rightStart, nodes2));
    let result2 = [];
    if (from2 > 0)
      this.decomposeLeft(from2, result2);
    let left = result2.length;
    for (let node of nodes2)
      result2.push(node);
    if (from2 > 0)
      mergeGaps(result2, left - 1);
    if (to < this.length) {
      let right = result2.length;
      this.decomposeRight(to, result2);
      mergeGaps(result2, right);
    }
    return HeightMap.of(result2);
  }
  decomposeLeft(to, result2) {
    let left = this.left.length;
    if (to <= left)
      return this.left.decomposeLeft(to, result2);
    result2.push(this.left);
    if (this.break) {
      left++;
      if (to >= left)
        result2.push(null);
    }
    if (to > left)
      this.right.decomposeLeft(to - left, result2);
  }
  decomposeRight(from2, result2) {
    let left = this.left.length, right = left + this.break;
    if (from2 >= right)
      return this.right.decomposeRight(from2 - right, result2);
    if (from2 < left)
      this.left.decomposeRight(from2, result2);
    if (this.break && from2 < right)
      result2.push(null);
    result2.push(this.right);
  }
  balanced(left, right) {
    if (left.size > 2 * right.size || right.size > 2 * left.size)
      return HeightMap.of(this.break ? [left, null, right] : [left, right]);
    this.left = replace2(this.left, left);
    this.right = replace2(this.right, right);
    this.setHeight(left.height + right.height);
    this.outdated = left.outdated || right.outdated;
    this.size = left.size + right.size;
    this.length = left.length + this.break + right.length;
    return this;
  }
  updateHeight(oracle, offset = 0, force = false, measured) {
    let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
    if (measured && measured.from <= offset + left.length && measured.more)
      rebalance = left = left.updateHeight(oracle, offset, force, measured);
    else
      left.updateHeight(oracle, offset, force);
    if (measured && measured.from <= rightStart + right.length && measured.more)
      rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
    else
      right.updateHeight(oracle, rightStart, force);
    if (rebalance)
      return this.balanced(left, right);
    this.height = this.left.height + this.right.height;
    this.outdated = false;
    return this;
  }
  toString() {
    return this.left + (this.break ? " " : "-") + this.right;
  }
};
function mergeGaps(nodes2, around) {
  let before2, after2;
  if (nodes2[around] == null && (before2 = nodes2[around - 1]) instanceof HeightMapGap && (after2 = nodes2[around + 1]) instanceof HeightMapGap)
    nodes2.splice(around - 1, 3, new HeightMapGap(before2.length + 1 + after2.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), last3 = this.nodes[this.nodes.length - 1];
      if (last3 instanceof HeightMapText)
        last3.length += end - this.pos;
      else if (end > this.pos || !this.isCovered)
        this.nodes.push(new HeightMapText(end - this.pos, -1, 0));
      this.writtenTo = end;
      if (to > end) {
        this.nodes.push(null);
        this.writtenTo++;
        this.lineStart = -1;
      }
    }
    this.pos = to;
  }
  point(from2, to, deco) {
    if (from2 < 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 - from2;
      if (deco.block) {
        this.addBlock(new HeightMapBlock(len, height, deco));
      } else if (len || breaks || height >= relevantWidgetHeight) {
        this.addLineDeco(height, breaks, len);
      }
    } else if (to > from2) {
      this.span(from2, 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: from2, to } = this.oracle.doc.lineAt(this.pos);
    this.lineStart = from2;
    this.lineEnd = to;
    if (this.writtenTo < from2) {
      if (this.writtenTo < from2 - 1 || this.nodes[this.nodes.length - 1] == null)
        this.nodes.push(this.blankContent(this.writtenTo, from2 - 1));
      this.nodes.push(null);
    }
    if (this.pos > from2)
      this.nodes.push(new HeightMapText(this.pos - from2, -1, 0));
    this.writtenTo = this.pos;
  }
  blankContent(from2, to) {
    let gap = new HeightMapGap(to - from2);
    if (this.oracle.doc.lineAt(from2).to == to)
      gap.flags |= 4;
    return gap;
  }
  ensureLine() {
    this.enterLine();
    let last3 = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
    if (last3 instanceof HeightMapText)
      return last3;
    let line = new HeightMapText(0, -1, 0);
    this.nodes.push(line);
    return line;
  }
  addBlock(block3) {
    this.enterLine();
    let deco = block3.deco;
    if (deco && deco.startSide > 0 && !this.isCovered)
      this.ensureLine();
    this.nodes.push(block3);
    this.writtenTo = this.pos = this.pos + block3.length;
    if (deco && deco.endSide > 0)
      this.covering = block3;
  }
  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(from2) {
    let last3 = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
    if (this.lineStart > -1 && !(last3 instanceof HeightMapText) && !this.isCovered)
      this.nodes.push(new HeightMapText(0, -1, 0));
    else if (this.writtenTo < this.pos || last3 == null)
      this.nodes.push(this.blankContent(this.writtenTo, this.pos));
    let pos = from2;
    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, decorations3, from2, to) {
    let builder = new _NodeBuilder(from2, oracle);
    RangeSet.spans(decorations3, from2, to, builder, 0);
    return builder.finish(from2);
  }
};
function heightRelevantDecoChanges(a3, b3, diff) {
  let comp = new DecorationComparator2();
  RangeSet.compare(a3, b3, diff, comp, 0);
  return comp.changes;
}
var DecorationComparator2 = class {
  constructor() {
    this.changes = [];
  }
  compareRange() {
  }
  comparePoint(from2, to, a3, b3) {
    if (from2 < to || a3 && a3.heightRelevant || b3 && b3.heightRelevant)
      addRange2(from2, to, this.changes, 5);
  }
};
function visiblePixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  let doc4 = dom.ownerDocument, win = doc4.defaultView || window;
  let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
  let top2 = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
  for (let parent = dom.parentNode; parent && parent != doc4.body; ) {
    if (parent.nodeType == 1) {
      let elt = parent;
      let style3 = window.getComputedStyle(elt);
      if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style3.overflow != "visible") {
        let parentRect = elt.getBoundingClientRect();
        left = Math.max(left, parentRect.left);
        right = Math.min(right, parentRect.right);
        top2 = Math.max(top2, parentRect.top);
        bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom);
      }
      parent = style3.position == "absolute" || style3.position == "fixed" ? elt.offsetParent : elt.parentNode;
    } else if (parent.nodeType == 11) {
      parent = parent.host;
    } else {
      break;
    }
  }
  return {
    left: left - rect.left,
    right: Math.max(left, right) - rect.left,
    top: top2 - (rect.top + paddingTop),
    bottom: Math.max(top2, bottom) - (rect.top + paddingTop)
  };
}
function inWindow(elt) {
  let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window;
  return rect.left < win.innerWidth && rect.right > 0 && rect.top < win.innerHeight && rect.bottom > 0;
}
function fullPixelRange(dom, paddingTop) {
  let rect = dom.getBoundingClientRect();
  return {
    left: 0,
    right: rect.right - rect.left,
    top: paddingTop,
    bottom: rect.bottom - (rect.top + paddingTop)
  };
}
var LineGap = class {
  constructor(from2, to, size4, displaySize) {
    this.from = from2;
    this.to = to;
    this.size = size4;
    this.displaySize = displaySize;
  }
  static same(a3, b3) {
    if (a3.length != b3.length)
      return false;
    for (let i3 = 0; i3 < a3.length; i3++) {
      let gA = a3[i3], gB = b3[i3];
      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(size4, vertical) {
    super();
    this.size = size4;
    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(state) {
    this.state = state;
    this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
    this.inView = true;
    this.paddingTop = 0;
    this.paddingBottom = 0;
    this.contentDOMWidth = 0;
    this.contentDOMHeight = 0;
    this.editorHeight = 0;
    this.editorWidth = 0;
    this.scrollTop = 0;
    this.scrolledToBottom = false;
    this.scaleX = 1;
    this.scaleY = 1;
    this.scrollAnchorPos = 0;
    this.scrollAnchorHeight = -1;
    this.scaler = IdScaler;
    this.scrollTarget = null;
    this.printing = false;
    this.mustMeasureContent = true;
    this.defaultTextDirection = Direction.LTR;
    this.visibleRanges = [];
    this.mustEnforceCursorAssoc = false;
    let guessWrapping = state.facet(contentAttributes).some((v3) => typeof v3 != "function" && v3.class == "cm-lineWrapping");
    this.heightOracle = new HeightOracle(guessWrapping);
    this.stateDeco = staticDeco(state);
    this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
    for (let i3 = 0; i3 < 2; i3++) {
      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: main2 } = this.state.selection;
    for (let i3 = 0; i3 <= 1; i3++) {
      let pos = i3 ? main2.head : main2.anchor;
      if (!viewports.some(({ from: from2, to }) => pos >= from2 && pos <= to)) {
        let { from: from2, to } = this.lineBlockAt(pos);
        viewports.push(new Viewport(from2, to));
      }
    }
    this.viewports = viewports.sort((a3, b3) => a3.from - b3.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, (block3) => {
      this.viewportLines.push(scaleBlock(block3, this.scaler));
    });
  }
  update(update2, scrollTarget = null) {
    this.state = update2.state;
    let prevDeco = this.stateDeco;
    this.stateDeco = staticDeco(this.state);
    let contentChanges = update2.changedRanges;
    let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update2 ? update2.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, update2.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
    if (this.heightMap.height != prevHeight || heightChangeFlag)
      update2.flags |= 2;
    if (scrollAnchor) {
      this.scrollAnchorPos = update2.changes.mapPos(scrollAnchor.from, -1);
      this.scrollAnchorHeight = scrollAnchor.top;
    } else {
      this.scrollAnchorPos = -1;
      this.scrollAnchorHeight = prevHeight;
    }
    let viewport = heightChanges.length ? this.mapViewport(this.viewport, update2.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;
    update2.flags |= this.updateForViewport();
    if (viewportChange || !update2.changes.empty || update2.flags & 2)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update2.changes)));
    update2.flags |= this.computeVisibleRanges(update2.changes);
    if (scrollTarget)
      this.scrollTarget = scrollTarget;
    if (!this.mustEnforceCursorAssoc && (update2.selectionSet || update2.focusChanged) && update2.view.lineWrapping && update2.state.selection.main.empty && update2.state.selection.main.assoc && !update2.state.facet(nativeSelectionHidden))
      this.mustEnforceCursorAssoc = true;
  }
  measure(view) {
    let dom = view.contentDOM, style3 = window.getComputedStyle(dom);
    let oracle = this.heightOracle;
    let whiteSpace = style3.whiteSpace;
    this.defaultTextDirection = style3.direction == "rtl" ? Direction.RTL : Direction.LTR;
    let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace) || this.mustMeasureContent;
    let domRect = dom.getBoundingClientRect();
    let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
    this.contentDOMHeight = domRect.height;
    this.mustMeasureContent = false;
    let result2 = 0, bias = 0;
    if (domRect.width && domRect.height) {
      let { scaleX, scaleY } = getScale(dom, domRect);
      if (scaleX > 5e-3 && Math.abs(this.scaleX - scaleX) > 5e-3 || scaleY > 5e-3 && Math.abs(this.scaleY - scaleY) > 5e-3) {
        this.scaleX = scaleX;
        this.scaleY = scaleY;
        result2 |= 16;
        refresh = measureContent = true;
      }
    }
    let paddingTop = (parseInt(style3.paddingTop) || 0) * this.scaleY;
    let paddingBottom = (parseInt(style3.paddingBottom) || 0) * this.scaleY;
    if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
      this.paddingTop = paddingTop;
      this.paddingBottom = paddingBottom;
      result2 |= 16 | 2;
    }
    if (this.editorWidth != view.scrollDOM.clientWidth) {
      if (oracle.lineWrapping)
        measureContent = true;
      this.editorWidth = view.scrollDOM.clientWidth;
      result2 |= 16;
    }
    let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
    if (this.scrollTop != scrollTop) {
      this.scrollAnchorHeight = -1;
      this.scrollTop = scrollTop;
    }
    this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
    let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
    let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
    this.pixelViewport = pixelViewport;
    let inView3 = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
    if (inView3 != this.inView) {
      this.inView = inView3;
      if (inView3)
        measureContent = true;
    }
    if (!this.inView && !this.scrollTarget && !inWindow(view.dom))
      return 0;
    let contentWidth = domRect.width;
    if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
      this.contentDOMWidth = domRect.width;
      this.editorHeight = view.scrollDOM.clientHeight;
      result2 |= 16;
    }
    if (measureContent) {
      let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
      if (oracle.mustRefreshForHeights(lineHeights))
        refresh = true;
      if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
        let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
        refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, Math.max(5, contentWidth / charWidth), lineHeights);
        if (refresh) {
          view.docView.minWidth = 0;
          result2 |= 16;
        }
      }
      if (dTop > 0 && dBottom > 0)
        bias = Math.max(dTop, dBottom);
      else if (dTop < 0 && dBottom < 0)
        bias = Math.min(dTop, dBottom);
      clearHeightChangeFlag();
      for (let vp of this.viewports) {
        let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
        this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
      }
      if (heightChangeFlag)
        result2 |= 2;
    }
    let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to);
    if (viewportChange) {
      if (result2 & 2)
        result2 |= this.updateScaler();
      this.viewport = this.getViewport(bias, this.scrollTarget);
      result2 |= this.updateForViewport();
    }
    if (result2 & 2 || viewportChange)
      this.updateViewportLines();
    if (this.lineGaps.length || this.viewport.to - this.viewport.from > 2e3 << 1)
      this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
    result2 |= this.computeVisibleRanges();
    if (this.mustEnforceCursorAssoc) {
      this.mustEnforceCursorAssoc = false;
      view.docView.enforceCursorAssoc();
    }
    return result2;
  }
  get visibleTop() {
    return this.scaler.fromDOM(this.pixelViewport.top);
  }
  get visibleBottom() {
    return this.scaler.fromDOM(this.pixelViewport.bottom);
  }
  getViewport(bias, scrollTarget) {
    let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1e3 / 2));
    let map5 = this.heightMap, oracle = this.heightOracle;
    let { visibleTop, visibleBottom } = this;
    let viewport = new Viewport(map5.lineAt(visibleTop - marginTop * 1e3, QueryType.ByHeight, oracle, 0, 0).from, map5.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 block3 = map5.lineAt(head2, QueryType.ByPos, oracle, 0, 0), topPos;
        if (scrollTarget.y == "center")
          topPos = (block3.top + block3.bottom) / 2 - viewHeight / 2;
        else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head2 < viewport.from)
          topPos = block3.top;
        else
          topPos = block3.bottom - viewHeight;
        viewport = new Viewport(map5.lineAt(topPos - 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).from, map5.lineAt(topPos + viewHeight + 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).to);
      }
    }
    return viewport;
  }
  mapViewport(viewport, changes) {
    let from2 = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
    return new Viewport(this.heightMap.lineAt(from2, 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: from2, to }, bias = 0) {
    if (!this.inView)
      return true;
    let { top: top2 } = this.heightMap.lineAt(from2, QueryType.ByPos, this.heightOracle, 0, 0);
    let { bottom } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);
    let { visibleTop, visibleBottom } = this;
    return (from2 == 0 || top2 <= visibleTop - Math.max(10, Math.min(
      -bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(
      bias,
      250
      /* VP.MaxCoverMargin */
    ))) && (top2 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3);
  }
  mapLineGaps(gaps, changes) {
    if (!gaps.length || changes.empty)
      return gaps;
    let mapped = [];
    for (let gap of gaps)
      if (!changes.touchesRange(gap.from, gap.to))
        mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize));
    return mapped;
  }
  // Computes positions in the viewport where the start or end of a
  // line should be hidden, trying to reuse existing line gaps when
  // appropriate to avoid unneccesary redraws.
  // Uses crude character-counting for the positioning and sizing,
  // since actual DOM coordinates aren't always available and
  // predictable. Relies on generous margins (see LG.Margin) to hide
  // the artifacts this might produce from the user.
  ensureLineGaps(current, mayMeasure) {
    let wrapping = this.heightOracle.lineWrapping;
    let margin = wrapping ? 1e4 : 2e3, halfMargin = margin >> 1, doubleMargin = margin << 1;
    if (this.defaultTextDirection != Direction.LTR && !wrapping)
      return [];
    let gaps = [];
    let addGap = (from2, to, line, structure) => {
      if (to - from2 < 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 > from2 && pos < to) {
          addGap(from2, pos - 10, line, structure);
          addGap(pos + 10, to, line, structure);
          return;
        }
      }
      let gap = find2(current, (gap2) => gap2.from >= line.from && gap2.to <= line.to && Math.abs(gap2.from - from2) < 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((r3) => r3.from <= to && r3.to >= to)) {
          let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
          if (lineStart > from2)
            to = lineStart;
        }
        let size4 = this.gapSize(line, from2, to, structure);
        let displaySize = wrapping || size4 < 2e6 ? size4 : 2e6;
        gap = new LineGap(from2, to, size4, 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 top2, bot;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
          top2 = targetFrac - spaceFrac;
          bot = targetFrac + spaceFrac;
        } else {
          top2 = (this.visibleTop - line.top - marginHeight) / line.height;
          bot = (this.visibleBottom - line.top + marginHeight) / line.height;
        }
        viewFrom = findPosition(structure, top2);
        viewTo = findPosition(structure, bot);
      } else {
        let totalWidth = structure.total * this.heightOracle.charWidth;
        let marginWidth = margin * this.heightOracle.charWidth;
        let horizOffset = 0;
        if (totalWidth > 2e6)
          for (let old of current) {
            if (old.from >= 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 left, right;
        if (target != null) {
          let targetFrac = findFraction(structure, target);
          let spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth;
          left = targetFrac - spaceFrac;
          right = targetFrac + spaceFrac;
        } else {
          left = (pxLeft - marginWidth) / totalWidth;
          right = (pxRight + marginWidth) / totalWidth;
        }
        viewFrom = findPosition(structure, left);
        viewTo = findPosition(structure, right);
      }
      if (viewFrom > 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, from2, to, structure) {
    let fraction = findFraction(structure, to) - findFraction(structure, from2);
    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(from2, to) {
        ranges.push({ from: from2, to });
      },
      point() {
      }
    }, 20);
    let changed = 0;
    if (ranges.length != this.visibleRanges.length) {
      changed = 8 | 4;
    } else {
      for (let i3 = 0; i3 < ranges.length && !(changed & 8); i3++) {
        let old = this.visibleRanges[i3], nw = ranges[i3];
        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((b3) => b3.from <= pos && b3.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((l3) => l3.top <= height && l3.bottom >= height) || scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);
  }
  scrollAnchorAt(scrollTop) {
    let block3 = this.lineBlockAtHeight(scrollTop + 8);
    return block3.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block3 : 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(from2, to) {
    this.from = from2;
    this.to = to;
  }
};
function lineStructure(from2, to, stateDeco) {
  let ranges = [], pos = from2, total = 0;
  RangeSet.spans(stateDeco, from2, to, {
    span() {
    },
    point(from3, to2) {
      if (from3 > pos) {
        ranges.push({ from: pos, to: from3 });
        total += from3 - 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 i3 = 0; ; i3++) {
    let { from: from2, to } = ranges[i3], size4 = to - from2;
    if (dist2 <= size4)
      return from2 + dist2;
    dist2 -= size4;
  }
}
function findFraction(structure, pos) {
  let counted = 0;
  for (let { from: from2, to } of structure.ranges) {
    if (pos <= to) {
      counted += pos - from2;
      break;
    }
    counted += to - from2;
  }
  return counted / structure.total;
}
function find2(array, f3) {
  for (let val of array)
    if (f3(val))
      return val;
  return void 0;
}
var IdScaler = {
  toDOM(n4) {
    return n4;
  },
  fromDOM(n4) {
    return n4;
  },
  scale: 1,
  eq(other) {
    return other == this;
  }
};
function staticDeco(state) {
  let deco = state.facet(decorations).filter((d3) => typeof d3 != "function");
  let outer = state.facet(outerDecorations).filter((d3) => typeof d3 != "function");
  if (outer.length)
    deco.push(RangeSet.join(outer));
  return deco;
}
var BigScaler = class _BigScaler {
  constructor(oracle, heightMap, viewports) {
    let vpHeight = 0, base3 = 0, domBase = 0;
    this.viewports = viewports.map(({ from: from2, to }) => {
      let top2 = heightMap.lineAt(from2, QueryType.ByPos, oracle, 0, 0).top;
      let bottom = heightMap.lineAt(to, QueryType.ByPos, oracle, 0, 0).bottom;
      vpHeight += bottom - top2;
      return { from: from2, to, top: top2, bottom, domTop: 0, domBottom: 0 };
    });
    this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight);
    for (let obj of this.viewports) {
      obj.domTop = domBase + (obj.top - base3) * this.scale;
      domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
      base3 = obj.bottom;
    }
  }
  toDOM(n4) {
    for (let i3 = 0, base3 = 0, domBase = 0; ; i3++) {
      let vp = i3 < this.viewports.length ? this.viewports[i3] : null;
      if (!vp || n4 < vp.top)
        return domBase + (n4 - base3) * this.scale;
      if (n4 <= vp.bottom)
        return vp.domTop + (n4 - vp.top);
      base3 = vp.bottom;
      domBase = vp.domBottom;
    }
  }
  fromDOM(n4) {
    for (let i3 = 0, base3 = 0, domBase = 0; ; i3++) {
      let vp = i3 < this.viewports.length ? this.viewports[i3] : null;
      if (!vp || n4 < vp.domTop)
        return base3 + (n4 - domBase) / this.scale;
      if (n4 <= vp.domBottom)
        return vp.top + (n4 - vp.domTop);
      base3 = 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, i3) => vp.from == other.viewports[i3].from && vp.to == other.viewports[i3].to);
  }
};
function scaleBlock(block3, scaler) {
  if (scaler.scale == 1)
    return block3;
  let bTop = scaler.toDOM(block3.top), bBottom = scaler.toDOM(block3.bottom);
  return new BlockInfo(block3.from, block3.length, bTop, bBottom - bTop, Array.isArray(block3._content) ? block3._content.map((b3) => scaleBlock(b3, scaler)) : block3._content);
}
var theme = /* @__PURE__ */ Facet.define({ combine: (strs) => strs.join(" ") });
var darkTheme = /* @__PURE__ */ Facet.define({ combine: (values2) => values2.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(main2, spec, scopes) {
  return new StyleModule(spec, {
    finish(sel) {
      return /&/.test(sel) ? sel.replace(/&\w*/, (m3) => {
        if (m3 == "&")
          return main2;
        if (!scopes || !scopes[m3])
          throw new RangeError(`Unsupported selector: ${m3}`);
        return scopes[m3];
      }) : main2 + " " + 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",
    zIndex: 200
  },
  ".cm-gutters-before": { insetInlineStart: 0 },
  ".cm-gutters-after": { insetInlineEnd: 0 },
  "&light .cm-gutters": {
    backgroundColor: "#f5f5f5",
    color: "#6c6c6c",
    border: "0px solid #ddd",
    "&.cm-gutters-before": { borderRightWidth: "1px" },
    "&.cm-gutters-after": { borderLeftWidth: "1px" }
  },
  "&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-dialog": {
    padding: "2px 19px 4px 6px",
    position: "relative",
    "& label": { fontSize: "80%" }
  },
  ".cm-dialog-close": {
    position: "absolute",
    top: "3px",
    right: "4px",
    backgroundColor: "inherit",
    border: "none",
    font: "inherit",
    fontSize: "14px",
    padding: "0"
  },
  ".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",
    userSelect: "none"
  },
  ".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((m3) => m3.type == "childList" && m3.removedNodes.length || m3.type == "characterData" && m3.oldValue.length > m3.target.nodeValue.length))
        this.flushSoon();
      else
        this.flush();
    });
    if (window.EditContext && browser.android && 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 _a4;
        if (((_a4 = this.view.docView) === null || _a4 === void 0 ? void 0 : _a4.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((entries2) => {
        if (this.parentCheck < 0)
          this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3);
        if (entries2.length > 0 && entries2[entries2.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((entries2) => {
        if (entries2.length > 0 && entries2[entries2.length - 1].intersectionRatio > 0)
          this.onScrollChanged(document.createEvent("Event"));
      }, {});
    }
    this.listenForScroll();
    this.readSelectionRange();
  }
  onScrollChanged(e3) {
    this.view.inputState.runHandlers("scroll", e3);
    if (this.intersecting)
      this.view.measure();
  }
  onScroll(e3) {
    if (this.intersecting)
      this.flush(false);
    if (this.editContext)
      this.view.requestMeasure(this.editContext.measureReq);
    this.onScrollChanged(e3);
  }
  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((g3, i3) => g3 != gaps[i3]))) {
      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 context = sel.anchorNode && view.docView.tile.nearest(sel.anchorNode);
    if (context && context.isWidget() && context.widget.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 selection = getSelection2(view.root);
    if (!selection)
      return false;
    let range2 = browser.safari && view.root.nodeType == 11 && view.root.activeElement == this.dom && safariSelectionRangeHack(this.view, selection) || selection;
    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 i3 = 0, changed = null;
    for (let dom = this.dom; dom; ) {
      if (dom.nodeType == 1) {
        if (!changed && i3 < this.scrollTargets.length && this.scrollTargets[i3] == dom)
          i3++;
        else if (!changed)
          changed = this.scrollTargets.slice(0, i3);
        if (changed)
          changed.push(dom);
        dom = dom.assignedSlot || dom.parentNode;
      } else if (dom.nodeType == 11) {
        dom = dom.host;
      } else {
        break;
      }
    }
    if (i3 < this.scrollTargets.length && !changed)
      changed = this.scrollTargets.slice(0, i3);
    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(f3) {
    if (!this.active)
      return f3();
    try {
      this.stop();
      return f3();
    } 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 _a4;
    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 || !!((_a4 = this.delayedAndroidKey) === null || _a4 === void 0 ? void 0 : _a4.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 from2 = -1, to = -1, typeOver = false;
    for (let record of records) {
      let range2 = this.readMutation(record);
      if (!range2)
        continue;
      if (range2.typeOver)
        typeOver = true;
      if (from2 == -1) {
        ({ from: from2, to } = range2);
      } else {
        from2 = Math.min(range2.from, from2);
        to = Math.max(range2.to, to);
      }
    }
    return { from: from2, to, typeOver };
  }
  readChange() {
    let { from: from2, to, typeOver } = this.processRecords();
    let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
    if (from2 < 0 && !newSel)
      return null;
    if (from2 > -1)
      this.lastChange = Date.now();
    this.view.inputState.lastFocusTime = 0;
    this.selectionChanged = false;
    let change = new DOMChange(this.view, from2, 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 && !sameSelPos(this.view.state.selection, domChange.newSel.main)))
      this.view.update([]);
    return handled;
  }
  readMutation(rec) {
    let tile = this.view.docView.tile.nearest(rec.target);
    if (!tile || tile.isWidget())
      return null;
    tile.markDirty(rec.type == "attributes");
    if (rec.type == "childList") {
      let childBefore = findChild(tile, rec.previousSibling || rec.target.previousSibling, -1);
      let childAfter = findChild(tile, rec.nextSibling || rec.target.nextSibling, 1);
      return {
        from: childBefore ? tile.posAfter(childBefore) : tile.posAtStart,
        to: childAfter ? tile.posBefore(childAfter) : tile.posAtEnd,
        typeOver: false
      };
    } else if (rec.type == "characterData") {
      return { from: tile.posAtStart, to: tile.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(update2) {
    if (this.editContext) {
      this.editContext.update(update2);
      if (update2.startState.facet(editable) != update2.state.facet(editable))
        update2.view.contentDOM.editContext = update2.state.facet(editable) ? this.editContext.editContext : null;
    }
  }
  destroy() {
    var _a4, _b, _c;
    this.stop();
    (_a4 = this.intersection) === null || _a4 === void 0 ? void 0 : _a4.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(tile, dom, dir) {
  while (dom) {
    let curTile = Tile.get(dom);
    if (curTile && curTile.parent == tile)
      return curTile;
    let parent = dom.parentNode;
    dom = parent != tile.dom ? parent : 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, 1);
  if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
function safariSelectionRangeHack(view, selection) {
  if (selection.getComposedRanges) {
    let range2 = selection.getComposedRanges(view.root)[0];
    if (range2)
      return buildSelectionRangeFromRange(view, range2);
  }
  let found2 = null;
  function read(event2) {
    event2.preventDefault();
    event2.stopImmediatePropagation();
    found2 = event2.getTargetRanges()[0];
  }
  view.contentDOM.addEventListener("beforeinput", read, true);
  view.dom.ownerDocument.execCommand("indent");
  view.contentDOM.removeEventListener("beforeinput", read, true);
  return found2 ? buildSelectionRangeFromRange(view, found2) : 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 context = this.editContext = new window.EditContext({
      text: view.state.doc.sliceString(this.from, this.to),
      selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))),
      selectionEnd: this.toContextPos(view.state.selection.main.head)
    });
    this.handlers.textupdate = (e3) => {
      let main2 = view.state.selection.main, { anchor, head: head2 } = main2;
      let from2 = this.toEditorPos(e3.updateRangeStart), to = this.toEditorPos(e3.updateRangeEnd);
      if (view.inputState.composing >= 0 && !this.composing)
        this.composing = { contextBase: e3.updateRangeStart, editorBase: from2, drifted: false };
      let deletes = to - from2 > e3.text.length;
      if (from2 == this.from && anchor < this.from)
        from2 = anchor;
      else if (to == this.to && anchor > this.to)
        to = anchor;
      let diff = findDiff(view.state.sliceDoc(from2, to), e3.text, (deletes ? main2.from : main2.to) - from2, deletes ? "end" : null);
      if (!diff) {
        let newSel = EditorSelection.single(this.toEditorPos(e3.selectionStart), this.toEditorPos(e3.selectionEnd));
        if (!sameSelPos(newSel, main2))
          view.dispatch({ selection: newSel, userEvent: "select" });
        return;
      }
      let change = {
        from: diff.from + from2,
        to: diff.toA + from2,
        insert: Text.of(e3.text.slice(diff.from, diff.toB).split("\n"))
      };
      if ((browser.mac || browser.android) && change.from == head2 - 1 && /^\. ?$/.test(e3.text) && view.contentDOM.getAttribute("autocorrect") == "off")
        change = { from: from2, to, insert: Text.of([e3.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(e3.selectionStart, newLen), this.toEditorPos(e3.selectionEnd, newLen)));
      }
      if (this.pendingContextChange) {
        this.revertPending(view.state);
        this.setSelection(view.state);
      }
      if (change.from < change.to && !change.insert.length && view.inputState.composing >= 0 && !/[\\p{Alphabetic}\\p{Number}_]/.test(context.text.slice(Math.max(0, e3.updateRangeStart - 1), Math.min(context.text.length, e3.updateRangeStart + 1))))
        this.handlers.compositionend(e3);
    };
    this.handlers.characterboundsupdate = (e3) => {
      let rects = [], prev = null;
      for (let i3 = this.toEditorPos(e3.rangeStart), end = this.toEditorPos(e3.rangeEnd); i3 < end; i3++) {
        let rect = view.coordsForChar(i3);
        prev = rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top) || prev || new DOMRect();
        rects.push(prev);
      }
      context.updateCharacterBounds(e3.rangeStart, rects);
    };
    this.handlers.textformatupdate = (e3) => {
      let deco = [];
      for (let format2 of e3.getTextFormats()) {
        let lineStyle = format2.underlineStyle, thickness = format2.underlineThickness;
        if (!/none/i.test(lineStyle) && !/none/i.test(thickness)) {
          let from2 = this.toEditorPos(format2.rangeStart), to = this.toEditorPos(format2.rangeEnd);
          if (from2 < to) {
            let style3 = `text-decoration: underline ${/^[a-z]/.test(lineStyle) ? lineStyle + " " : lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${/thin/i.test(thickness) ? 1 : 2}px`;
            deco.push(Decoration.mark({ attributes: { style: style3 } }).range(from2, 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)
      context.addEventListener(event2, this.handlers[event2]);
    this.measureReq = { read: (view2) => {
      this.editContext.updateControlBounds(view2.contentDOM.getBoundingClientRect());
      let sel = getSelection2(view2.root);
      if (sel && sel.rangeCount)
        this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());
    } };
  }
  applyEdits(update2) {
    let off = 0, abort = false, pending = this.pendingContextChange;
    update2.changes.iterChanges((fromA, toA, _fromB, _toB, insert4) => {
      if (abort)
        return;
      let dLen = insert4.length - (toA - fromA);
      if (pending && toA >= pending.to) {
        if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert4)) {
          pending = this.pendingContextChange = null;
          off += dLen;
          this.to += dLen;
          return;
        } else {
          pending = null;
          this.revertPending(update2.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 + insert4.length > 3e4) {
          abort = true;
          return;
        }
        this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert4.toString());
        this.to += dLen;
      }
      off += dLen;
    });
    if (pending && !abort)
      this.revertPending(update2.state);
    return !abort;
  }
  update(update2) {
    let reverted = this.pendingContextChange, startSel = update2.startState.selection.main;
    if (this.composing && (this.composing.drifted || !update2.changes.touchesRange(startSel.from, startSel.to) && update2.transactions.some((tr2) => !tr2.isUserEvent("input.type") && tr2.changes.touchesRange(this.from, this.to)))) {
      this.composing.drifted = true;
      this.composing.editorBase = update2.changes.mapPos(this.composing.editorBase);
    } else if (!this.applyEdits(update2) || !this.rangeIsValid(update2.state)) {
      this.pendingContextChange = null;
      this.reset(update2.state);
    } else if (update2.docChanged || update2.selectionSet || reverted) {
      this.setSelection(update2.state);
    }
    if (update2.geometryChanged || update2.docChanged || update2.selectionSet)
      update2.view.requestMeasure(this.measureReq);
  }
  resetRange(state) {
    let { head: head2 } = state.selection.main;
    this.from = Math.max(
      0,
      head2 - 1e4
      /* CxVp.Margin */
    );
    this.to = Math.min(
      state.doc.length,
      head2 + 1e4
      /* CxVp.Margin */
    );
  }
  reset(state) {
    this.resetRange(state);
    this.editContext.updateText(0, this.editContext.text.length, state.doc.sliceString(this.from, this.to));
    this.setSelection(state);
  }
  revertPending(state) {
    let pending = this.pendingContextChange;
    this.pendingContextChange = null;
    this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state.doc.sliceString(pending.from, pending.to));
  }
  setSelection(state) {
    let { main: main2 } = state.selection;
    let start = this.toContextPos(Math.max(this.from, Math.min(this.to, main2.anchor)));
    let end = this.toContextPos(main2.head);
    if (this.editContext.selectionStart != start || this.editContext.selectionEnd != end)
      this.editContext.updateSelection(start, end);
  }
  rangeIsValid(state) {
    let { head: head2 } = state.selection.main;
    return !(this.from > 0 && head2 - this.from < 500 || this.to < state.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 c3 = this.composing;
    return c3 && c3.drifted ? c3.editorBase + (contextPos - c3.contextBase) : contextPos + this.from;
  }
  toContextPos(editorPos) {
    let c3 = this.composing;
    return c3 && c3.drifted ? c3.contextBase + (editorPos - c3.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 && 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 && 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(config3 = {}) {
    var _a4;
    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 (config3.parent)
      config3.parent.appendChild(this.dom);
    let { dispatch } = config3;
    this.dispatchTransactions = config3.dispatchTransactions || dispatch && ((trs) => trs.forEach((tr2) => dispatch(tr2, this))) || ((trs) => this.update(trs));
    this.dispatch = this.dispatch.bind(this);
    this._root = config3.root || getRoot(config3.parent) || document;
    this.viewState = new ViewState(config3.state || EditorState2.create(config3));
    if (config3.scrollTo && config3.scrollTo.is(scrollIntoView))
      this.viewState.scrollTarget = config3.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 ((_a4 = document.fonts) === null || _a4 === void 0 ? void 0 : _a4.ready)
      document.fonts.ready.then(() => {
        this.viewState.mustMeasureContent = true;
        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, update2;
    let state = this.state;
    for (let tr2 of transactions) {
      if (tr2.startState != state)
        throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
      state = tr2.state;
    }
    if (this.destroyed) {
      this.viewState.state = state;
      return;
    }
    let focus2 = this.hasFocus, focusFlag = 0, dispatchFocus = null;
    if (transactions.some((tr2) => tr2.annotation(isFocusChange))) {
      this.inputState.notifiedFocused = focus2;
      focusFlag = 1;
    } else if (focus2 != this.inputState.notifiedFocused) {
      this.inputState.notifiedFocused = focus2;
      dispatchFocus = focusChangeTransaction(state, focus2);
      if (!dispatchFocus)
        focusFlag = 1;
    }
    let pendingKey = this.observer.delayedAndroidKey, domChange = null;
    if (pendingKey) {
      this.observer.clearDelayedAndroidKey();
      domChange = this.observer.readChange();
      if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
        domChange = null;
    } else {
      this.observer.clear();
    }
    if (state.facet(EditorState2.phrases) != this.state.facet(EditorState2.phrases))
      return this.setState(state);
    update2 = ViewUpdate.create(this, state, transactions);
    update2.flags |= focusFlag;
    let scrollTarget = this.viewState.scrollTarget;
    try {
      this.updateState = 2;
      for (let tr2 of transactions) {
        if (scrollTarget)
          scrollTarget = scrollTarget.map(tr2.changes);
        if (tr2.scrollIntoView) {
          let { main: main2 } = tr2.state.selection;
          scrollTarget = new ScrollTarget(main2.empty ? main2 : EditorSelection.cursor(main2.head, main2.head > main2.anchor ? -1 : 1));
        }
        for (let e3 of tr2.effects)
          if (e3.is(scrollIntoView))
            scrollTarget = e3.value.clip(this.state);
      }
      this.viewState.update(update2, scrollTarget);
      this.bidiCache = CachedOrder.update(this.bidiCache, update2.changes);
      if (!update2.empty) {
        this.updatePlugins(update2);
        this.inputState.update(update2);
      }
      redrawn = this.docView.update(update2);
      if (this.state.facet(styleModule) != this.styleModules)
        this.mountStyles();
      attrsChanged = this.updateAttrs();
      this.showAnnouncements(transactions);
      this.docView.updateSelection(redrawn, transactions.some((tr2) => tr2.isUserEvent("select.pointer")));
    } finally {
      this.updateState = 0;
    }
    if (update2.startState.facet(theme) != update2.state.facet(theme))
      this.viewState.mustMeasureContent = true;
    if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
      this.requestMeasure();
    if (redrawn)
      this.docViewUpdate();
    if (!update2.empty)
      for (let listener of this.state.facet(updateListener)) {
        try {
          listener(update2);
        } catch (e3) {
          logException(this.state, e3, "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(update2) {
    let prevSpecs = update2.startState.facet(viewPlugin), specs = update2.state.facet(viewPlugin);
    if (prevSpecs != specs) {
      let newPlugins = [];
      for (let spec of specs) {
        let found2 = prevSpecs.indexOf(spec);
        if (found2 < 0) {
          newPlugins.push(new PluginInstance(spec));
        } else {
          let plugin = this.plugins[found2];
          plugin.mustUpdate = update2;
          newPlugins.push(plugin);
        }
      }
      for (let plugin of this.plugins)
        if (plugin.mustUpdate != update2)
          plugin.destroy(this);
      this.plugins = newPlugins;
      this.pluginMap.clear();
    } else {
      for (let p4 of this.plugins)
        p4.mustUpdate = update2;
    }
    for (let i3 = 0; i3 < this.plugins.length; i3++)
      this.plugins[i3].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 (e3) {
          logException(this.state, e3, "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 i3 = 0; ; i3++) {
        if (scrollAnchorHeight < 0) {
          if (isScrolledToBottom(sDOM)) {
            scrollAnchorPos = -1;
            scrollAnchorHeight = this.viewState.heightMap.height;
          } else {
            let block3 = this.viewState.scrollAnchorAt(scrollTop);
            scrollAnchorPos = block3.from;
            scrollAnchorHeight = block3.top;
          }
        }
        this.updateState = 1;
        let changed = this.viewState.measure(this);
        if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
          break;
        if (i3 > 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((m3) => {
          try {
            return m3.read(this);
          } catch (e3) {
            logException(this.state, e3);
            return BadMeasure;
          }
        });
        let update2 = ViewUpdate.create(this, this.state, []), redrawn = false;
        update2.flags |= changed;
        if (!updated)
          updated = update2;
        else
          updated.flags |= changed;
        this.updateState = 2;
        if (!update2.empty) {
          this.updatePlugins(update2);
          this.inputState.update(update2);
          this.updateAttrs();
          redrawn = this.docView.update(update2);
          if (redrawn)
            this.docViewUpdate();
        }
        for (let i4 = 0; i4 < measuring.length; i4++)
          if (measured[i4] != BadMeasure) {
            try {
              let m3 = measuring[i4];
              if (m3.write)
                m3.write(measured[i4], this);
            } catch (e3) {
              logException(this.state, e3);
            }
          }
        if (redrawn)
          this.docView.updateSelection(true);
        if (!update2.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 first2 = true;
    for (let tr2 of trs)
      for (let effect2 of tr2.effects)
        if (effect2.is(_EditorView.announce)) {
          if (first2)
            this.announceDOM.textContent = "";
          first2 = 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(request2) {
    if (this.measureScheduled < 0)
      this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
    if (request2) {
      if (this.measureRequests.indexOf(request2) > -1)
        return;
      if (request2.key != null)
        for (let i3 = 0; i3 < this.measureRequests.length; i3++) {
          if (this.measureRequests[i3].key === request2.key) {
            this.measureRequests[i3] = request2;
            return;
          }
        }
      this.measureRequests.push(request2);
    }
  }
  /**
  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.plugin != plugin)
      this.pluginMap.set(plugin, known = this.plugins.find((p4) => p4.plugin == 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(start, forward, by) {
    return skipAtoms(this, start, moveByChar(this, start, forward, by));
  }
  /**
  Move a cursor position across the next group of either
  [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
  non-whitespace characters.
  */
  moveByGroup(start, forward) {
    return skipAtoms(this, start, moveByChar(this, start, forward, (initial2) => byGroup(this, start.head, initial2)));
  }
  /**
  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 order2 = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
    let span = order2[end ? order2.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(start, forward, includeWrap = true) {
    return moveToLineBoundary(this, start, forward, includeWrap);
  }
  /**
  Move a cursor position vertically. When `distance` isn't given,
  it defaults to moving to the next line (including wrapped
  lines). Otherwise, `distance` should provide a positive distance
  in pixels.
  
  When `start` has a
  [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
  motion will use that as a target horizontal position. Otherwise,
  the cursor's own horizontal position is used. The returned
  cursor will have its goal column set to whichever column was
  used.
  */
  moveVertically(start, forward, distance) {
    return skipAtoms(this, start, moveVertically(this, start, forward, distance));
  }
  /**
  Find the DOM parent node and offset (child offset if `node` is
  an element, character offset when it is a text node) at the
  given document position.
  
  Note that for positions that aren't currently in
  `visibleRanges`, the resulting DOM position isn't necessarily
  meaningful (it may just point before or after a placeholder
  element).
  */
  domAtPos(pos, side = 1) {
    return this.docView.domAtPos(pos, side);
  }
  /**
  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();
    let found2 = posAtCoords(this, coords, precise);
    return found2 && found2.pos;
  }
  posAndSideAtCoords(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), order2 = this.bidiSpans(line);
    let span = order2[BidiSpan.find(order2, 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 order2 = computeOrder(line.text, dir, isolates);
    this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order2));
    return order2;
  }
  /**
  Check whether the editor has focus.
  */
  get hasFocus() {
    var _a4;
    return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a4 = this.inputState) === null || _a4 === void 0 ? void 0 : _a4.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(root3) {
    if (this._root != root3) {
      this._root = root3;
      this.observer.setWindow((root3.nodeType == 9 ? root3 : root3.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, options2 = {}) {
    return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options2.y, options2.x, options2.yMargin, options2.xMargin));
  }
  /**
  Return an effect that resets the editor to its current (at the
  time this method was called) scroll position. Note that this
  only affects the editor's own scrollable element, not parents.
  See also
  [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
  
  The effect should be used with a document identical to the one
  it was created for. Failing to do so is not an error, but may
  not scroll to the expected position. You can
  [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
  */
  scrollSnapshot() {
    let { scrollTop, scrollLeft } = this.scrollDOM;
    let ref = this.viewState.scrollAnchorAt(scrollTop);
    return scrollIntoView.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(handlers3) {
    return ViewPlugin.define(() => ({}), { eventHandlers: handlers3 });
  }
  /**
  Create an extension that registers DOM event observers. Contrary
  to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
  observers can't be prevented from running by a higher-precedence
  handler returning true. They also don't prevent other handlers
  and observers from running when they return true, and should not
  call `preventDefault`.
  */
  static domEventObservers(observers2) {
    return ViewPlugin.define(() => ({}), { eventObservers: observers2 });
  }
  /**
  Create a theme extension. The first argument can be a
  [`style-mod`](https://github.com/marijnh/style-mod#documentation)
  style spec providing the styles for the theme. These will be
  prefixed with a generated class for the style.
  
  Because the selectors will be prefixed with a scope class, rule
  that directly match the editor's [wrapper
  element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
  added—need to be explicitly differentiated by adding an `&` to
  the selector for that element—for example
  `&.cm-focused`.
  
  When `dark` is set to true, the theme will be marked as dark,
  which will cause the `&dark` rules from [base
  themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
  `&light` when a light theme is active).
  */
  static theme(spec, options2) {
    let prefix5 = StyleModule.newName();
    let result2 = [theme.of(prefix5), styleModule.of(buildTheme(`.${prefix5}`, spec))];
    if (options2 && options2.dark)
      result2.push(darkTheme.of(true));
    return result2;
  }
  /**
  Create an extension that adds styles to the base theme. Like
  with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
  place of the editor wrapper element when directly targeting
  that. You can also use `&dark` or `&light` instead to only
  target editors with a dark or light theme.
  */
  static baseTheme(spec) {
    return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
  }
  /**
  Retrieve an editor view instance from the view's DOM
  representation.
  */
  static findFromDOM(dom) {
    var _a4;
    let content2 = dom.querySelector(".cm-content");
    let tile = content2 && Tile.get(content2) || Tile.get(dom);
    return ((_a4 = tile === null || tile === void 0 ? void 0 : tile.root) === null || _a4 === void 0 ? void 0 : _a4.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.blockWrappers = blockWrappers;
EditorView.outerDecorations = outerDecorations;
EditorView.atomicRanges = atomicRanges;
EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
EditorView.scrollMargins = scrollMargins;
EditorView.darkTheme = darkTheme;
EditorView.cspNonce = /* @__PURE__ */ Facet.define({ combine: (values2) => values2.length ? values2[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(from2, to, dir, isolates, fresh, order2) {
    this.from = from2;
    this.to = to;
    this.dir = dir;
    this.isolates = isolates;
    this.fresh = fresh;
    this.order = order2;
  }
  static update(cache5, changes) {
    if (changes.empty && !cache5.some((c3) => c3.fresh))
      return cache5;
    let result2 = [], lastDir = cache5.length ? cache5[cache5.length - 1].dir : Direction.LTR;
    for (let i3 = Math.max(0, cache5.length - 10); i3 < cache5.length; i3++) {
      let entry = cache5[i3];
      if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
        result2.push(new _CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
    }
    return result2;
  }
};
function attrsFromFacet(view, facet, base3) {
  for (let sources = view.state.facet(facet), i3 = sources.length - 1; i3 >= 0; i3--) {
    let source = sources[i3], value2 = typeof source == "function" ? source(view) : source;
    if (value2)
      combineAttrs(value2, base3);
  }
  return base3;
}
var currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
function normalizeKeyName(name2, platform) {
  const parts = name2.split(/-(?!$)/);
  let result2 = parts[parts.length - 1];
  if (result2 == "Space")
    result2 = " ";
  let alt, ctrl, shift2, meta2;
  for (let i3 = 0; i3 < parts.length - 1; ++i3) {
    const mod = parts[i3];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta2 = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      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)
    result2 = "Alt-" + result2;
  if (ctrl)
    result2 = "Ctrl-" + result2;
  if (meta2)
    result2 = "Meta-" + result2;
  if (shift2)
    result2 = "Shift-" + result2;
  return result2;
}
function modifiers2(name2, event2, shift2) {
  if (event2.altKey)
    name2 = "Alt-" + name2;
  if (event2.ctrlKey)
    name2 = "Ctrl-" + name2;
  if (event2.metaKey)
    name2 = "Meta-" + name2;
  if (shift2 !== false && event2.shiftKey)
    name2 = "Shift-" + name2;
  return name2;
}
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(state) {
  let bindings = state.facet(keymap);
  let map5 = Keymaps.get(bindings);
  if (!map5)
    Keymaps.set(bindings, map5 = buildKeymap(bindings.reduce((a3, b3) => a3.concat(b3), [])));
  return map5;
}
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 = (name2, is) => {
    let current = isPrefix[name2];
    if (current == null)
      isPrefix[name2] = is;
    else if (current != is)
      throw new Error("Key binding " + name2 + " is used both as a regular binding and as a multi-stroke prefix");
  };
  let add4 = (scope, key2, command2, preventDefault, stopPropagation) => {
    var _a4, _b;
    let scopeObj = bound[scope] || (bound[scope] = /* @__PURE__ */ Object.create(null));
    let parts = key2.split(/ (?!$)/).map((k2) => normalizeKeyName(k2, platform));
    for (let i3 = 1; i3 < parts.length; i3++) {
      let prefix5 = parts.slice(0, i3).join(" ");
      checkPrefix(prefix5, true);
      if (!scopeObj[prefix5])
        scopeObj[prefix5] = {
          preventDefault: true,
          stopPropagation: false,
          run: [(view) => {
            let ourObj = storedPrefix = { view, prefix: prefix5, scope };
            setTimeout(() => {
              if (storedPrefix == ourObj)
                storedPrefix = null;
            }, PrefixTimeout);
            return true;
          }]
        };
    }
    let full = parts.join(" ");
    checkPrefix(full, false);
    let binding = scopeObj[full] || (scopeObj[full] = {
      preventDefault: false,
      stopPropagation: false,
      run: ((_b = (_a4 = scopeObj._any) === null || _a4 === void 0 ? void 0 : _a4.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
    });
    if (command2)
      binding.run.push(command2);
    if (preventDefault)
      binding.preventDefault = true;
    if (stopPropagation)
      binding.stopPropagation = true;
  };
  for (let b3 of bindings) {
    let scopes = b3.scope ? b3.scope.split(" ") : ["editor"];
    if (b3.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: any2 } = b3;
        for (let key2 in scopeObj)
          scopeObj[key2].run.push((view) => any2(view, currentKeyEvent));
      }
    let name2 = b3[platform] || b3.key;
    if (!name2)
      continue;
    for (let scope of scopes) {
      add4(scope, name2, b3.run, b3.preventDefault, b3.stopPropagation);
      if (b3.shift)
        add4(scope, "Shift-" + name2, b3.shift, b3.preventDefault, b3.stopPropagation);
    }
  }
  return bound;
}
var currentKeyEvent = null;
function runHandlers(map5, event2, view, scope) {
  currentKeyEvent = event2;
  let name2 = keyName(event2);
  let charCode = codePointAt2(name2, 0), isChar = codePointSize2(charCode) == name2.length && name2 != " ";
  let prefix5 = "", handled = false, prevented = false, stopPropagation = false;
  if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
    prefix5 = 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)
              stopPropagation = true;
            return true;
          }
        }
      if (binding.preventDefault) {
        if (binding.stopPropagation)
          stopPropagation = true;
        prevented = true;
      }
    }
    return false;
  };
  let scopeObj = map5[scope], baseName, shiftName;
  if (scopeObj) {
    if (runFor(scopeObj[prefix5 + modifiers2(name2, 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) && // Alt-combinations on macOS tend to be typed characters
    !(browser.mac && event2.altKey && !(event2.ctrlKey || event2.metaKey)) && (baseName = base[event2.keyCode]) && baseName != name2) {
      if (runFor(scopeObj[prefix5 + modifiers2(baseName, event2, true)])) {
        handled = true;
      } else if (event2.shiftKey && (shiftName = shift[event2.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix5 + modifiers2(shiftName, event2, false)])) {
        handled = true;
      }
    } else if (isChar && event2.shiftKey && runFor(scopeObj[prefix5 + modifiers2(name2, event2, true)])) {
      handled = true;
    }
    if (!handled && runFor(scopeObj._any))
      handled = true;
  }
  if (prevented)
    handled = true;
  if (handled && stopPropagation)
    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(className2, left, top2, width, height) {
    this.className = className2;
    this.left = left;
    this.top = top2;
    this.width = width;
    this.height = height;
  }
  draw() {
    let elt = document.createElement("div");
    elt.className = this.className;
    this.adjust(elt);
    return elt;
  }
  update(elt, prev) {
    if (prev.className != this.className)
      return false;
    this.adjust(elt);
    return true;
  }
  adjust(elt) {
    elt.style.left = this.left + "px";
    elt.style.top = this.top + "px";
    if (this.width != null)
      elt.style.width = this.width + "px";
    elt.style.height = this.height + "px";
  }
  eq(p4) {
    return this.left == p4.left && this.top == p4.top && this.width == p4.width && this.height == p4.height && this.className == p4.className;
  }
  /**
  Create a set of rectangles for the given selection range,
  assigning them theclass`className`. Will create a single
  rectangle for empty ranges, and a set of selection-style
  rectangles covering the range's content (in a bidi-aware
  way) for non-empty ones.
  */
  static forRange(view, className2, range2) {
    if (range2.empty) {
      let pos = view.coordsAtPos(range2.head, range2.assoc || 1);
      if (!pos)
        return [];
      let base3 = getBase(view);
      return [new _RectangleMarker(className2, pos.left - base3.left, pos.top - base3.top, null, pos.bottom - pos.top)];
    } else {
      return rectanglesForRange(view, className2, range2);
    }
  }
};
function getBase(view) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
  return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
}
function wrappedLine(view, pos, side, inside) {
  let coords = view.coordsAtPos(pos, side * 2);
  if (!coords)
    return inside;
  let editorRect = view.dom.getBoundingClientRect();
  let y3 = (coords.top + coords.bottom) / 2;
  let left = view.posAtCoords({ x: editorRect.left + 1, y: y3 });
  let right = view.posAtCoords({ x: editorRect.right - 1, y: y3 });
  if (left == null || right == null)
    return inside;
  return { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) };
}
function rectanglesForRange(view, className2, range2) {
  if (range2.to <= view.viewport.from || range2.from >= view.viewport.to)
    return [];
  let from2 = 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(), base3 = 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, from2, 1), endBlock = blockAt(view, to, -1);
  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, from2, 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 top2 = visualStart ? drawForLine(range2.from, null, visualStart) : drawForWidget(startBlock, false);
    let bottom = 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 && top2.bottom + view.defaultLineHeight / 2 < bottom.top)
      between.push(piece(leftSide, top2.bottom, rightSide, bottom.top));
    else if (top2.bottom < bottom.top && view.elementAtHeight((top2.bottom + bottom.top) / 2).type == BlockType.Text)
      top2.bottom = bottom.top = (top2.bottom + bottom.top) / 2;
    return pieces(top2).concat(between).concat(pieces(bottom));
  }
  function piece(left, top2, right, bottom) {
    return new RectangleMarker(className2, left - base3.left, top2 - base3.top, Math.max(0, right - left), bottom - top2);
  }
  function pieces({ top: top2, bottom, horizontal }) {
    let pieces2 = [];
    for (let i3 = 0; i3 < horizontal.length; i3 += 2)
      pieces2.push(piece(horizontal[i3], top2, horizontal[i3 + 1], bottom));
    return pieces2;
  }
  function drawForLine(from3, to2, line) {
    let top2 = 1e9, bottom = -1e9, horizontal = [];
    function addSpan(from4, fromOpen, to3, toOpen, dir) {
      let fromCoords = view.coordsAtPos(from4, from4 == line.to ? -2 : 2);
      let toCoords = view.coordsAtPos(to3, to3 == line.from ? 2 : -2);
      if (!fromCoords || !toCoords)
        return;
      top2 = Math.min(fromCoords.top, toCoords.top, top2);
      bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
      if (dir == Direction.LTR)
        horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
      else
        horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
    }
    let start = from3 !== null && from3 !== void 0 ? from3 : line.from, end = to2 !== null && to2 !== void 0 ? to2 : line.to;
    for (let r3 of view.visibleRanges)
      if (r3.to > start && r3.from < end) {
        for (let pos = Math.max(r3.from, start), endPos = Math.min(r3.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), from3 == null && spanFrom <= start, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir);
          }
          pos = docLine.to + 1;
          if (pos >= endPos)
            break;
        }
      }
    if (horizontal.length == 0)
      addSpan(start, from3 == null, end, to2 == null, view.textDirection);
    return { top: top2, bottom, horizontal };
  }
  function drawForWidget(block3, top2) {
    let y3 = contentRect.top + (top2 ? block3.top : block3.bottom);
    return { top: y3, bottom: y3, horizontal: [] };
  }
}
function sameMarker(a3, b3) {
  return a3.constructor == b3.constructor && a3.eq(b3);
}
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(update2) {
    if (update2.startState.facet(layerOrder) != update2.state.facet(layerOrder))
      this.setOrder(update2.state);
    if (this.layer.update(update2, this.dom) || update2.geometryChanged) {
      this.scale();
      update2.view.requestMeasure(this.measureReq);
    }
  }
  docViewUpdate(view) {
    if (this.layer.updateOnDocViewUpdate !== false)
      view.requestMeasure(this.measureReq);
  }
  setOrder(state) {
    let pos = 0, order2 = state.facet(layerOrder);
    while (pos < order2.length && order2[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((p4, i3) => !sameMarker(p4, this.drawn[i3]))) {
      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;
      if (browser.safari && browser.safari_version >= 26)
        this.dom.style.display = this.dom.firstChild ? "" : "none";
    }
  }
  destroy() {
    if (this.layer.destroy)
      this.layer.destroy(this.dom, this.view);
    this.dom.remove();
  }
};
var layerOrder = /* @__PURE__ */ Facet.define();
function layer(config3) {
  return [
    ViewPlugin.define((v3) => new LayerView(v3, config3)),
    layerOrder.of(config3)
  ];
}
var selectionConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      cursorBlinkRate: 1200,
      drawRangeCursor: true
    }, {
      cursorBlinkRate: (a3, b3) => Math.min(a3, b3),
      drawRangeCursor: (a3, b3) => a3 || b3
    });
  }
});
function drawSelection(config3 = {}) {
  return [
    selectionConfig.of(config3),
    cursorLayer,
    selectionLayer,
    hideNativeSelection,
    nativeSelectionHidden.of(true)
  ];
}
function configChanged(update2) {
  return update2.startState.facet(selectionConfig) != update2.state.facet(selectionConfig);
}
var cursorLayer = /* @__PURE__ */ layer({
  above: true,
  markers(view) {
    let { state } = view, conf = state.facet(selectionConfig);
    let cursors = [];
    for (let r3 of state.selection.ranges) {
      let prim = r3 == state.selection.main;
      if (r3.empty || conf.drawRangeCursor) {
        let className2 = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
        let cursor = r3.empty ? r3 : EditorSelection.cursor(r3.head, r3.head > r3.anchor ? -1 : 1);
        for (let piece of RectangleMarker.forRange(view, className2, cursor))
          cursors.push(piece);
      }
    }
    return cursors;
  },
  update(update2, dom) {
    if (update2.transactions.some((tr2) => tr2.selection))
      dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
    let confChange = configChanged(update2);
    if (confChange)
      setBlinkRate(update2.state, dom);
    return update2.docChanged || update2.selectionSet || confChange;
  },
  mount(dom, view) {
    setBlinkRate(view.state, dom);
  },
  class: "cm-cursorLayer"
});
function setBlinkRate(state, dom) {
  dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
}
var selectionLayer = /* @__PURE__ */ layer({
  above: false,
  markers(view) {
    return view.state.selection.ranges.map((r3) => r3.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r3)).reduce((a3, b3) => a3.concat(b3));
  },
  update(update2, dom) {
    return update2.docChanged || update2.selectionSet || update2.viewportChanged || configChanged(update2);
  },
  class: "cm-selectionLayer"
});
var hideNativeSelection = /* @__PURE__ */ Prec.highest(/* @__PURE__ */ EditorView.theme({
  ".cm-line": {
    "& ::selection, &::selection": { backgroundColor: "transparent !important" },
    caretColor: "transparent !important"
  },
  ".cm-content": {
    caretColor: "transparent !important",
    "& :focus": {
      caretColor: "initial !important",
      "&::selection, & ::selection": {
        backgroundColor: "Highlight !important"
      }
    }
  }
}));
var setDropCursorPos = /* @__PURE__ */ StateEffect.define({
  map(pos, mapping) {
    return pos == null ? null : mapping.mapPos(pos);
  }
});
var dropCursorPos = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(pos, tr2) {
    if (pos != null)
      pos = tr2.changes.mapPos(pos);
    return tr2.effects.reduce((pos2, e3) => e3.is(setDropCursorPos) ? e3.value : pos2, pos);
  }
});
var drawDropCursor = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.cursor = null;
    this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };
  }
  update(update2) {
    var _a4;
    let cursorPos = update2.state.field(dropCursorPos);
    if (cursorPos == null) {
      if (this.cursor != null) {
        (_a4 = this.cursor) === null || _a4 === void 0 ? void 0 : _a4.remove();
        this.cursor = null;
      }
    } else {
      if (!this.cursor) {
        this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
        this.cursor.className = "cm-dropCursor";
      }
      if (update2.startState.field(dropCursorPos) != cursorPos || update2.docChanged || update2.geometryChanged)
        this.view.requestMeasure(this.measureReq);
    }
  }
  readPos() {
    let { view } = this;
    let pos = view.state.field(dropCursorPos);
    let rect = pos != null && view.coordsAtPos(pos);
    if (!rect)
      return null;
    let outer = view.scrollDOM.getBoundingClientRect();
    return {
      left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
      top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
      height: rect.bottom - rect.top
    };
  }
  drawCursor(pos) {
    if (this.cursor) {
      let { scaleX, scaleY } = this.view;
      if (pos) {
        this.cursor.style.left = pos.left / scaleX + "px";
        this.cursor.style.top = pos.top / scaleY + "px";
        this.cursor.style.height = pos.height / scaleY + "px";
      } else {
        this.cursor.style.left = "-100000px";
      }
    }
  }
  destroy() {
    if (this.cursor)
      this.cursor.remove();
  }
  setDropPos(pos) {
    if (this.view.state.field(dropCursorPos) != pos)
      this.view.dispatch({ effects: setDropCursorPos.of(pos) });
  }
}, {
  eventObservers: {
    dragover(event2) {
      this.setDropPos(this.view.posAtCoords({ x: event2.clientX, y: event2.clientY }));
    },
    dragleave(event2) {
      if (event2.target == this.view.contentDOM || !this.view.contentDOM.contains(event2.relatedTarget))
        this.setDropPos(null);
    },
    dragend() {
      this.setDropPos(null);
    },
    drop() {
      this.setDropPos(null);
    }
  }
});
function dropCursor() {
  return [dropCursorPos, drawDropCursor];
}
function iterMatches(doc4, re2, from2, to, f3) {
  re2.lastIndex = 0;
  for (let cursor = doc4.iterRange(from2, to), pos = from2, m3; !cursor.next().done; pos += cursor.value.length) {
    if (!cursor.lineBreak)
      while (m3 = re2.exec(cursor.value))
        f3(pos + m3.index, m3);
  }
}
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 result2 = [];
  for (let { from: from2, to } of visible) {
    from2 = Math.max(view.state.doc.lineAt(from2).from, from2 - maxLength);
    to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
    if (result2.length && result2[result2.length - 1].to >= from2)
      result2[result2.length - 1].to = to;
    else
      result2.push({ from: from2, to });
  }
  return result2;
}
var MatchDecorator = class {
  /**
  Create a decorator.
  */
  constructor(config3) {
    const { regexp, decoration, decorate, boundary, maxLength = 1e3 } = config3;
    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 = (match2, view, from2, add4) => decorate(add4, from2, from2 + match2[0].length, match2, view);
    } else if (typeof decoration == "function") {
      this.addMatch = (match2, view, from2, add4) => {
        let deco = decoration(match2, view, from2);
        if (deco)
          add4(from2, from2 + match2[0].length, deco);
      };
    } else if (decoration) {
      this.addMatch = (match2, _view, from2, add4) => add4(from2, from2 + match2[0].length, decoration);
    } else {
      throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
    }
    this.boundary = boundary;
    this.maxLength = maxLength;
  }
  /**
  Compute the full set of decorations for matches in the given
  view's viewport. You'll want to call this when initializing your
  plugin.
  */
  createDeco(view) {
    let build = new RangeSetBuilder(), add4 = build.add.bind(build);
    for (let { from: from2, to } of matchRanges(view, this.maxLength))
      iterMatches(view.state.doc, this.regexp, from2, to, (from3, m3) => this.addMatch(m3, view, from3, add4));
    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(update2, deco) {
    let changeFrom = 1e9, changeTo = -1;
    if (update2.docChanged)
      update2.changes.iterChanges((_f, _t, from2, to) => {
        if (to >= update2.view.viewport.from && from2 <= update2.view.viewport.to) {
          changeFrom = Math.min(from2, changeFrom);
          changeTo = Math.max(to, changeTo);
        }
      });
    if (update2.viewportMoved || changeTo - changeFrom > 1e3)
      return this.createDeco(update2.view);
    if (changeTo > -1)
      return this.updateRange(update2.view, deco.map(update2.changes), changeFrom, changeTo);
    return deco;
  }
  updateRange(view, deco, updateFrom, updateTo) {
    for (let r3 of view.visibleRanges) {
      let from2 = Math.max(r3.from, updateFrom), to = Math.min(r3.to, updateTo);
      if (to >= from2) {
        let fromLine = view.state.doc.lineAt(from2), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
        let start = Math.max(r3.from, fromLine.from), end = Math.min(r3.to, toLine.to);
        if (this.boundary) {
          for (; from2 > fromLine.from; from2--)
            if (this.boundary.test(fromLine.text[from2 - 1 - fromLine.from])) {
              start = from2;
              break;
            }
          for (; to < toLine.to; to++)
            if (this.boundary.test(toLine.text[to - toLine.from])) {
              end = to;
              break;
            }
        }
        let ranges = [], m3;
        let add4 = (from3, to2, deco2) => ranges.push(deco2.range(from3, to2));
        if (fromLine == toLine) {
          this.regexp.lastIndex = start - fromLine.from;
          while ((m3 = this.regexp.exec(fromLine.text)) && m3.index < end - fromLine.from)
            this.addMatch(m3, view, m3.index + fromLine.from, add4);
        } else {
          iterMatches(view.state.doc, this.regexp, start, end, (from3, m4) => this.addMatch(m4, view, from3, add4));
        }
        deco = deco.update({ filterFrom: start, filterTo: end, filter: (from3, to2) => from3 < start || 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 _a4;
  if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
    let styles = document.body.style;
    _supportsTabSize = ((_a4 = styles.tabSize) !== null && _a4 !== void 0 ? _a4 : styles.MozTabSize) != null;
  }
  return _supportsTabSize || false;
}
var specialCharConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let config3 = combineConfig(configs, {
      render: null,
      specialChars: Specials,
      addSpecialChars: null
    });
    if (config3.replaceTabs = !supportsTabSize())
      config3.specialChars = new RegExp("	|" + config3.specialChars.source, UnicodeRegexpSupport);
    if (config3.addSpecialChars)
      config3.specialChars = new RegExp(config3.specialChars.source + "|" + config3.addSpecialChars.source, UnicodeRegexpSupport);
    return config3;
  }
});
function highlightSpecialChars(config3 = {}) {
  return [specialCharConfig.of(config3), 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: (m3, view, pos) => {
          let { doc: doc4 } = view.state;
          let code2 = codePointAt2(m3[0], 0);
          if (code2 == 9) {
            let line = doc4.lineAt(pos);
            let size4 = view.state.tabSize, col = countColumn(line.text, size4, pos - line.from);
            return Decoration.replace({
              widget: new TabWidget((size4 - col % size4) * this.view.defaultCharacterWidth / this.view.scaleX)
            });
          }
          return this.decorationCache[code2] || (this.decorationCache[code2] = Decoration.replace({ widget: new SpecialCharWidget(conf, code2) }));
        },
        boundary: conf.replaceTabs ? void 0 : /[^]/
      });
    }
    update(update2) {
      let conf = update2.state.facet(specialCharConfig);
      if (update2.startState.facet(specialCharConfig) != conf) {
        this.decorator = this.makeDecorator(conf);
        this.decorations = this.decorator.createDeco(update2.view);
      } else {
        this.decorations = this.decorator.updateDeco(update2, this.decorations);
      }
    }
  }, {
    decorations: (v3) => v3.decorations
  }));
}
var DefaultPlaceholder = "\u2022";
function placeholder$1(code2) {
  if (code2 >= 32)
    return DefaultPlaceholder;
  if (code2 == 10)
    return "\u2424";
  return String.fromCharCode(9216 + code2);
}
var SpecialCharWidget = class extends WidgetType {
  constructor(options2, code2) {
    super();
    this.options = options2;
    this.code = code2;
  }
  eq(other) {
    return other.code == this.code;
  }
  toDOM(view) {
    let ph = placeholder$1(this.code);
    let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
    let custom = this.options.render && this.options.render(this.code, desc, ph);
    if (custom)
      return custom;
    let span = document.createElement("span");
    span.textContent = ph;
    span.title = desc;
    span.setAttribute("aria-label", desc);
    span.className = "cm-specialChar";
    return span;
  }
  ignoreEvent() {
    return false;
  }
};
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(update2) {
    if (update2.docChanged || update2.selectionSet)
      this.decorations = this.getDeco(update2.view);
  }
  getDeco(view) {
    let lastLineStart = -1, deco = [];
    for (let r3 of view.state.selection.ranges) {
      let line = view.lineBlockAt(r3.head);
      if (line.from > lastLineStart) {
        deco.push(lineDeco.range(line.from));
        lastLineStart = line.from;
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v3) => v3.decorations
});
var MaxOff = 2e3;
function rectangleFor(state, a3, b3) {
  let startLine = Math.min(a3.line, b3.line), endLine = Math.max(a3.line, b3.line);
  let ranges = [];
  if (a3.off > MaxOff || b3.off > MaxOff || a3.col < 0 || b3.col < 0) {
    let startOff = Math.min(a3.off, b3.off), endOff = Math.max(a3.off, b3.off);
    for (let i3 = startLine; i3 <= endLine; i3++) {
      let line = state.doc.line(i3);
      if (line.length <= endOff)
        ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
    }
  } else {
    let startCol = Math.min(a3.col, b3.col), endCol = Math.max(a3.col, b3.col);
    for (let i3 = startLine; i3 <= endLine; i3++) {
      let line = state.doc.line(i3);
      let start = findColumn(line.text, startCol, state.tabSize, true);
      if (start < 0) {
        ranges.push(EditorSelection.cursor(line.to));
      } else {
        let end = findColumn(line.text, endCol, state.tabSize);
        ranges.push(EditorSelection.range(line.from + start, line.from + end));
      }
    }
  }
  return ranges;
}
function absoluteColumn(view, x3) {
  let ref = view.coordsAtPos(view.viewport.from);
  return ref ? Math.round(Math.abs((ref.left - x3) / 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 start = getPos(view, event2), startSel = view.state.selection;
  if (!start)
    return null;
  return {
    update(update2) {
      if (update2.docChanged) {
        let newStart = update2.changes.mapPos(update2.startState.doc.line(start.line).from);
        let newLine = update2.state.doc.lineAt(newStart);
        start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
        startSel = startSel.map(update2.changes);
      }
    },
    get(event3, _extend, multiple) {
      let cur2 = getPos(view, event3);
      if (!cur2)
        return startSel;
      let ranges = rectangleFor(view.state, start, cur2);
      if (!ranges.length)
        return startSel;
      if (multiple)
        return EditorSelection.create(ranges.concat(startSel.ranges));
      else
        return EditorSelection.create(ranges);
    }
  };
}
function rectangularSelection(options2) {
  let filter4 = (options2 === null || options2 === void 0 ? void 0 : options2.eventFilter) || ((e3) => e3.altKey && e3.button == 0);
  return EditorView.mouseSelectionStyle.of((view, event2) => filter4(event2) ? rectangleSelectionStyle(view, event2) : null);
}
var keys4 = {
  Alt: [18, (e3) => !!e3.altKey],
  Control: [17, (e3) => !!e3.ctrlKey],
  Shift: [16, (e3) => !!e3.shiftKey],
  Meta: [91, (e3) => !!e3.metaKey]
};
var showCrosshair = { style: "cursor: crosshair" };
function crosshairCursor(options2 = {}) {
  let [code2, getter] = keys4[options2.key || "Alt"];
  let plugin = ViewPlugin.fromClass(class {
    constructor(view) {
      this.view = view;
      this.isDown = false;
    }
    set(isDown) {
      if (this.isDown != isDown) {
        this.isDown = isDown;
        this.view.update([]);
      }
    }
  }, {
    eventObservers: {
      keydown(e3) {
        this.set(e3.keyCode == code2 || getter(e3));
      },
      keyup(e3) {
        if (e3.keyCode == code2 || !getter(e3))
          this.set(false);
      },
      mousemove(e3) {
        this.set(getter(e3));
      }
    }
  });
  return [
    plugin,
    EditorView.contentAttributes.of((view) => {
      var _a4;
      return ((_a4 = view.plugin(plugin)) === null || _a4 === void 0 ? void 0 : _a4.isDown) ? showCrosshair : 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((t3) => t3);
    let prev = null;
    this.tooltipViews = this.tooltips.map((t3) => prev = createTooltipView(t3, prev));
  }
  update(update2, above) {
    var _a4;
    let input = update2.state.facet(this.facet);
    let tooltips = input.filter((x3) => x3);
    if (input === this.input) {
      for (let t3 of this.tooltipViews)
        if (t3.update)
          t3.update(update2);
      return false;
    }
    let tooltipViews = [], newAbove = above ? [] : null;
    for (let i3 = 0; i3 < tooltips.length; i3++) {
      let tip = tooltips[i3], known = -1;
      if (!tip)
        continue;
      for (let i4 = 0; i4 < this.tooltips.length; i4++) {
        let other = this.tooltips[i4];
        if (other && other.create == tip.create)
          known = i4;
      }
      if (known < 0) {
        tooltipViews[i3] = this.createTooltipView(tip, i3 ? tooltipViews[i3 - 1] : null);
        if (newAbove)
          newAbove[i3] = !!tip.above;
      } else {
        let tooltipView = tooltipViews[i3] = this.tooltipViews[known];
        if (newAbove)
          newAbove[i3] = above[known];
        if (tooltipView.update)
          tooltipView.update(update2);
      }
    }
    for (let t3 of this.tooltipViews)
      if (tooltipViews.indexOf(t3) < 0) {
        this.removeTooltipView(t3);
        (_a4 = t3.destroy) === null || _a4 === void 0 ? void 0 : _a4.call(t3);
      }
    if (above) {
      newAbove.forEach((val, i3) => above[i3] = 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: (values2) => {
    var _a4, _b, _c;
    return {
      position: browser.ios ? "absolute" : ((_a4 = values2.find((conf) => conf.position)) === null || _a4 === void 0 ? void 0 : _a4.position) || "fixed",
      parent: ((_b = values2.find((conf) => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
      tooltipSpace: ((_c = values2.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 config3 = view.state.facet(tooltipConfig);
    this.position = config3.position;
    this.parent = config3.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, (t3, p4) => this.createTooltip(t3, p4), (t3) => {
      if (this.resizeObserver)
        this.resizeObserver.unobserve(t3.dom);
      t3.dom.remove();
    });
    this.above = this.manager.tooltips.map((t3) => !!t3.above);
    this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver((entries2) => {
      if (Date.now() > this.lastTransaction - 50 && entries2.length > 0 && entries2[entries2.length - 1].intersectionRatio < 1)
        this.measureSoon();
    }, { threshold: [1] }) : null;
    this.observeIntersection();
    view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
    this.maybeMeasure();
  }
  createContainer() {
    if (this.parent) {
      this.container = document.createElement("div");
      this.container.style.position = "relative";
      this.container.className = this.view.themeClasses;
      this.parent.appendChild(this.container);
    } else {
      this.container = this.view.dom;
    }
  }
  observeIntersection() {
    if (this.intersectionObserver) {
      this.intersectionObserver.disconnect();
      for (let tooltip of this.manager.tooltipViews)
        this.intersectionObserver.observe(tooltip.dom);
    }
  }
  measureSoon() {
    if (this.measureTimeout < 0)
      this.measureTimeout = setTimeout(() => {
        this.measureTimeout = -1;
        this.maybeMeasure();
      }, 50);
  }
  update(update2) {
    if (update2.transactions.length)
      this.lastTransaction = Date.now();
    let updated = this.manager.update(update2, this.above);
    if (updated)
      this.observeIntersection();
    let shouldMeasure = updated || update2.geometryChanged;
    let newConfig = update2.state.facet(tooltipConfig);
    if (newConfig.position != this.position && !this.madeAbsolute) {
      this.position = newConfig.position;
      for (let t3 of this.manager.tooltipViews)
        t3.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 t3 of this.manager.tooltipViews)
        this.container.appendChild(t3.dom);
      shouldMeasure = true;
    } else if (this.parent && this.view.themeClasses != this.classes) {
      this.classes = this.container.className = this.view.themeClasses;
    }
    if (shouldMeasure)
      this.maybeMeasure();
  }
  createTooltip(tooltip, prev) {
    let tooltipView = tooltip.create(this.view);
    let before2 = prev ? prev.dom : null;
    tooltipView.dom.classList.add("cm-tooltip");
    if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
      let arrow2 = document.createElement("div");
      arrow2.className = "cm-tooltip-arrow";
      tooltipView.dom.appendChild(arrow2);
    }
    tooltipView.dom.style.position = this.position;
    tooltipView.dom.style.top = Outside;
    tooltipView.dom.style.left = "0px";
    this.container.insertBefore(tooltipView.dom, before2);
    if (tooltipView.mount)
      tooltipView.mount(this.view);
    if (this.resizeObserver)
      this.resizeObserver.observe(tooltipView.dom);
    return tooltipView;
  }
  destroy() {
    var _a4, _b, _c;
    this.view.win.removeEventListener("resize", this.measureSoon);
    for (let tooltipView of this.manager.tooltipViews) {
      tooltipView.dom.remove();
      (_a4 = tooltipView.destroy) === null || _a4 === void 0 ? void 0 : _a4.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.safari) {
        let rect = dom.getBoundingClientRect();
        makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1;
      } else {
        makeAbsolute = !!dom.offsetParent && dom.offsetParent != this.container.ownerDocument.body;
      }
    }
    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((t3, i3) => {
        let tv = this.manager.tooltipViews[i3];
        return tv.getCoords ? tv.getCoords(t3.pos) : this.view.coordsAtPos(t3.pos);
      }),
      size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
      space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
      scaleX,
      scaleY,
      makeAbsolute
    };
  }
  writeMeasure(measured) {
    var _a4;
    if (measured.makeAbsolute) {
      this.madeAbsolute = true;
      this.position = "absolute";
      for (let t3 of this.manager.tooltipViews)
        t3.dom.style.position = "absolute";
    }
    let { visible, space, scaleX, scaleY } = measured;
    let others = [];
    for (let i3 = 0; i3 < this.manager.tooltips.length; i3++) {
      let tooltip = this.manager.tooltips[i3], tView = this.manager.tooltipViews[i3], { dom } = tView;
      let pos = measured.pos[i3], size4 = measured.size[i3];
      if (!pos || tooltip.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 arrow2 = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
      let arrowHeight = arrow2 ? 7 : 0;
      let width = size4.right - size4.left, height = (_a4 = knownHeight.get(tView)) !== null && _a4 !== void 0 ? _a4 : size4.bottom - size4.top;
      let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
      let left = size4.width > space.right - space.left ? ltr ? space.left : space.right - size4.width : ltr ? Math.max(space.left, Math.min(pos.left - (arrow2 ? 14 : 0) + offset.x, space.right - width)) : Math.min(Math.max(space.left, pos.left - width + (arrow2 ? 14 : 0) - offset.x), space.right - width);
      let above = this.above[i3];
      if (!tooltip.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[i3] = !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 top2 = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
      let right = left + width;
      if (tView.overlap !== true) {
        for (let r3 of others)
          if (r3.left < right && r3.right > left && r3.top < top2 + height && r3.bottom > top2)
            top2 = above ? r3.top - height - 2 - arrowHeight : r3.bottom + arrowHeight + 2;
      }
      if (this.position == "absolute") {
        dom.style.top = (top2 - measured.parent.top) / scaleY + "px";
        setLeftStyle(dom, (left - measured.parent.left) / scaleX);
      } else {
        dom.style.top = top2 / scaleY + "px";
        setLeftStyle(dom, left / scaleX);
      }
      if (arrow2) {
        let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 - 7);
        arrow2.style.left = arrowLeft / scaleX + "px";
      }
      if (tView.overlap !== true)
        others.push({ left, top: top2, right, bottom: top2 + height });
      dom.classList.toggle("cm-tooltip-above", above);
      dom.classList.toggle("cm-tooltip-below", !above);
      if (tView.positioned)
        tView.positioned(measured.space);
    }
  }
  maybeMeasure() {
    if (this.manager.tooltips.length) {
      if (this.view.inView)
        this.view.requestMeasure(this.measureReq);
      if (this.inView != this.view.inView) {
        this.inView = this.view.inView;
        if (!this.inView)
          for (let tv of this.manager.tooltipViews)
            tv.dom.style.top = Outside;
      }
    }
  }
}, {
  eventObservers: {
    scroll() {
      this.maybeMeasure();
    }
  }
});
function setLeftStyle(elt, value2) {
  let current = parseInt(elt.style.left, 10);
  if (isNaN(current) || Math.abs(value2 - current) > 1)
    elt.style.left = value2 + "px";
}
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((a3, i3) => a3.concat(i3), [])
});
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, (t3, p4) => this.createHostedView(t3, p4), (t3) => t3.dom.remove());
  }
  createHostedView(tooltip, prev) {
    let hostedView = tooltip.create(this.view);
    hostedView.dom.classList.add("cm-tooltip-section");
    this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
    if (this.mounted && hostedView.mount)
      hostedView.mount(this.view);
    return hostedView;
  }
  mount(view) {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.mount)
        hostedView.mount(view);
    }
    this.mounted = true;
  }
  positioned(space) {
    for (let hostedView of this.manager.tooltipViews) {
      if (hostedView.positioned)
        hostedView.positioned(space);
    }
  }
  update(update2) {
    this.manager.update(update2);
  }
  destroy() {
    var _a4;
    for (let t3 of this.manager.tooltipViews)
      (_a4 = t3.destroy) === null || _a4 === void 0 ? void 0 : _a4.call(t3);
  }
  passProp(name2) {
    let value2 = void 0;
    for (let view of this.manager.tooltipViews) {
      let given = view[name2];
      if (given !== void 0) {
        if (value2 === void 0)
          value2 = given;
        else if (value2 !== given)
          return void 0;
      }
    }
    return value2;
  }
  get offset() {
    return this.passProp("offset");
  }
  get getCoords() {
    return this.passProp("getCoords");
  }
  get overlap() {
    return this.passProp("overlap");
  }
  get resize() {
    return this.passProp("resize");
  }
};
var showHoverTooltipHost = /* @__PURE__ */ showTooltip.compute([showHoverTooltip], (state) => {
  let tooltips = state.facet(showHoverTooltip);
  if (tooltips.length === 0)
    return null;
  return {
    pos: Math.min(...tooltips.map((t3) => t3.pos)),
    end: Math.max(...tooltips.map((t3) => {
      var _a4;
      return (_a4 = t3.end) !== null && _a4 !== void 0 ? _a4 : t3.pos;
    })),
    create: HoverTooltipHost.create,
    above: tooltips[0].above,
    arrow: tooltips.some((t3) => t3.arrow)
  };
});
var HoverPlugin = class {
  constructor(view, source, field2, setHover, hoverTime) {
    this.view = view;
    this.source = source;
    this.field = field2;
    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 tile = view.docView.tile.nearest(lastMove.target);
    if (!tile)
      return;
    let pos, side = 1;
    if (tile.isWidget()) {
      pos = tile.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((s3) => s3.from <= pos && s3.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 pending = this.pending = { pos };
      open.then((result2) => {
        if (this.pending == pending) {
          this.pending = null;
          if (result2 && !(Array.isArray(result2) && !result2.length))
            view.dispatch({ effects: this.setHover.of(Array.isArray(result2) ? result2 : [result2]) });
        }
      }, (e3) => logException(view.state, e3, "hover tooltip"));
    } else if (open && !(Array.isArray(open) && !open.length)) {
      view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
    }
  }
  get tooltip() {
    let plugin = this.view.plugin(tooltipPlugin);
    let index2 = plugin ? plugin.manager.tooltips.findIndex((t3) => t3.create == HoverTooltipHost.create) : -1;
    return index2 > -1 ? plugin.manager.tooltipViews[index2] : null;
  }
  mousemove(event2) {
    var _a4, _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 } = this;
    if (active.length && tooltip && !isInTooltip(tooltip.dom, event2) || this.pending) {
      let { pos } = active[0] || this.pending, end = (_b = (_a4 = active[0]) === null || _a4 === void 0 ? void 0 : _a4.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 } = this;
      let inTooltip = tooltip && tooltip.dom.contains(event2.relatedTarget);
      if (!inTooltip)
        this.view.dispatch({ effects: this.setHover.of([]) });
      else
        this.watchTooltipLeave(tooltip.dom);
    }
  }
  watchTooltipLeave(tooltip) {
    let watch = (event2) => {
      tooltip.removeEventListener("mouseleave", watch);
      if (this.active.length && !this.view.dom.contains(event2.relatedTarget))
        this.view.dispatch({ effects: this.setHover.of([]) });
    };
    tooltip.addEventListener("mouseleave", watch);
  }
  destroy() {
    clearTimeout(this.hoverTimeout);
    clearTimeout(this.restartTimeout);
    this.view.dom.removeEventListener("mouseleave", this.mouseleave);
    this.view.dom.removeEventListener("mousemove", this.mousemove);
  }
};
var tooltipMargin = 4;
function isInTooltip(tooltip, event2) {
  let { left, right, top: top2, bottom } = tooltip.getBoundingClientRect(), arrow2;
  if (arrow2 = tooltip.querySelector(".cm-tooltip-arrow")) {
    let arrowRect = arrow2.getBoundingClientRect();
    top2 = Math.min(arrowRect.top, top2);
    bottom = Math.max(arrowRect.bottom, bottom);
  }
  return event2.clientX >= left - tooltipMargin && event2.clientX <= right + tooltipMargin && event2.clientY >= top2 - tooltipMargin && event2.clientY <= bottom + tooltipMargin;
}
function isOverRange(view, from2, to, x3, y3, margin) {
  let rect = view.scrollDOM.getBoundingClientRect();
  let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
  if (rect.left > x3 || rect.right < x3 || rect.top > y3 || Math.min(rect.bottom, docBottom) < y3)
    return false;
  let pos = view.posAtCoords({ x: x3, y: y3 }, false);
  return pos >= from2 && pos <= to;
}
function hoverTooltip(source, options2 = {}) {
  let setHover = StateEffect.define();
  let hoverState = StateField.define({
    create() {
      return [];
    },
    update(value2, tr2) {
      if (value2.length) {
        if (options2.hideOnChange && (tr2.docChanged || tr2.selection))
          value2 = [];
        else if (options2.hideOn)
          value2 = value2.filter((v3) => !options2.hideOn(tr2, v3));
        if (tr2.docChanged) {
          let mapped = [];
          for (let tooltip of value2) {
            let newPos = tr2.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
            if (newPos != null) {
              let copy2 = Object.assign(/* @__PURE__ */ Object.create(null), tooltip);
              copy2.pos = newPos;
              if (copy2.end != null)
                copy2.end = tr2.changes.mapPos(copy2.end);
              mapped.push(copy2);
            }
          }
          value2 = mapped;
        }
      }
      for (let effect2 of tr2.effects) {
        if (effect2.is(setHover))
          value2 = effect2.value;
        if (effect2.is(closeHoverTooltipEffect))
          value2 = [];
      }
      return value2;
    },
    provide: (f3) => showHoverTooltip.from(f3)
  });
  return {
    active: hoverState,
    extension: [
      hoverState,
      ViewPlugin.define((view) => new HoverPlugin(
        view,
        source,
        hoverState,
        setHover,
        options2.hoverTime || 300
        /* Hover.Time */
      )),
      showHoverTooltipHost
    ]
  };
}
function getTooltip(view, tooltip) {
  let plugin = view.plugin(tooltipPlugin);
  if (!plugin)
    return null;
  let found2 = plugin.manager.tooltips.indexOf(tooltip);
  return found2 < 0 ? null : plugin.manager.tooltipViews[found2];
}
var closeHoverTooltipEffect = /* @__PURE__ */ StateEffect.define();
var panelConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    let topContainer, bottomContainer;
    for (let c3 of configs) {
      topContainer = topContainer || c3.topContainer;
      bottomContainer = bottomContainer || c3.bottomContainer;
    }
    return { topContainer, bottomContainer };
  }
});
function getPanel(view, panel) {
  let plugin = view.plugin(panelPlugin);
  let index2 = plugin ? plugin.specs.indexOf(panel) : -1;
  return index2 > -1 ? plugin.panels[index2] : null;
}
var panelPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.input = view.state.facet(showPanel);
    this.specs = this.input.filter((s3) => s3);
    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((p4) => p4.top));
    this.bottom.sync(this.panels.filter((p4) => !p4.top));
    for (let p4 of this.panels) {
      p4.dom.classList.add("cm-panel");
      if (p4.mount)
        p4.mount();
    }
  }
  update(update2) {
    let conf = update2.state.facet(panelConfig);
    if (this.top.container != conf.topContainer) {
      this.top.sync([]);
      this.top = new PanelGroup(update2.view, true, conf.topContainer);
    }
    if (this.bottom.container != conf.bottomContainer) {
      this.bottom.sync([]);
      this.bottom = new PanelGroup(update2.view, false, conf.bottomContainer);
    }
    this.top.syncClasses();
    this.bottom.syncClasses();
    let input = update2.state.facet(showPanel);
    if (input != this.input) {
      let specs = input.filter((x3) => x3);
      let panels = [], top2 = [], bottom = [], mount = [];
      for (let spec of specs) {
        let known = this.specs.indexOf(spec), panel;
        if (known < 0) {
          panel = spec(update2.view);
          mount.push(panel);
        } else {
          panel = this.panels[known];
          if (panel.update)
            panel.update(update2);
        }
        panels.push(panel);
        (panel.top ? top2 : bottom).push(panel);
      }
      this.specs = specs;
      this.panels = panels;
      this.top.sync(top2);
      this.bottom.sync(bottom);
      for (let p4 of mount) {
        p4.dom.classList.add("cm-panel");
        if (p4.mount)
          p4.mount();
      }
    } else {
      for (let p4 of this.panels)
        if (p4.update)
          p4.update(update2);
    }
  }
  destroy() {
    this.top.sync([]);
    this.bottom.sync([]);
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value2 = view.plugin(plugin);
    return value2 && { top: value2.top.scrollMargin(), bottom: value2.bottom.scrollMargin() };
  })
});
var PanelGroup = class {
  constructor(view, top2, container) {
    this.view = view;
    this.top = top2;
    this.container = container;
    this.dom = void 0;
    this.classes = "";
    this.panels = [];
    this.syncClasses();
  }
  sync(panels) {
    for (let p4 of this.panels)
      if (p4.destroy && panels.indexOf(p4) < 0)
        p4.destroy();
    this.panels = panels;
    this.syncDOM();
  }
  syncDOM() {
    if (this.panels.length == 0) {
      if (this.dom) {
        this.dom.remove();
        this.dom = void 0;
      }
      return;
    }
    if (!this.dom) {
      this.dom = document.createElement("div");
      this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
      this.dom.style[this.top ? "top" : "bottom"] = "0";
      let parent = this.container || this.view.dom;
      parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
    }
    let curDOM = this.dom.firstChild;
    for (let 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
});
function showDialog(view, config3) {
  let resolve2;
  let promise = new Promise((r3) => resolve2 = r3);
  let panelCtor = (view2) => createDialog(view2, config3, resolve2);
  if (view.state.field(dialogField, false)) {
    view.dispatch({ effects: openDialogEffect.of(panelCtor) });
  } else {
    view.dispatch({ effects: StateEffect.appendConfig.of(dialogField.init(() => [panelCtor])) });
  }
  let close2 = closeDialogEffect.of(panelCtor);
  return { close: close2, result: promise.then((form) => {
    let queue2 = view.win.queueMicrotask || ((f3) => view.win.setTimeout(f3, 10));
    queue2(() => {
      if (view.state.field(dialogField).indexOf(panelCtor) > -1)
        view.dispatch({ effects: close2 });
    });
    return form;
  }) };
}
var dialogField = /* @__PURE__ */ StateField.define({
  create() {
    return [];
  },
  update(dialogs, tr2) {
    for (let e3 of tr2.effects) {
      if (e3.is(openDialogEffect))
        dialogs = [e3.value].concat(dialogs);
      else if (e3.is(closeDialogEffect))
        dialogs = dialogs.filter((d3) => d3 != e3.value);
    }
    return dialogs;
  },
  provide: (f3) => showPanel.computeN([f3], (state) => state.field(f3))
});
var openDialogEffect = /* @__PURE__ */ StateEffect.define();
var closeDialogEffect = /* @__PURE__ */ StateEffect.define();
function createDialog(view, config3, result2) {
  let content2 = config3.content ? config3.content(view, () => done(null)) : null;
  if (!content2) {
    content2 = crelt("form");
    if (config3.input) {
      let input = crelt("input", config3.input);
      if (/^(text|password|number|email|tel|url)$/.test(input.type))
        input.classList.add("cm-textfield");
      if (!input.name)
        input.name = "input";
      content2.appendChild(crelt("label", (config3.label || "") + ": ", input));
    } else {
      content2.appendChild(document.createTextNode(config3.label || ""));
    }
    content2.appendChild(document.createTextNode(" "));
    content2.appendChild(crelt("button", { class: "cm-button", type: "submit" }, config3.submitLabel || "OK"));
  }
  let forms = content2.nodeName == "FORM" ? [content2] : content2.querySelectorAll("form");
  for (let i3 = 0; i3 < forms.length; i3++) {
    let form = forms[i3];
    form.addEventListener("keydown", (event2) => {
      if (event2.keyCode == 27) {
        event2.preventDefault();
        done(null);
      } else if (event2.keyCode == 13) {
        event2.preventDefault();
        done(form);
      }
    });
    form.addEventListener("submit", (event2) => {
      event2.preventDefault();
      done(form);
    });
  }
  let panel = crelt("div", content2, crelt("button", {
    onclick: () => done(null),
    "aria-label": view.state.phrase("close"),
    class: "cm-dialog-close",
    type: "button"
  }, ["\xD7"]));
  if (config3.class)
    panel.className = config3.class;
  panel.classList.add("cm-dialog");
  function done(form) {
    if (panel.contains(panel.ownerDocument.activeElement))
      view.focus();
    result2(form);
  }
  return {
    dom: panel,
    top: config3.top,
    mount: () => {
      if (config3.focus) {
        let focus2;
        if (typeof config3.focus == "string")
          focus2 = content2.querySelector(config3.focus);
        else
          focus2 = content2.querySelector("input") || content2.querySelector("button");
        if (focus2 && "select" in focus2)
          focus2.select();
        else if (focus2 && "focus" in focus2)
          focus2.focus();
      }
    }
  };
}
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 defaults3 = {
  class: "",
  renderEmptyElements: false,
  elementStyle: "",
  markers: () => RangeSet.empty,
  lineMarker: () => null,
  widgetMarker: () => null,
  lineMarkerChange: null,
  initialSpacer: null,
  updateSpacer: null,
  domEventHandlers: {},
  side: "before"
};
var activeGutters = /* @__PURE__ */ Facet.define();
function gutter(config3) {
  return [gutters(), activeGutters.of({ ...defaults3, ...config3 })];
}
var unfixGutters = /* @__PURE__ */ Facet.define({
  combine: (values2) => values2.some((x3) => x3)
});
function gutters(config3) {
  let result2 = [
    gutterView
  ];
  if (config3 && config3.fixed === false)
    result2.push(unfixGutters.of(true));
  return result2;
}
var gutterView = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.domAfter = null;
    this.prevViewport = view.viewport;
    this.dom = document.createElement("div");
    this.dom.className = "cm-gutters cm-gutters-before";
    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));
    this.fixed = !view.state.facet(unfixGutters);
    for (let gutter2 of this.gutters) {
      if (gutter2.config.side == "after")
        this.getDOMAfter().appendChild(gutter2.dom);
      else
        this.dom.appendChild(gutter2.dom);
    }
    if (this.fixed) {
      this.dom.style.position = "sticky";
    }
    this.syncGutters(false);
    view.scrollDOM.insertBefore(this.dom, view.contentDOM);
  }
  getDOMAfter() {
    if (!this.domAfter) {
      this.domAfter = document.createElement("div");
      this.domAfter.className = "cm-gutters cm-gutters-after";
      this.domAfter.setAttribute("aria-hidden", "true");
      this.domAfter.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
      this.domAfter.style.position = this.fixed ? "sticky" : "";
      this.view.scrollDOM.appendChild(this.domAfter);
    }
    return this.domAfter;
  }
  update(update2) {
    if (this.updateGutters(update2)) {
      let vpA = this.prevViewport, vpB = update2.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 (update2.geometryChanged) {
      let min3 = this.view.contentHeight / this.view.scaleY + "px";
      this.dom.style.minHeight = min3;
      if (this.domAfter)
        this.domAfter.style.minHeight = min3;
    }
    if (this.view.state.facet(unfixGutters) != !this.fixed) {
      this.fixed = !this.fixed;
      this.dom.style.position = this.fixed ? "sticky" : "";
      if (this.domAfter)
        this.domAfter.style.position = this.fixed ? "sticky" : "";
    }
    this.prevViewport = update2.view.viewport;
  }
  syncGutters(detach) {
    let after2 = this.dom.nextSibling;
    if (detach) {
      this.dom.remove();
      if (this.domAfter)
        this.domAfter.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 first2 = true;
        for (let b3 of line.type) {
          if (b3.type == BlockType.Text && first2) {
            advanceCursor(lineClasses, classSet, b3.from);
            for (let cx of contexts)
              cx.line(this.view, b3, classSet);
            first2 = false;
          } else if (b3.widget) {
            for (let cx of contexts)
              cx.widget(this.view, b3);
          }
        }
      } 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, after2);
      if (this.domAfter)
        this.view.scrollDOM.appendChild(this.domAfter);
    }
  }
  updateGutters(update2) {
    let prev = update2.startState.facet(activeGutters), cur2 = update2.state.facet(activeGutters);
    let change = update2.docChanged || update2.heightChanged || update2.viewportChanged || !RangeSet.eq(update2.startState.facet(gutterLineClass), update2.state.facet(gutterLineClass), update2.view.viewport.from, update2.view.viewport.to);
    if (prev == cur2) {
      for (let gutter2 of this.gutters)
        if (gutter2.update(update2))
          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(update2);
          gutters2.push(this.gutters[known]);
        }
      }
      for (let g3 of this.gutters) {
        g3.dom.remove();
        if (gutters2.indexOf(g3) < 0)
          g3.destroy();
      }
      for (let g3 of gutters2) {
        if (g3.config.side == "after")
          this.getDOMAfter().appendChild(g3.dom);
        else
          this.dom.appendChild(g3.dom);
      }
      this.gutters = gutters2;
    }
    return change;
  }
  destroy() {
    for (let view of this.gutters)
      view.destroy();
    this.dom.remove();
    if (this.domAfter)
      this.domAfter.remove();
  }
}, {
  provide: (plugin) => EditorView.scrollMargins.of((view) => {
    let value2 = view.plugin(plugin);
    if (!value2 || value2.gutters.length == 0 || !value2.fixed)
      return null;
    let before2 = value2.dom.offsetWidth * view.scaleX, after2 = value2.domAfter ? value2.domAfter.offsetWidth * view.scaleX : 0;
    return view.textDirection == Direction.LTR ? { left: before2, right: after2 } : { right: before2, left: after2 };
  })
});
function asArray4(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, block3, markers) {
    let { gutter: gutter2 } = this, above = (block3.top - this.height) / view.scaleY, height = block3.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 = block3.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, block3) {
    let marker = this.gutter.config.widgetMarker(view, block3.widget, block3), markers = marker ? [marker] : null;
    for (let cls of view.state.facet(gutterWidgetClass)) {
      let marker2 = cls(view, block3.widget, block3);
      if (marker2)
        (markers || (markers = [])).push(marker2);
    }
    if (markers)
      this.addElement(view, block3, markers);
  }
  finish() {
    let gutter2 = this.gutter;
    while (gutter2.elements.length > this.i) {
      let last3 = gutter2.elements.pop();
      gutter2.dom.removeChild(last3.dom);
      last3.destroy();
    }
  }
};
var SingleGutterView = class {
  constructor(view, config3) {
    this.view = view;
    this.config = config3;
    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 config3.domEventHandlers) {
      this.dom.addEventListener(prop2, (event2) => {
        let target = event2.target, y3;
        if (target != this.dom && this.dom.contains(target)) {
          while (target.parentNode != this.dom)
            target = target.parentNode;
          let rect = target.getBoundingClientRect();
          y3 = (rect.top + rect.bottom) / 2;
        } else {
          y3 = event2.clientY;
        }
        let line = view.lineBlockAtHeight(y3 - view.documentTop);
        if (config3.domEventHandlers[prop2](view, line, event2))
          event2.preventDefault();
      });
    }
    this.markers = asArray4(config3.markers(view));
    if (config3.initialSpacer) {
      this.spacer = new GutterElement(view, 0, 0, [config3.initialSpacer(view)]);
      this.dom.appendChild(this.spacer.dom);
      this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
    }
  }
  update(update2) {
    let prevMarkers = this.markers;
    this.markers = asArray4(this.config.markers(update2.view));
    if (this.spacer && this.config.updateSpacer) {
      let updated = this.config.updateSpacer(this.spacer.markers[0], update2);
      if (updated != this.spacer.markers[0])
        this.spacer.update(update2.view, 0, 0, [updated]);
    }
    let vp = update2.view.viewport;
    return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update2) : 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 c3 = marker.elementClass;
        if (c3)
          cls += " " + c3;
        for (let i3 = iOld; i3 < this.markers.length; i3++)
          if (this.markers[i3].compare(marker)) {
            skipTo = i3;
            matched = true;
            break;
          }
      } else {
        skipTo = this.markers.length;
      }
      while (iOld < skipTo) {
        let next2 = this.markers[iOld++];
        if (next2.toDOM) {
          next2.destroy(domPos);
          let after2 = domPos.nextSibling;
          domPos.remove();
          domPos = after2;
        }
      }
      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(a3, b3) {
  if (a3.length != b3.length)
    return false;
  for (let i3 = 0; i3 < a3.length; i3++)
    if (!a3[i3].compare(b3[i3]))
      return false;
  return true;
}
var activeLineGutterMarker = /* @__PURE__ */ new class extends GutterMarker {
  constructor() {
    super(...arguments);
    this.elementClass = "cm-activeLineGutter";
  }
}();
var activeLineGutterHighlighter = /* @__PURE__ */ gutterLineClass.compute(["selection"], (state) => {
  let marks3 = [], last3 = -1;
  for (let range2 of state.selection.ranges) {
    let linePos = state.doc.lineAt(range2.head).from;
    if (linePos > last3) {
      last3 = linePos;
      marks3.push(activeLineGutterMarker.range(linePos));
    }
  }
  return RangeSet.of(marks3);
});
function highlightActiveLineGutter() {
  return activeLineGutterHighlighter;
}

// node_modules/@lezer/common/dist/index.js
var DefaultBufferLength = 1024;
var nextPropID = 0;
var Range2 = class {
  constructor(from2, to) {
    this.from = from2;
    this.to = to;
  }
};
var NodeProp = class {
  /**
  Create a new node prop type.
  */
  constructor(config3 = {}) {
    this.id = nextPropID++;
    this.perNode = !!config3.perNode;
    this.deserialize = config3.deserialize || (() => {
      throw new Error("This node type doesn't define a deserialize function");
    });
    this.combine = config3.combine || null;
  }
  /**
  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(match2) {
    if (this.perNode)
      throw new RangeError("Can't add per-node props to node types");
    if (typeof match2 != "function")
      match2 = NodeType2.match(match2);
    return (type) => {
      let result2 = match2(type);
      return result2 === void 0 ? null : [this, result2];
    };
  }
};
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: (value2) => {
  if (value2 && value2 != "rtl" && value2 != "ltr" && value2 != "auto")
    throw new RangeError("Invalid value for isolate: " + value2);
  return value2 || "auto";
} });
NodeProp.contextHash = new NodeProp({ perNode: true });
NodeProp.lookAhead = new NodeProp({ perNode: true });
NodeProp.mounted = new NodeProp({ perNode: true });
var MountedTree = class {
  constructor(tree, overlay, parser4, bracketed = false) {
    this.tree = tree;
    this.overlay = overlay;
    this.parser = parser4;
    this.bracketed = bracketed;
  }
  /**
  @internal
  */
  static get(tree) {
    return tree && tree.props && tree.props[NodeProp.mounted.id];
  }
};
var noProps = /* @__PURE__ */ Object.create(null);
var NodeType2 = class _NodeType {
  /**
  @internal
  */
  constructor(name2, props2, id, flags = 0) {
    this.name = name2;
    this.props = props2;
    this.id = id;
    this.flags = flags;
  }
  /**
  Define a node type.
  */
  static define(spec) {
    let props2 = spec.props && spec.props.length ? /* @__PURE__ */ Object.create(null) : noProps;
    let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
    let type = new _NodeType(spec.name || "", props2, spec.id, flags);
    if (spec.props)
      for (let src of spec.props) {
        if (!Array.isArray(src))
          src = src(type);
        if (src) {
          if (src[0].perNode)
            throw new RangeError("Can't store a per-node prop on a node type");
          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(name2) {
    if (typeof name2 == "string") {
      if (this.name == name2)
        return true;
      let group2 = this.prop(NodeProp.group);
      return group2 ? group2.indexOf(name2) > -1 : false;
    }
    return this.id == name2;
  }
  /**
  Create a function from node types to arbitrary values by
  specifying an object whose property names are node or
  [group](#common.NodeProp^group) names. Often useful with
  [`NodeProp.add`](#common.NodeProp.add). You can put multiple
  names, separated by spaces, in a single property name to map
  multiple node names to a single value.
  */
  static match(map5) {
    let direct = /* @__PURE__ */ Object.create(null);
    for (let prop2 in map5)
      for (let name2 of prop2.split(" "))
        direct[name2] = map5[prop2];
    return (node) => {
      for (let groups = node.prop(NodeProp.group), i3 = -1; i3 < (groups ? groups.length : 0); i3++) {
        let found2 = direct[i3 < 0 ? node.name : groups[i3]];
        if (found2)
          return found2;
      }
    };
  }
};
NodeType2.none = new NodeType2(
  "",
  /* @__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 i3 = 0; i3 < types2.length; i3++)
      if (types2[i3].id != i3)
        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 source of props2) {
        let add4 = source(type);
        if (add4) {
          if (!newProps)
            newProps = Object.assign({}, type.props);
          let value2 = add4[1], prop2 = add4[0];
          if (prop2.combine && prop2.id in newProps)
            value2 = prop2.combine(newProps[prop2.id], value2);
          newProps[prop2.id] = value2;
        }
      }
      newTypes.push(newProps ? new NodeType2(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";
  IterMode2[IterMode2["EnterBracketed"] = 16] = "EnterBracketed";
})(IterMode || (IterMode = {}));
var Tree = class _Tree {
  /**
  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, value2] of props2)
        this.props[typeof prop2 == "number" ? prop2 : prop2.id] = value2;
    }
  }
  /**
  @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: from2 = 0, to = this.length } = spec;
    let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
    for (let c3 = this.cursor(mode | IterMode.IncludeAnonymous); ; ) {
      let entered = false;
      if (c3.from <= to && c3.to >= from2 && (!anon && c3.type.isAnonymous || enter(c3) !== false)) {
        if (c3.firstChild())
          continue;
        entered = true;
      }
      for (; ; ) {
        if (entered && leave && (anon || !c3.type.isAnonymous))
          leave(c3);
        if (c3.nextSibling())
          break;
        if (!c3.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 result2 = [];
    if (this.props)
      for (let id in this.props)
        result2.push([+id, this.props[id]]);
    return result2;
  }
  /**
  Balance the direct children of this tree, producing a copy of
  which may have children grouped into subtrees with type
  [`NodeType.none`](#common.NodeType^none).
  */
  balance(config3 = {}) {
    return this.children.length <= 8 ? this : balanceRange(NodeType2.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children2, positions, length) => new _Tree(this.type, children2, positions, length, this.propValues), config3.makeTree || ((children2, positions, length) => new _Tree(NodeType2.none, children2, positions, length)));
  }
  /**
  Build a tree from a postfix-ordered buffer of node information,
  or a cursor over such a buffer.
  */
  static build(data2) {
    return buildTree(data2);
  }
};
Tree.empty = new Tree(NodeType2.none, [], [], 0);
var FlatBufferCursor = class _FlatBufferCursor {
  constructor(buffer, index2) {
    this.buffer = buffer;
    this.index = index2;
  }
  get id() {
    return this.buffer[this.index - 4];
  }
  get start() {
    return this.buffer[this.index - 3];
  }
  get end() {
    return this.buffer[this.index - 2];
  }
  get size() {
    return this.buffer[this.index - 1];
  }
  get pos() {
    return this.index;
  }
  next() {
    this.index -= 4;
  }
  fork() {
    return new _FlatBufferCursor(this.buffer, this.index);
  }
};
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 NodeType2.none;
  }
  /**
  @internal
  */
  toString() {
    let result2 = [];
    for (let index2 = 0; index2 < this.buffer.length; ) {
      result2.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result2.join(",");
  }
  /**
  @internal
  */
  childString(index2) {
    let id = this.buffer[index2], endIndex = this.buffer[index2 + 3];
    let type = this.set.types[id], result2 = type.name;
    if (/\W/.test(result2) && !type.isError)
      result2 = JSON.stringify(result2);
    index2 += 4;
    if (endIndex == index2)
      return result2;
    let children2 = [];
    while (index2 < endIndex) {
      children2.push(this.childString(index2));
      index2 = this.buffer[index2 + 3];
    }
    return result2 + "(" + children2.join(",") + ")";
  }
  /**
  @internal
  */
  findChild(startIndex, endIndex, dir, pos, side) {
    let { buffer } = this, pick = -1;
    for (let i3 = startIndex; i3 != endIndex; i3 = buffer[i3 + 3]) {
      if (checkSide(side, pos, buffer[i3 + 1], buffer[i3 + 2])) {
        pick = i3;
        if (dir > 0)
          break;
      }
    }
    return pick;
  }
  /**
  @internal
  */
  slice(startI, endI, from2) {
    let b3 = this.buffer;
    let copy2 = new Uint16Array(endI - startI), len = 0;
    for (let i3 = startI, j = 0; i3 < endI; ) {
      copy2[j++] = b3[i3++];
      copy2[j++] = b3[i3++] - from2;
      let to = copy2[j++] = b3[i3++] - from2;
      copy2[j++] = b3[i3++] - startI;
      len = Math.max(len, to);
    }
    return new _TreeBuffer(copy2, len, this.set);
  }
};
function checkSide(side, pos, from2, to) {
  switch (side) {
    case -2:
      return from2 < pos;
    case -1:
      return to >= pos && from2 < pos;
    case 0:
      return from2 < pos && to > pos;
    case 1:
      return from2 <= pos && to > pos;
    case 2:
      return to > pos;
    case 4:
      return true;
  }
}
function resolveNode(node, pos, side, overlays) {
  var _a4;
  while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
    let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
    if (!parent)
      return node;
    node = parent;
  }
  let mode = overlays ? 0 : IterMode.IgnoreOverlays;
  if (overlays)
    for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
      if (scan instanceof TreeNode && scan.index < 0 && ((_a4 = parent.enter(pos, side, mode)) === null || _a4 === void 0 ? void 0 : _a4.from) != scan.from)
        node = parent;
    }
  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, before2 = null, after2 = null) {
    let r3 = getChildren(this, type, before2, after2);
    return r3.length ? r3[0] : null;
  }
  getChildren(type, before2 = null, after2 = null) {
    return getChildren(this, type, before2, after2);
  }
  resolve(pos, side = 0) {
    return resolveNode(this, pos, side, false);
  }
  resolveInner(pos, side = 0) {
    return resolveNode(this, pos, side, true);
  }
  matchContext(context) {
    return matchNodeContext(this.parent, context);
  }
  enterUnfinishedNodesBefore(pos) {
    let scan = this.childBefore(pos), node = this;
    while (scan) {
      let last3 = scan.lastChild;
      if (!last3 || last3.to != scan.to)
        break;
      if (last3.type.isError && last3.from == last3.to) {
        node = scan;
        scan = last3.prevSibling;
      } else {
        scan = last3;
      }
    }
    return node;
  }
  get node() {
    return this;
  }
  get next() {
    return this.parent;
  }
};
var TreeNode = class _TreeNode extends BaseNode {
  constructor(_tree, from2, index2, _parent) {
    super();
    this._tree = _tree;
    this.from = from2;
    this.index = index2;
    this._parent = _parent;
  }
  get type() {
    return this._tree.type;
  }
  get name() {
    return this._tree.type.name;
  }
  get to() {
    return this.from + this._tree.length;
  }
  nextChild(i3, dir, pos, side, mode = 0) {
    for (let parent = this; ; ) {
      for (let { children: children2, positions } = parent._tree, e3 = dir > 0 ? children2.length : -1; i3 != e3; i3 += dir) {
        let next2 = children2[i3], start = positions[i3] + parent.from, mounted;
        if (!(mode & IterMode.EnterBracketed && next2 instanceof Tree && (mounted = MountedTree.get(next2)) && !mounted.overlay && mounted.bracketed && pos >= start && pos <= start + next2.length) && !checkSide(side, pos, start, start + next2.length))
          continue;
        if (next2 instanceof TreeBuffer) {
          if (mode & IterMode.ExcludeBuffers)
            continue;
          let index2 = next2.findChild(0, next2.buffer.length, dir, pos - start, side);
          if (index2 > -1)
            return new BufferNode(new BufferContext(parent, next2, i3, start), null, index2);
        } else if (mode & IterMode.IncludeAnonymous || (!next2.type.isAnonymous || hasChild(next2))) {
          let mounted2;
          if (!(mode & IterMode.IgnoreMounts) && (mounted2 = MountedTree.get(next2)) && !mounted2.overlay)
            return new _TreeNode(mounted2.tree, start, i3, parent);
          let inner = new _TreeNode(next2, start, i3, parent);
          return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next2.children.length - 1 : 0, dir, pos, side, mode);
        }
      }
      if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous)
        return null;
      if (parent.index >= 0)
        i3 = parent.index + dir;
      else
        i3 = dir < 0 ? -1 : parent._parent._tree.children.length;
      parent = parent._parent;
      if (!parent)
        return null;
    }
  }
  get firstChild() {
    return this.nextChild(
      0,
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.nextChild(
      this._tree.children.length - 1,
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(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 */
    );
  }
  prop(prop2) {
    return this._tree.prop(prop2);
  }
  enter(pos, side, mode = 0) {
    let mounted;
    if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
      let rPos = pos - this.from, enterBracketed = mode & IterMode.EnterBracketed && mounted.bracketed;
      for (let { from: from2, to } of mounted.overlay) {
        if ((side > 0 || enterBracketed ? from2 <= rPos : from2 < rPos) && (side < 0 || enterBracketed ? 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, before2, after2) {
  let cur2 = node.cursor(), result2 = [];
  if (!cur2.firstChild())
    return result2;
  if (before2 != null)
    for (let found2 = false; !found2; ) {
      found2 = cur2.type.is(before2);
      if (!cur2.nextSibling())
        return result2;
    }
  for (; ; ) {
    if (after2 != null && cur2.type.is(after2))
      return result2;
    if (cur2.type.is(type))
      result2.push(cur2.node);
    if (!cur2.nextSibling())
      return after2 == null ? result2 : [];
  }
}
function matchNodeContext(node, context, i3 = context.length - 1) {
  for (let p4 = node; i3 >= 0; p4 = p4.parent) {
    if (!p4)
      return false;
    if (!p4.type.isAnonymous) {
      if (context[i3] && context[i3] != p4.name)
        return false;
      i3--;
    }
  }
  return true;
}
var BufferContext = class {
  constructor(parent, buffer, index2, start) {
    this.parent = parent;
    this.buffer = buffer;
    this.index = index2;
    this.start = start;
  }
};
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(context, _parent, index2) {
    super();
    this.context = context;
    this._parent = _parent;
    this.index = index2;
    this.type = context.buffer.set.types[context.buffer.buffer[index2]];
  }
  child(dir, pos, side) {
    let { buffer } = this.context;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
    return index2 < 0 ? null : new _BufferNode(this.context, this, index2);
  }
  get firstChild() {
    return this.child(
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  get lastChild() {
    return this.child(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  childAfter(pos) {
    return this.child(
      1,
      pos,
      2
      /* Side.After */
    );
  }
  childBefore(pos) {
    return this.child(
      -1,
      pos,
      -2
      /* Side.Before */
    );
  }
  prop(prop2) {
    return this.type.prop(prop2);
  }
  enter(pos, side, mode = 0) {
    if (mode & IterMode.ExcludeBuffers)
      return null;
    let { buffer } = this.context;
    let index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
    return index2 < 0 ? null : new _BufferNode(this.context, this, index2);
  }
  get parent() {
    return this._parent || this.context.parent.nextSignificantParent();
  }
  externalSibling(dir) {
    return this._parent ? null : this.context.parent.nextChild(
      this.context.index + dir,
      dir,
      0,
      4
      /* Side.DontCare */
    );
  }
  get nextSibling() {
    let { buffer } = this.context;
    let after2 = buffer.buffer[this.index + 3];
    if (after2 < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
      return new _BufferNode(this.context, this._parent, after2);
    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 from2 = buffer.buffer[this.index + 1];
      children2.push(buffer.slice(startI, endI, from2));
      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 i3 = 1; i3 < heads.length; i3++) {
    let node = heads[i3];
    if (node.from > picked.from || node.to < picked.to) {
      picked = node;
      pick = i3;
    }
  }
  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 parent = scan.parent;
      (layers || (layers = [inner])).push(parent.resolve(pos, side));
      scan = parent;
    } else {
      let mount = MountedTree.get(scan.tree);
      if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
        let root3 = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
        (layers || (layers = [inner])).push(resolveNode(root3, 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.buffer = null;
    this.stack = [];
    this.index = 0;
    this.bufferNode = null;
    this.mode = mode & ~IterMode.EnterBracketed;
    if (node instanceof TreeNode) {
      this.yieldNode(node);
    } else {
      this._tree = node.context.parent;
      this.buffer = node.context;
      for (let n4 = node._parent; n4; n4 = n4._parent)
        this.stack.unshift(n4.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(index2, type) {
    this.index = index2;
    let { start, buffer } = this.buffer;
    this.type = type || buffer.set.types[buffer.buffer[index2]];
    this.from = start + buffer.buffer[index2 + 1];
    this.to = start + buffer.buffer[index2 + 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 index2 = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
    if (index2 < 0)
      return false;
    this.stack.push(this.index);
    return this.yieldBuf(index2);
  }
  /**
  Move the cursor to this node's first child. When this returns
  false, the node has no child, and the cursor has not been moved.
  */
  firstChild() {
    return this.enterChild(
      1,
      0,
      4
      /* Side.DontCare */
    );
  }
  /**
  Move the cursor to this node's last child.
  */
  lastChild() {
    return this.enterChild(
      -1,
      0,
      4
      /* Side.DontCare */
    );
  }
  /**
  Move the cursor to the first child that ends after `pos`.
  */
  childAfter(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 parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
    this.buffer = null;
    return this.yieldNode(parent);
  }
  /**
  @internal
  */
  sibling(dir) {
    if (!this.buffer)
      return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
    let { buffer } = this.buffer, d3 = this.stack.length - 1;
    if (dir < 0) {
      let parentStart = d3 < 0 ? 0 : this.stack[d3] + 4;
      if (this.index != parentStart)
        return this.yieldBuf(buffer.findChild(
          parentStart,
          this.index,
          -1,
          0,
          4
          /* Side.DontCare */
        ));
    } else {
      let after2 = buffer.buffer[this.index + 3];
      if (after2 < (d3 < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d3] + 3]))
        return this.yieldBuf(after2);
    }
    return d3 < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
  }
  /**
  Move to this node's next sibling, if any.
  */
  nextSibling() {
    return this.sibling(1);
  }
  /**
  Move to this node's previous sibling, if any.
  */
  prevSibling() {
    return this.sibling(-1);
  }
  atLastNode(dir) {
    let index2, parent, { buffer } = this;
    if (buffer) {
      if (dir > 0) {
        if (this.index < buffer.buffer.buffer.length)
          return false;
      } else {
        for (let i3 = 0; i3 < this.index; i3++)
          if (buffer.buffer.buffer[i3 + 3] < this.index)
            return false;
      }
      ({ index: index2, parent } = buffer);
    } else {
      ({ index: index2, _parent: parent } = this._tree);
    }
    for (; parent; { index: index2, _parent: parent } = parent) {
      if (index2 > -1)
        for (let i3 = index2 + dir, e3 = dir < 0 ? -1 : parent._tree.children.length; i3 != e3; i3 += dir) {
          let child = parent._tree.children[i3];
          if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child))
            return false;
        }
    }
    return true;
  }
  move(dir, enter) {
    if (enter && this.enterChild(
      dir,
      0,
      4
      /* Side.DontCare */
    ))
      return true;
    for (; ; ) {
      if (this.sibling(dir))
        return true;
      if (this.atLastNode(dir) || !this.parent())
        return false;
    }
  }
  /**
  Move to the next node in a
  [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
  traversal, going from a node to its first child or, if the
  current node is empty or `enter` is false, its next sibling or
  the next sibling of the first parent node that has one.
  */
  next(enter = true) {
    return this.move(1, enter);
  }
  /**
  Move to the next node in a last-to-first pre-order traversal. A
  node is followed by its last child or, if it has none, its
  previous sibling or the previous sibling of the first parent
  node that has one.
  */
  prev(enter = true) {
    return this.move(-1, enter);
  }
  /**
  Move the cursor to the innermost node that covers `pos`. If
  `side` is -1, it will enter nodes that end at `pos`. If it is 1,
  it will enter nodes that start at `pos`.
  */
  moveTo(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 cache5 = this.bufferNode, result2 = null, depth2 = 0;
    if (cache5 && cache5.context == this.buffer) {
      scan: for (let index2 = this.index, d3 = this.stack.length; d3 >= 0; ) {
        for (let c3 = cache5; c3; c3 = c3._parent)
          if (c3.index == index2) {
            if (index2 == this.index)
              return c3;
            result2 = c3;
            depth2 = d3 + 1;
            break scan;
          }
        index2 = this.stack[--d3];
      }
    }
    for (let i3 = depth2; i3 < this.stack.length; i3++)
      result2 = new BufferNode(this.buffer, result2, this.stack[i3]);
    return this.bufferNode = new BufferNode(this.buffer, result2, this.index);
  }
  /**
  Get the [tree](#common.Tree) that represents the current node, if
  any. Will return null when the node is in a [tree
  buffer](#common.TreeBuffer).
  */
  get tree() {
    return this.buffer ? null : this._tree._tree;
  }
  /**
  Iterate over the current node and all its descendants, calling
  `enter` when entering a node and `leave`, if given, when leaving
  one. When `enter` returns `false`, any children of that node are
  skipped, and `leave` isn't called for it.
  */
  iterate(enter, leave) {
    for (let depth2 = 0; ; ) {
      let mustLeave = false;
      if (this.type.isAnonymous || enter(this) !== false) {
        if (this.firstChild()) {
          depth2++;
          continue;
        }
        if (!this.type.isAnonymous)
          mustLeave = true;
      }
      for (; ; ) {
        if (mustLeave && leave)
          leave(this);
        mustLeave = this.type.isAnonymous;
        if (!depth2)
          return;
        if (this.nextSibling())
          break;
        this.parent();
        depth2--;
        mustLeave = true;
      }
    }
  }
  /**
  Test whether the current node matches a given context—a sequence
  of direct parent node names. Empty strings in the context array
  are treated as wildcards.
  */
  matchContext(context) {
    if (!this.buffer)
      return matchNodeContext(this.node.parent, context);
    let { buffer } = this.buffer, { types: types2 } = buffer.set;
    for (let i3 = context.length - 1, d3 = this.stack.length - 1; i3 >= 0; d3--) {
      if (d3 < 0)
        return matchNodeContext(this._tree, context, i3);
      let type = types2[buffer.buffer[this.stack[d3]]];
      if (!type.isAnonymous) {
        if (context[i3] && context[i3] != type.name)
          return false;
        i3--;
      }
    }
    return true;
  }
};
function hasChild(tree) {
  return tree.children.some((ch) => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
}
function buildTree(data2) {
  var _a4;
  let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data2;
  let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
  let types2 = nodeSet.types;
  let contextHash = 0, lookAhead = 0;
  function takeNode(parentStart, minPos, children3, positions2, inRepeat, depth2) {
    let { id, start, end, size: size4 } = cursor;
    let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
    if (size4 < 0) {
      cursor.next();
      if (size4 == -1) {
        let node2 = reused[id];
        children3.push(node2);
        positions2.push(start - parentStart);
        return;
      } else if (size4 == -3) {
        contextHash = id;
        return;
      } else if (size4 == -4) {
        lookAhead = id;
        return;
      } else {
        throw new RangeError(`Unrecognized record size: ${size4}`);
      }
    }
    let type = types2[id], node, buffer2;
    let startPos = start - parentStart;
    if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) {
      let data3 = new Uint16Array(buffer2.size - buffer2.skip);
      let endPos = cursor.pos - buffer2.size, index2 = data3.length;
      while (cursor.pos > endPos)
        index2 = copyToBuffer(buffer2.start, data3, index2);
      node = new TreeBuffer(data3, end - buffer2.start, nodeSet);
      startPos = buffer2.start - parentStart;
    } else {
      let endPos = cursor.pos - size4;
      cursor.next();
      let localChildren = [], localPositions = [];
      let localInRepeat = id >= minRepeatType ? id : -1;
      let lastGroup = 0, lastEnd = end;
      while (cursor.pos > endPos) {
        if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
          if (cursor.end <= lastEnd - maxBufferLength) {
            makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
            lastGroup = localChildren.length;
            lastEnd = cursor.end;
          }
          cursor.next();
        } else if (depth2 > 2500) {
          takeFlatNode(start, endPos, localChildren, localPositions);
        } else {
          takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth2 + 1);
        }
      }
      if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
        makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
      localChildren.reverse();
      localPositions.reverse();
      if (localInRepeat > -1 && lastGroup > 0) {
        let make = makeBalanced(type, contextAtStart);
        node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
      } else {
        node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart);
      }
    }
    children3.push(node);
    positions2.push(startPos);
  }
  function takeFlatNode(parentStart, minPos, children3, positions2) {
    let nodes2 = [];
    let nodeCount = 0, stopAt = -1;
    while (cursor.pos > minPos) {
      let { id, start, end, size: size4 } = cursor;
      if (size4 > 4) {
        cursor.next();
      } else if (stopAt > -1 && start < stopAt) {
        break;
      } else {
        if (stopAt < 0)
          stopAt = end - maxBufferLength;
        nodes2.push(id, start, end);
        nodeCount++;
        cursor.next();
      }
    }
    if (nodeCount) {
      let buffer2 = new Uint16Array(nodeCount * 4);
      let start = nodes2[nodes2.length - 2];
      for (let i3 = nodes2.length - 3, j = 0; i3 >= 0; i3 -= 3) {
        buffer2[j++] = nodes2[i3];
        buffer2[j++] = nodes2[i3 + 1] - start;
        buffer2[j++] = nodes2[i3 + 2] - start;
        buffer2[j++] = j;
      }
      children3.push(new TreeBuffer(buffer2, nodes2[2] - start, nodeSet));
      positions2.push(start - parentStart);
    }
  }
  function makeBalanced(type, contextHash2) {
    return (children3, positions2, length2) => {
      let lookAhead2 = 0, lastI = children3.length - 1, last3, lookAheadProp;
      if (lastI >= 0 && (last3 = children3[lastI]) instanceof Tree) {
        if (!lastI && last3.type == type && last3.length == length2)
          return last3;
        if (lookAheadProp = last3.prop(NodeProp.lookAhead))
          lookAhead2 = positions2[lastI] + last3.length + lookAheadProp;
      }
      return makeTree(type, children3, positions2, length2, lookAhead2, contextHash2);
    };
  }
  function makeRepeatLeaf(children3, positions2, base3, i3, from2, to, type, lookAhead2, contextHash2) {
    let localChildren = [], localPositions = [];
    while (children3.length > i3) {
      localChildren.push(children3.pop());
      localPositions.push(positions2.pop() + base3 - from2);
    }
    children3.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from2, lookAhead2 - to, contextHash2));
    positions2.push(from2 - base3);
  }
  function makeTree(type, children3, positions2, length2, lookAhead2, contextHash2, props2) {
    if (contextHash2) {
      let pair2 = [NodeProp.contextHash, contextHash2];
      props2 = props2 ? [pair2].concat(props2) : [pair2];
    }
    if (lookAhead2 > 25) {
      let pair2 = [NodeProp.lookAhead, lookAhead2];
      props2 = props2 ? [pair2].concat(props2) : [pair2];
    }
    return new Tree(type, children3, positions2, length2, props2);
  }
  function findBufferSize(maxSize, inRepeat) {
    let fork = cursor.fork();
    let size4 = 0, start = 0, skip3 = 0, minStart = fork.end - maxBufferLength;
    let result2 = { size: 0, start: 0, skip: 0 };
    scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos; ) {
      let nodeSize3 = fork.size;
      if (fork.id == inRepeat && nodeSize3 >= 0) {
        result2.size = size4;
        result2.start = start;
        result2.skip = skip3;
        skip3 += 4;
        size4 += 4;
        fork.next();
        continue;
      }
      let startPos = fork.pos - nodeSize3;
      if (nodeSize3 < 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 || fork.size == -4)
            localSkipped += 4;
          else
            break scan;
        } else if (fork.id >= minRepeatType) {
          localSkipped += 4;
        }
        fork.next();
      }
      start = nodeStart2;
      size4 += nodeSize3;
      skip3 += localSkipped;
    }
    if (inRepeat < 0 || size4 == maxSize) {
      result2.size = size4;
      result2.start = start;
      result2.skip = skip3;
    }
    return result2.size > 4 ? result2 : void 0;
  }
  function copyToBuffer(bufferStart, buffer2, index2) {
    let { id, start, end, size: size4 } = cursor;
    cursor.next();
    if (size4 >= 0 && id < minRepeatType) {
      let startIndex = index2;
      if (size4 > 4) {
        let endPos = cursor.pos - (size4 - 4);
        while (cursor.pos > endPos)
          index2 = copyToBuffer(bufferStart, buffer2, index2);
      }
      buffer2[--index2] = startIndex;
      buffer2[--index2] = end - bufferStart;
      buffer2[--index2] = start - bufferStart;
      buffer2[--index2] = id;
    } else if (size4 == -3) {
      contextHash = id;
    } else if (size4 == -4) {
      lookAhead = id;
    }
    return index2;
  }
  let children2 = [], positions = [];
  while (cursor.pos > 0)
    takeNode(data2.start || 0, data2.bufferStart || 0, children2, positions, -1, 0);
  let length = (_a4 = data2.length) !== null && _a4 !== void 0 ? _a4 : children2.length ? positions[0] + children2[0].length : 0;
  return new Tree(types2[data2.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 size4 = nodeSizeCache.get(node);
  if (size4 == null) {
    size4 = 1;
    for (let child of node.children) {
      if (child.type != balanceType || !(child instanceof Tree)) {
        size4 = 1;
        break;
      }
      size4 += nodeSize(balanceType, child);
    }
    nodeSizeCache.set(node, size4);
  }
  return size4;
}
function balanceRange(balanceType, children2, positions, from2, to, start, length, mkTop, mkTree) {
  let total = 0;
  for (let i3 = from2; i3 < to; i3++)
    total += nodeSize(balanceType, children2[i3]);
  let maxChild = Math.ceil(
    total * 1.5 / 8
    /* Balance.BranchFactor */
  );
  let localChildren = [], localPositions = [];
  function divide(children3, positions2, from3, to2, offset) {
    for (let i3 = from3; i3 < to2; ) {
      let groupFrom = i3, groupStart = positions2[i3], groupSize = nodeSize(balanceType, children3[i3]);
      i3++;
      for (; i3 < to2; i3++) {
        let nextSize = nodeSize(balanceType, children3[i3]);
        if (groupSize + nextSize >= maxChild)
          break;
        groupSize += nextSize;
      }
      if (i3 == 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[i3 - 1] + children3[i3 - 1].length - groupStart;
        localChildren.push(balanceRange(balanceType, children3, positions2, groupFrom, i3, groupStart, length2, null, mkTree));
      }
      localPositions.push(groupStart + offset - start);
    }
  }
  divide(children2, positions, from2, 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(from2, to, tree, offset, openStart = false, openEnd = false) {
    this.from = from2;
    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 = [], partial2 = false) {
    let result2 = [new _TreeFragment(0, tree.length, tree, 0, false, partial2)];
    for (let f3 of fragments)
      if (f3.to > tree.length)
        result2.push(f3);
    return result2;
  }
  /**
  Apply a set of edits to an array of fragments, removing or
  splitting fragments as necessary to remove edited ranges, and
  adjusting offsets for fragments that moved.
  */
  static applyChanges(fragments, changes, minGap = 128) {
    if (!changes.length)
      return fragments;
    let result2 = [];
    let fI = 1, nextF = fragments.length ? fragments[0] : null;
    for (let cI = 0, 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)
            result2.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 result2;
  }
};
var Parser2 = 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((r3) => new Range2(r3.from, r3.to)) : [new Range2(0, 0)];
    return this.createParse(input, fragments || [], ranges);
  }
  /**
  Run a full parse, returning the resulting tree.
  */
  parse(input, fragments, ranges) {
    let parse4 = this.startParse(input, fragments, ranges);
    for (; ; ) {
      let done = parse4.advance();
      if (done)
        return done;
    }
  }
};
var StringInput = class {
  constructor(string3) {
    this.string = string3;
  }
  get length() {
    return this.string.length;
  }
  chunk(from2) {
    return this.string.slice(from2);
  }
  get lineChunks() {
    return false;
  }
  read(from2, to) {
    return this.string.slice(from2, to);
  }
};
var stoppedInner = new NodeProp({ perNode: true });

// node_modules/@lezer/highlight/dist/index.js
var nextTagID = 0;
var Tag = class _Tag {
  /**
  @internal
  */
  constructor(name2, set4, base3, modified) {
    this.name = name2;
    this.set = set4;
    this.base = base3;
    this.modified = modified;
    this.id = nextTagID++;
  }
  toString() {
    let { name: name2 } = this;
    for (let mod of this.modified)
      if (mod.name)
        name2 = `${mod.name}(${name2})`;
    return name2;
  }
  static define(nameOrParent, parent) {
    let name2 = typeof nameOrParent == "string" ? nameOrParent : "?";
    if (nameOrParent instanceof _Tag)
      parent = nameOrParent;
    if (parent === null || parent === void 0 ? void 0 : parent.base)
      throw new Error("Can not derive from a modified tag");
    let tag = new _Tag(name2, [], null, []);
    tag.set.push(tag);
    if (parent)
      for (let t3 of parent.set)
        tag.set.push(t3);
    return tag;
  }
  /**
  Define a tag _modifier_, which is a function that, given a tag,
  will return a tag that is a subtag of the original. Applying the
  same modifier to a twice tag will return the same value (`m1(t1)
  == m1(t1)`) and applying multiple modifiers will, regardless or
  order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
  
  When multiple modifiers are applied to a given base tag, each
  smaller set of modifiers is registered as a parent, so that for
  example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
  `m1(m3(t1)`, and so on.
  */
  static defineModifier(name2) {
    let mod = new Modifier(name2);
    return (tag) => {
      if (tag.modified.indexOf(mod) > -1)
        return tag;
      return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a3, b3) => a3.id - b3.id));
    };
  }
};
var nextModifierID = 0;
var Modifier = class _Modifier {
  constructor(name2) {
    this.name = name2;
    this.instances = [];
    this.id = nextModifierID++;
  }
  static get(base3, mods) {
    if (!mods.length)
      return base3;
    let exists = mods[0].instances.find((t3) => t3.base == base3 && sameArray2(mods, t3.modified));
    if (exists)
      return exists;
    let set4 = [], tag = new Tag(base3.name, set4, base3, mods);
    for (let m3 of mods)
      m3.instances.push(tag);
    let configs = powerSet(mods);
    for (let parent of base3.set)
      if (!parent.modified.length)
        for (let config3 of configs)
          set4.push(_Modifier.get(parent, config3));
    return tag;
  }
};
function sameArray2(a3, b3) {
  return a3.length == b3.length && a3.every((x3, i3) => x3 == b3[i3]);
}
function powerSet(array) {
  let sets = [[]];
  for (let i3 = 0; i3 < array.length; i3++) {
    for (let j = 0, e3 = sets.length; j < e3; j++) {
      sets.push(sets[j].concat(array[i3]));
    }
  }
  return sets.sort((a3, b3) => b3.length - a3.length);
}
function styleTags(spec) {
  let byName = /* @__PURE__ */ Object.create(null);
  for (let prop2 in spec) {
    let tags2 = spec[prop2];
    if (!Array.isArray(tags2))
      tags2 = [tags2];
    for (let part of prop2.split(" "))
      if (part) {
        let pieces = [], mode = 2, rest2 = part;
        for (let pos = 0; ; ) {
          if (rest2 == "..." && pos > 0 && pos + 3 == part.length) {
            mode = 1;
            break;
          }
          let m3 = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest2);
          if (!m3)
            throw new RangeError("Invalid path: " + part);
          pieces.push(m3[0] == "*" ? "" : m3[0][0] == '"' ? JSON.parse(m3[0]) : m3[0]);
          pos += m3[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);
          rest2 = part.slice(pos);
        }
        let last3 = pieces.length - 1, inner = pieces[last3];
        if (!inner)
          throw new RangeError("Invalid path: " + part);
        let rule = new Rule(tags2, mode, last3 > 0 ? pieces.slice(0, last3) : null);
        byName[inner] = rule.sort(byName[inner]);
      }
  }
  return ruleNodeProp.add(byName);
}
var ruleNodeProp = new NodeProp({
  combine(a3, b3) {
    let cur2, root3, take;
    while (a3 || b3) {
      if (!a3 || b3 && a3.depth >= b3.depth) {
        take = b3;
        b3 = b3.next;
      } else {
        take = a3;
        a3 = a3.next;
      }
      if (cur2 && cur2.mode == take.mode && !take.context && !cur2.context)
        continue;
      let copy2 = new Rule(take.tags, take.mode, take.context);
      if (cur2)
        cur2.next = copy2;
      else
        root3 = copy2;
      cur2 = copy2;
    }
    return root3;
  }
});
var Rule = class {
  constructor(tags2, mode, context, next2) {
    this.tags = tags2;
    this.mode = mode;
    this.context = context;
    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(tags2, options2) {
  let map5 = /* @__PURE__ */ Object.create(null);
  for (let style3 of tags2) {
    if (!Array.isArray(style3.tag))
      map5[style3.tag.id] = style3.class;
    else
      for (let tag of style3.tag)
        map5[tag.id] = style3.class;
  }
  let { scope, all: all2 = null } = options2 || {};
  return {
    style: (tags3) => {
      let cls = all2;
      for (let tag of tags3) {
        for (let sub of tag.set) {
          let tagClass = map5[sub.id];
          if (tagClass) {
            cls = cls ? cls + " " + tagClass : tagClass;
            break;
          }
        }
      }
      return cls;
    },
    scope
  };
}
function highlightTags(highlighters, tags2) {
  let result2 = null;
  for (let highlighter of highlighters) {
    let value2 = highlighter.style(tags2);
    if (value2)
      result2 = result2 ? result2 + " " + value2 : value2;
  }
  return result2;
}
function highlightTree(tree, highlighter, putStyle, from2 = 0, to = tree.length) {
  let builder = new HighlightBuilder(from2, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
  builder.highlightRange(tree.cursor(), from2, 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, from2, to, inheritedClass, highlighters) {
    let { type, from: start, to: end } = cursor;
    if (start >= to || end <= from2)
      return;
    if (type.isTop)
      highlighters = this.highlighters.filter((h3) => !h3.scope || h3.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(from2, start), cls);
    if (rule.opaque)
      return;
    let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
    if (mounted && mounted.overlay) {
      let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
      let innerHighlighters = this.highlighters.filter((h3) => !h3.scope || h3.scope(mounted.tree.type));
      let hasChild2 = cursor.firstChild();
      for (let i3 = 0, pos = start; ; i3++) {
        let next2 = i3 < mounted.overlay.length ? mounted.overlay[i3] : null;
        let nextPos = next2 ? next2.from + start : end;
        let rangeFrom2 = Math.max(from2, 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 + start;
        if (pos > from2) {
          this.highlightRange(inner.cursor(), Math.max(from2, next2.from + start), 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 <= from2)
          continue;
        if (cursor.from >= to)
          break;
        this.highlightRange(cursor, from2, 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 t2 = Tag.define;
var comment = t2();
var name = t2();
var typeName = t2(name);
var propertyName = t2(name);
var literal = t2();
var string = t2(literal);
var number = t2(literal);
var content = t2();
var heading = t2(content);
var keyword = t2();
var operator = t2();
var punctuation = t2();
var bracket = t2(punctuation);
var meta = t2();
var tags = {
  /**
  A comment.
  */
  comment,
  /**
  A line [comment](#highlight.tags.comment).
  */
  lineComment: t2(comment),
  /**
  A block [comment](#highlight.tags.comment).
  */
  blockComment: t2(comment),
  /**
  A documentation [comment](#highlight.tags.comment).
  */
  docComment: t2(comment),
  /**
  Any kind of identifier.
  */
  name,
  /**
  The [name](#highlight.tags.name) of a variable.
  */
  variableName: t2(name),
  /**
  A type [name](#highlight.tags.name).
  */
  typeName,
  /**
  A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
  */
  tagName: t2(typeName),
  /**
  A property or field [name](#highlight.tags.name).
  */
  propertyName,
  /**
  An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
  */
  attributeName: t2(propertyName),
  /**
  The [name](#highlight.tags.name) of a class.
  */
  className: t2(name),
  /**
  A label [name](#highlight.tags.name).
  */
  labelName: t2(name),
  /**
  A namespace [name](#highlight.tags.name).
  */
  namespace: t2(name),
  /**
  The [name](#highlight.tags.name) of a macro.
  */
  macroName: t2(name),
  /**
  A literal value.
  */
  literal,
  /**
  A string [literal](#highlight.tags.literal).
  */
  string,
  /**
  A documentation [string](#highlight.tags.string).
  */
  docString: t2(string),
  /**
  A character literal (subtag of [string](#highlight.tags.string)).
  */
  character: t2(string),
  /**
  An attribute value (subtag of [string](#highlight.tags.string)).
  */
  attributeValue: t2(string),
  /**
  A number [literal](#highlight.tags.literal).
  */
  number,
  /**
  An integer [number](#highlight.tags.number) literal.
  */
  integer: t2(number),
  /**
  A floating-point [number](#highlight.tags.number) literal.
  */
  float: t2(number),
  /**
  A boolean [literal](#highlight.tags.literal).
  */
  bool: t2(literal),
  /**
  Regular expression [literal](#highlight.tags.literal).
  */
  regexp: t2(literal),
  /**
  An escape [literal](#highlight.tags.literal), for example a
  backslash escape in a string.
  */
  escape: t2(literal),
  /**
  A color [literal](#highlight.tags.literal).
  */
  color: t2(literal),
  /**
  A URL [literal](#highlight.tags.literal).
  */
  url: t2(literal),
  /**
  A language keyword.
  */
  keyword,
  /**
  The [keyword](#highlight.tags.keyword) for the self or this
  object.
  */
  self: t2(keyword),
  /**
  The [keyword](#highlight.tags.keyword) for null.
  */
  null: t2(keyword),
  /**
  A [keyword](#highlight.tags.keyword) denoting some atomic value.
  */
  atom: t2(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that represents a unit.
  */
  unit: t2(keyword),
  /**
  A modifier [keyword](#highlight.tags.keyword).
  */
  modifier: t2(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that acts as an operator.
  */
  operatorKeyword: t2(keyword),
  /**
  A control-flow related [keyword](#highlight.tags.keyword).
  */
  controlKeyword: t2(keyword),
  /**
  A [keyword](#highlight.tags.keyword) that defines something.
  */
  definitionKeyword: t2(keyword),
  /**
  A [keyword](#highlight.tags.keyword) related to defining or
  interfacing with modules.
  */
  moduleKeyword: t2(keyword),
  /**
  An operator.
  */
  operator,
  /**
  An [operator](#highlight.tags.operator) that dereferences something.
  */
  derefOperator: t2(operator),
  /**
  Arithmetic-related [operator](#highlight.tags.operator).
  */
  arithmeticOperator: t2(operator),
  /**
  Logical [operator](#highlight.tags.operator).
  */
  logicOperator: t2(operator),
  /**
  Bit [operator](#highlight.tags.operator).
  */
  bitwiseOperator: t2(operator),
  /**
  Comparison [operator](#highlight.tags.operator).
  */
  compareOperator: t2(operator),
  /**
  [Operator](#highlight.tags.operator) that updates its operand.
  */
  updateOperator: t2(operator),
  /**
  [Operator](#highlight.tags.operator) that defines something.
  */
  definitionOperator: t2(operator),
  /**
  Type-related [operator](#highlight.tags.operator).
  */
  typeOperator: t2(operator),
  /**
  Control-flow [operator](#highlight.tags.operator).
  */
  controlOperator: t2(operator),
  /**
  Program or markup punctuation.
  */
  punctuation,
  /**
  [Punctuation](#highlight.tags.punctuation) that separates
  things.
  */
  separator: t2(punctuation),
  /**
  Bracket-style [punctuation](#highlight.tags.punctuation).
  */
  bracket,
  /**
  Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
  tokens).
  */
  angleBracket: t2(bracket),
  /**
  Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
  tokens).
  */
  squareBracket: t2(bracket),
  /**
  Parentheses (usually `(` and `)` tokens). Subtag of
  [bracket](#highlight.tags.bracket).
  */
  paren: t2(bracket),
  /**
  Braces (usually `{` and `}` tokens). Subtag of
  [bracket](#highlight.tags.bracket).
  */
  brace: t2(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: t2(heading),
  /**
  A level 2 [heading](#highlight.tags.heading).
  */
  heading2: t2(heading),
  /**
  A level 3 [heading](#highlight.tags.heading).
  */
  heading3: t2(heading),
  /**
  A level 4 [heading](#highlight.tags.heading).
  */
  heading4: t2(heading),
  /**
  A level 5 [heading](#highlight.tags.heading).
  */
  heading5: t2(heading),
  /**
  A level 6 [heading](#highlight.tags.heading).
  */
  heading6: t2(heading),
  /**
  A prose [content](#highlight.tags.content) separator (such as a horizontal rule).
  */
  contentSeparator: t2(content),
  /**
  [Content](#highlight.tags.content) that represents a list.
  */
  list: t2(content),
  /**
  [Content](#highlight.tags.content) that represents a quote.
  */
  quote: t2(content),
  /**
  [Content](#highlight.tags.content) that is emphasized.
  */
  emphasis: t2(content),
  /**
  [Content](#highlight.tags.content) that is styled strong.
  */
  strong: t2(content),
  /**
  [Content](#highlight.tags.content) that is part of a link.
  */
  link: t2(content),
  /**
  [Content](#highlight.tags.content) that is styled as code or
  monospace.
  */
  monospace: t2(content),
  /**
  [Content](#highlight.tags.content) that has a strike-through
  style.
  */
  strikethrough: t2(content),
  /**
  Inserted text in a change-tracking format.
  */
  inserted: t2(),
  /**
  Deleted text.
  */
  deleted: t2(),
  /**
  Changed text.
  */
  changed: t2(),
  /**
  An invalid or unsyntactic element.
  */
  invalid: t2(),
  /**
  Metadata or meta-instruction.
  */
  meta,
  /**
  [Metadata](#highlight.tags.meta) that applies to the entire
  document.
  */
  documentMeta: t2(meta),
  /**
  [Metadata](#highlight.tags.meta) that annotates or adds
  attributes to a given syntactic element.
  */
  annotation: t2(meta),
  /**
  Processing instruction or preprocessor directive. Subtag of
  [meta](#highlight.tags.meta).
  */
  processingInstruction: t2(meta),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates that a
  given element is being defined. Expected to be used with the
  various [name](#highlight.tags.name) tags.
  */
  definition: Tag.defineModifier("definition"),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates that
  something is constant. Mostly expected to be used with
  [variable names](#highlight.tags.variableName).
  */
  constant: Tag.defineModifier("constant"),
  /**
  [Modifier](#highlight.Tag^defineModifier) used to indicate that
  a [variable](#highlight.tags.variableName) or [property
  name](#highlight.tags.propertyName) is being called or defined
  as a function.
  */
  function: Tag.defineModifier("function"),
  /**
  [Modifier](#highlight.Tag^defineModifier) that can be applied to
  [names](#highlight.tags.name) to indicate that they belong to
  the language's standard environment.
  */
  standard: Tag.defineModifier("standard"),
  /**
  [Modifier](#highlight.Tag^defineModifier) that indicates a given
  [names](#highlight.tags.name) is local to some scope.
  */
  local: Tag.defineModifier("local"),
  /**
  A generic variant [modifier](#highlight.Tag^defineModifier) that
  can be used to tag language-specific alternative variants of
  some common tag. It is recommended for themes to define special
  forms of at least the [string](#highlight.tags.string) and
  [variable name](#highlight.tags.variableName) tags, since those
  come up a lot.
  */
  special: Tag.defineModifier("special")
};
for (let name2 in tags) {
  let val = tags[name2];
  if (val instanceof Tag)
    val.name = name2;
}
var classHighlighter = tagHighlighter([
  { tag: tags.link, class: "tok-link" },
  { tag: tags.heading, class: "tok-heading" },
  { tag: tags.emphasis, class: "tok-emphasis" },
  { tag: tags.strong, class: "tok-strong" },
  { tag: tags.keyword, class: "tok-keyword" },
  { tag: tags.atom, class: "tok-atom" },
  { tag: tags.bool, class: "tok-bool" },
  { tag: tags.url, class: "tok-url" },
  { tag: tags.labelName, class: "tok-labelName" },
  { tag: tags.inserted, class: "tok-inserted" },
  { tag: tags.deleted, class: "tok-deleted" },
  { tag: tags.literal, class: "tok-literal" },
  { tag: tags.string, class: "tok-string" },
  { tag: tags.number, class: "tok-number" },
  { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
  { tag: tags.variableName, class: "tok-variableName" },
  { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
  { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
  { tag: tags.special(tags.variableName), class: "tok-variableName2" },
  { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
  { tag: tags.typeName, class: "tok-typeName" },
  { tag: tags.namespace, class: "tok-namespace" },
  { tag: tags.className, class: "tok-className" },
  { tag: tags.macroName, class: "tok-macroName" },
  { tag: tags.propertyName, class: "tok-propertyName" },
  { tag: tags.operator, class: "tok-operator" },
  { tag: tags.comment, class: "tok-comment" },
  { tag: tags.meta, class: "tok-meta" },
  { tag: tags.invalid, class: "tok-invalid" },
  { tag: tags.punctuation, class: "tok-punctuation" }
]);

// node_modules/@codemirror/language/dist/index.js
var _a;
var languageDataProp = /* @__PURE__ */ new NodeProp();
function defineLanguageFacet(baseData) {
  return Facet.define({
    combine: baseData ? (values2) => values2.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(data2, parser4, extraExtensions = [], name2 = "") {
    this.data = data2;
    this.name = name2;
    if (!EditorState2.prototype.hasOwnProperty("tree"))
      Object.defineProperty(EditorState2.prototype, "tree", { get() {
        return syntaxTree(this);
      } });
    this.parser = parser4;
    this.extension = [
      language.of(this),
      EditorState2.languageData.of((state, pos, side) => {
        let top2 = topNodeAt(state, pos, side), data3 = top2.type.prop(languageDataProp);
        if (!data3)
          return [];
        let base3 = state.facet(data3), sub = top2.type.prop(sublanguageProp);
        if (sub) {
          let innerNode = top2.resolve(pos - top2.from, side);
          for (let sublang of sub)
            if (sublang.test(innerNode, state)) {
              let data4 = state.facet(sublang.facet);
              return sublang.type == "replace" ? data4 : data4.concat(base3);
            }
        }
        return base3;
      })
    ].concat(extraExtensions);
  }
  /**
  Query whether this language is active at the given position.
  */
  isActiveAt(state, pos, side = -1) {
    return topNodeAt(state, 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(state) {
    let lang2 = state.facet(language);
    if ((lang2 === null || lang2 === void 0 ? void 0 : lang2.data) == this.data)
      return [{ from: 0, to: state.doc.length }];
    if (!lang2 || !lang2.allowsNesting)
      return [];
    let result2 = [];
    let explore = (tree, from2) => {
      if (tree.prop(languageDataProp) == this.data) {
        result2.push({ from: from2, to: from2 + tree.length });
        return;
      }
      let mount = tree.prop(NodeProp.mounted);
      if (mount) {
        if (mount.tree.prop(languageDataProp) == this.data) {
          if (mount.overlay)
            for (let r3 of mount.overlay)
              result2.push({ from: r3.from + from2, to: r3.to + from2 });
          else
            result2.push({ from: from2, to: from2 + tree.length });
          return;
        } else if (mount.overlay) {
          let size4 = result2.length;
          explore(mount.tree, mount.overlay[0].from + from2);
          if (result2.length > size4)
            return;
        }
      }
      for (let i3 = 0; i3 < tree.children.length; i3++) {
        let ch = tree.children[i3];
        if (ch instanceof Tree)
          explore(ch, tree.positions[i3] + from2);
      }
    };
    explore(syntaxTree(state), 0);
    return result2;
  }
  /**
  Indicates whether this language allows nested languages. The
  default implementation returns true.
  */
  get allowsNesting() {
    return true;
  }
};
Language.setState = /* @__PURE__ */ StateEffect.define();
function topNodeAt(state, pos, side) {
  let topLang = state.facet(language), tree = syntaxTree(state).topNode;
  if (!topLang || topLang.allowsNesting) {
    for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers | IterMode.EnterBracketed))
      if (node.type.isTop)
        tree = node;
  }
  return tree;
}
var LRLanguage = class _LRLanguage extends Language {
  constructor(data2, parser4, name2) {
    super(data2, parser4, [], name2);
    this.parser = parser4;
  }
  /**
  Define a language from a parser.
  */
  static define(spec) {
    let data2 = defineLanguageFacet(spec.languageData);
    return new _LRLanguage(data2, spec.parser.configure({
      props: [languageDataProp.add((type) => type.isTop ? data2 : void 0)]
    }), spec.name);
  }
  /**
  Create a new instance of this language with a reconfigured
  version of its parser and optionally a new name.
  */
  configure(options2, name2) {
    return new _LRLanguage(this.data, this.parser.configure(options2), name2 || this.name);
  }
  get allowsNesting() {
    return this.parser.hasWrappers();
  }
};
function syntaxTree(state) {
  let field2 = state.field(Language.state, false);
  return field2 ? field2.tree : Tree.empty;
}
var DocInput = class {
  /**
  Create an input object for the given document.
  */
  constructor(doc4) {
    this.doc = doc4;
    this.cursorPos = 0;
    this.string = "";
    this.cursor = doc4.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(from2, to) {
    let stringStart = this.cursorPos - this.string.length;
    if (from2 < stringStart || to >= this.cursorPos)
      return this.doc.sliceString(from2, to);
    else
      return this.string.slice(from2 - stringStart, to - stringStart);
  }
};
var currentContext = null;
var ParseContext2 = class _ParseContext {
  constructor(parser4, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
    this.parser = parser4;
    this.state = state;
    this.fragments = fragments;
    this.tree = tree;
    this.treeLen = treeLen;
    this.viewport = viewport;
    this.skipped = skipped;
    this.scheduleOn = scheduleOn;
    this.parse = null;
    this.tempSkipped = [];
  }
  /**
  @internal
  */
  static create(parser4, state, viewport) {
    return new _ParseContext(parser4, state, [], Tree.empty, 0, viewport, [], null);
  }
  startParse() {
    return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
  }
  /**
  @internal
  */
  work(until, upto) {
    if (upto != null && upto >= this.state.doc.length)
      upto = void 0;
    if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
      this.takeTree();
      return true;
    }
    return this.withContext(() => {
      var _a4;
      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 = (_a4 = this.parse.stoppedAt) !== null && _a4 !== void 0 ? _a4 : 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(f3) {
    let prev = currentContext;
    currentContext = this;
    try {
      return f3();
    } finally {
      currentContext = prev;
    }
  }
  withoutTempSkipped(fragments) {
    for (let r3; r3 = this.tempSkipped.pop(); )
      fragments = cutFragments(fragments, r3.from, r3.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 r3 of this.skipped) {
          let from2 = changes.mapPos(r3.from, 1), to = changes.mapPos(r3.to, -1);
          if (from2 < to)
            skipped.push({ from: from2, 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 i3 = 0; i3 < this.skipped.length; i3++) {
      let { from: from2, to } = this.skipped[i3];
      if (from2 < viewport.to && to > viewport.from) {
        this.fragments = cutFragments(this.fragments, from2, to);
        this.skipped.splice(i3--, 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(from2, to) {
    this.skipped.push({ from: from2, 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 Parser2 {
      createParse(input, fragments, ranges) {
        let from2 = ranges[0].from, to = ranges[ranges.length - 1].to;
        let parser4 = {
          parsedPos: from2,
          advance() {
            let cx = currentContext;
            if (cx) {
              for (let r3 of ranges)
                cx.tempSkipped.push(r3);
              if (until)
                cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
            }
            this.parsedPos = to;
            return new Tree(NodeType2.none, [], [], to - from2);
          },
          stoppedAt: null,
          stopAt() {
          }
        };
        return parser4;
      }
    }();
  }
  /**
  @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, from2, to) {
  return TreeFragment.applyChanges(fragments, [{ fromA: from2, toA: to, fromB: from2, toB: to }]);
}
var LanguageState = class _LanguageState {
  constructor(context) {
    this.context = context;
    this.tree = context.tree;
  }
  apply(tr2) {
    if (!tr2.docChanged && this.tree == this.context.tree)
      return this;
    let newCx = this.context.changes(tr2.changes, tr2.state);
    let upto = this.context.treeLen == tr2.startState.doc.length ? void 0 : Math.max(tr2.changes.mapPos(this.context.treeLen), newCx.viewport.to);
    if (!newCx.work(20, upto))
      newCx.takeTree();
    return new _LanguageState(newCx);
  }
  static init(state) {
    let vpTo = Math.min(3e3, state.doc.length);
    let parseState = ParseContext2.create(state.facet(language).parser, state, { from: 0, to: vpTo });
    if (!parseState.work(20, vpTo))
      parseState.takeTree();
    return new _LanguageState(parseState);
  }
};
Language.state = /* @__PURE__ */ StateField.define({
  create: LanguageState.init,
  update(value2, tr2) {
    for (let e3 of tr2.effects)
      if (e3.is(Language.setState))
        return e3.value;
    if (tr2.startState.facet(language) != tr2.state.facet(language))
      return LanguageState.init(tr2.state);
    return value2.apply(tr2);
  }
});
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(update2) {
    let cx = this.view.state.field(Language.state).context;
    if (cx.updateViewport(update2.view.viewport) || this.view.viewport.to > cx.treeLen)
      this.scheduleWork();
    if (update2.docChanged || update2.selectionSet) {
      if (this.view.hasFocus)
        this.chunkBudget += 50;
      this.scheduleWork();
    }
    this.checkAsyncSchedule(cx);
  }
  scheduleWork() {
    if (this.working)
      return;
    let { state } = this.view, field2 = state.field(Language.state);
    if (field2.tree != field2.context.tree || !field2.context.isDone(state.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, viewport: { to: vpTo } } = this.view, field2 = state.field(Language.state);
    if (field2.tree == field2.context.tree && field2.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 = field2.context.treeLen < vpTo && state.doc.length > vpTo + 1e3;
    let done = field2.context.work(() => {
      return isInputPending && isInputPending() || Date.now() > endTime;
    }, vpTo + (viewportFirst ? 0 : 1e5));
    this.chunkBudget -= Date.now() - now;
    if (done || this.chunkBudget <= 0) {
      field2.context.takeTree();
      this.view.dispatch({ effects: Language.setState.of(new LanguageState(field2.context)) });
    }
    if (this.chunkBudget > 0 && !(done && !viewportFirst))
      this.scheduleWork();
    this.checkAsyncSchedule(field2.context);
  }
  checkAsyncSchedule(cx) {
    if (cx.scheduleOn) {
      this.workScheduled++;
      cx.scheduleOn.then(() => this.scheduleWork()).catch((err) => logException(this.view.state, err)).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], (state) => {
      let lang2 = state.facet(language2);
      return lang2 && lang2.name ? { "data-language": lang2.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: (values2) => {
    if (!values2.length)
      return "  ";
    let unit = values2[0];
    if (!unit || /\S/.test(unit) || Array.from(unit).some((e3) => e3 != unit[0]))
      throw new Error("Invalid indent unit: " + JSON.stringify(values2[0]));
    return unit;
  }
});
function getIndentUnit(state) {
  let unit = state.facet(indentUnit);
  return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
}
function indentString(state, cols) {
  let result2 = "", ts = state.tabSize, ch = state.facet(indentUnit)[0];
  if (ch == "	") {
    while (cols >= ts) {
      result2 += "	";
      cols -= ts;
    }
    ch = " ";
  }
  for (let i3 = 0; i3 < cols; i3++)
    result2 += ch;
  return result2;
}
function getIndentation(context, pos) {
  if (context instanceof EditorState2)
    context = new IndentContext(context);
  for (let service of context.state.facet(indentService)) {
    let result2 = service(context, pos);
    if (result2 !== void 0)
      return result2;
  }
  let tree = syntaxTree(context.state);
  return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
}
var IndentContext = class {
  /**
  Create an indent context.
  */
  constructor(state, options2 = {}) {
    this.state = state;
    this.options = options2;
    this.unit = getIndentUnit(state);
  }
  /**
  Get a description of the line at the given position, taking
  [simulated line
  breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  into account. If there is such a break at `pos`, the `bias`
  argument determines whether the part of the line line before or
  after the break is used.
  */
  lineAt(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: text3, from: from2 } = this.lineAt(pos, bias);
    return text3.slice(pos - from2, Math.min(text3.length, pos + 100 - from2));
  }
  /**
  Find the column for the given position.
  */
  column(pos, bias = 1) {
    let { text: text3, from: from2 } = this.lineAt(pos, bias);
    let result2 = this.countColumn(text3, pos - from2);
    let override2 = this.options.overrideIndentation ? this.options.overrideIndentation(from2) : -1;
    if (override2 > -1)
      result2 += override2 - this.countColumn(text3, text3.search(/\S|$/));
    return result2;
  }
  /**
  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: text3, from: from2 } = this.lineAt(pos, bias);
    let override2 = this.options.overrideIndentation;
    if (override2) {
      let overriden = override2(from2);
      if (overriden > -1)
        return overriden;
    }
    return this.countColumn(text3, text3.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 stack = ast.resolveStack(pos);
  let inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos);
  if (inner != stack.node) {
    let add4 = [];
    for (let cur2 = inner; cur2 && !(cur2.from < stack.node.from || cur2.to > stack.node.to || cur2.from == stack.node.from && cur2.type == stack.node.type); cur2 = cur2.parent)
      add4.push(cur2);
    for (let i3 = add4.length - 1; i3 >= 0; i3--)
      stack = { node: add4[i3], next: stack };
  }
  return indentFor(stack, cx, pos);
}
function indentFor(stack, cx, pos) {
  for (let cur2 = stack; 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 first2 = tree.firstChild, close2;
  if (first2 && (close2 = first2.type.prop(NodeProp.closedBy))) {
    let last3 = tree.lastChild, closed = last3 && close2.indexOf(last3.name) > -1;
    return (cx) => delimitedStrategy(cx, true, 1, void 0, closed && !ignoreClosed(cx) ? last3.from : void 0);
  }
  return tree.parent == null ? topIndent : null;
}
function topIndent() {
  return 0;
}
var TreeIndentContext = class _TreeIndentContext extends IndentContext {
  constructor(base3, pos, context) {
    super(base3.state, base3.options);
    this.base = base3;
    this.pos = pos;
    this.context = context;
  }
  /**
  The syntax tree node to which the indentation strategy
  applies.
  */
  get node() {
    return this.context.node;
  }
  /**
  @internal
  */
  static create(base3, pos, context) {
    return new _TreeIndentContext(base3, pos, context);
  }
  /**
  Get the text directly after `this.pos`, either the entire line
  or the next 100 characters, whichever is shorter.
  */
  get textAfter() {
    return this.textAfterPos(this.pos);
  }
  /**
  Get the indentation at the reference line for `this.node`, which
  is the line on which it starts, unless there is a node that is
  _not_ a parent of this node covering the start of that line. If
  so, the line at the start of that node is tried, again skipping
  on if it is covered by another such node.
  */
  get baseIndent() {
    return this.baseIndentFor(this.node);
  }
  /**
  Get the indentation for the reference line of the given node
  (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
  */
  baseIndentFor(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(parent, of) {
  for (let cur2 = of; cur2; cur2 = cur2.parent)
    if (parent == cur2)
      return true;
  return false;
}
function bracketedAligned(context) {
  let tree = context.node;
  let openToken = tree.childAfter(tree.from), last3 = tree.lastChild;
  if (!openToken)
    return null;
  let sim = context.options.simulateBreak;
  let openLine = context.state.doc.lineAt(openToken.from);
  let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
  for (let pos = openToken.to; ; ) {
    let next2 = tree.childAfter(pos);
    if (!next2 || next2 == last3)
      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(context, align, units, closing3, closedAt) {
  let after2 = context.textAfter, space = after2.match(/^\s*/)[0].length;
  let closed = closing3 && after2.slice(space, space + closing3.length) == closing3 || closedAt == context.pos + space;
  let aligned = align ? bracketedAligned(context) : null;
  if (aligned)
    return closed ? context.column(aligned.from) : context.column(aligned.to);
  return context.baseIndent + (closed ? 0 : context.unit * units);
}
function continuedIndent({ except, units = 1 } = {}) {
  return (context) => {
    let matchExcept = except && except.test(context.textAfter);
    return context.baseIndent + (matchExcept ? 0 : units * context.unit);
  };
}
var DontIndentBeyond = 200;
function indentOnInput() {
  return EditorState2.transactionFilter.of((tr2) => {
    if (!tr2.docChanged || !tr2.isUserEvent("input.type") && !tr2.isUserEvent("input.complete"))
      return tr2;
    let rules = tr2.startState.languageDataAt("indentOnInput", tr2.startState.selection.main.head);
    if (!rules.length)
      return tr2;
    let doc4 = tr2.newDoc, { head: head2 } = tr2.newSelection.main, line = doc4.lineAt(head2);
    if (head2 > line.from + DontIndentBeyond)
      return tr2;
    let lineStart = doc4.sliceString(line.from, head2);
    if (!rules.some((r3) => r3.test(lineStart)))
      return tr2;
    let { state } = tr2, last3 = -1, changes = [];
    for (let { head: head3 } of state.selection.ranges) {
      let line2 = state.doc.lineAt(head3);
      if (line2.from == last3)
        continue;
      last3 = line2.from;
      let indent = getIndentation(state, line2.from);
      if (indent == null)
        continue;
      let cur2 = /^\s*/.exec(line2.text)[0];
      let norm = indentString(state, indent);
      if (cur2 != norm)
        changes.push({ from: line2.from, to: line2.from + cur2.length, insert: norm });
    }
    return changes.length ? [tr2, { changes, sequential: true }] : tr2;
  });
}
var foldService = /* @__PURE__ */ Facet.define();
var foldNodeProp = /* @__PURE__ */ new NodeProp();
function foldInside(node) {
  let first2 = node.firstChild, last3 = node.lastChild;
  return first2 && first2.to < last3.from ? { from: first2.to, to: last3.type.isError ? node.to : last3.from } : null;
}
function syntaxFolding(state, start, end) {
  let tree = syntaxTree(state);
  if (tree.length < end)
    return null;
  let stack = tree.resolveStack(end, 1);
  let found2 = null;
  for (let iter = stack; iter; iter = iter.next) {
    let cur2 = iter.node;
    if (cur2.to <= end || cur2.from > end)
      continue;
    if (found2 && cur2.from < start)
      break;
    let prop2 = cur2.type.prop(foldNodeProp);
    if (prop2 && (cur2.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur2))) {
      let value2 = prop2(cur2, state);
      if (value2 && value2.from <= end && value2.from >= start && value2.to > end)
        found2 = value2;
    }
  }
  return found2;
}
function isUnfinished(node) {
  let ch = node.lastChild;
  return ch && ch.to == node.to && ch.type.isError;
}
function foldable(state, lineStart, lineEnd) {
  for (let service of state.facet(foldService)) {
    let result2 = service(state, lineStart, lineEnd);
    if (result2)
      return result2;
  }
  return syntaxFolding(state, lineStart, lineEnd);
}
function mapRange(range2, mapping) {
  let from2 = mapping.mapPos(range2.from, 1), to = mapping.mapPos(range2.to, -1);
  return from2 >= to ? void 0 : { from: from2, 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((l3) => l3.from <= head2 && l3.to >= head2))
      continue;
    lines.push(view.lineBlockAt(head2));
  }
  return lines;
}
var foldState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(folded, tr2) {
    if (tr2.isUserEvent("delete"))
      tr2.changes.iterChangedRanges((fromA, toA) => folded = clearTouchedFolds(folded, fromA, toA));
    folded = folded.map(tr2.changes);
    for (let e3 of tr2.effects) {
      if (e3.is(foldEffect) && !foldExists(folded, e3.value.from, e3.value.to)) {
        let { preparePlaceholder } = tr2.state.facet(foldConfig);
        let widget = !preparePlaceholder ? foldWidget : Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr2.state, e3.value)) });
        folded = folded.update({ add: [widget.range(e3.value.from, e3.value.to)] });
      } else if (e3.is(unfoldEffect)) {
        folded = folded.update({
          filter: (from2, to) => e3.value.from != from2 || e3.value.to != to,
          filterFrom: e3.value.from,
          filterTo: e3.value.to
        });
      }
    }
    if (tr2.selection)
      folded = clearTouchedFolds(folded, tr2.selection.main.head);
    return folded;
  },
  provide: (f3) => EditorView.decorations.from(f3),
  toJSON(folded, state) {
    let ranges = [];
    folded.between(0, state.doc.length, (from2, to) => {
      ranges.push(from2, to);
    });
    return ranges;
  },
  fromJSON(value2) {
    if (!Array.isArray(value2) || value2.length % 2)
      throw new RangeError("Invalid JSON for fold state");
    let ranges = [];
    for (let i3 = 0; i3 < value2.length; ) {
      let from2 = value2[i3++], to = value2[i3++];
      if (typeof from2 != "number" || typeof to != "number")
        throw new RangeError("Invalid JSON for fold state");
      ranges.push(foldWidget.range(from2, to));
    }
    return Decoration.set(ranges, true);
  }
});
function clearTouchedFolds(folded, from2, to = from2) {
  let touched = false;
  folded.between(from2, to, (a3, b3) => {
    if (a3 < to && b3 > from2)
      touched = true;
  });
  return !touched ? folded : folded.update({
    filterFrom: from2,
    filterTo: to,
    filter: (a3, b3) => a3 >= to || b3 <= from2
  });
}
function findFold(state, from2, to) {
  var _a4;
  let found2 = null;
  (_a4 = state.field(foldState, false)) === null || _a4 === void 0 ? void 0 : _a4.between(from2, to, (from3, to2) => {
    if (!found2 || found2.from > from3)
      found2 = { from: from3, to: to2 };
  });
  return found2;
}
function foldExists(folded, from2, to) {
  let found2 = false;
  folded.between(from2, from2, (a3, b3) => {
    if (a3 == from2 && b3 == to)
      found2 = true;
  });
  return found2;
}
function maybeEnable(state, other) {
  return state.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 } = view, effects = [];
  for (let pos = 0; pos < state.doc.length; ) {
    let line = view.lineBlockAt(pos), range2 = foldable(state, 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 field2 = view.state.field(foldState, false);
  if (!field2 || !field2.size)
    return false;
  let effects = [];
  field2.between(0, view.state.doc.length, (from2, to) => {
    effects.push(unfoldEffect.of({ from: from2, 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(values2) {
    return combineConfig(values2, defaultConfig);
  }
});
function codeFolding(config3) {
  let result2 = [foldState, baseTheme$12];
  if (config3)
    result2.push(foldConfig.of(config3));
  return result2;
}
function widgetToDOM(view, prepared) {
  let { state } = view, conf = state.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", state.phrase("folded code"));
  element2.title = state.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(value2) {
    super();
    this.value = value2;
  }
  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(config3, open) {
    super();
    this.config = config3;
    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(config3 = {}) {
  let fullConfig = { ...foldGutterDefaults, ...config3 };
  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(update2) {
      if (update2.docChanged || update2.viewportChanged || update2.startState.facet(language) != update2.state.facet(language) || update2.startState.field(foldState, false) != update2.state.field(foldState, false) || syntaxTree(update2.startState) != syntaxTree(update2.state) || fullConfig.foldingChanged(update2))
        this.markers = this.buildMarkers(update2.view);
    }
    buildMarkers(view) {
      let builder = new RangeSetBuilder();
      for (let line of view.viewportLineBlocks) {
        let mark2 = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null;
        if (mark2)
          builder.add(line.from, line.from, mark2);
      }
      return builder.finish();
    }
  });
  let { domEventHandlers } = fullConfig;
  return [
    markers,
    gutter({
      class: "cm-foldGutter",
      markers(view) {
        var _a4;
        return ((_a4 = view.plugin(markers)) === null || _a4 === void 0 ? void 0 : _a4.markers) || RangeSet.empty;
      },
      initialSpacer() {
        return new FoldMarker(fullConfig, false);
      },
      domEventHandlers: {
        ...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, options2) {
    this.specs = specs;
    let modSpec;
    function def(spec) {
      let cls = StyleModule.newName();
      (modSpec || (modSpec = /* @__PURE__ */ Object.create(null)))["." + cls] = spec;
      return cls;
    }
    const all2 = typeof options2.all == "string" ? options2.all : options2.all ? def(options2.all) : void 0;
    const scopeOpt = options2.scope;
    this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? (type) => type == scopeOpt : void 0;
    this.style = tagHighlighter(specs.map((style3) => ({
      tag: style3.tag,
      class: style3.class || def(Object.assign({}, style3, { tag: null }))
    })), {
      all: all2
    }).style;
    this.module = modSpec ? new StyleModule(modSpec) : null;
    this.themeType = options2.themeType;
  }
  /**
  Create a highlighter style that associates the given styles to
  the given tags. The specs must be objects that hold a style tag
  or array of tags in their `tag` property, and either a single
  `class` property providing a static CSS class (for highlighter
  that rely on external styling), or a
  [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
  set of CSS properties (which define the styling for those tags).
  
  The CSS rules created for a highlighter will be emitted in the
  order of the spec's properties. That means that for elements that
  have multiple tags associated with them, styles defined further
  down in the list will have a higher CSS precedence than styles
  defined earlier.
  */
  static define(specs, options2) {
    return new _HighlightStyle(specs, options2 || {});
  }
};
var highlighterFacet = /* @__PURE__ */ Facet.define();
var fallbackHighlighter = /* @__PURE__ */ Facet.define({
  combine(values2) {
    return values2.length ? [values2[0]] : null;
  }
});
function getHighlighters(state) {
  let main2 = state.facet(highlighterFacet);
  return main2.length ? main2 : state.facet(fallbackHighlighter);
}
function syntaxHighlighting(highlighter, options2) {
  let ext = [treeHighlighter], themeType;
  if (highlighter instanceof HighlightStyle) {
    if (highlighter.module)
      ext.push(EditorView.styleModule.of(highlighter.module));
    themeType = highlighter.themeType;
  }
  if (options2 === null || options2 === void 0 ? void 0 : options2.fallback)
    ext.push(fallbackHighlighter.of(highlighter));
  else if (themeType)
    ext.push(highlighterFacet.computeN([EditorView.darkTheme], (state) => {
      return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
    }));
  else
    ext.push(highlighterFacet.of(highlighter));
  return ext;
}
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(update2) {
    let tree = syntaxTree(update2.state), highlighters = getHighlighters(update2.state);
    let styleChange = highlighters != getHighlighters(update2.startState);
    let { viewport } = update2.view, decoratedToMapped = update2.changes.mapPos(this.decoratedTo, 1);
    if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
      this.decorations = this.decorations.map(update2.changes);
      this.decoratedTo = decoratedToMapped;
    } else if (tree != this.tree || update2.viewportChanged || styleChange) {
      this.tree = tree;
      this.decorations = this.buildDeco(update2.view, highlighters);
      this.decoratedTo = viewport.to;
    }
  }
  buildDeco(view, highlighters) {
    if (!highlighters || !this.tree.length)
      return Decoration.none;
    let builder = new RangeSetBuilder();
    for (let { from: from2, to } of view.visibleRanges) {
      highlightTree(this.tree, highlighters, (from3, to2, style3) => {
        builder.add(from3, to2, this.markCache[style3] || (this.markCache[style3] = Decoration.mark({ class: style3 })));
      }, from2, to);
    }
    return builder.finish();
  }
};
var treeHighlighter = /* @__PURE__ */ Prec.high(/* @__PURE__ */ ViewPlugin.fromClass(TreeHighlighter, {
  decorations: (v3) => v3.decorations
}));
var defaultHighlightStyle = /* @__PURE__ */ HighlightStyle.define([
  {
    tag: tags.meta,
    color: "#404740"
  },
  {
    tag: tags.link,
    textDecoration: "underline"
  },
  {
    tag: tags.heading,
    textDecoration: "underline",
    fontWeight: "bold"
  },
  {
    tag: tags.emphasis,
    fontStyle: "italic"
  },
  {
    tag: tags.strong,
    fontWeight: "bold"
  },
  {
    tag: tags.strikethrough,
    textDecoration: "line-through"
  },
  {
    tag: tags.keyword,
    color: "#708"
  },
  {
    tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
    color: "#219"
  },
  {
    tag: [tags.literal, tags.inserted],
    color: "#164"
  },
  {
    tag: [tags.string, tags.deleted],
    color: "#a11"
  },
  {
    tag: [tags.regexp, tags.escape, /* @__PURE__ */ tags.special(tags.string)],
    color: "#e40"
  },
  {
    tag: /* @__PURE__ */ tags.definition(tags.variableName),
    color: "#00f"
  },
  {
    tag: /* @__PURE__ */ tags.local(tags.variableName),
    color: "#30a"
  },
  {
    tag: [tags.typeName, tags.namespace],
    color: "#085"
  },
  {
    tag: tags.className,
    color: "#167"
  },
  {
    tag: [/* @__PURE__ */ tags.special(tags.variableName), tags.macroName],
    color: "#256"
  },
  {
    tag: /* @__PURE__ */ tags.definition(tags.propertyName),
    color: "#00c"
  },
  {
    tag: tags.comment,
    color: "#940"
  },
  {
    tag: tags.invalid,
    color: "#f00"
  }
]);
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(match2) {
  let decorations3 = [];
  let mark2 = match2.matched ? matchingMark : nonmatchingMark;
  decorations3.push(mark2.range(match2.start.from, match2.start.to));
  if (match2.end)
    decorations3.push(mark2.range(match2.end.from, match2.end.to));
  return decorations3;
}
var bracketMatchingState = /* @__PURE__ */ StateField.define({
  create() {
    return Decoration.none;
  },
  update(deco, tr2) {
    if (!tr2.docChanged && !tr2.selection)
      return deco;
    let decorations3 = [];
    let config3 = tr2.state.facet(bracketMatchingConfig);
    for (let range2 of tr2.state.selection.ranges) {
      if (!range2.empty)
        continue;
      let match2 = matchBrackets(tr2.state, range2.head, -1, config3) || range2.head > 0 && matchBrackets(tr2.state, range2.head - 1, 1, config3) || config3.afterCursor && (matchBrackets(tr2.state, range2.head, 1, config3) || range2.head < tr2.state.doc.length && matchBrackets(tr2.state, range2.head + 1, -1, config3));
      if (match2)
        decorations3 = decorations3.concat(config3.renderMatch(match2, tr2.state));
    }
    return Decoration.set(decorations3, true);
  },
  provide: (f3) => EditorView.decorations.from(f3)
});
var bracketMatchingUnique = [
  bracketMatchingState,
  baseTheme2
];
function bracketMatching(config3 = {}) {
  return [bracketMatchingConfig.of(config3), 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 index2 = brackets.indexOf(node.name);
    if (index2 > -1 && index2 % 2 == (dir < 0 ? 1 : 0))
      return [brackets[index2 + dir]];
  }
  return null;
}
function findHandle(node) {
  let hasHandle = node.type.prop(bracketMatchingHandle);
  return hasHandle ? hasHandle(node.node) : node;
}
function matchBrackets(state, pos, dir, config3 = {}) {
  let maxScanDistance = config3.maxScanDistance || DefaultScanDist, brackets = config3.brackets || DefaultBrackets;
  let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
  for (let cur2 = node; cur2; cur2 = cur2.parent) {
    let matches3 = matchingNodes(cur2.type, dir, brackets);
    if (matches3 && 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(state, pos, dir, cur2, handle2, matches3, brackets);
    }
  }
  return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, handle2, matching, brackets) {
  let parent = token.parent, firstToken = { from: handle2.from, to: handle2.to };
  let depth2 = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.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 (depth2 == 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)) {
          depth2++;
        } else if (matchingNodes(cursor.type, -dir, brackets)) {
          if (depth2 == 0) {
            let endHandle = findHandle(cursor);
            return {
              start: firstToken,
              end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : void 0,
              matched: false
            };
          }
          depth2--;
        }
      }
    } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
  return { start: firstToken, matched: false };
}
function matchPlainBrackets(state, pos, dir, tree, tokenType2, maxScanDistance, brackets) {
  let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.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 = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth2 = 0;
  for (let distance = 0; !iter.next().done && distance <= maxScanDistance; ) {
    let text3 = iter.value;
    if (dir < 0)
      distance += text3.length;
    let basePos = pos + distance * dir;
    for (let pos2 = dir > 0 ? 0 : text3.length - 1, end = dir > 0 ? text3.length : -1; pos2 != end; pos2 += dir) {
      let found2 = brackets.indexOf(text3[pos2]);
      if (found2 < 0 || tree.resolveInner(basePos + pos2, 1).type != tokenType2)
        continue;
      if (found2 % 2 == 0 == dir > 0) {
        depth2++;
      } else if (depth2 == 1) {
        return { start: startToken, end: { from: basePos + pos2, to: basePos + pos2 + 1 }, matched: found2 >> 1 == bracket2 >> 1 };
      } else {
        depth2--;
      }
    }
    if (dir > 0)
      distance += text3.length;
  }
  return iter.done ? { start: startToken, matched: false } : null;
}
var noTokens = /* @__PURE__ */ Object.create(null);
var typeArray = [NodeType2.none];
var warned = [];
var byTag = /* @__PURE__ */ Object.create(null);
var defaultTable = /* @__PURE__ */ Object.create(null);
for (let [legacyName, name2] of [
  ["variable", "variableName"],
  ["variable-2", "variableName.special"],
  ["string-2", "string.special"],
  ["def", "variableName.definition"],
  ["tag", "tagName"],
  ["attribute", "attributeName"],
  ["type", "typeName"],
  ["builtin", "variableName.standard"],
  ["qualifier", "modifier"],
  ["error", "invalid"],
  ["header", "heading"],
  ["property", "propertyName"]
])
  defaultTable[legacyName] = /* @__PURE__ */ createTokenType(noTokens, name2);
function warnForPart(part, msg2) {
  if (warned.indexOf(part) > -1)
    return;
  warned.push(part);
  console.warn(msg2);
}
function createTokenType(extra, tagStr) {
  let tags$1 = [];
  for (let name3 of tagStr.split(" ")) {
    let found2 = [];
    for (let part of name3.split(".")) {
      let value2 = extra[part] || tags[part];
      if (!value2) {
        warnForPart(part, `Unknown highlighting tag ${part}`);
      } else if (typeof value2 == "function") {
        if (!found2.length)
          warnForPart(part, `Modifier ${part} used at start of tag`);
        else
          found2 = found2.map(value2);
      } else {
        if (found2.length)
          warnForPart(part, `Tag ${part} used as modifier`);
        else
          found2 = Array.isArray(value2) ? value2 : [value2];
      }
    }
    for (let tag of found2)
      tags$1.push(tag);
  }
  if (!tags$1.length)
    return 0;
  let name2 = tagStr.replace(/ /g, "_"), key2 = name2 + " " + tags$1.map((t3) => t3.id);
  let known = byTag[key2];
  if (known)
    return known.id;
  let type = byTag[key2] = NodeType2.define({
    id: typeArray.length,
    name: name2,
    props: [styleTags({ [name2]: tags$1 })]
  });
  typeArray.push(type);
  return type.id;
}
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/commands/dist/index.js
var toggleComment = (target) => {
  let { state } = target, line = state.doc.lineAt(state.selection.main.from), config3 = getConfig(target.state, line.from);
  return config3.line ? toggleLineComment(target) : config3.block ? toggleBlockCommentByLine(target) : false;
};
function command(f3, option2) {
  return ({ state, dispatch }) => {
    if (state.readOnly)
      return false;
    let tr2 = f3(option2, state);
    if (!tr2)
      return false;
    dispatch(state.update(tr2));
    return true;
  };
}
var toggleLineComment = /* @__PURE__ */ command(
  changeLineComment,
  0
  /* CommentOption.Toggle */
);
var toggleBlockComment = /* @__PURE__ */ command(
  changeBlockComment,
  0
  /* CommentOption.Toggle */
);
var toggleBlockCommentByLine = /* @__PURE__ */ command(
  (o3, s3) => changeBlockComment(o3, s3, selectedLineRanges(s3)),
  0
  /* CommentOption.Toggle */
);
function getConfig(state, pos) {
  let data2 = state.languageDataAt("commentTokens", pos, 1);
  return data2.length ? data2[0] : {};
}
var SearchMargin = 50;
function findBlockComment(state, { open, close: close2 }, from2, to) {
  let textBefore = state.sliceDoc(from2 - SearchMargin, from2);
  let textAfter = state.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 + close2.length) == close2) {
    return {
      open: { pos: from2 - spaceBefore, margin: spaceBefore && 1 },
      close: { pos: to + spaceAfter, margin: spaceAfter && 1 }
    };
  }
  let startText, endText;
  if (to - from2 <= 2 * SearchMargin) {
    startText = endText = state.sliceDoc(from2, to);
  } else {
    startText = state.sliceDoc(from2, from2 + SearchMargin);
    endText = state.sliceDoc(to - SearchMargin, to);
  }
  let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
  let endOff = endText.length - endSpace - close2.length;
  if (startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close2.length) == close2) {
    return {
      open: {
        pos: from2 + startSpace + open.length,
        margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0
      },
      close: {
        pos: to - endSpace - close2.length,
        margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0
      }
    };
  }
  return null;
}
function selectedLineRanges(state) {
  let ranges = [];
  for (let r3 of state.selection.ranges) {
    let fromLine = state.doc.lineAt(r3.from);
    let toLine = r3.to <= fromLine.to ? fromLine : state.doc.lineAt(r3.to);
    if (toLine.from > fromLine.from && toLine.from == r3.to)
      toLine = r3.to == fromLine.to + 1 ? fromLine : state.doc.lineAt(r3.to - 1);
    let last3 = ranges.length - 1;
    if (last3 >= 0 && ranges[last3].to > fromLine.from)
      ranges[last3].to = toLine.to;
    else
      ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
  }
  return ranges;
}
function changeBlockComment(option2, state, ranges = state.selection.ranges) {
  let tokens = ranges.map((r3) => getConfig(state, r3.from).block);
  if (!tokens.every((c3) => c3))
    return null;
  let comments = ranges.map((r3, i3) => findBlockComment(state, tokens[i3], r3.from, r3.to));
  if (option2 != 2 && !comments.every((c3) => c3)) {
    return { changes: state.changes(ranges.map((range2, i3) => {
      if (comments[i3])
        return [];
      return [{ from: range2.from, insert: tokens[i3].open + " " }, { from: range2.to, insert: " " + tokens[i3].close }];
    })) };
  } else if (option2 != 1 && comments.some((c3) => c3)) {
    let changes = [];
    for (let i3 = 0, comment4; i3 < comments.length; i3++)
      if (comment4 = comments[i3]) {
        let token = tokens[i3], { open, close: close2 } = comment4;
        changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close2.pos - close2.margin, to: close2.pos + token.close.length });
      }
    return { changes };
  }
  return null;
}
function changeLineComment(option2, state, ranges = state.selection.ranges) {
  let lines = [];
  let prevLine = -1;
  ranges: for (let { from: from2, to } of ranges) {
    let startI = lines.length, minIndent = 1e9, token;
    for (let pos = from2; pos <= to; ) {
      let line = state.doc.lineAt(pos);
      if (token == void 0) {
        token = getConfig(state, line.from).line;
        if (!token)
          continue ranges;
      }
      if (line.from > prevLine && (from2 == to || to > line.from)) {
        prevLine = line.from;
        let indent = /^\s*/.exec(line.text)[0].length;
        let empty4 = indent == line.length;
        let comment4 = line.text.slice(indent, indent + token.length) == token ? indent : -1;
        if (indent < line.text.length && indent < minIndent)
          minIndent = indent;
        lines.push({ line, comment: comment4, token, indent, empty: empty4, single: false });
      }
      pos = line.to + 1;
    }
    if (minIndent < 1e9) {
      for (let i3 = startI; i3 < lines.length; i3++)
        if (lines[i3].indent < lines[i3].line.text.length)
          lines[i3].indent = minIndent;
    }
    if (lines.length == startI + 1)
      lines[startI].single = true;
  }
  if (option2 != 2 && lines.some((l3) => l3.comment < 0 && (!l3.empty || l3.single))) {
    let changes = [];
    for (let { line, token, indent, empty: empty4, single } of lines)
      if (single || !empty4)
        changes.push({ from: line.from + indent, insert: token + " " });
    let changeSet = state.changes(changes);
    return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
  } else if (option2 != 1 && lines.some((l3) => l3.comment >= 0)) {
    let changes = [];
    for (let { line, comment: comment4, token } of lines)
      if (comment4 >= 0) {
        let from2 = line.from + comment4, to = from2 + token.length;
        if (line.text[to - line.from] == " ")
          to++;
        changes.push({ from: from2, 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: (a3, b3) => (tr2, adj) => a3(tr2, adj) || b3(tr2, adj)
    });
  }
});
var historyField_ = /* @__PURE__ */ StateField.define({
  create() {
    return HistoryState.empty;
  },
  update(state, tr2) {
    let config3 = tr2.state.facet(historyConfig);
    let fromHist = tr2.annotation(fromHistory);
    if (fromHist) {
      let item = HistEvent.fromTransaction(tr2, fromHist.selection), from2 = fromHist.side;
      let other = from2 == 0 ? state.undone : state.done;
      if (item)
        other = updateBranch(other, other.length, config3.minDepth, item);
      else
        other = addSelection(other, tr2.startState.selection);
      return new HistoryState(from2 == 0 ? fromHist.rest : other, from2 == 0 ? other : fromHist.rest);
    }
    let isolate = tr2.annotation(isolateHistory);
    if (isolate == "full" || isolate == "before")
      state = state.isolate();
    if (tr2.annotation(Transaction2.addToHistory) === false)
      return !tr2.changes.empty ? state.addMapping(tr2.changes.desc) : state;
    let event2 = HistEvent.fromTransaction(tr2);
    let time3 = tr2.annotation(Transaction2.time), userEvent = tr2.annotation(Transaction2.userEvent);
    if (event2)
      state = state.addChanges(event2, time3, userEvent, config3, tr2);
    else if (tr2.selection)
      state = state.addSelection(tr2.startState.selection, time3, userEvent, config3.newGroupDelay);
    if (isolate == "full" || isolate == "after")
      state = state.isolate();
    return state;
  },
  toJSON(value2) {
    return { done: value2.done.map((e3) => e3.toJSON()), undone: value2.undone.map((e3) => e3.toJSON()) };
  },
  fromJSON(json2) {
    return new HistoryState(json2.done.map(HistEvent.fromJSON), json2.undone.map(HistEvent.fromJSON));
  }
});
function history(config3 = {}) {
  return [
    historyField_,
    historyConfig.of(config3),
    EditorView.domEventHandlers({
      beforeinput(e3, view) {
        let command2 = e3.inputType == "historyUndo" ? undo : e3.inputType == "historyRedo" ? redo : null;
        if (!command2)
          return false;
        e3.preventDefault();
        return command2(view);
      }
    })
  ];
}
function cmd(side, selection) {
  return function({ state, dispatch }) {
    if (!selection && state.readOnly)
      return false;
    let historyState = state.field(historyField_, false);
    if (!historyState)
      return false;
    let tr2 = historyState.pop(side, state, selection);
    if (!tr2)
      return false;
    dispatch(tr2);
    return true;
  };
}
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(after2) {
    return new _HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after2);
  }
  toJSON() {
    var _a4, _b, _c;
    return {
      changes: (_a4 = this.changes) === null || _a4 === void 0 ? void 0 : _a4.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((s3) => s3.toJSON())
    };
  }
  static fromJSON(json2) {
    return new _HistEvent(json2.changes && ChangeSet.fromJSON(json2.changes), [], json2.mapped && ChangeDesc.fromJSON(json2.mapped), json2.startSelection && EditorSelection.fromJSON(json2.startSelection), json2.selectionsAfter.map(EditorSelection.fromJSON));
  }
  // This does not check `addToHistory` and such, it assumes the
  // transaction needs to be converted to an item. Returns null when
  // there are no changes or effects in the transaction.
  static fromTransaction(tr2, selection) {
    let effects = none2;
    for (let invert2 of tr2.startState.facet(invertedEffects)) {
      let result2 = invert2(tr2);
      if (result2.length)
        effects = effects.concat(result2);
    }
    if (!effects.length && tr2.changes.empty)
      return null;
    return new _HistEvent(tr2.changes.invert(tr2.startState.doc), effects, void 0, selection || tr2.startState.selection, none2);
  }
  static selection(selections) {
    return new _HistEvent(void 0, none2, void 0, void 0, selections);
  }
};
function updateBranch(branch, to, maxLen, newEvent) {
  let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
  let newBranch = branch.slice(start, to);
  newBranch.push(newEvent);
  return newBranch;
}
function isAdjacent(a3, b3) {
  let ranges = [], isAdjacent2 = false;
  a3.iterChangedRanges((f3, t3) => ranges.push(f3, t3));
  b3.iterChangedRanges((_f, _t, f3, t3) => {
    for (let i3 = 0; i3 < ranges.length; ) {
      let from2 = ranges[i3++], to = ranges[i3++];
      if (t3 >= from2 && f3 <= to)
        isAdjacent2 = true;
    }
  });
  return isAdjacent2;
}
function eqSelectionShape(a3, b3) {
  return a3.ranges.length == b3.ranges.length && a3.ranges.filter((r3, i3) => r3.empty != b3.ranges[i3].empty).length === 0;
}
function conc(a3, b3) {
  return !a3.length ? b3 : !b3.length ? a3 : a3.concat(b3);
}
var none2 = [];
var MaxSelectionsPerEvent = 200;
function addSelection(branch, selection) {
  if (!branch.length) {
    return [HistEvent.selection([selection])];
  } else {
    let lastEvent = branch[branch.length - 1];
    let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
    if (sels.length && sels[sels.length - 1].eq(selection))
      return branch;
    sels.push(selection);
    return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
  }
}
function popSelection(branch) {
  let last3 = branch[branch.length - 1];
  let newBranch = branch.slice();
  newBranch[branch.length - 1] = last3.setSelAfter(last3.selectionsAfter.slice(0, last3.selectionsAfter.length - 1));
  return newBranch;
}
function addMappingToBranch(branch, mapping) {
  if (!branch.length)
    return branch;
  let length = branch.length, selections = none2;
  while (length) {
    let event2 = mapEvent(branch[length - 1], mapping, selections);
    if (event2.changes && !event2.changes.empty || event2.effects.length) {
      let result2 = branch.slice(0, length);
      result2[length - 1] = event2;
      return result2;
    } else {
      mapping = event2.mapped;
      length--;
      selections = event2.selectionsAfter;
    }
  }
  return selections.length ? [HistEvent.selection(selections)] : none2;
}
function mapEvent(event2, mapping, extraSelections) {
  let selections = conc(event2.selectionsAfter.length ? event2.selectionsAfter.map((s3) => s3.map(mapping)) : none2, extraSelections);
  if (!event2.changes)
    return HistEvent.selection(selections);
  let mappedChanges = event2.changes.map(mapping), before2 = mapping.mapDesc(event2.changes, true);
  let fullMapping = event2.mapped ? event2.mapped.composeDesc(before2) : before2;
  return new HistEvent(mappedChanges, StateEffect.mapEffects(event2.effects, mapping), fullMapping, event2.startSelection.map(before2), 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, time3, userEvent, config3, tr2) {
    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 && time3 - this.prevTime < config3.newGroupDelay && config3.joinToEvent(tr2, 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, config3.minDepth, new HistEvent(event2.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event2.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none2));
    } else {
      done = updateBranch(done, done.length, config3.minDepth, event2);
    }
    return new _HistoryState(done, none2, time3, userEvent);
  }
  addSelection(selection, time3, userEvent, newGroupDelay) {
    let last3 = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none2;
    if (last3.length > 0 && time3 - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last3[last3.length - 1], selection))
      return this;
    return new _HistoryState(addSelection(this.done, selection), this.undone, time3, userEvent);
  }
  addMapping(mapping) {
    return new _HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
  }
  pop(side, state, onlySelection) {
    let branch = side == 0 ? this.done : this.undone;
    if (branch.length == 0)
      return null;
    let event2 = branch[branch.length - 1], selection = event2.selectionsAfter[0] || (event2.startSelection ? event2.startSelection.map(event2.changes.invertedDesc, 1) : state.selection);
    if (onlySelection && event2.selectionsAfter.length) {
      return state.update({
        selection: event2.selectionsAfter[event2.selectionsAfter.length - 1],
        annotations: fromHistory.of({ side, rest: popSelection(branch), selection }),
        userEvent: side == 0 ? "select.undo" : "select.redo",
        scrollIntoView: true
      });
    } else if (!event2.changes) {
      return null;
    } else {
      let rest2 = branch.length == 1 ? none2 : branch.slice(0, branch.length - 1);
      if (event2.mapped)
        rest2 = addMappingToBranch(rest2, event2.mapped);
      return state.update({
        changes: event2.changes,
        selection: event2.startSelection,
        effects: event2.effects,
        annotations: fromHistory.of({ side, rest: rest2, selection }),
        filter: false,
        userEvent: side == 0 ? "undo" : "redo",
        scrollIntoView: true
      });
    }
  }
};
HistoryState.empty = /* @__PURE__ */ new HistoryState(none2, none2);
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(state, selection) {
  return state.update({ selection, scrollIntoView: true, userEvent: "select" });
}
function moveSel({ state, dispatch }, how) {
  let selection = updateSel(state.selection, how);
  if (selection.eq(state.selection, true))
    return false;
  dispatch(setSel(state, selection));
  return true;
}
function rangeEnd(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(state, node, bracketProp) {
  if (node.type.prop(bracketProp))
    return true;
  let len = node.to - node.from;
  return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
}
function moveBySyntax(state, start, forward) {
  let pos = syntaxTree(state).resolveInner(start.head);
  let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
  for (let at = start.head; ; ) {
    let next2 = forward ? pos.childAfter(at) : pos.childBefore(at);
    if (!next2)
      break;
    if (interestingNode(state, next2, bracketProp))
      pos = next2;
    else
      at = forward ? next2.to : next2.from;
  }
  let bracket2 = pos.type.prop(bracketProp), match2, newPos;
  if (bracket2 && (match2 = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match2.matched)
    newPos = forward ? match2.end.to : match2.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 source of view.state.facet(EditorView.scrollMargins)) {
      let margins = source(view);
      if (margins === null || margins === void 0 ? void 0 : margins.top)
        marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
      if (margins === null || margins === void 0 ? void 0 : margins.bottom)
        marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
    }
    height = view.scrollDOM.clientHeight - marginTop - marginBottom;
  } else {
    height = (view.dom.ownerDocument.defaultView || window).innerHeight;
  }
  return {
    marginTop,
    marginBottom,
    selfScroll,
    height: Math.max(view.defaultLineHeight, height - 5)
  };
}
function cursorByPage(view, forward) {
  let page = pageInfo(view);
  let { state } = view, selection = updateSel(state.selection, (range2) => {
    return range2.empty ? view.moveVertically(range2, forward, page.height) : rangeEnd(range2, forward);
  });
  if (selection.eq(state.selection))
    return false;
  let effect2;
  if (page.selfScroll) {
    let startPos = view.coordsAtPos(state.selection.main.head);
    let scrollRect = view.scrollDOM.getBoundingClientRect();
    let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
    if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
      effect2 = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop });
  }
  view.dispatch(setSel(state, selection), { effects: effect2 });
  return true;
}
var cursorPageUp = (view) => cursorByPage(view, false);
var cursorPageDown = (view) => cursorByPage(view, true);
function moveByLineBoundary(view, start, forward) {
  let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
  if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
    moved = view.moveToLineBoundary(start, 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 && start.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(state, dispatch, extend) {
  let found2 = false, selection = updateSel(state.selection, (range2) => {
    let matching = matchBrackets(state, range2.head, -1) || matchBrackets(state, range2.head, 1) || range2.head > 0 && matchBrackets(state, range2.head - 1, 1) || range2.head < state.doc.length && matchBrackets(state, range2.head + 1, -1);
    if (!matching || !matching.end)
      return range2;
    found2 = true;
    let head2 = matching.start.from == range2.head ? matching.end.to : matching.end.from;
    return extend ? EditorSelection.range(range2.anchor, head2) : EditorSelection.cursor(head2);
  });
  if (!found2)
    return false;
  dispatch(setSel(state, selection));
  return true;
}
var cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);
function extendSel(target, how) {
  let selection = updateSel(target.state.selection, (range2) => {
    let head2 = how(range2);
    return EditorSelection.range(range2.anchor, head2.head, head2.goalColumn, head2.bidiLevel || void 0);
  });
  if (selection.eq(target.state.selection))
    return false;
  target.dispatch(setSel(target.state, selection));
  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, dispatch }) => {
  dispatch(setSel(state, { anchor: 0 }));
  return true;
};
var cursorDocEnd = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: state.doc.length }));
  return true;
};
var selectDocStart = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
  return true;
};
var selectDocEnd = ({ state, dispatch }) => {
  dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
  return true;
};
var selectAll = ({ state, dispatch }) => {
  dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
  return true;
};
var selectLine = ({ state, dispatch }) => {
  let ranges = selectedLineBlocks(state).map(({ from: from2, to }) => EditorSelection.range(from2, Math.min(to + 1, state.doc.length)));
  dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
  return true;
};
var selectParentSyntax = ({ state, dispatch }) => {
  let selection = updateSel(state.selection, (range2) => {
    let tree = syntaxTree(state), stack = tree.resolveStack(range2.from, 1);
    if (range2.empty) {
      let stackBefore = tree.resolveStack(range2.from, -1);
      if (stackBefore.node.from >= stack.node.from && stackBefore.node.to <= stack.node.to)
        stack = stackBefore;
    }
    for (let cur2 = stack; 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 (selection.eq(state.selection))
    return false;
  dispatch(setSel(state, selection));
  return true;
};
function addCursorVertically(view, forward) {
  let { state } = view, sel = state.selection, ranges = state.selection.ranges.slice();
  for (let range2 of state.selection.ranges) {
    let line = state.doc.lineAt(range2.head);
    if (forward ? line.to < view.state.doc.length : line.from > 0)
      for (let cur2 = range2; ; ) {
        let next2 = view.moveVertically(cur2, forward);
        if (next2.head < line.from || next2.head > line.to) {
          if (!ranges.some((r3) => r3.head == next2.head))
            ranges.push(next2);
          break;
        } else if (next2.head == cur2.head) {
          break;
        } else {
          cur2 = next2;
        }
      }
  }
  if (ranges.length == sel.ranges.length)
    return false;
  view.dispatch(setSel(state, EditorSelection.create(ranges, ranges.length - 1)));
  return true;
}
var addCursorAbove = (view) => addCursorVertically(view, false);
var addCursorBelow = (view) => addCursorVertically(view, true);
var simplifySelection = ({ state, dispatch }) => {
  let cur2 = state.selection, selection = null;
  if (cur2.ranges.length > 1)
    selection = EditorSelection.create([cur2.main]);
  else if (!cur2.main.empty)
    selection = EditorSelection.create([EditorSelection.cursor(cur2.main.head)]);
  if (!selection)
    return false;
  dispatch(setSel(state, selection));
  return true;
};
function deleteBy(target, by) {
  if (target.state.readOnly)
    return false;
  let event2 = "delete.selection", { state } = target;
  let changes = state.changeByRange((range2) => {
    let { from: from2, to } = range2;
    if (from2 == to) {
      let towards = by(range2);
      if (towards < from2) {
        event2 = "delete.backward";
        towards = skipAtomic(target, towards, false);
      } else if (towards > from2) {
        event2 = "delete.forward";
        towards = skipAtomic(target, towards, true);
      }
      from2 = Math.min(from2, towards);
      to = Math.max(to, towards);
    } else {
      from2 = skipAtomic(target, from2, false);
      to = skipAtomic(target, to, true);
    }
    return from2 == to ? { range: range2 } : { changes: { from: from2, to }, range: EditorSelection.cursor(from2, from2 < range2.head ? -1 : 1) };
  });
  if (changes.changes.empty)
    return false;
  target.dispatch(state.update(changes, {
    scrollIntoView: true,
    userEvent: event2,
    effects: event2 == "delete.selection" ? EditorView.announce.of(state.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((f3) => f3(target)))
      ranges.between(pos, pos, (from2, to) => {
        if (from2 < pos && to > pos)
          pos = forward ? to : from2;
      });
  return pos;
}
var deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, (range2) => {
  let pos = range2.from, { state } = target, line = state.doc.lineAt(pos), before2, targetPos;
  if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before2 = line.text.slice(0, pos - line.from))) {
    if (before2[before2.length - 1] == "	")
      return pos - 1;
    let col = countColumn(before2, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
    for (let i3 = 0; i3 < drop && before2[before2.length - 1 - i3] == " "; i3++)
      pos--;
    targetPos = pos;
  } else {
    targetPos = findClusterBreak2(line.text, pos - line.from, forward, forward) + line.from;
    if (targetPos == pos && line.number != (forward ? state.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 } = target, line = state.doc.lineAt(pos);
  let categorize = state.charCategorizer(pos);
  for (let cat = null; ; ) {
    if (pos == (forward ? line.to : line.from)) {
      if (pos == range2.head && line.number != (forward ? state.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, dispatch }) => {
  if (state.readOnly)
    return false;
  let changes = state.changeByRange((range2) => {
    return {
      changes: { from: range2.from, to: range2.to, insert: Text.of(["", ""]) },
      range: EditorSelection.cursor(range2.from)
    };
  });
  dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
  return true;
};
var transposeChars = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let changes = state.changeByRange((range2) => {
    if (!range2.empty || range2.from == 0 || range2.from == state.doc.length)
      return { range: range2 };
    let pos = range2.from, line = state.doc.lineAt(pos);
    let from2 = 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: from2, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from2, pos)) },
      range: EditorSelection.cursor(to)
    };
  });
  if (changes.changes.empty)
    return false;
  dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
  return true;
};
function selectedLineBlocks(state) {
  let blocks = [], upto = -1;
  for (let range2 of state.selection.ranges) {
    let startLine = state.doc.lineAt(range2.from), endLine = state.doc.lineAt(range2.to);
    if (!range2.empty && range2.to == endLine.from)
      endLine = state.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(state, dispatch, forward) {
  if (state.readOnly)
    return false;
  let changes = [], ranges = [];
  for (let block3 of selectedLineBlocks(state)) {
    if (forward ? block3.to == state.doc.length : block3.from == 0)
      continue;
    let nextLine = state.doc.lineAt(forward ? block3.to + 1 : block3.from - 1);
    let size4 = nextLine.length + 1;
    if (forward) {
      changes.push({ from: block3.to, to: nextLine.to }, { from: block3.from, insert: nextLine.text + state.lineBreak });
      for (let r3 of block3.ranges)
        ranges.push(EditorSelection.range(Math.min(state.doc.length, r3.anchor + size4), Math.min(state.doc.length, r3.head + size4)));
    } else {
      changes.push({ from: nextLine.from, to: block3.from }, { from: block3.to, insert: state.lineBreak + nextLine.text });
      for (let r3 of block3.ranges)
        ranges.push(EditorSelection.range(r3.anchor - size4, r3.head - size4));
    }
  }
  if (!changes.length)
    return false;
  dispatch(state.update({
    changes,
    scrollIntoView: true,
    selection: EditorSelection.create(ranges, state.selection.mainIndex),
    userEvent: "move.line"
  }));
  return true;
}
var moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
var moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
function copyLine(state, dispatch, forward) {
  if (state.readOnly)
    return false;
  let changes = [];
  for (let block3 of selectedLineBlocks(state)) {
    if (forward)
      changes.push({ from: block3.from, insert: state.doc.slice(block3.from, block3.to) + state.lineBreak });
    else
      changes.push({ from: block3.to, insert: state.lineBreak + state.doc.slice(block3.from, block3.to) });
  }
  let changeSet = state.changes(changes);
  dispatch(state.update({
    changes: changeSet,
    selection: state.selection.map(changeSet, forward ? 1 : -1),
    scrollIntoView: true,
    userEvent: "input.copyline"
  }));
  return true;
}
var copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
var copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
var deleteLine = (view) => {
  if (view.state.readOnly)
    return false;
  let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from: from2, to }) => {
    if (from2 > 0)
      from2--;
    else if (to < state.doc.length)
      to++;
    return { from: from2, to };
  }));
  let selection = updateSel(state.selection, (range2) => {
    let dist2 = void 0;
    if (view.lineWrapping) {
      let block3 = view.lineBlockAt(range2.head), pos = view.coordsAtPos(range2.head, range2.assoc || 1);
      if (pos)
        dist2 = block3.bottom + view.documentTop - pos.bottom + view.defaultLineHeight / 2;
    }
    return view.moveVertically(range2, true, dist2);
  }).map(changes);
  view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" });
  return true;
};
function isBetweenBrackets(state, pos) {
  if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
    return { from: pos, to: pos };
  let context = syntaxTree(state).resolveInner(pos);
  let before2 = context.childBefore(pos), after2 = context.childAfter(pos), closedBy;
  if (before2 && after2 && before2.to <= pos && after2.from >= pos && (closedBy = before2.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after2.name) > -1 && state.doc.lineAt(before2.to).from == state.doc.lineAt(after2.from).from && !/\S/.test(state.sliceDoc(before2.to, after2.from)))
    return { from: before2.to, to: after2.from };
  return null;
}
var insertNewlineAndIndent = /* @__PURE__ */ newlineAndIndent(false);
var insertBlankLine = /* @__PURE__ */ newlineAndIndent(true);
function newlineAndIndent(atEof) {
  return ({ state, dispatch }) => {
    if (state.readOnly)
      return false;
    let changes = state.changeByRange((range2) => {
      let { from: from2, to } = range2, line = state.doc.lineAt(from2);
      let explode = !atEof && from2 == to && isBetweenBrackets(state, from2);
      if (atEof)
        from2 = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
      let cx = new IndentContext(state, { simulateBreak: from2, simulateDoubleBreak: !!explode });
      let indent = getIndentation(cx, from2);
      if (indent == null)
        indent = countColumn(/^\s*/.exec(state.doc.lineAt(from2).text)[0], state.tabSize);
      while (to < line.to && /\s/.test(line.text[to - line.from]))
        to++;
      if (explode)
        ({ from: from2, to } = explode);
      else if (from2 > line.from && from2 < line.from + 100 && !/\S/.test(line.text.slice(0, from2)))
        from2 = line.from;
      let insert4 = ["", indentString(state, indent)];
      if (explode)
        insert4.push(indentString(state, cx.lineIndent(line.from, -1)));
      return {
        changes: { from: from2, to, insert: Text.of(insert4) },
        range: EditorSelection.cursor(from2 + 1 + insert4[1].length)
      };
    });
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
    return true;
  };
}
function changeBySelectedLine(state, f3) {
  let atLine = -1;
  return state.changeByRange((range2) => {
    let changes = [];
    for (let pos = range2.from; pos <= range2.to; ) {
      let line = state.doc.lineAt(pos);
      if (line.number > atLine && (range2.empty || range2.to > line.from)) {
        f3(line, changes, range2);
        atLine = line.number;
      }
      pos = line.to + 1;
    }
    let changeSet = state.changes(changes);
    return {
      changes,
      range: EditorSelection.range(changeSet.mapPos(range2.anchor, 1), changeSet.mapPos(range2.head, 1))
    };
  });
}
var indentSelection = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let updated = /* @__PURE__ */ Object.create(null);
  let context = new IndentContext(state, { overrideIndentation: (start) => {
    let found2 = updated[start];
    return found2 == null ? -1 : found2;
  } });
  let changes = changeBySelectedLine(state, (line, changes2, range2) => {
    let indent = getIndentation(context, line.from);
    if (indent == null)
      return;
    if (!/\S/.test(line.text))
      indent = 0;
    let cur2 = /^\s*/.exec(line.text)[0];
    let norm = indentString(state, 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(state.update(changes, { userEvent: "indent" }));
  return true;
};
var indentMore = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
    changes.push({ from: line.from, insert: state.facet(indentUnit) });
  }), { userEvent: "input.indent" }));
  return true;
};
var indentLess = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
    let space = /^\s*/.exec(line.text)[0];
    if (!space)
      return;
    let col = countColumn(space, state.tabSize), keep = 0;
    let insert4 = indentString(state, Math.max(0, col - getIndentUnit(state)));
    while (keep < space.length && keep < insert4.length && space.charCodeAt(keep) == insert4.charCodeAt(keep))
      keep++;
    changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert4.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, preventDefault: true },
  { key: "Delete", run: deleteCharForward, preventDefault: true },
  { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward, preventDefault: true },
  { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward, preventDefault: true },
  { mac: "Mod-Backspace", run: deleteLineBoundaryBackward, preventDefault: true },
  { mac: "Mod-Delete", run: deleteLineBoundaryForward, preventDefault: true }
].concat(/* @__PURE__ */ emacsStyleKeymap.map((b3) => ({ mac: b3.key, run: b3.run, shift: b3.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: "Mod-Alt-ArrowUp", run: addCursorAbove },
  { key: "Mod-Alt-ArrowDown", run: addCursorBelow },
  { 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/@codemirror/search/dist/index.js
var basicNormalize = typeof String.prototype.normalize == "function" ? (x3) => x3.normalize("NFKD") : (x3) => x3;
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(text3, query2, from2 = 0, to = text3.length, normalize5, test2) {
    this.test = test2;
    this.value = { from: 0, to: 0 };
    this.done = false;
    this.matches = [];
    this.buffer = "";
    this.bufferPos = 0;
    this.iter = text3.iterRange(from2, to);
    this.bufferStart = from2;
    this.normalize = normalize5 ? (x3) => normalize5(basicNormalize(x3)) : 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), start = this.bufferStart + this.bufferPos;
      this.bufferPos += codePointSize2(next2);
      let norm = this.normalize(str);
      if (norm.length)
        for (let i3 = 0, pos = start; ; i3++) {
          let code2 = norm.charCodeAt(i3);
          let match2 = this.match(code2, pos, this.bufferPos + this.bufferStart);
          if (i3 == norm.length - 1) {
            if (match2) {
              this.value = match2;
              return this;
            }
            break;
          }
          if (pos == start && i3 < str.length && str.charCodeAt(i3) == code2)
            pos++;
        }
    }
  }
  match(code2, pos, end) {
    let match2 = null;
    for (let i3 = 0; i3 < this.matches.length; i3 += 2) {
      let index2 = this.matches[i3], keep = false;
      if (this.query.charCodeAt(index2) == code2) {
        if (index2 == this.query.length - 1) {
          match2 = { from: this.matches[i3 + 1], to: end };
        } else {
          this.matches[i3]++;
          keep = true;
        }
      }
      if (!keep) {
        this.matches.splice(i3, 2);
        i3 -= 2;
      }
    }
    if (this.query.charCodeAt(0) == code2) {
      if (this.query.length == 1)
        match2 = { from: pos, to: end };
      else
        this.matches.push(1, pos);
    }
    if (match2 && this.test && !this.test(match2.from, match2.to, this.buffer, this.bufferStart))
      match2 = null;
    return match2;
  }
};
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(text3, query2, options2, from2 = 0, to = text3.length) {
    this.text = text3;
    this.to = to;
    this.curLine = "";
    this.done = false;
    this.value = empty;
    if (/\\[sWDnr]|\n|\r|\[\^/.test(query2))
      return new MultilineRegExpCursor(text3, query2, options2, from2, to);
    this.re = new RegExp(query2, baseFlags + ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreCase) ? "i" : ""));
    this.test = options2 === null || options2 === void 0 ? void 0 : options2.test;
    this.iter = text3.iter();
    let startLine = text3.lineAt(from2);
    this.curLineStart = startLine.from;
    this.matchPos = toCharEnd(text3, from2);
    this.getLine(this.curLineStart);
  }
  getLine(skip3) {
    this.iter.next(skip3);
    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 match2 = this.matchPos <= this.to && this.re.exec(this.curLine);
      if (match2) {
        let from2 = this.curLineStart + match2.index, to = from2 + match2[0].length;
        this.matchPos = toCharEnd(this.text, to + (from2 == to ? 1 : 0));
        if (from2 == this.curLineStart + this.curLine.length)
          this.nextLine();
        if ((from2 < to || from2 > this.value.to) && (!this.test || this.test(from2, to, match2))) {
          this.value = { from: from2, to, match: match2 };
          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(from2, text3) {
    this.from = from2;
    this.text = text3;
  }
  get to() {
    return this.from + this.text.length;
  }
  static get(doc4, from2, to) {
    let cached = flattened.get(doc4);
    if (!cached || cached.from >= to || cached.to <= from2) {
      let flat = new _FlattenedDoc(from2, doc4.sliceString(from2, to));
      flattened.set(doc4, flat);
      return flat;
    }
    if (cached.from == from2 && cached.to == to)
      return cached;
    let { text: text3, from: cachedFrom } = cached;
    if (cachedFrom > from2) {
      text3 = doc4.sliceString(from2, cachedFrom) + text3;
      cachedFrom = from2;
    }
    if (cached.to < to)
      text3 += doc4.sliceString(cached.to, to);
    flattened.set(doc4, new _FlattenedDoc(cachedFrom, text3));
    return new _FlattenedDoc(from2, text3.slice(from2 - cachedFrom, to - cachedFrom));
  }
};
var MultilineRegExpCursor = class {
  constructor(text3, query2, options2, from2, to) {
    this.text = text3;
    this.to = to;
    this.done = false;
    this.value = empty;
    this.matchPos = toCharEnd(text3, from2);
    this.re = new RegExp(query2, baseFlags + ((options2 === null || options2 === void 0 ? void 0 : options2.ignoreCase) ? "i" : ""));
    this.test = options2 === null || options2 === void 0 ? void 0 : options2.test;
    this.flat = FlattenedDoc.get(text3, from2, this.chunkEnd(
      from2 + 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 match2 = this.re.exec(this.flat.text);
      if (match2 && !match2[0] && match2.index == off) {
        this.re.lastIndex = off + 1;
        match2 = this.re.exec(this.flat.text);
      }
      if (match2) {
        let from2 = this.flat.from + match2.index, to = from2 + match2[0].length;
        if ((this.flat.to >= this.to || match2.index + match2[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from2, to, match2))) {
          this.value = { from: from2, to, match: match2 };
          this.matchPos = toCharEnd(this.text, to + (from2 == 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(source) {
  try {
    new RegExp(source, baseFlags);
    return true;
  } catch (_a4) {
    return false;
  }
}
function toCharEnd(text3, pos) {
  if (pos >= text3.length)
    return pos;
  let line = text3.lineAt(pos), next2;
  while (pos < line.to && (next2 = line.text.charCodeAt(pos - line.from)) >= 56320 && next2 < 57344)
    pos++;
  return pos;
}
var gotoLine = (view) => {
  let { state } = view;
  let line = String(state.doc.lineAt(view.state.selection.main.head).number);
  let { close: close2, result: result2 } = showDialog(view, {
    label: state.phrase("Go to line"),
    input: { type: "text", name: "line", value: line },
    focus: true,
    submitLabel: state.phrase("go")
  });
  result2.then((form) => {
    let match2 = form && /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(form.elements["line"].value);
    if (!match2) {
      view.dispatch({ effects: close2 });
      return;
    }
    let startLine = state.doc.lineAt(state.selection.main.head);
    let [, sign, ln, cl, percent] = match2;
    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 / state.doc.lines;
      line2 = Math.round(state.doc.lines * pc);
    } else if (ln && sign) {
      line2 = line2 * (sign == "-" ? -1 : 1) + startLine.number;
    }
    let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line2)));
    let selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
    view.dispatch({
      effects: [close2, EditorView.scrollIntoView(selection.from, { y: "center" })],
      selection
    });
  });
  return true;
};
var defaultHighlightOptions = {
  highlightWordAroundCursor: false,
  minSelectionLength: 1,
  maxMatches: 100,
  wholeWords: false
};
var highlightConfig = /* @__PURE__ */ Facet.define({
  combine(options2) {
    return combineConfig(options2, defaultHighlightOptions, {
      highlightWordAroundCursor: (a3, b3) => a3 || b3,
      minSelectionLength: Math.min,
      maxMatches: Math.min
    });
  }
});
function highlightSelectionMatches(options2) {
  let ext = [defaultTheme, matchHighlighter];
  if (options2)
    ext.push(highlightConfig.of(options2));
  return ext;
}
var matchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch" });
var mainMatchDeco = /* @__PURE__ */ Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
function insideWordBoundaries(check, state, from2, to) {
  return (from2 == 0 || check(state.sliceDoc(from2 - 1, from2)) != CharCategory.Word) && (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word);
}
function insideWord(check, state, from2, to) {
  return check(state.sliceDoc(from2, from2 + 1)) == CharCategory.Word && check(state.sliceDoc(to - 1, to)) == CharCategory.Word;
}
var matchHighlighter = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = this.getDeco(view);
  }
  update(update2) {
    if (update2.selectionSet || update2.docChanged || update2.viewportChanged)
      this.decorations = this.getDeco(update2.view);
  }
  getDeco(view) {
    let conf = view.state.facet(highlightConfig);
    let { state } = view, sel = state.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 = state.wordAt(range2.head);
      if (!word)
        return Decoration.none;
      check = state.charCategorizer(range2.head);
      query2 = state.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 = state.sliceDoc(range2.from, range2.to);
        check = state.charCategorizer(range2.head);
        if (!(insideWordBoundaries(check, state, range2.from, range2.to) && insideWord(check, state, range2.from, range2.to)))
          return Decoration.none;
      } else {
        query2 = state.sliceDoc(range2.from, range2.to);
        if (!query2)
          return Decoration.none;
      }
    }
    let deco = [];
    for (let part of view.visibleRanges) {
      let cursor = new SearchCursor(state.doc, query2, part.from, part.to);
      while (!cursor.next().done) {
        let { from: from2, to } = cursor.value;
        if (!check || insideWordBoundaries(check, state, from2, to)) {
          if (range2.empty && from2 <= range2.from && to >= range2.to)
            deco.push(mainMatchDeco.range(from2, to));
          else if (from2 >= range2.to || to <= range2.from)
            deco.push(matchDeco.range(from2, to));
          if (deco.length > conf.maxMatches)
            return Decoration.none;
        }
      }
    }
    return Decoration.set(deco);
  }
}, {
  decorations: (v3) => v3.decorations
});
var defaultTheme = /* @__PURE__ */ EditorView.baseTheme({
  ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
  ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
});
var selectWord = ({ state, dispatch }) => {
  let { selection } = state;
  let newSel = EditorSelection.create(selection.ranges.map((range2) => state.wordAt(range2.head) || EditorSelection.cursor(range2.head)), selection.mainIndex);
  if (newSel.eq(selection))
    return false;
  dispatch(state.update({ selection: newSel }));
  return true;
};
function findNextOccurrence(state, query2) {
  let { main: main2, ranges } = state.selection;
  let word = state.wordAt(main2.head), fullWord = word && word.from == main2.from && word.to == main2.to;
  for (let cycled = false, cursor = new SearchCursor(state.doc, query2, ranges[ranges.length - 1].to); ; ) {
    cursor.next();
    if (cursor.done) {
      if (cycled)
        return null;
      cursor = new SearchCursor(state.doc, query2, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
      cycled = true;
    } else {
      if (cycled && ranges.some((r3) => r3.from == cursor.value.from))
        continue;
      if (fullWord) {
        let word2 = state.wordAt(cursor.value.from);
        if (!word2 || word2.from != cursor.value.from || word2.to != cursor.value.to)
          continue;
      }
      return cursor.value;
    }
  }
}
var selectNextOccurrence = ({ state, dispatch }) => {
  let { ranges } = state.selection;
  if (ranges.some((sel) => sel.from === sel.to))
    return selectWord({ state, dispatch });
  let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
  if (state.selection.ranges.some((r3) => state.sliceDoc(r3.from, r3.to) != searchedText))
    return false;
  let range2 = findNextOccurrence(state, searchedText);
  if (!range2)
    return false;
  dispatch(state.update({
    selection: state.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(config3) {
    this.search = config3.search;
    this.caseSensitive = !!config3.caseSensitive;
    this.literal = !!config3.literal;
    this.regexp = !!config3.regexp;
    this.replace = config3.replace || "";
    this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
    this.unquoted = this.unquote(this.search);
    this.wholeWord = !!config3.wholeWord;
    this.test = config3.test;
  }
  /**
  @internal
  */
  unquote(text3) {
    return this.literal ? text3 : text3.replace(/\\([nrt\\])/g, (_5, 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 && this.test == other.test;
  }
  /**
  @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(state, from2 = 0, to) {
    let st = state.doc ? state : EditorState2.create({ doc: state });
    if (to == null)
      to = st.doc.length;
    return this.regexp ? regexpCursor(this, st, from2, to) : stringCursor(this, st, from2, to);
  }
};
var QueryType2 = class {
  constructor(spec) {
    this.spec = spec;
  }
};
function wrapStringTest(test2, state, inner) {
  return (from2, to, buffer, bufferPos) => {
    if (inner && !inner(from2, to, buffer, bufferPos))
      return false;
    let match2 = from2 >= bufferPos && to <= bufferPos + buffer.length ? buffer.slice(from2 - bufferPos, to - bufferPos) : state.doc.sliceString(from2, to);
    return test2(match2, state, from2, to);
  };
}
function stringCursor(spec, state, from2, to) {
  let test2;
  if (spec.wholeWord)
    test2 = stringWordTest(state.doc, state.charCategorizer(state.selection.main.head));
  if (spec.test)
    test2 = wrapStringTest(spec.test, state, test2);
  return new SearchCursor(state.doc, spec.unquoted, from2, to, spec.caseSensitive ? void 0 : (x3) => x3.toLowerCase(), test2);
}
function stringWordTest(doc4, categorizer) {
  return (from2, to, buf, bufPos) => {
    if (bufPos > from2 || bufPos + buf.length < to) {
      bufPos = Math.max(0, from2 - 2);
      buf = doc4.sliceString(bufPos, Math.min(doc4.length, to + 2));
    }
    return (categorizer(charBefore(buf, from2 - bufPos)) != CharCategory.Word || categorizer(charAfter(buf, from2 - 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(state, curFrom, curTo) {
    let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
    if (cursor.done) {
      let end = Math.min(state.doc.length, curFrom + this.spec.unquoted.length);
      cursor = stringCursor(this.spec, state, 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(state, from2, to) {
    for (let pos = to; ; ) {
      let start = Math.max(from2, pos - 1e4 - this.spec.unquoted.length);
      let cursor = stringCursor(this.spec, state, start, pos), range2 = null;
      while (!cursor.nextOverlapping().done)
        range2 = cursor.value;
      if (range2)
        return range2;
      if (start == from2)
        return null;
      pos -= 1e4;
    }
  }
  prevMatch(state, curFrom, curTo) {
    let found2 = this.prevMatchInRange(state, 0, curFrom);
    if (!found2)
      found2 = this.prevMatchInRange(state, Math.max(0, curTo - this.spec.unquoted.length), state.doc.length);
    return found2 && (found2.from != curFrom || found2.to != curTo) ? found2 : null;
  }
  getReplacement(_result) {
    return this.spec.unquote(this.spec.replace);
  }
  matchAll(state, limit) {
    let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = [];
    while (!cursor.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor.value);
    }
    return ranges;
  }
  highlight(state, from2, to, add4) {
    let cursor = stringCursor(this.spec, state, Math.max(0, from2 - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
    while (!cursor.next().done)
      add4(cursor.value.from, cursor.value.to);
  }
};
function wrapRegexpTest(test2, state, inner) {
  return (from2, to, match2) => {
    return (!inner || inner(from2, to, match2)) && test2(match2[0], state, from2, to);
  };
}
function regexpCursor(spec, state, from2, to) {
  let test2;
  if (spec.wholeWord)
    test2 = regexpWordTest(state.charCategorizer(state.selection.main.head));
  if (spec.test)
    test2 = wrapRegexpTest(spec.test, state, test2);
  return new RegExpCursor(state.doc, spec.search, { ignoreCase: !spec.caseSensitive, test: test2 }, from2, to);
}
function charBefore(str, index2) {
  return str.slice(findClusterBreak2(str, index2, false), index2);
}
function charAfter(str, index2) {
  return str.slice(index2, findClusterBreak2(str, index2));
}
function regexpWordTest(categorizer) {
  return (_from, _to, match2) => !match2[0].length || (categorizer(charBefore(match2.input, match2.index)) != CharCategory.Word || categorizer(charAfter(match2.input, match2.index)) != CharCategory.Word) && (categorizer(charAfter(match2.input, match2.index + match2[0].length)) != CharCategory.Word || categorizer(charBefore(match2.input, match2.index + match2[0].length)) != CharCategory.Word);
}
var RegExpQuery = class extends QueryType2 {
  nextMatch(state, curFrom, curTo) {
    let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
    if (cursor.done)
      cursor = regexpCursor(this.spec, state, 0, curFrom).next();
    return cursor.done ? null : cursor.value;
  }
  prevMatchInRange(state, from2, to) {
    for (let size4 = 1; ; size4++) {
      let start = Math.max(
        from2,
        to - size4 * 1e4
        /* FindPrev.ChunkSize */
      );
      let cursor = regexpCursor(this.spec, state, start, to), range2 = null;
      while (!cursor.next().done)
        range2 = cursor.value;
      if (range2 && (start == from2 || range2.from > start + 10))
        return range2;
      if (start == from2)
        return null;
    }
  }
  prevMatch(state, curFrom, curTo) {
    return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length);
  }
  getReplacement(result2) {
    return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m3, i3) => {
      if (i3 == "&")
        return result2.match[0];
      if (i3 == "$")
        return "$";
      for (let l3 = i3.length; l3 > 0; l3--) {
        let n4 = +i3.slice(0, l3);
        if (n4 > 0 && n4 < result2.match.length)
          return result2.match[n4] + i3.slice(l3);
      }
      return m3;
    });
  }
  matchAll(state, limit) {
    let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
    while (!cursor.next().done) {
      if (ranges.length >= limit)
        return null;
      ranges.push(cursor.value);
    }
    return ranges;
  }
  highlight(state, from2, to, add4) {
    let cursor = regexpCursor(this.spec, state, Math.max(
      0,
      from2 - 250
      /* RegExp.HighlightMargin */
    ), Math.min(to + 250, state.doc.length));
    while (!cursor.next().done)
      add4(cursor.value.from, cursor.value.to);
  }
};
var setSearchQuery = /* @__PURE__ */ StateEffect.define();
var togglePanel = /* @__PURE__ */ StateEffect.define();
var searchState = /* @__PURE__ */ StateField.define({
  create(state) {
    return new SearchState(defaultQuery(state).create(), null);
  },
  update(value2, tr2) {
    for (let effect2 of tr2.effects) {
      if (effect2.is(setSearchQuery))
        value2 = new SearchState(effect2.value.create(), value2.panel);
      else if (effect2.is(togglePanel))
        value2 = new SearchState(value2.query, effect2.value ? createSearchPanel : null);
    }
    return value2;
  },
  provide: (f3) => showPanel.from(f3, (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(update2) {
    let state = update2.state.field(searchState);
    if (state != update2.startState.field(searchState) || update2.docChanged || update2.selectionSet || update2.viewportChanged)
      this.decorations = this.highlight(state);
  }
  highlight({ query: query2, panel }) {
    if (!panel || !query2.spec.valid)
      return Decoration.none;
    let { view } = this;
    let builder = new RangeSetBuilder();
    for (let i3 = 0, ranges = view.visibleRanges, l3 = ranges.length; i3 < l3; i3++) {
      let { from: from2, to } = ranges[i3];
      while (i3 < l3 - 1 && to > ranges[i3 + 1].from - 2 * 250)
        to = ranges[++i3].to;
      query2.highlight(view.state, from2, to, (from3, to2) => {
        let selected = view.state.selection.ranges.some((r3) => r3.from == from3 && r3.to == to2);
        builder.add(from3, to2, selected ? selectedMatchMark : matchMark);
      });
    }
    return builder.finish();
  }
}, {
  decorations: (v3) => v3.decorations
});
function searchCommand(f3) {
  return (view) => {
    let state = view.state.field(searchState, false);
    return state && state.query.spec.valid ? f3(view, state) : 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 selection = EditorSelection.single(next2.from, next2.to);
  let config3 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection,
    effects: [announceMatch(view, next2), config3.scrollToMatch(selection.main, view)],
    userEvent: "select.search"
  });
  selectSearchInput(view);
  return true;
});
var findPrevious = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  let { state } = view, { from: from2 } = state.selection.main;
  let prev = query2.prevMatch(state, from2, from2);
  if (!prev)
    return false;
  let selection = EditorSelection.single(prev.from, prev.to);
  let config3 = view.state.facet(searchConfigFacet);
  view.dispatch({
    selection,
    effects: [announceMatch(view, prev), config3.scrollToMatch(selection.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((r3) => EditorSelection.range(r3.from, r3.to))),
    userEvent: "select.search.matches"
  });
  return true;
});
var selectSelectionMatches = ({ state, dispatch }) => {
  let sel = state.selection;
  if (sel.ranges.length > 1 || sel.main.empty)
    return false;
  let { from: from2, to } = sel.main;
  let ranges = [], main2 = 0;
  for (let cur2 = new SearchCursor(state.doc, state.sliceDoc(from2, to)); !cur2.next().done; ) {
    if (ranges.length > 1e3)
      return false;
    if (cur2.value.from == from2)
      main2 = ranges.length;
    ranges.push(EditorSelection.range(cur2.value.from, cur2.value.to));
  }
  dispatch(state.update({
    selection: EditorSelection.create(ranges, main2),
    userEvent: "select.search.matches"
  }));
  return true;
};
var replaceNext = /* @__PURE__ */ searchCommand((view, { query: query2 }) => {
  let { state } = view, { from: from2, to } = state.selection.main;
  if (state.readOnly)
    return false;
  let match2 = query2.nextMatch(state, from2, from2);
  if (!match2)
    return false;
  let next2 = match2;
  let changes = [], selection, replacement;
  let effects = [];
  if (next2.from == from2 && next2.to == to) {
    replacement = state.toText(query2.getReplacement(next2));
    changes.push({ from: next2.from, to: next2.to, insert: replacement });
    next2 = query2.nextMatch(state, next2.from, next2.to);
    effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from2).number) + "."));
  }
  let changeSet = view.state.changes(changes);
  if (next2) {
    selection = EditorSelection.single(next2.from, next2.to).map(changeSet);
    effects.push(announceMatch(view, next2));
    effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view));
  }
  view.dispatch({
    changes: changeSet,
    selection,
    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((match2) => {
    let { from: from2, to } = match2;
    return { from: from2, to, insert: query2.getReplacement(match2) };
  });
  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(state, fallback) {
  var _a4, _b, _c, _d, _e;
  let sel = state.selection.main;
  let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
  if (fallback && !selText)
    return fallback;
  let config3 = state.facet(searchConfigFacet);
  return new SearchQuery({
    search: ((_a4 = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a4 !== void 0 ? _a4 : config3.literal) ? selText : selText.replace(/\n/g, "\\n"),
    caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config3.caseSensitive,
    literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config3.literal,
    regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config3.regexp,
    wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config3.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 state = view.state.field(searchState, false);
  if (state && state.panel) {
    let searchInput = getSearchInput(view);
    if (searchInput && searchInput != view.root.activeElement) {
      let query2 = defaultQuery(view.state, state.query.spec);
      if (query2.valid)
        view.dispatch({ effects: setSearchQuery.of(query2) });
      searchInput.focus();
      searchInput.select();
    }
  } else {
    view.dispatch({ effects: [
      togglePanel.of(true),
      state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
    ] });
  }
  return true;
};
var closeSearchPanel = (view) => {
  let state = view.state.field(searchState, false);
  if (!state || !state.panel)
    return false;
  let panel = getPanel(view, createSearchPanel);
  if (panel && panel.dom.contains(view.root.activeElement))
    view.focus();
  view.dispatch({ effects: togglePanel.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(name2, onclick, content2) {
      return crelt("button", { class: "cm-button", name: name2, onclick, type: "button" }, content2);
    }
    this.dom = crelt("div", { onkeydown: (e3) => this.keydown(e3), 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(e3) {
    if (runScopeHandlers(this.view, e3, "search-panel")) {
      e3.preventDefault();
    } else if (e3.keyCode == 13 && e3.target == this.searchField) {
      e3.preventDefault();
      (e3.shiftKey ? findPrevious : findNext)(this.view);
    } else if (e3.keyCode == 13 && e3.target == this.replaceField) {
      e3.preventDefault();
      replaceNext(this.view);
    }
  }
  update(update2) {
    for (let tr2 of update2.transactions)
      for (let effect2 of tr2.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: from2, to }) {
  let line = view.state.doc.lineAt(from2), lineEnd = view.state.doc.lineAt(to).to;
  let start = Math.max(line.from, from2 - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
  let text3 = view.state.sliceDoc(start, end);
  if (start != line.from) {
    for (let i3 = 0; i3 < AnnounceMargin; i3++)
      if (!Break.test(text3[i3 + 1]) && Break.test(text3[i3])) {
        text3 = text3.slice(i3);
        break;
      }
  }
  if (end != lineEnd) {
    for (let i3 = text3.length - 1; i3 > text3.length - AnnounceMargin; i3--)
      if (!Break.test(text3[i3 - 1]) && Break.test(text3[i3])) {
        text3 = text3.slice(0, i3);
        break;
      }
  }
  return EditorView.announce.of(`${view.state.phrase("current match")}. ${text3} ${view.state.phrase("on line")} ${line.number}.`);
}
var baseTheme3 = /* @__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),
  baseTheme3
];

// 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(state, pos, explicit, view) {
    this.state = state;
    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 start = Math.max(line.from, this.pos - 250);
    let str = line.text.slice(start - line.from, this.pos - line.from);
    let found2 = str.search(ensureAnchor(expr, false));
    return found2 < 0 ? null : { from: start + found2, to: this.pos, text: str.slice(found2) };
  }
  /**
  Yields true when the query has been aborted. Can be useful in
  asynchronous queries to avoid doing work that will be ignored.
  */
  get aborted() {
    return this.abortListeners == null;
  }
  /**
  Allows you to register abort handlers, which will be called when
  the query is
  [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
  
  By default, running queries will not be aborted for regular
  typing or backspacing, on the assumption that they are likely to
  return a result with a
  [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
  allows the result to be used after all. Passing `onDocChange:
  true` will cause this query to be aborted for any document
  change.
  */
  addEventListener(type, listener, options2) {
    if (type == "abort" && this.abortListeners) {
      this.abortListeners.push(listener);
      if (options2 && options2.onDocChange)
        this.abortOnDocChange = true;
    }
  }
};
function toSet(chars) {
  let flat = Object.keys(chars).join("");
  let words = /\w/.test(flat);
  if (words)
    flat = flat.replace(/\w/g, "");
  return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
}
function prefixMatch(options2) {
  let first2 = /* @__PURE__ */ Object.create(null), rest2 = /* @__PURE__ */ Object.create(null);
  for (let { label } of options2) {
    first2[label[0]] = true;
    for (let i3 = 1; i3 < label.length; i3++)
      rest2[label[i3]] = true;
  }
  let source = toSet(first2) + toSet(rest2) + "*$";
  return [new RegExp("^" + source), new RegExp(source)];
}
function completeFromList(list2) {
  let options2 = list2.map((o3) => typeof o3 == "string" ? { label: o3 } : o3);
  let [validFor, match2] = options2.every((o3) => /^\w+$/.test(o3.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options2);
  return (context) => {
    let token = context.matchBefore(match2);
    return token || context.explicit ? { from: token ? token.from : context.pos, options: options2, validFor } : null;
  };
}
var Option = class {
  constructor(completion, source, match2, score2) {
    this.completion = completion;
    this.source = source;
    this.match = match2;
    this.score = score2;
  }
};
function cur(state) {
  return state.selection.main.from;
}
function ensureAnchor(expr, start) {
  var _a4;
  let { source } = expr;
  let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
  if (!addStart && !addEnd)
    return expr;
  return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a4 = expr.flags) !== null && _a4 !== void 0 ? _a4 : expr.ignoreCase ? "i" : "");
}
var pickedCompletion = /* @__PURE__ */ Annotation.define();
function insertCompletionText(state, text3, from2, to) {
  let { main: main2 } = state.selection, fromOff = from2 - main2.from, toOff = to - main2.from;
  return {
    ...state.changeByRange((range2) => {
      if (range2 != main2 && from2 != to && state.sliceDoc(range2.from + fromOff, range2.from + toOff) != state.sliceDoc(from2, to))
        return { range: range2 };
      let lines = state.toText(text3);
      return {
        changes: { from: range2.from + fromOff, to: to == main2.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(source) {
  if (!Array.isArray(source))
    return source;
  let known = SourceCache.get(source);
  if (!known)
    SourceCache.set(source, known = completeFromList(source));
  return known;
}
var startCompletionEffect = /* @__PURE__ */ StateEffect.define();
var closeCompletionEffect = /* @__PURE__ */ StateEffect.define();
var FuzzyMatcher = class {
  constructor(pattern2) {
    this.pattern = pattern2;
    this.chars = [];
    this.folded = [];
    this.any = [];
    this.precise = [];
    this.byWord = [];
    this.score = 0;
    this.matched = [];
    for (let p4 = 0; p4 < pattern2.length; ) {
      let char = codePointAt2(pattern2, p4), size4 = codePointSize2(char);
      this.chars.push(char);
      let part = pattern2.slice(p4, p4 + size4), upper = part.toUpperCase();
      this.folded.push(codePointAt2(upper == part ? part.toLowerCase() : upper, 0));
      p4 += size4;
    }
    this.astral = pattern2.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: any2, precise, byWord } = this;
    if (chars.length == 1) {
      let first2 = codePointAt2(word, 0), firstSize = codePointSize2(first2);
      let score2 = firstSize == word.length ? 0 : -100;
      if (first2 == chars[0]) ;
      else if (first2 == folded[0])
        score2 += -200;
      else
        return null;
      return this.ret(score2, [0, firstSize]);
    }
    let direct = word.indexOf(this.pattern);
    if (direct == 0)
      return this.ret(word.length == this.pattern.length ? 0 : -100, [0, this.pattern.length]);
    let len = chars.length, anyTo = 0;
    if (direct < 0) {
      for (let i3 = 0, e3 = Math.min(word.length, 200); i3 < e3 && anyTo < len; ) {
        let next2 = codePointAt2(word, i3);
        if (next2 == chars[anyTo] || next2 == folded[anyTo])
          any2[anyTo++] = i3;
        i3 += 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 i3 = 0, e3 = Math.min(word.length, 200), prevType = 0; i3 < e3 && byWordTo < len; ) {
      let next2 = codePointAt2(word, i3);
      if (direct < 0) {
        if (preciseTo < len && next2 == chars[preciseTo])
          precise[preciseTo++] = i3;
        if (adjacentTo < len) {
          if (next2 == chars[adjacentTo] || next2 == folded[adjacentTo]) {
            if (adjacentTo == 0)
              adjacentStart = i3;
            adjacentEnd = i3 + 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 (!i3 || type == 1 && hasLower || prevType == 0 && type != 0) {
        if (chars[byWordTo] == next2 || folded[byWordTo] == next2 && (byWordFolded = true))
          byWord[byWordTo++] = i3;
        else if (byWord.length)
          wordAdjacent = false;
      }
      prevType = type;
      i3 += 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((any2[0] ? -700 : 0) + -200 + -1100, any2, word);
  }
  result(score2, positions, word) {
    let result2 = [], i3 = 0;
    for (let pos of positions) {
      let to = pos + (this.astral ? codePointSize2(codePointAt2(word, pos)) : 1);
      if (i3 && result2[i3 - 1] == pos)
        result2[i3 - 1] = to;
      else {
        result2[i3++] = pos;
        result2[i3++] = to;
      }
    }
    return this.ret(score2 - word.length, result2);
  }
};
var StrictMatcher = class {
  constructor(pattern2) {
    this.pattern = pattern2;
    this.matched = [];
    this.score = 0;
    this.folded = pattern2.toLowerCase();
  }
  match(word) {
    if (word.length < this.pattern.length)
      return null;
    let start = word.slice(0, this.pattern.length);
    let match2 = start == this.pattern ? 0 : start.toLowerCase() == this.folded ? -200 : null;
    if (match2 == null)
      return null;
    this.matched = [0, start.length];
    this.score = match2 + (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: (a3, b3) => (a3.sortText || a3.label).localeCompare(b3.sortText || b3.label),
      interactionDelay: 75,
      updateSyncTime: 100
    }, {
      defaultKeymap: (a3, b3) => a3 && b3,
      closeOnBlur: (a3, b3) => a3 && b3,
      icons: (a3, b3) => a3 && b3,
      tooltipClass: (a3, b3) => (c3) => joinClass(a3(c3), b3(c3)),
      optionClass: (a3, b3) => (c3) => joinClass(a3(c3), b3(c3)),
      addToOptions: (a3, b3) => a3.concat(b3),
      filterStrict: (a3, b3) => a3 || b3
    });
  }
});
function joinClass(a3, b3) {
  return a3 ? b3 ? a3 + " " + b3 : a3 : b3;
}
function defaultPositionInfo(view, list2, option2, info, space, tooltip) {
  let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;
  let side = "top", offset, maxWidth;
  let spaceLeft = list2.left - space.left, spaceRight = space.right - list2.right;
  let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;
  if (left && spaceLeft < Math.min(infoWidth, spaceRight))
    left = false;
  else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))
    left = true;
  if (infoWidth <= (left ? spaceLeft : spaceRight)) {
    offset = Math.max(space.top, Math.min(option2.top, space.bottom - infoHeight)) - list2.top;
    maxWidth = Math.min(400, left ? spaceLeft : spaceRight);
  } else {
    narrow = true;
    maxWidth = Math.min(
      400,
      (rtl ? list2.right : space.right - list2.left) - 30
      /* Info.Margin */
    );
    let spaceBelow = space.bottom - list2.bottom;
    if (spaceBelow >= infoHeight || spaceBelow > list2.top) {
      offset = option2.bottom - list2.top;
    } else {
      side = "bottom";
      offset = list2.bottom - option2.top;
    }
  }
  let scaleY = (list2.bottom - list2.top) / tooltip.offsetHeight;
  let scaleX = (list2.right - list2.left) / tooltip.offsetWidth;
  return {
    style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
    class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left ? "left" : "right")
  };
}
function optionContent(config3) {
  let content2 = config3.addToOptions.slice();
  if (config3.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, match2) {
      let labelElt = document.createElement("span");
      labelElt.className = "cm-completionLabel";
      let label = completion.displayLabel || completion.label, off = 0;
      for (let j = 0; j < match2.length; ) {
        let from2 = match2[j++], to = match2[j++];
        if (from2 > off)
          labelElt.appendChild(document.createTextNode(label.slice(off, from2)));
        let span = labelElt.appendChild(document.createElement("span"));
        span.appendChild(document.createTextNode(label.slice(from2, 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((a3, b3) => a3.position - b3.position).map((a3) => a3.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: options2, selected } = cState.open;
    let config3 = view.state.facet(completionConfig);
    this.optionContent = optionContent(config3);
    this.optionClass = config3.optionClass;
    this.tooltipClass = config3.tooltipClass;
    this.range = rangeAroundSelected(options2.length, selected, config3.maxRenderedOptions);
    this.dom = document.createElement("div");
    this.dom.className = "cm-tooltip-autocomplete";
    this.updateTooltipClass(view.state);
    this.dom.addEventListener("mousedown", (e3) => {
      let { options: options3 } = view.state.field(stateField).open;
      for (let dom = e3.target, match2; dom && dom != this.dom; dom = dom.parentNode) {
        if (dom.nodeName == "LI" && (match2 = /-(\d+)$/.exec(dom.id)) && +match2[1] < options3.length) {
          this.applyCompletion(view, options3[+match2[1]]);
          e3.preventDefault();
          return;
        }
      }
    });
    this.dom.addEventListener("focusout", (e3) => {
      let state = view.state.field(this.stateField, false);
      if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur && e3.relatedTarget != view.contentDOM)
        view.dispatch({ effects: closeCompletionEffect.of(null) });
    });
    this.showOptions(options2, cState.id);
  }
  mount() {
    this.updateSel();
  }
  showOptions(options2, id) {
    if (this.list)
      this.list.remove();
    this.list = this.dom.appendChild(this.createListBox(options2, id, this.range));
    this.list.addEventListener("scroll", () => {
      if (this.info)
        this.view.requestMeasure(this.placeInfoReq);
    });
  }
  update(update2) {
    var _a4;
    let cState = update2.state.field(this.stateField);
    let prevState = update2.startState.field(this.stateField);
    this.updateTooltipClass(update2.state);
    if (cState != prevState) {
      let { options: options2, selected, disabled } = cState.open;
      if (!prevState.open || prevState.open.options != options2) {
        this.range = rangeAroundSelected(options2.length, selected, update2.state.facet(completionConfig).maxRenderedOptions);
        this.showOptions(options2, cState.id);
      }
      this.updateSel();
      if (disabled != ((_a4 = prevState.open) === null || _a4 === void 0 ? void 0 : _a4.disabled))
        this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
    }
  }
  updateTooltipClass(state) {
    let cls = this.tooltipClass(state);
    if (cls != this.currentClass) {
      for (let c3 of this.currentClass.split(" "))
        if (c3)
          this.dom.classList.remove(c3);
      for (let c3 of cls.split(" "))
        if (c3)
          this.dom.classList.add(c3);
      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);
    }
    let newSel = this.updateSelectedOption(open.selected);
    if (newSel) {
      this.destroyInfo();
      let { completion } = open.options[open.selected];
      let { info } = completion;
      if (!info)
        return;
      let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
      if (!infoResult)
        return;
      if ("then" in infoResult) {
        infoResult.then((obj) => {
          if (obj && this.view.state.field(this.stateField, false) == cState)
            this.addInfoPane(obj, completion);
        }).catch((e3) => logException(this.view.state, e3, "completion info"));
      } else {
        this.addInfoPane(infoResult, completion);
        newSel.setAttribute("aria-describedby", this.info.id);
      }
    }
  }
  addInfoPane(content2, completion) {
    this.destroyInfo();
    let wrap4 = this.info = document.createElement("div");
    wrap4.className = "cm-tooltip cm-completionInfo";
    wrap4.id = "cm-completionInfo-" + Math.floor(Math.random() * 65535).toString(16);
    if (content2.nodeType != null) {
      wrap4.appendChild(content2);
      this.infoDestroy = null;
    } else {
      let { dom, destroy } = content2;
      wrap4.appendChild(dom);
      this.infoDestroy = destroy || null;
    }
    this.dom.appendChild(wrap4);
    this.view.requestMeasure(this.placeInfoReq);
  }
  updateSelectedOption(selected) {
    let set4 = null;
    for (let opt = this.list.firstChild, i3 = this.range.from; opt; opt = opt.nextSibling, i3++) {
      if (opt.nodeName != "LI" || !opt.id) {
        i3--;
      } else if (i3 == selected) {
        if (!opt.hasAttribute("aria-selected")) {
          opt.setAttribute("aria-selected", "true");
          set4 = opt;
        }
      } else {
        if (opt.hasAttribute("aria-selected")) {
          opt.removeAttribute("aria-selected");
          opt.removeAttribute("aria-describedby");
        }
      }
    }
    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(options2, id, range2) {
    const ul = document.createElement("ul");
    ul.id = id;
    ul.setAttribute("role", "listbox");
    ul.setAttribute("aria-expanded", "true");
    ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
    ul.addEventListener("mousedown", (e3) => {
      if (e3.target == ul)
        e3.preventDefault();
    });
    let curSection = null;
    for (let i3 = range2.from; i3 < range2.to; i3++) {
      let { completion, match: match2 } = options2[i3], { section } = completion;
      if (section) {
        let name2 = typeof section == "string" ? section : section.name;
        if (name2 != curSection && (i3 > range2.from || range2.from == 0)) {
          curSection = name2;
          if (typeof section != "string" && section.header) {
            ul.appendChild(section.header(section));
          } else {
            let header = ul.appendChild(document.createElement("completion-section"));
            header.textContent = name2;
          }
        }
      }
      const li2 = ul.appendChild(document.createElement("li"));
      li2.id = id + "-" + i3;
      li2.setAttribute("role", "option");
      let cls = this.optionClass(completion);
      if (cls)
        li2.className = cls;
      for (let source of this.optionContent) {
        let node = source(completion, this.view.state, this.view, match2);
        if (node)
          li2.appendChild(node);
      }
    }
    if (range2.from)
      ul.classList.add("cm-completionListIncompleteTop");
    if (range2.to < options2.length)
      ul.classList.add("cm-completionListIncompleteBottom");
    return ul;
  }
  destroyInfo() {
    if (this.info) {
      if (this.infoDestroy)
        this.infoDestroy();
      this.info.remove();
      this.info = null;
    }
  }
  destroy() {
    this.destroyInfo();
  }
};
function completionTooltip(stateField, applyCompletion2) {
  return (view) => new CompletionTooltip(view, stateField, applyCompletion2);
}
function scrollIntoView2(container, element2) {
  let parent = container.getBoundingClientRect();
  let self2 = element2.getBoundingClientRect();
  let scaleY = parent.height / container.offsetHeight;
  if (self2.top < parent.top)
    container.scrollTop -= (parent.top - self2.top) / scaleY;
  else if (self2.bottom > parent.bottom)
    container.scrollTop += (self2.bottom - parent.bottom) / scaleY;
}
function score(option2) {
  return (option2.boost || 0) * 100 + (option2.apply ? 10 : 0) + (option2.info ? 5 : 0) + (option2.type ? 1 : 0);
}
function sortOptions(active, state) {
  let options2 = [];
  let sections = null, dynamicSectionScore = null;
  let addOption = (option2) => {
    options2.push(option2);
    let { section } = option2.completion;
    if (section) {
      if (!sections)
        sections = [];
      let name2 = typeof section == "string" ? section : section.name;
      if (!sections.some((s3) => s3.name == name2))
        sections.push(typeof section == "string" ? { name: name2 } : section);
    }
  };
  let conf = state.facet(completionConfig);
  for (let a3 of active)
    if (a3.hasResult()) {
      let getMatch = a3.result.getMatch;
      if (a3.result.filter === false) {
        for (let option2 of a3.result.options) {
          addOption(new Option(option2, a3.source, getMatch ? getMatch(option2) : [], 1e9 - options2.length));
        }
      } else {
        let pattern2 = state.sliceDoc(a3.from, a3.to), match2;
        let matcher2 = conf.filterStrict ? new StrictMatcher(pattern2) : new FuzzyMatcher(pattern2);
        for (let option2 of a3.result.options)
          if (match2 = matcher2.match(option2.label)) {
            let matched = !option2.displayLabel ? match2.matched : getMatch ? getMatch(option2, match2.matched) : [];
            let score2 = match2.score + (option2.boost || 0);
            addOption(new Option(option2, a3.source, matched, score2));
            if (typeof option2.section == "object" && option2.section.rank === "dynamic") {
              let { name: name2 } = option2.section;
              if (!dynamicSectionScore)
                dynamicSectionScore = /* @__PURE__ */ Object.create(null);
              dynamicSectionScore[name2] = Math.max(score2, dynamicSectionScore[name2] || -1e9);
            }
          }
      }
    }
  if (sections) {
    let sectionOrder = /* @__PURE__ */ Object.create(null), pos = 0;
    let cmp4 = (a3, b3) => {
      return (a3.rank === "dynamic" && b3.rank === "dynamic" ? dynamicSectionScore[b3.name] - dynamicSectionScore[a3.name] : 0) || (typeof a3.rank == "number" ? a3.rank : 1e9) - (typeof b3.rank == "number" ? b3.rank : 1e9) || (a3.name < b3.name ? -1 : 1);
    };
    for (let s3 of sections.sort(cmp4)) {
      pos -= 1e5;
      sectionOrder[s3.name] = pos;
    }
    for (let option2 of options2) {
      let { section } = option2.completion;
      if (section)
        option2.score += sectionOrder[typeof section == "string" ? section : section.name];
    }
  }
  let result2 = [], prev = null;
  let compare4 = conf.compareCompletions;
  for (let opt of options2.sort((a3, b3) => b3.score - a3.score || compare4(a3.completion, b3.completion))) {
    let cur2 = opt.completion;
    if (!prev || prev.label != cur2.label || prev.detail != cur2.detail || prev.type != null && cur2.type != null && prev.type != cur2.type || prev.apply != cur2.apply || prev.boost != cur2.boost)
      result2.push(opt);
    else if (score(opt.completion) > score(prev))
      result2[result2.length - 1] = opt;
    prev = opt.completion;
  }
  return result2;
}
var CompletionDialog = class _CompletionDialog {
  constructor(options2, attrs2, tooltip, timestamp2, selected, disabled) {
    this.options = options2;
    this.attrs = attrs2;
    this.tooltip = tooltip;
    this.timestamp = timestamp2;
    this.selected = selected;
    this.disabled = disabled;
  }
  setSelected(selected, id) {
    return selected == this.selected || selected >= this.options.length ? this : new _CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
  }
  static build(active, state, id, prev, conf, didSetActive) {
    if (prev && !didSetActive && active.some((s3) => s3.isPending))
      return prev.setDisabled();
    let options2 = sortOptions(active, state);
    if (!options2.length)
      return prev && active.some((a3) => a3.isPending) ? prev.setDisabled() : null;
    let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
    if (prev && prev.selected != selected && prev.selected != -1) {
      let selectedValue = prev.options[prev.selected].completion;
      for (let i3 = 0; i3 < options2.length; i3++)
        if (options2[i3].completion == selectedValue) {
          selected = i3;
          break;
        }
    }
    return new _CompletionDialog(options2, makeAttrs(id, selected), {
      pos: active.reduce((a3, b3) => b3.hasResult() ? Math.min(a3, b3.from) : a3, 1e8),
      create: createTooltip,
      above: conf.aboveCursor
    }, prev ? prev.timestamp : Date.now(), selected, false);
  }
  map(changes) {
    return new _CompletionDialog(this.options, this.attrs, { ...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, id, open) {
    this.active = active;
    this.id = id;
    this.open = open;
  }
  static start() {
    return new _CompletionState(none3, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
  }
  update(tr2) {
    let { state } = tr2, conf = state.facet(completionConfig);
    let sources = conf.override || state.languageDataAt("autocomplete", cur(state)).map(asSource);
    let active = sources.map((source) => {
      let value2 = this.active.find((s3) => s3.source == source) || new ActiveSource(
        source,
        this.active.some(
          (a3) => a3.state != 0
          /* State.Inactive */
        ) ? 1 : 0
        /* State.Inactive */
      );
      return value2.update(tr2, conf);
    });
    if (active.length == this.active.length && active.every((a3, i3) => a3 == this.active[i3]))
      active = this.active;
    let open = this.open, didSet = tr2.effects.some((e3) => e3.is(setActiveEffect));
    if (open && tr2.docChanged)
      open = open.map(tr2.changes);
    if (tr2.selection || active.some((a3) => a3.hasResult() && tr2.changes.touchesRange(a3.from, a3.to)) || !sameResults(active, this.active) || didSet)
      open = CompletionDialog.build(active, state, this.id, open, conf, didSet);
    else if (open && open.disabled && !active.some((a3) => a3.isPending))
      open = null;
    if (!open && active.every((a3) => !a3.isPending) && active.some((a3) => a3.hasResult()))
      active = active.map((a3) => a3.hasResult() ? new ActiveSource(
        a3.source,
        0
        /* State.Inactive */
      ) : a3);
    for (let effect2 of tr2.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(a3, b3) {
  if (a3 == b3)
    return true;
  for (let iA = 0, iB = 0; ; ) {
    while (iA < a3.length && !a3[iA].hasResult())
      iA++;
    while (iB < b3.length && !b3[iB].hasResult())
      iB++;
    let endA = iA == a3.length, endB = iB == b3.length;
    if (endA || endB)
      return endA == endB;
    if (a3[iA++].result != b3[iB++].result)
      return false;
  }
}
var baseAttrs = {
  "aria-autocomplete": "list"
};
var noAttrs2 = {};
function makeAttrs(id, selected) {
  let result2 = {
    "aria-autocomplete": "list",
    "aria-haspopup": "listbox",
    "aria-controls": id
  };
  if (selected > -1)
    result2["aria-activedescendant"] = id + "-" + selected;
  return result2;
}
var none3 = [];
function getUpdateType(tr2, conf) {
  if (tr2.isUserEvent("input.complete")) {
    let completion = tr2.annotation(pickedCompletion);
    if (completion && conf.activateOnCompletion(completion))
      return 4 | 8;
  }
  let typing = tr2.isUserEvent("input.type");
  return typing && conf.activateOnTyping ? 4 | 1 : typing ? 1 : tr2.isUserEvent("delete.backward") ? 2 : tr2.selection ? 8 : tr2.docChanged ? 16 : 0;
}
var ActiveSource = class _ActiveSource {
  constructor(source, state, explicit = false) {
    this.source = source;
    this.state = state;
    this.explicit = explicit;
  }
  hasResult() {
    return false;
  }
  get isPending() {
    return this.state == 1;
  }
  update(tr2, conf) {
    let type = getUpdateType(tr2, conf), value2 = this;
    if (type & 8 || type & 16 && this.touches(tr2))
      value2 = new _ActiveSource(
        value2.source,
        0
        /* State.Inactive */
      );
    if (type & 4 && value2.state == 0)
      value2 = new _ActiveSource(
        this.source,
        1
        /* State.Pending */
      );
    value2 = value2.updateFor(tr2, type);
    for (let effect2 of tr2.effects) {
      if (effect2.is(startCompletionEffect))
        value2 = new _ActiveSource(value2.source, 1, effect2.value);
      else if (effect2.is(closeCompletionEffect))
        value2 = new _ActiveSource(
          value2.source,
          0
          /* State.Inactive */
        );
      else if (effect2.is(setActiveEffect)) {
        for (let active of effect2.value)
          if (active.source == value2.source)
            value2 = active;
      }
    }
    return value2;
  }
  updateFor(tr2, type) {
    return this.map(tr2.changes);
  }
  map(changes) {
    return this;
  }
  touches(tr2) {
    return tr2.changes.touchesRange(cur(tr2.state));
  }
};
var ActiveResult = class _ActiveResult extends ActiveSource {
  constructor(source, explicit, limit, result2, from2, to) {
    super(source, 3, explicit);
    this.limit = limit;
    this.result = result2;
    this.from = from2;
    this.to = to;
  }
  hasResult() {
    return true;
  }
  updateFor(tr2, type) {
    var _a4;
    if (!(type & 3))
      return this.map(tr2.changes);
    let result2 = this.result;
    if (result2.map && !tr2.changes.empty)
      result2 = result2.map(result2, tr2.changes);
    let from2 = tr2.changes.mapPos(this.from), to = tr2.changes.mapPos(this.to, 1);
    let pos = cur(tr2.state);
    if (pos > to || !result2 || type & 2 && (cur(tr2.startState) == this.from || pos < this.limit))
      return new ActiveSource(
        this.source,
        type & 4 ? 1 : 0
        /* State.Inactive */
      );
    let limit = tr2.changes.mapPos(this.limit);
    if (checkValid(result2.validFor, tr2.state, from2, to))
      return new _ActiveResult(this.source, this.explicit, limit, result2, from2, to);
    if (result2.update && (result2 = result2.update(result2, from2, to, new CompletionContext(tr2.state, pos, false))))
      return new _ActiveResult(this.source, this.explicit, limit, result2, result2.from, (_a4 = result2.to) !== null && _a4 !== void 0 ? _a4 : cur(tr2.state));
    return new ActiveSource(this.source, 1, this.explicit);
  }
  map(mapping) {
    if (mapping.empty)
      return this;
    let result2 = this.result.map ? this.result.map(this.result, mapping) : this.result;
    if (!result2)
      return new ActiveSource(
        this.source,
        0
        /* State.Inactive */
      );
    return new _ActiveResult(this.source, this.explicit, mapping.mapPos(this.limit), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
  }
  touches(tr2) {
    return tr2.changes.touchesRange(this.from, this.to);
  }
};
function checkValid(validFor, state, from2, to) {
  if (!validFor)
    return false;
  let text3 = state.sliceDoc(from2, to);
  return typeof validFor == "function" ? validFor(text3, from2, to, state) : ensureAnchor(validFor, true).test(text3);
}
var setActiveEffect = /* @__PURE__ */ StateEffect.define({
  map(sources, mapping) {
    return sources.map((s3) => s3.map(mapping));
  }
});
var setSelectedEffect = /* @__PURE__ */ StateEffect.define();
var completionState = /* @__PURE__ */ StateField.define({
  create() {
    return CompletionState.start();
  },
  update(value2, tr2) {
    return value2.update(tr2);
  },
  provide: (f3) => [
    showTooltip.from(f3, (val) => val.tooltip),
    EditorView.contentAttributes.from(f3, (state) => state.attrs)
  ]
});
function applyCompletion(view, option2) {
  const apply3 = option2.completion.apply || option2.completion.label;
  let result2 = view.state.field(completionState).active.find((a3) => a3.source == option2.source);
  if (!(result2 instanceof ActiveResult))
    return false;
  if (typeof apply3 == "string")
    view.dispatch({
      ...insertCompletionText(view.state, apply3, result2.from, result2.to),
      annotations: pickedCompletion.of(option2.completion)
    });
  else
    apply3(view, option2.completion, result2.from, result2.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 step2 = 1, tooltip;
    if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
      step2 = Math.max(2, Math.floor(tooltip.dom.offsetHeight / tooltip.dom.querySelector("li").offsetHeight) - 1);
    let { length } = cState.open.options;
    let selected = cState.open.selected > -1 ? cState.open.selected + step2 * (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(
    (a3) => a3.state != 0
    /* State.Inactive */
  ))
    return false;
  view.dispatch({ effects: closeCompletionEffect.of(null) });
  return true;
};
var RunningQuery = class {
  constructor(active, context) {
    this.active = active;
    this.context = context;
    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(update2) {
    let cState = update2.state.field(completionState);
    let conf = update2.state.facet(completionConfig);
    if (!update2.selectionSet && !update2.docChanged && update2.startState.field(completionState) == cState)
      return;
    let doesReset = update2.transactions.some((tr2) => {
      let type = getUpdateType(tr2, conf);
      return type & 8 || (tr2.selection || tr2.docChanged) && !(type & 3);
    });
    for (let i3 = 0; i3 < this.running.length; i3++) {
      let query2 = this.running[i3];
      if (doesReset || query2.context.abortOnDocChange && update2.docChanged || query2.updates.length + update2.transactions.length > MaxUpdateCount && Date.now() - query2.time > MinAbortTime) {
        for (let handler of query2.context.abortListeners) {
          try {
            handler();
          } catch (e3) {
            logException(this.view.state, e3);
          }
        }
        query2.context.abortListeners = null;
        this.running.splice(i3--, 1);
      } else {
        query2.updates.push(...update2.transactions);
      }
    }
    if (this.debounceUpdate > -1)
      clearTimeout(this.debounceUpdate);
    if (update2.transactions.some((tr2) => tr2.effects.some((e3) => e3.is(startCompletionEffect))))
      this.pendingStart = true;
    let delay = this.pendingStart ? 50 : conf.activateOnTypingDelay;
    this.debounceUpdate = cState.active.some((a3) => a3.isPending && !this.running.some((q) => q.active.source == a3.source)) ? setTimeout(() => this.startUpdate(), delay) : -1;
    if (this.composing != 0)
      for (let tr2 of update2.transactions) {
        if (tr2.isUserEvent("input.type"))
          this.composing = 2;
        else if (this.composing == 2 && tr2.selection)
          this.composing = 3;
      }
  }
  startUpdate() {
    this.debounceUpdate = -1;
    this.pendingStart = false;
    let { state } = this.view, cState = state.field(completionState);
    for (let active of cState.active) {
      if (active.isPending && !this.running.some((r3) => r3.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 } = this.view, pos = cur(state);
    let context = new CompletionContext(state, pos, active.explicit, this.view);
    let pending = new RunningQuery(active, context);
    this.running.push(pending);
    Promise.resolve(active.source(context)).then((result2) => {
      if (!pending.context.aborted) {
        pending.done = result2 || null;
        this.scheduleAccept();
      }
    }, (err) => {
      this.view.dispatch({ effects: closeCompletionEffect.of(null) });
      logException(this.view.state, err);
    });
  }
  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 _a4;
    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 i3 = 0; i3 < this.running.length; i3++) {
      let query2 = this.running[i3];
      if (query2.done === void 0)
        continue;
      this.running.splice(i3--, 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, (_a4 = query2.done.to) !== null && _a4 !== void 0 ? _a4 : pos);
        for (let tr2 of query2.updates)
          active = active.update(tr2, conf);
        if (active.hasResult()) {
          updated.push(active);
          continue;
        }
      }
      let current = cState.active.find((a3) => a3.source == query2.active.source);
      if (current && current.isPending) {
        if (query2.done == null) {
          let active = new ActiveSource(
            query2.active.source,
            0
            /* State.Inactive */
          );
          for (let tr2 of query2.updates)
            active = active.update(tr2, 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 state = this.view.state.field(completionState, false);
      if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
        let dialog2 = state.open && getTooltip(this.view, state.open.tooltip);
        if (!dialog2 || !dialog2.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 field2 = view.state.field(completionState, false);
    if (!field2 || !field2.open || field2.open.disabled || field2.open.selected < 0 || event2.key.length > 1 || event2.ctrlKey && !(windows && event2.altKey) || event2.metaKey)
      return false;
    let option2 = field2.open.options[field2.open.selected];
    let result2 = field2.active.find((a3) => a3.source == option2.source);
    let commitChars = option2.completion.commitCharacters || result2.result.commitCharacters;
    if (commitChars && commitChars.indexOf(event2.key) > -1)
      applyCompletion(view, option2);
    return false;
  }
}));
var baseTheme4 = /* @__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(field2, line, from2, to) {
    this.field = field2;
    this.line = line;
    this.from = from2;
    this.to = to;
  }
};
var FieldRange = class _FieldRange {
  constructor(field2, from2, to) {
    this.field = field2;
    this.from = from2;
    this.to = to;
  }
  map(changes) {
    let from2 = changes.mapPos(this.from, -1, MapMode.TrackDel);
    let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
    return from2 == null || to == null ? null : new _FieldRange(this.field, from2, to);
  }
};
var Snippet = class _Snippet {
  constructor(lines, fieldPositions) {
    this.lines = lines;
    this.fieldPositions = fieldPositions;
  }
  instantiate(state, pos) {
    let text3 = [], lineStart = [pos];
    let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
    for (let line of this.lines) {
      if (text3.length) {
        let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
        for (let i3 = 0; i3 < tabs; i3++)
          indent += state.facet(indentUnit);
        lineStart.push(pos + indent.length - tabs);
        line = indent + line.slice(tabs);
      }
      text3.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: text3, ranges };
  }
  static parse(template3) {
    let fields2 = [];
    let lines = [], positions = [], m3;
    for (let line of template3.split(/\r\n?|\n/)) {
      while (m3 = /[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(line)) {
        let seq2 = m3[1] ? +m3[1] : null, rawName = m3[2] || m3[3] || "", found2 = -1;
        let name2 = rawName.replace(/\\[{}]/g, (m4) => m4[1]);
        for (let i3 = 0; i3 < fields2.length; i3++) {
          if (seq2 != null ? fields2[i3].seq == seq2 : name2 ? fields2[i3].name == name2 : false)
            found2 = i3;
        }
        if (found2 < 0) {
          let i3 = 0;
          while (i3 < fields2.length && (seq2 == null || fields2[i3].seq != null && fields2[i3].seq < seq2))
            i3++;
          fields2.splice(i3, 0, { seq: seq2, name: name2 });
          found2 = i3;
          for (let pos of positions)
            if (pos.field >= found2)
              pos.field++;
        }
        for (let pos of positions)
          if (pos.line == lines.length && pos.from > m3.index) {
            let snip = m3[2] ? 3 + (m3[1] || "").length : 2;
            pos.from -= snip;
            pos.to -= snip;
          }
        positions.push(new FieldPos(found2, lines.length, m3.index, m3.index + name2.length));
        line = line.slice(0, m3.index) + rawName + line.slice(m3.index + m3[0].length);
      }
      line = line.replace(/\\([{}])/g, (_5, brace, index2) => {
        for (let pos of positions)
          if (pos.line == lines.length && pos.from > index2) {
            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((r3) => (r3.from == r3.to ? fieldMarker : fieldRange).range(r3.from, r3.to)), true);
  }
  map(changes) {
    let ranges = [];
    for (let r3 of this.ranges) {
      let mapped = r3.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((r3) => r3.field == this.active && r3.from <= range2.from && r3.to >= range2.to));
  }
};
var setActive = /* @__PURE__ */ StateEffect.define({
  map(value2, changes) {
    return value2 && value2.map(changes);
  }
});
var moveToField = /* @__PURE__ */ StateEffect.define();
var snippetState = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(value2, tr2) {
    for (let effect2 of tr2.effects) {
      if (effect2.is(setActive))
        return effect2.value;
      if (effect2.is(moveToField) && value2)
        return new ActiveSnippet(value2.ranges, effect2.value);
    }
    if (value2 && tr2.docChanged)
      value2 = value2.map(tr2.changes);
    if (value2 && tr2.selection && !value2.selectionInsideField(tr2.selection))
      value2 = null;
    return value2;
  },
  provide: (f3) => EditorView.decorations.from(f3, (val) => val ? val.deco : Decoration.none)
});
function fieldSelection(ranges, field2) {
  return EditorSelection.create(ranges.filter((r3) => r3.field == field2).map((r3) => EditorSelection.range(r3.from, r3.to)));
}
function snippet(template3) {
  let snippet2 = Snippet.parse(template3);
  return (editor, completion, from2, to) => {
    let { text: text3, ranges } = snippet2.instantiate(editor.state, from2);
    let { main: main2 } = editor.state.selection;
    let spec = {
      changes: { from: from2, to: to == main2.from ? main2.to : to, insert: Text.of(text3) },
      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((r3) => r3.field > 0)) {
      let active = new ActiveSnippet(ranges, 0);
      let effects = spec.effects = [setActive.of(active)];
      if (editor.state.field(snippetState, false) === void 0)
        effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme4]));
    }
    editor.dispatch(editor.state.update(spec));
  };
}
function moveField(dir) {
  return ({ state, dispatch }) => {
    let active = state.field(snippetState, false);
    if (!active || dir < 0 && active.active == 0)
      return false;
    let next2 = active.active + dir, last3 = dir > 0 && !active.ranges.some((r3) => r3.field == next2 + dir);
    dispatch(state.update({
      selection: fieldSelection(active.ranges, next2),
      effects: setActive.of(last3 ? null : new ActiveSnippet(active.ranges, next2)),
      scrollIntoView: true
    }));
    return true;
  };
}
var clearSnippet = ({ state, dispatch }) => {
  let active = state.field(snippetState, false);
  if (!active)
    return false;
  dispatch(state.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], (state) => state.facet(snippetKeymap)));
function snippetCompletion(template3, completion) {
  return { ...completion, apply: snippet(template3) };
}
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 match2 = active.ranges.find((r3) => r3.from <= pos && r3.to >= pos);
    if (!match2 || match2.field == active.active)
      return false;
    view.dispatch({
      selection: fieldSelection(active.ranges, match2.field),
      effects: setActive.of(active.ranges.some((r3) => r3.field > match2.field) ? new ActiveSnippet(active.ranges, match2.field) : null),
      scrollIntoView: true
    });
    return true;
  }
});
var defaults4 = {
  brackets: ["(", "[", "{", "'", '"'],
  before: ")]}:;>",
  stringPrefixes: []
};
var closeBracketEffect = /* @__PURE__ */ StateEffect.define({
  map(value2, mapping) {
    let mapped = mapping.mapPos(value2, -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(value2, tr2) {
    value2 = value2.map(tr2.changes);
    if (tr2.selection) {
      let line = tr2.state.doc.lineAt(tr2.selection.main.head);
      value2 = value2.update({ filter: (from2) => from2 >= line.from && from2 <= line.to });
    }
    for (let effect2 of tr2.effects)
      if (effect2.is(closeBracketEffect))
        value2 = value2.update({ add: [closedBracket.range(effect2.value, effect2.value + 1)] });
    return value2;
  }
});
function closeBrackets() {
  return [inputHandler2, bracketState];
}
var definedClosing = "()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";
function closing(ch) {
  for (let i3 = 0; i3 < definedClosing.length; i3 += 2)
    if (definedClosing.charCodeAt(i3) == ch)
      return definedClosing.charAt(i3 + 1);
  return fromCodePoint(ch < 128 ? ch : ch + 1);
}
function config(state, pos) {
  return state.languageDataAt("closeBrackets", pos)[0] || defaults4;
}
var android = typeof navigator == "object" && /* @__PURE__ */ /Android\b/.test(navigator.userAgent);
var inputHandler2 = /* @__PURE__ */ EditorView.inputHandler.of((view, from2, to, insert4) => {
  if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)
    return false;
  let sel = view.state.selection.main;
  if (insert4.length > 2 || insert4.length == 2 && codePointSize2(codePointAt2(insert4, 0)) == 1 || from2 != sel.from || to != sel.to)
    return false;
  let tr2 = insertBracket(view.state, insert4);
  if (!tr2)
    return false;
  view.dispatch(tr2);
  return true;
});
var deleteBracketPair = ({ state, dispatch }) => {
  if (state.readOnly)
    return false;
  let conf = config(state, state.selection.main.head);
  let tokens = conf.brackets || defaults4.brackets;
  let dont = null, changes = state.changeByRange((range2) => {
    if (range2.empty) {
      let before2 = prevChar(state.doc, range2.head);
      for (let token of tokens) {
        if (token == before2 && nextChar(state.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(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
  return !dont;
};
var closeBracketsKeymap = [
  { key: "Backspace", run: deleteBracketPair }
];
function insertBracket(state, bracket2) {
  let conf = config(state, state.selection.main.head);
  let tokens = conf.brackets || defaults4.brackets;
  for (let tok of tokens) {
    let closed = closing(codePointAt2(tok, 0));
    if (bracket2 == tok)
      return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) : handleOpen(state, tok, closed, conf.before || defaults4.before);
    if (bracket2 == closed && closedBracketAt(state, state.selection.main.from))
      return handleClose(state, tok, closed);
  }
  return null;
}
function closedBracketAt(state, pos) {
  let found2 = false;
  state.field(bracketState).between(0, state.doc.length, (from2) => {
    if (from2 == pos)
      found2 = true;
  });
  return found2;
}
function nextChar(doc4, pos) {
  let next2 = doc4.sliceString(pos, pos + 2);
  return next2.slice(0, codePointSize2(codePointAt2(next2, 0)));
}
function prevChar(doc4, pos) {
  let prev = doc4.sliceString(pos - 2, pos);
  return codePointSize2(codePointAt2(prev, 0)) == prev.length ? prev : prev.slice(1);
}
function handleOpen(state, open, close2, closeBefore) {
  let dont = null, changes = state.changeByRange((range2) => {
    if (!range2.empty)
      return {
        changes: [{ insert: open, from: range2.from }, { insert: close2, from: range2.to }],
        effects: closeBracketEffect.of(range2.to + open.length),
        range: EditorSelection.range(range2.anchor + open.length, range2.head + open.length)
      };
    let next2 = nextChar(state.doc, range2.head);
    if (!next2 || /\s/.test(next2) || closeBefore.indexOf(next2) > -1)
      return {
        changes: { insert: open + close2, from: range2.head },
        effects: closeBracketEffect.of(range2.head + open.length),
        range: EditorSelection.cursor(range2.head + open.length)
      };
    return { range: dont = range2 };
  });
  return dont ? null : state.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleClose(state, _open, close2) {
  let dont = null, changes = state.changeByRange((range2) => {
    if (range2.empty && nextChar(state.doc, range2.head) == close2)
      return {
        changes: { from: range2.head, to: range2.head + close2.length, insert: close2 },
        range: EditorSelection.cursor(range2.head + close2.length)
      };
    return dont = { range: range2 };
  });
  return dont ? null : state.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function handleSame(state, token, allowTriple, config3) {
  let stringPrefixes = config3.stringPrefixes || defaults4.stringPrefixes;
  let dont = null, changes = state.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(state.doc, pos), start;
    if (next2 == token) {
      if (nodeStart(state, pos)) {
        return {
          changes: { insert: token + token, from: pos },
          effects: closeBracketEffect.of(pos + token.length),
          range: EditorSelection.cursor(pos + token.length)
        };
      } else if (closedBracketAt(state, pos)) {
        let isTriple = allowTriple && state.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 && state.sliceDoc(pos - 2 * token.length, pos) == token + token && (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state, start)) {
      return {
        changes: { insert: token + token + token + token, from: pos },
        effects: closeBracketEffect.of(pos + token.length),
        range: EditorSelection.cursor(pos + token.length)
      };
    } else if (state.charCategorizer(pos)(next2) != CharCategory.Word) {
      if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, 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 : state.update(changes, {
    scrollIntoView: true,
    userEvent: "input.type"
  });
}
function nodeStart(state, pos) {
  let tree = syntaxTree(state).resolveInner(pos + 1);
  return tree.parent && tree.from == pos;
}
function probablyInString(state, pos, quoteToken, prefixes) {
  let node = syntaxTree(state).resolveInner(pos, -1);
  let maxPrefix = prefixes.reduce((m3, p4) => Math.max(m3, p4.length), 0);
  for (let i3 = 0; i3 < 5; i3++) {
    let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
    let quotePos = start.indexOf(quoteToken);
    if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {
      let first2 = node.firstChild;
      while (first2 && first2.from == node.from && first2.to - first2.from > quoteToken.length + quotePos) {
        if (state.sliceDoc(first2.to - quoteToken.length, first2.to) == quoteToken)
          return false;
        first2 = first2.firstChild;
      }
      return true;
    }
    let parent = node.to == pos && node.parent;
    if (!parent)
      break;
    node = parent;
  }
  return false;
}
function canStartStringAt(state, pos, prefixes) {
  let charCat = state.charCategorizer(pos);
  if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word)
    return pos;
  for (let prefix5 of prefixes) {
    let start = pos - prefix5.length;
    if (state.sliceDoc(start, pos) == prefix5 && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word)
      return start;
  }
  return -1;
}
function autocompletion(config3 = {}) {
  return [
    commitCharacters,
    completionState,
    completionConfig.of(config3),
    completionPlugin,
    completionKeymapExt,
    baseTheme4
  ];
}
var completionKeymap = [
  { key: "Ctrl-Space", run: startCompletion },
  { mac: "Alt-`", run: startCompletion },
  { mac: "Alt-i", 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], (state) => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));

// node_modules/@codemirror/lint/dist/index.js
var SelectedDiagnostic = class {
  constructor(from2, to, diagnostic) {
    this.from = from2;
    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, state) {
    let diagnosticFilter = state.facet(lintConfig).markerFilter;
    if (diagnosticFilter)
      diagnostics = diagnosticFilter(diagnostics, state);
    let sorted = diagnostics.slice().sort((a3, b3) => a3.from - b3.from || a3.to - b3.to);
    let deco = new RangeSetBuilder(), active = [], pos = 0;
    let scan = state.doc.iter(), scanPos = 0, docLen = state.doc.length;
    for (let i3 = 0; ; ) {
      let next2 = i3 == sorted.length ? null : sorted[i3];
      if (!next2 && !active.length)
        break;
      let from2, to;
      if (active.length) {
        from2 = pos;
        to = active.reduce((p4, d3) => Math.min(p4, d3.to), next2 && next2.from > from2 ? next2.from : 1e8);
      } else {
        from2 = next2.from;
        if (from2 > docLen)
          break;
        to = next2.to;
        active.push(next2);
        i3++;
      }
      while (i3 < sorted.length) {
        let next3 = sorted[i3];
        if (next3.from == from2 && (next3.to > next3.from || next3.to == from2)) {
          active.push(next3);
          i3++;
          to = Math.min(next3.to, to);
        } else {
          to = Math.min(next3.from, to);
          break;
        }
      }
      to = Math.min(to, docLen);
      let widget = false;
      if (active.some((d3) => d3.from == from2 && (d3.to == to || to == docLen))) {
        widget = from2 == to;
        if (!widget && to - from2 < 10) {
          let behind = from2 - (scanPos + scan.value.length);
          if (behind > 0) {
            scan.next(behind);
            scanPos = from2;
          }
          for (let check = from2; ; ) {
            if (check >= to) {
              widget = true;
              break;
            }
            if (!scan.lineBreak && scanPos + scan.value.length > check)
              break;
            check = scanPos + scan.value.length;
            scanPos += scan.value.length;
            scan.next();
          }
        }
      }
      let sev = maxSeverity(active);
      if (widget) {
        deco.add(from2, from2, Decoration.widget({
          widget: new DiagnosticWidget(sev),
          diagnostics: active.slice()
        }));
      } else {
        let markClass = active.reduce((c3, d3) => d3.markClass ? c3 + " " + d3.markClass : c3, "");
        deco.add(from2, to, Decoration.mark({
          class: "cm-lintRange cm-lintRange-" + sev + markClass,
          diagnostics: active.slice(),
          inclusiveEnd: active.some((a3) => a3.to > to)
        }));
      }
      pos = to;
      if (pos == docLen)
        break;
      for (let i4 = 0; i4 < active.length; i4++)
        if (active[i4].to <= pos)
          active.splice(i4--, 1);
    }
    let set4 = deco.finish();
    return new _LintState(set4, panel, findDiagnostic(set4));
  }
};
function findDiagnostic(diagnostics, diagnostic = null, after2 = 0) {
  let found2 = null;
  diagnostics.between(after2, 1e9, (from2, to, { spec }) => {
    if (diagnostic && spec.diagnostics.indexOf(diagnostic) < 0)
      return;
    if (!found2)
      found2 = new SelectedDiagnostic(from2, to, diagnostic || spec.diagnostics[0]);
    else if (spec.diagnostics.indexOf(found2.diagnostic) < 0)
      return false;
    else
      found2 = new SelectedDiagnostic(found2.from, to, found2.diagnostic);
  });
  return found2;
}
function hideTooltip(tr2, tooltip) {
  let from2 = tooltip.pos, to = tooltip.end || from2;
  let result2 = tr2.state.facet(lintConfig).hideOn(tr2, from2, to);
  if (result2 != null)
    return result2;
  let line = tr2.startState.doc.lineAt(tooltip.pos);
  return !!(tr2.effects.some((e3) => e3.is(setDiagnosticsEffect)) || tr2.changes.touchesRange(line.from, Math.max(line.to, to)));
}
function maybeEnableLint(state, effects) {
  return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
}
function setDiagnostics(state, diagnostics) {
  return {
    effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)])
  };
}
var setDiagnosticsEffect = /* @__PURE__ */ StateEffect.define();
var togglePanel2 = /* @__PURE__ */ StateEffect.define();
var movePanelSelection = /* @__PURE__ */ StateEffect.define();
var lintState = /* @__PURE__ */ StateField.define({
  create() {
    return new LintState(Decoration.none, null, null);
  },
  update(value2, tr2) {
    if (tr2.docChanged && value2.diagnostics.size) {
      let mapped = value2.diagnostics.map(tr2.changes), selected = null, panel = value2.panel;
      if (value2.selected) {
        let selPos = tr2.changes.mapPos(value2.selected.from, 1);
        selected = findDiagnostic(mapped, value2.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
      }
      if (!mapped.size && panel && tr2.state.facet(lintConfig).autoPanel)
        panel = null;
      value2 = new LintState(mapped, panel, selected);
    }
    for (let effect2 of tr2.effects) {
      if (effect2.is(setDiagnosticsEffect)) {
        let panel = !tr2.state.facet(lintConfig).autoPanel ? value2.panel : effect2.value.length ? LintPanel.open : null;
        value2 = LintState.init(effect2.value, panel, tr2.state);
      } else if (effect2.is(togglePanel2)) {
        value2 = new LintState(value2.diagnostics, effect2.value ? LintPanel.open : null, value2.selected);
      } else if (effect2.is(movePanelSelection)) {
        value2 = new LintState(value2.diagnostics, value2.panel, effect2.value);
      }
    }
    return value2;
  },
  provide: (f3) => [
    showPanel.from(f3, (val) => val.panel),
    EditorView.decorations.from(f3, (s3) => s3.diagnostics)
  ]
});
var activeMark = /* @__PURE__ */ Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
function lintTooltip(view, pos, side) {
  let { diagnostics } = view.state.field(lintState);
  let found2, start = -1, end = -1;
  diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from2, to, { spec }) => {
    if (pos >= from2 && pos <= to && (from2 == to || (pos > from2 || side > 0) && (pos < to || side < 0))) {
      found2 = spec.diagnostics;
      start = from2;
      end = to;
      return false;
    }
  });
  let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
  if (found2 && diagnosticFilter)
    found2 = diagnosticFilter(found2, view.state);
  if (!found2)
    return null;
  return {
    pos: start,
    end,
    above: view.state.doc.lineAt(start).to < end,
    create() {
      return { dom: diagnosticsTooltip(view, found2) };
    }
  };
}
function diagnosticsTooltip(view, diagnostics) {
  return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map((d3) => renderDiagnostic(view, d3, false)));
}
var openLintPanel = (view) => {
  let field2 = view.state.field(lintState, false);
  if (!field2 || !field2.panel)
    view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel2.of(true)]) });
  let panel = getPanel(view, LintPanel.open);
  if (panel)
    panel.dom.querySelector(".cm-panel-lint ul").focus();
  return true;
};
var closeLintPanel = (view) => {
  let field2 = view.state.field(lintState, false);
  if (!field2 || !field2.panel)
    return false;
  view.dispatch({ effects: togglePanel2.of(false) });
  return true;
};
var nextDiagnostic = (view) => {
  let field2 = view.state.field(lintState, false);
  if (!field2)
    return false;
  let sel = view.state.selection.main, next2 = findDiagnostic(field2.diagnostics, null, sel.to + 1);
  if (!next2) {
    next2 = findDiagnostic(field2.diagnostics, null, 0);
    if (!next2 || 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 lintPlugin = /* @__PURE__ */ ViewPlugin.fromClass(class {
  constructor(view) {
    this.view = view;
    this.timeout = -1;
    this.set = true;
    let { delay } = view.state.facet(lintConfig);
    this.lintTime = Date.now() + delay;
    this.run = this.run.bind(this);
    this.timeout = setTimeout(this.run, delay);
  }
  run() {
    clearTimeout(this.timeout);
    let now = Date.now();
    if (now < this.lintTime - 10) {
      this.timeout = setTimeout(this.run, this.lintTime - now);
    } else {
      this.set = false;
      let { state } = this.view, { sources } = state.facet(lintConfig);
      if (sources.length)
        batchResults(sources.map((s3) => Promise.resolve(s3(this.view))), (annotations) => {
          if (this.view.state.doc == state.doc)
            this.view.dispatch(setDiagnostics(this.view.state, annotations.reduce((a3, b3) => a3.concat(b3))));
        }, (error2) => {
          logException(this.view.state, error2);
        });
    }
  }
  update(update2) {
    let config3 = update2.state.facet(lintConfig);
    if (update2.docChanged || config3 != update2.startState.facet(lintConfig) || config3.needsRefresh && config3.needsRefresh(update2)) {
      this.lintTime = Date.now() + config3.delay;
      if (!this.set) {
        this.set = true;
        this.timeout = setTimeout(this.run, config3.delay);
      }
    }
  }
  force() {
    if (this.set) {
      this.lintTime = Date.now();
      this.run();
    }
  }
  destroy() {
    clearTimeout(this.timeout);
  }
});
function batchResults(promises, sink, error2) {
  let collected = [], timeout = -1;
  for (let p4 of promises)
    p4.then((value2) => {
      collected.push(value2);
      clearTimeout(timeout);
      if (collected.length == promises.length)
        sink(collected);
      else
        timeout = setTimeout(() => sink(collected), 200);
    }, error2);
}
var lintConfig = /* @__PURE__ */ Facet.define({
  combine(input) {
    return {
      sources: input.map((i3) => i3.source).filter((x3) => x3 != null),
      ...combineConfig(input.map((i3) => i3.config), {
        delay: 750,
        markerFilter: null,
        tooltipFilter: null,
        needsRefresh: null,
        hideOn: () => null
      }, {
        delay: Math.max,
        markerFilter: combineFilter,
        tooltipFilter: combineFilter,
        needsRefresh: (a3, b3) => !a3 ? b3 : !b3 ? a3 : (u3) => a3(u3) || b3(u3),
        hideOn: (a3, b3) => !a3 ? b3 : !b3 ? a3 : (t3, x3, y3) => a3(t3, x3, y3) || b3(t3, x3, y3),
        autoPanel: (a3, b3) => a3 || b3
      })
    };
  }
});
function combineFilter(a3, b3) {
  return !a3 ? b3 : !b3 ? a3 : (d3, s3) => b3(a3(d3, s3), s3);
}
function linter(source, config3 = {}) {
  return [
    lintConfig.of({ source, config: config3 }),
    lintPlugin,
    lintExtensions
  ];
}
function assignKeys(actions2) {
  let assigned = [];
  if (actions2)
    actions: for (let { name: name2 } of actions2) {
      for (let i3 = 0; i3 < name2.length; i3++) {
        let ch = name2[i3];
        if (/[a-zA-Z]/.test(ch) && !assigned.some((c3) => c3.toLowerCase() == ch.toLowerCase())) {
          assigned.push(ch);
          continue actions;
        }
      }
      assigned.push("");
    }
  return assigned;
}
function renderDiagnostic(view, diagnostic, inPanel) {
  var _a4;
  let keys5 = 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), (_a4 = diagnostic.actions) === null || _a4 === void 0 ? void 0 : _a4.map((action, i3) => {
    let fired = false, click = (e3) => {
      e3.preventDefault();
      if (fired)
        return;
      fired = true;
      let found2 = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
      if (found2)
        action.apply(view, found2.from, found2.to);
    };
    let { name: name2 } = action, keyIndex = keys5[i3] ? name2.indexOf(keys5[i3]) : -1;
    let nameElt = keyIndex < 0 ? name2 : [
      name2.slice(0, keyIndex),
      crelt("u", name2.slice(keyIndex, keyIndex + 1)),
      name2.slice(keyIndex + 1)
    ];
    let markClass = action.markClass ? " " + action.markClass : "";
    return crelt("button", {
      type: "button",
      class: "cm-diagnosticAction" + markClass,
      onclick: click,
      onmousedown: click,
      "aria-label": ` Action: ${name2}${keyIndex < 0 ? "" : ` (access key "${keys5[i3]})"`}.`
    }, 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.ctrlKey || event2.altKey || event2.metaKey)
        return;
      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], keys5 = assignKeys(diagnostic.actions);
        for (let i3 = 0; i3 < keys5.length; i3++)
          if (keys5[i3].toUpperCase().charCodeAt(0) == event2.keyCode) {
            let found2 = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
            if (found2)
              diagnostic.actions[i3].apply(view, found2.from, found2.to);
          }
      } else {
        return;
      }
      event2.preventDefault();
    };
    let onclick = (event2) => {
      for (let i3 = 0; i3 < this.items.length; i3++) {
        if (this.items[i3].dom.contains(event2.target))
          this.moveSelection(i3);
      }
    };
    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 i3 = 0; i3 < this.items.length; i3++)
      if (this.items[i3].diagnostic == selected.diagnostic)
        return i3;
    return -1;
  }
  update() {
    let { diagnostics, selected } = this.view.state.field(lintState);
    let i3 = 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 found2 = -1, item;
        for (let j = i3; j < this.items.length; j++)
          if (this.items[j].diagnostic == diagnostic) {
            found2 = j;
            break;
          }
        if (found2 < 0) {
          item = new PanelItem(this.view, diagnostic);
          this.items.splice(i3, 0, item);
          needsSync = true;
        } else {
          item = this.items[found2];
          if (found2 > i3) {
            this.items.splice(i3, found2 - i3);
            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");
        }
        i3++;
      }
    });
    while (i3 < 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 rm3() {
      let prev = domPos;
      domPos = prev.nextSibling;
      prev.remove();
    }
    for (let item of this.items) {
      if (item.dom.parentNode == this.list) {
        while (domPos != item.dom)
          rm3();
        domPos = item.dom.nextSibling;
      } else {
        this.list.insertBefore(item.dom, domPos);
      }
    }
    while (domPos)
      rm3();
  }
  moveSelection(selectedIndex) {
    if (this.selectedIndex < 0)
      return;
    let field2 = this.view.state.field(lintState);
    let selection = findDiagnostic(field2.diagnostics, this.items[selectedIndex].diagnostic);
    if (!selection)
      return;
    this.view.dispatch({
      selection: { anchor: selection.from, head: selection.to },
      scrollIntoView: true,
      effects: movePanelSelection.of(selection)
    });
  }
  static open(view) {
    return new _LintPanel(view);
  }
};
function svg(content2, attrs2 = `viewBox="0 0 40 40"`) {
  return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs2}>${encodeURIComponent(content2)}</svg>')`;
}
function underline(color) {
  return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
var baseTheme5 = /* @__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 d3 of diagnostics) {
    let w3 = severityWeight(d3.severity);
    if (w3 > weight) {
      weight = w3;
      sev = d3.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 mousemove = (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", mousemove);
    if (view.state.field(lintGutterTooltip))
      view.dispatch({ effects: setLintGutterTooltip.of(null) });
  };
  window.addEventListener("mousemove", mousemove);
}
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(doc4, diagnostics) {
  let byLine = /* @__PURE__ */ Object.create(null);
  for (let diagnostic of diagnostics) {
    let line = doc4.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, block3) => {
    let diagnostics = [];
    view.state.field(lintGutterMarkers).between(block3.from, block3.to, (from2, to, value2) => {
      if (from2 > block3.from && from2 < block3.to)
        diagnostics.push(...value2.diagnostics);
    });
    return diagnostics.length ? new LintGutterMarker(diagnostics) : null;
  }
});
var lintGutterMarkers = /* @__PURE__ */ StateField.define({
  create() {
    return RangeSet.empty;
  },
  update(markers, tr2) {
    markers = markers.map(tr2.changes);
    let diagnosticFilter = tr2.state.facet(lintGutterConfig).markerFilter;
    for (let effect2 of tr2.effects) {
      if (effect2.is(setDiagnosticsEffect)) {
        let diagnostics = effect2.value;
        if (diagnosticFilter)
          diagnostics = diagnosticFilter(diagnostics || [], tr2.state);
        markers = markersForDiagnostics(tr2.state.doc, diagnostics.slice(0));
      }
    }
    return markers;
  }
});
var setLintGutterTooltip = /* @__PURE__ */ StateEffect.define();
var lintGutterTooltip = /* @__PURE__ */ StateField.define({
  create() {
    return null;
  },
  update(tooltip, tr2) {
    if (tooltip && tr2.docChanged)
      tooltip = hideTooltip(tr2, tooltip) ? null : { ...tooltip, pos: tr2.changes.mapPos(tooltip.pos) };
    return tr2.effects.reduce((t3, e3) => e3.is(setLintGutterTooltip) ? e3.value : t3, tooltip);
  },
  provide: (field2) => showTooltip.from(field2)
});
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], (state) => {
    let { selected, panel } = state.field(lintState);
    return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
      activeMark.range(selected.from, selected.to)
    ]);
  }),
  /* @__PURE__ */ hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
  baseTheme5
];
var lintGutterConfig = /* @__PURE__ */ Facet.define({
  combine(configs) {
    return combineConfig(configs, {
      hoverTime: 300,
      markerFilter: null,
      tooltipFilter: null
    });
  }
});
function lintGutter(config3 = {}) {
  return [lintGutterConfig.of(config3), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}

// node_modules/@lezer/lr/dist/index.js
var Stack = class _Stack {
  /**
  @internal
  */
  constructor(p4, stack, state, reducePos, pos, score2, buffer, bufferBase, curContext, lookAhead = 0, parent) {
    this.p = p4;
    this.stack = stack;
    this.state = state;
    this.reducePos = reducePos;
    this.pos = pos;
    this.score = score2;
    this.buffer = buffer;
    this.bufferBase = bufferBase;
    this.curContext = curContext;
    this.lookAhead = lookAhead;
    this.parent = parent;
  }
  /**
  @internal
  */
  toString() {
    return `[${this.stack.filter((_5, i3) => i3 % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
  }
  // Start an empty stack
  /**
  @internal
  */
  static start(p4, state, pos = 0) {
    let cx = p4.parser.context;
    return new _Stack(p4, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
  }
  /**
  The stack's current [context](#lr.ContextTracker) value, if
  any. Its type will depend on the context tracker's type
  parameter, or it will be `null` if there is no context
  tracker.
  */
  get context() {
    return this.curContext ? this.curContext.context : null;
  }
  // Push a state onto the stack, tracking its start position as well
  // as the buffer base at that point.
  /**
  @internal
  */
  pushState(state, start) {
    this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
    this.state = state;
  }
  // Apply a reduce action
  /**
  @internal
  */
  reduce(action) {
    var _a4;
    let depth2 = action >> 19, type = action & 65535;
    let { parser: parser4 } = this.p;
    let lookaheadRecord = this.reducePos < this.pos - 25 && this.setLookAhead(this.pos);
    let dPrec = parser4.dynamicPrecedence(type);
    if (dPrec)
      this.score += dPrec;
    if (depth2 == 0) {
      this.pushState(parser4.getGoto(this.state, type, true), this.reducePos);
      if (type < parser4.minRepeatTerm)
        this.storeNode(type, this.reducePos, this.reducePos, lookaheadRecord ? 8 : 4, true);
      this.reduceContext(type, this.reducePos);
      return;
    }
    let base3 = this.stack.length - (depth2 - 1) * 3 - (action & 262144 ? 6 : 0);
    let start = base3 ? this.stack[base3 - 2] : this.p.ranges[0].from, size4 = this.reducePos - start;
    if (size4 >= 2e3 && !((_a4 = this.p.parser.nodeSet.types[type]) === null || _a4 === void 0 ? void 0 : _a4.isAnonymous)) {
      if (start == this.p.lastBigReductionStart) {
        this.p.bigReductionCount++;
        this.p.lastBigReductionSize = size4;
      } else if (this.p.lastBigReductionSize < size4) {
        this.p.bigReductionCount = 1;
        this.p.lastBigReductionStart = start;
        this.p.lastBigReductionSize = size4;
      }
    }
    let bufferBase = base3 ? this.stack[base3 - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
    if (type < parser4.minRepeatTerm || action & 131072) {
      let pos = parser4.stateFlag(
        this.state,
        1
        /* StateFlag.Skipped */
      ) ? this.pos : this.reducePos;
      this.storeNode(type, start, pos, count + 4, true);
    }
    if (action & 262144) {
      this.state = this.stack[base3];
    } else {
      let baseStateID = this.stack[base3 - 3];
      this.state = parser4.getGoto(baseStateID, type, true);
    }
    while (this.stack.length > base3)
      this.stack.pop();
    this.reduceContext(type, start);
  }
  // Shift a value into the buffer
  /**
  @internal
  */
  storeNode(term, start, end, size4 = 4, mustSink = false) {
    if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
      let cur2 = this, top2 = this.buffer.length;
      if (top2 == 0 && cur2.parent) {
        top2 = cur2.bufferBase - cur2.parent.bufferBase;
        cur2 = cur2.parent;
      }
      if (top2 > 0 && cur2.buffer[top2 - 4] == 0 && cur2.buffer[top2 - 1] > -1) {
        if (start == end)
          return;
        if (cur2.buffer[top2 - 2] >= start) {
          cur2.buffer[top2 - 2] = end;
          return;
        }
      }
    }
    if (!mustSink || this.pos == end) {
      this.buffer.push(term, start, end, size4);
    } else {
      let index2 = this.buffer.length;
      if (index2 > 0 && (this.buffer[index2 - 4] != 0 || this.buffer[index2 - 1] < 0)) {
        let mustMove = false;
        for (let scan = index2; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
          if (this.buffer[scan - 1] >= 0) {
            mustMove = true;
            break;
          }
        }
        if (mustMove)
          while (index2 > 0 && this.buffer[index2 - 2] > end) {
            this.buffer[index2] = this.buffer[index2 - 4];
            this.buffer[index2 + 1] = this.buffer[index2 - 3];
            this.buffer[index2 + 2] = this.buffer[index2 - 2];
            this.buffer[index2 + 3] = this.buffer[index2 - 1];
            index2 -= 4;
            if (size4 > 4)
              size4 -= 4;
          }
      }
      this.buffer[index2] = term;
      this.buffer[index2 + 1] = start;
      this.buffer[index2 + 2] = end;
      this.buffer[index2 + 3] = size4;
    }
  }
  // Apply a shift action
  /**
  @internal
  */
  shift(action, type, start, end) {
    if (action & 131072) {
      this.pushState(action & 65535, this.pos);
    } else if ((action & 262144) == 0) {
      let nextState = action, { parser: parser4 } = this.p;
      this.pos = end;
      let skipped = parser4.stateFlag(
        nextState,
        1
        /* StateFlag.Skipped */
      );
      if (!skipped && (end > start || type <= parser4.maxNode))
        this.reducePos = end;
      this.pushState(nextState, skipped ? start : Math.min(start, this.reducePos));
      this.shiftContext(type, start);
      if (type <= parser4.maxNode)
        this.buffer.push(type, start, end, 4);
    } else {
      this.pos = end;
      this.shiftContext(type, start);
      if (type <= this.p.parser.maxNode)
        this.buffer.push(type, start, end, 4);
    }
  }
  // Apply an action
  /**
  @internal
  */
  apply(action, next2, nextStart, nextEnd) {
    if (action & 65536)
      this.reduce(action);
    else
      this.shift(action, next2, nextStart, nextEnd);
  }
  // Add a prebuilt (reused) node into the buffer.
  /**
  @internal
  */
  useNode(value2, next2) {
    let index2 = this.p.reused.length - 1;
    if (index2 < 0 || this.p.reused[index2] != value2) {
      this.p.reused.push(value2);
      index2++;
    }
    let start = this.pos;
    this.reducePos = this.pos = start + value2.length;
    this.pushState(next2, start);
    this.buffer.push(
      index2,
      start,
      this.reducePos,
      -1
      /* size == -1 means this is a reused value */
    );
    if (this.curContext)
      this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value2, this, this.p.stream.reset(this.pos - value2.length)));
  }
  // Split the stack. Due to the buffer sharing and the fact
  // that `this.stack` tends to stay quite shallow, this isn't very
  // expensive.
  /**
  @internal
  */
  split() {
    let parent = this;
    let off = parent.buffer.length;
    while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
      off -= 4;
    let buffer = parent.buffer.slice(off), base3 = parent.bufferBase + off;
    while (parent && base3 == parent.bufferBase)
      parent = parent.parent;
    return new _Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base3, this.curContext, this.lookAhead, parent);
  }
  // Try to recover from an error by 'deleting' (ignoring) one token.
  /**
  @internal
  */
  recoverByDelete(next2, nextEnd) {
    let isNode2 = next2 <= this.p.parser.maxNode;
    if (isNode2)
      this.storeNode(next2, this.pos, nextEnd, 4);
    this.storeNode(0, this.pos, nextEnd, isNode2 ? 8 : 4);
    this.pos = this.reducePos = nextEnd;
    this.score -= 190;
  }
  /**
  Check if the given term would be able to be shifted (optionally
  after some reductions) on this stack. This can be useful for
  external tokenizers that want to make sure they only provide a
  given token when it applies.
  */
  canShift(term) {
    for (let sim = new SimulatedStack(this); ; ) {
      let action = this.p.parser.stateSlot(
        sim.state,
        4
        /* ParseState.DefaultReduce */
      ) || this.p.parser.hasAction(sim.state, term);
      if (action == 0)
        return false;
      if ((action & 65536) == 0)
        return true;
      sim.reduce(action);
    }
  }
  // Apply up to Recover.MaxNext recovery actions that conceptually
  // inserts some missing token or rule.
  /**
  @internal
  */
  recoverByInsert(next2) {
    if (this.stack.length >= 300)
      return [];
    let nextStates = this.p.parser.nextStates(this.state);
    if (nextStates.length > 4 << 1 || this.stack.length >= 120) {
      let best = [];
      for (let i3 = 0, s3; i3 < nextStates.length; i3 += 2) {
        if ((s3 = nextStates[i3 + 1]) != this.state && this.p.parser.hasAction(s3, next2))
          best.push(nextStates[i3], s3);
      }
      if (this.stack.length < 120)
        for (let i3 = 0; best.length < 4 << 1 && i3 < nextStates.length; i3 += 2) {
          let s3 = nextStates[i3 + 1];
          if (!best.some((v3, i4) => i4 & 1 && v3 == s3))
            best.push(nextStates[i3], s3);
        }
      nextStates = best;
    }
    let result2 = [];
    for (let i3 = 0; i3 < nextStates.length && result2.length < 4; i3 += 2) {
      let s3 = nextStates[i3 + 1];
      if (s3 == this.state)
        continue;
      let stack = this.split();
      stack.pushState(s3, this.pos);
      stack.storeNode(0, stack.pos, stack.pos, 4, true);
      stack.shiftContext(nextStates[i3], this.pos);
      stack.reducePos = this.pos;
      stack.score -= 200;
      result2.push(stack);
    }
    return result2;
  }
  // Force a reduce, if possible. Return false if that can't
  // be done.
  /**
  @internal
  */
  forceReduce() {
    let { parser: parser4 } = this.p;
    let reduce3 = parser4.stateSlot(
      this.state,
      5
      /* ParseState.ForcedReduce */
    );
    if ((reduce3 & 65536) == 0)
      return false;
    if (!parser4.validAction(this.state, reduce3)) {
      let depth2 = reduce3 >> 19, term = reduce3 & 65535;
      let target = this.stack.length - depth2 * 3;
      if (target < 0 || parser4.getGoto(this.stack[target], term, false) < 0) {
        let backup = this.findForcedReduction();
        if (backup == null)
          return false;
        reduce3 = backup;
      }
      this.storeNode(0, this.pos, this.pos, 4, true);
      this.score -= 100;
    }
    this.reducePos = this.pos;
    this.reduce(reduce3);
    return true;
  }
  /**
  Try to scan through the automaton to find some kind of reduction
  that can be applied. Used when the regular ForcedReduce field
  isn't a valid action. @internal
  */
  findForcedReduction() {
    let { parser: parser4 } = this.p, seen = [];
    let explore = (state, depth2) => {
      if (seen.includes(state))
        return;
      seen.push(state);
      return parser4.allActions(state, (action) => {
        if (action & (262144 | 131072)) ;
        else if (action & 65536) {
          let rDepth = (action >> 19) - depth2;
          if (rDepth > 1) {
            let term = action & 65535, target = this.stack.length - rDepth * 3;
            if (target >= 0 && parser4.getGoto(this.stack[target], term, false) >= 0)
              return rDepth << 19 | 65536 | term;
          }
        } else {
          let found2 = explore(action, depth2 + 1);
          if (found2 != null)
            return found2;
        }
      });
    };
    return explore(this.state, 0);
  }
  /**
  @internal
  */
  forceAll() {
    while (!this.p.parser.stateFlag(
      this.state,
      2
      /* StateFlag.Accepting */
    )) {
      if (!this.forceReduce()) {
        this.storeNode(0, this.pos, this.pos, 4, true);
        break;
      }
    }
    return this;
  }
  /**
  Check whether this state has no further actions (assumed to be a direct descendant of the
  top state, since any other states must be able to continue
  somehow). @internal
  */
  get deadEnd() {
    if (this.stack.length != 3)
      return false;
    let { parser: parser4 } = this.p;
    return parser4.data[parser4.stateSlot(
      this.state,
      1
      /* ParseState.Actions */
    )] == 65535 && !parser4.stateSlot(
      this.state,
      4
      /* ParseState.DefaultReduce */
    );
  }
  /**
  Restart the stack (put it back in its start state). Only safe
  when this.stack.length == 3 (state is directly below the top
  state). @internal
  */
  restart() {
    this.storeNode(0, this.pos, this.pos, 4, true);
    this.state = this.stack[0];
    this.stack.length = 0;
  }
  /**
  @internal
  */
  sameState(other) {
    if (this.state != other.state || this.stack.length != other.stack.length)
      return false;
    for (let i3 = 0; i3 < this.stack.length; i3 += 3)
      if (this.stack[i3] != other.stack[i3])
        return false;
    return true;
  }
  /**
  Get the parser used by this stack.
  */
  get parser() {
    return this.p.parser;
  }
  /**
  Test whether a given dialect (by numeric ID, as exported from
  the terms file) is enabled.
  */
  dialectEnabled(dialectID) {
    return this.p.parser.dialect.flags[dialectID];
  }
  shiftContext(term, start) {
    if (this.curContext)
      this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
  }
  reduceContext(term, start) {
    if (this.curContext)
      this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
  }
  /**
  @internal
  */
  emitContext() {
    let last3 = this.buffer.length - 1;
    if (last3 < 0 || this.buffer[last3] != -3)
      this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
  }
  /**
  @internal
  */
  emitLookAhead() {
    let last3 = this.buffer.length - 1;
    if (last3 < 0 || this.buffer[last3] != -4)
      this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
  }
  updateContext(context) {
    if (context != this.curContext.context) {
      let newCx = new StackContext(this.curContext.tracker, context);
      if (newCx.hash != this.curContext.hash)
        this.emitContext();
      this.curContext = newCx;
    }
  }
  /**
  @internal
  */
  setLookAhead(lookAhead) {
    if (lookAhead <= this.lookAhead)
      return false;
    this.emitLookAhead();
    this.lookAhead = lookAhead;
    return true;
  }
  /**
  @internal
  */
  close() {
    if (this.curContext && this.curContext.tracker.strict)
      this.emitContext();
    if (this.lookAhead > 0)
      this.emitLookAhead();
  }
};
var StackContext = class {
  constructor(tracker, context) {
    this.tracker = tracker;
    this.context = context;
    this.hash = tracker.strict ? tracker.hash(context) : 0;
  }
};
var SimulatedStack = class {
  constructor(start) {
    this.start = start;
    this.state = start.state;
    this.stack = start.stack;
    this.base = this.stack.length;
  }
  reduce(action) {
    let term = action & 65535, depth2 = action >> 19;
    if (depth2 == 0) {
      if (this.stack == this.start.stack)
        this.stack = this.stack.slice();
      this.stack.push(this.state, 0, 0);
      this.base += 3;
    } else {
      this.base -= (depth2 - 1) * 3;
    }
    let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
    this.state = goto;
  }
};
var StackBufferCursor = class _StackBufferCursor {
  constructor(stack, pos, index2) {
    this.stack = stack;
    this.pos = pos;
    this.index = index2;
    this.buffer = stack.buffer;
    if (this.index == 0)
      this.maybeNext();
  }
  static create(stack, pos = stack.bufferBase + stack.buffer.length) {
    return new _StackBufferCursor(stack, pos, pos - stack.bufferBase);
  }
  maybeNext() {
    let next2 = this.stack.parent;
    if (next2 != null) {
      this.index = this.stack.bufferBase - next2.bufferBase;
      this.stack = next2;
      this.buffer = next2.buffer;
    }
  }
  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];
  }
  next() {
    this.index -= 4;
    this.pos -= 4;
    if (this.index == 0)
      this.maybeNext();
  }
  fork() {
    return new _StackBufferCursor(this.stack, this.pos, this.index);
  }
};
function decodeArray(input, Type = Uint16Array) {
  if (typeof input != "string")
    return input;
  let array = null;
  for (let pos = 0, out = 0; pos < input.length; ) {
    let value2 = 0;
    for (; ; ) {
      let next2 = input.charCodeAt(pos++), stop = false;
      if (next2 == 126) {
        value2 = 65535;
        break;
      }
      if (next2 >= 92)
        next2--;
      if (next2 >= 34)
        next2--;
      let digit = next2 - 32;
      if (digit >= 46) {
        digit -= 46;
        stop = true;
      }
      value2 += digit;
      if (stop)
        break;
      value2 *= 46;
    }
    if (array)
      array[out++] = value2;
    else
      array = new Type(value2);
  }
  return array;
}
var CachedToken = class {
  constructor() {
    this.start = -1;
    this.value = -1;
    this.end = -1;
    this.extended = -1;
    this.lookAhead = 0;
    this.mask = 0;
    this.context = 0;
  }
};
var nullToken = new CachedToken();
var InputStream = class {
  /**
  @internal
  */
  constructor(input, ranges) {
    this.input = input;
    this.ranges = ranges;
    this.chunk = "";
    this.chunkOff = 0;
    this.chunk2 = "";
    this.chunk2Pos = 0;
    this.next = -1;
    this.token = nullToken;
    this.rangeIndex = 0;
    this.pos = this.chunkPos = ranges[0].from;
    this.range = ranges[0];
    this.end = ranges[ranges.length - 1].to;
    this.readNext();
  }
  /**
  @internal
  */
  resolveOffset(offset, assoc) {
    let range2 = this.range, index2 = this.rangeIndex;
    let pos = this.pos + offset;
    while (pos < range2.from) {
      if (!index2)
        return null;
      let next2 = this.ranges[--index2];
      pos -= range2.from - next2.to;
      range2 = next2;
    }
    while (assoc < 0 ? pos > range2.to : pos >= range2.to) {
      if (index2 == this.ranges.length - 1)
        return null;
      let next2 = this.ranges[++index2];
      pos += next2.from - range2.to;
      range2 = next2;
    }
    return pos;
  }
  /**
  @internal
  */
  clipPos(pos) {
    if (pos >= this.range.from && pos < this.range.to)
      return pos;
    for (let range2 of this.ranges)
      if (range2.to > pos)
        return Math.max(pos, range2.from);
    return this.end;
  }
  /**
  Look at a code unit near the stream position. `.peek(0)` equals
  `.next`, `.peek(-1)` gives you the previous character, and so
  on.
  
  Note that looking around during tokenizing creates dependencies
  on potentially far-away content, which may reduce the
  effectiveness incremental parsing—when looking forward—or even
  cause invalid reparses when looking backward more than 25 code
  units, since the library does not track lookbehind.
  */
  peek(offset) {
    let idx = this.chunkOff + offset, pos, result2;
    if (idx >= 0 && idx < this.chunk.length) {
      pos = this.pos + offset;
      result2 = this.chunk.charCodeAt(idx);
    } else {
      let resolved = this.resolveOffset(offset, 1);
      if (resolved == null)
        return -1;
      pos = resolved;
      if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
        result2 = this.chunk2.charCodeAt(pos - this.chunk2Pos);
      } else {
        let i3 = this.rangeIndex, range2 = this.range;
        while (range2.to <= pos)
          range2 = this.ranges[++i3];
        this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
        if (pos + this.chunk2.length > range2.to)
          this.chunk2 = this.chunk2.slice(0, range2.to - pos);
        result2 = this.chunk2.charCodeAt(0);
      }
    }
    if (pos >= this.token.lookAhead)
      this.token.lookAhead = pos + 1;
    return result2;
  }
  /**
  Accept a token. By default, the end of the token is set to the
  current stream position, but you can pass an offset (relative to
  the stream position) to change that.
  */
  acceptToken(token, endOffset = 0) {
    let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
    if (end == null || end < this.token.start)
      throw new RangeError("Token end out of bounds");
    this.token.value = token;
    this.token.end = end;
  }
  /**
  Accept a token ending at a specific given position.
  */
  acceptTokenTo(token, endPos) {
    this.token.value = token;
    this.token.end = endPos;
  }
  getChunk() {
    if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
      let { chunk: chunk2, chunkPos } = this;
      this.chunk = this.chunk2;
      this.chunkPos = this.chunk2Pos;
      this.chunk2 = chunk2;
      this.chunk2Pos = chunkPos;
      this.chunkOff = this.pos - this.chunkPos;
    } else {
      this.chunk2 = this.chunk;
      this.chunk2Pos = this.chunkPos;
      let nextChunk = this.input.chunk(this.pos);
      let end = this.pos + nextChunk.length;
      this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
      this.chunkPos = this.pos;
      this.chunkOff = 0;
    }
  }
  readNext() {
    if (this.chunkOff >= this.chunk.length) {
      this.getChunk();
      if (this.chunkOff == this.chunk.length)
        return this.next = -1;
    }
    return this.next = this.chunk.charCodeAt(this.chunkOff);
  }
  /**
  Move the stream forward N (defaults to 1) code units. Returns
  the new value of [`next`](#lr.InputStream.next).
  */
  advance(n4 = 1) {
    this.chunkOff += n4;
    while (this.pos + n4 >= this.range.to) {
      if (this.rangeIndex == this.ranges.length - 1)
        return this.setDone();
      n4 -= this.range.to - this.pos;
      this.range = this.ranges[++this.rangeIndex];
      this.pos = this.range.from;
    }
    this.pos += n4;
    if (this.pos >= this.token.lookAhead)
      this.token.lookAhead = this.pos + 1;
    return this.readNext();
  }
  setDone() {
    this.pos = this.chunkPos = this.end;
    this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
    this.chunk = "";
    return this.next = -1;
  }
  /**
  @internal
  */
  reset(pos, token) {
    if (token) {
      this.token = token;
      token.start = pos;
      token.lookAhead = pos + 1;
      token.value = token.extended = -1;
    } else {
      this.token = nullToken;
    }
    if (this.pos != pos) {
      this.pos = pos;
      if (pos == this.end) {
        this.setDone();
        return this;
      }
      while (pos < this.range.from)
        this.range = this.ranges[--this.rangeIndex];
      while (pos >= this.range.to)
        this.range = this.ranges[++this.rangeIndex];
      if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
        this.chunkOff = pos - this.chunkPos;
      } else {
        this.chunk = "";
        this.chunkOff = 0;
      }
      this.readNext();
    }
    return this;
  }
  /**
  @internal
  */
  read(from2, to) {
    if (from2 >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
      return this.chunk.slice(from2 - this.chunkPos, to - this.chunkPos);
    if (from2 >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
      return this.chunk2.slice(from2 - this.chunk2Pos, to - this.chunk2Pos);
    if (from2 >= this.range.from && to <= this.range.to)
      return this.input.read(from2, to);
    let result2 = "";
    for (let r3 of this.ranges) {
      if (r3.from >= to)
        break;
      if (r3.to > from2)
        result2 += this.input.read(Math.max(r3.from, from2), Math.min(r3.to, to));
    }
    return result2;
  }
};
var TokenGroup = class {
  constructor(data2, id) {
    this.data = data2;
    this.id = id;
  }
  token(input, stack) {
    let { parser: parser4 } = stack.p;
    readToken(this.data, input, stack, this.id, parser4.data, parser4.tokenPrecTable);
  }
};
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
var LocalTokenGroup = class {
  constructor(data2, precTable, elseToken) {
    this.precTable = precTable;
    this.elseToken = elseToken;
    this.data = typeof data2 == "string" ? decodeArray(data2) : data2;
  }
  token(input, stack) {
    let start = input.pos, skipped = 0;
    for (; ; ) {
      let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
      readToken(this.data, input, stack, 0, this.data, this.precTable);
      if (input.token.value > -1)
        break;
      if (this.elseToken == null)
        return;
      if (!atEof)
        skipped++;
      if (nextPos == null)
        break;
      input.reset(nextPos, input.token);
    }
    if (skipped) {
      input.reset(start, input.token);
      input.acceptToken(this.elseToken, skipped);
    }
  }
};
LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
function readToken(data2, input, stack, group2, precTable, precOffset) {
  let state = 0, groupMask = 1 << group2, { dialect } = stack.p.parser;
  scan: for (; ; ) {
    if ((groupMask & data2[state]) == 0)
      break;
    let accEnd = data2[state + 1];
    for (let i3 = state + 3; i3 < accEnd; i3 += 2)
      if ((data2[i3 + 1] & groupMask) > 0) {
        let term = data2[i3];
        if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
          input.acceptToken(term);
          break;
        }
      }
    let next2 = input.next, low = 0, high = data2[state + 2];
    if (input.next < 0 && high > low && data2[accEnd + high * 3 - 3] == 65535) {
      state = data2[accEnd + high * 3 - 1];
      continue scan;
    }
    for (; low < high; ) {
      let mid = low + high >> 1;
      let index2 = accEnd + mid + (mid << 1);
      let from2 = data2[index2], to = data2[index2 + 1] || 65536;
      if (next2 < from2)
        high = mid;
      else if (next2 >= to)
        low = mid + 1;
      else {
        state = data2[index2 + 2];
        input.advance();
        continue scan;
      }
    }
    break;
  }
}
function findOffset(data2, start, term) {
  for (let i3 = start, next2; (next2 = data2[i3]) != 65535; i3++)
    if (next2 == term)
      return i3 - start;
  return -1;
}
function overrides(token, prev, tableData, tableOffset) {
  let iPrev = findOffset(tableData, tableOffset, prev);
  return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
}
var verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
var stackIDs = null;
function cutAt(tree, pos, side) {
  let cursor = tree.cursor(IterMode.IncludeAnonymous);
  cursor.moveTo(pos);
  for (; ; ) {
    if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
      for (; ; ) {
        if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
          return side < 0 ? Math.max(0, Math.min(
            cursor.to - 1,
            pos - 25
            /* Lookahead.Margin */
          )) : Math.min(tree.length, Math.max(
            cursor.from + 1,
            pos + 25
            /* Lookahead.Margin */
          ));
        if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
          break;
        if (!cursor.parent())
          return side < 0 ? 0 : tree.length;
      }
  }
}
var FragmentCursor = class {
  constructor(fragments, nodeSet) {
    this.fragments = fragments;
    this.nodeSet = nodeSet;
    this.i = 0;
    this.fragment = null;
    this.safeFrom = -1;
    this.safeTo = -1;
    this.trees = [];
    this.start = [];
    this.index = [];
    this.nextFragment();
  }
  nextFragment() {
    let fr2 = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
    if (fr2) {
      this.safeFrom = fr2.openStart ? cutAt(fr2.tree, fr2.from + fr2.offset, 1) - fr2.offset : fr2.from;
      this.safeTo = fr2.openEnd ? cutAt(fr2.tree, fr2.to + fr2.offset, -1) - fr2.offset : fr2.to;
      while (this.trees.length) {
        this.trees.pop();
        this.start.pop();
        this.index.pop();
      }
      this.trees.push(fr2.tree);
      this.start.push(-fr2.offset);
      this.index.push(0);
      this.nextStart = this.safeFrom;
    } else {
      this.nextStart = 1e9;
    }
  }
  // `pos` must be >= any previously given `pos` for this cursor
  nodeAt(pos) {
    if (pos < this.nextStart)
      return null;
    while (this.fragment && this.safeTo <= pos)
      this.nextFragment();
    if (!this.fragment)
      return null;
    for (; ; ) {
      let last3 = this.trees.length - 1;
      if (last3 < 0) {
        this.nextFragment();
        return null;
      }
      let top2 = this.trees[last3], index2 = this.index[last3];
      if (index2 == top2.children.length) {
        this.trees.pop();
        this.start.pop();
        this.index.pop();
        continue;
      }
      let next2 = top2.children[index2];
      let start = this.start[last3] + top2.positions[index2];
      if (start > pos) {
        this.nextStart = start;
        return null;
      }
      if (next2 instanceof Tree) {
        if (start == pos) {
          if (start < this.safeFrom)
            return null;
          let end = start + next2.length;
          if (end <= this.safeTo) {
            let lookAhead = next2.prop(NodeProp.lookAhead);
            if (!lookAhead || end + lookAhead < this.fragment.to)
              return next2;
          }
        }
        this.index[last3]++;
        if (start + next2.length >= Math.max(this.safeFrom, pos)) {
          this.trees.push(next2);
          this.start.push(start);
          this.index.push(0);
        }
      } else {
        this.index[last3]++;
        this.nextStart = start + next2.length;
      }
    }
  }
};
var TokenCache = class {
  constructor(parser4, stream) {
    this.stream = stream;
    this.tokens = [];
    this.mainToken = null;
    this.actions = [];
    this.tokens = parser4.tokenizers.map((_5) => new CachedToken());
  }
  getActions(stack) {
    let actionIndex = 0;
    let main2 = null;
    let { parser: parser4 } = stack.p, { tokenizers } = parser4;
    let mask = parser4.stateSlot(
      stack.state,
      3
      /* ParseState.TokenizerMask */
    );
    let context = stack.curContext ? stack.curContext.hash : 0;
    let lookAhead = 0;
    for (let i3 = 0; i3 < tokenizers.length; i3++) {
      if ((1 << i3 & mask) == 0)
        continue;
      let tokenizer = tokenizers[i3], token = this.tokens[i3];
      if (main2 && !tokenizer.fallback)
        continue;
      if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
        this.updateCachedToken(token, tokenizer, stack);
        token.mask = mask;
        token.context = context;
      }
      if (token.lookAhead > token.end + 25)
        lookAhead = Math.max(token.lookAhead, lookAhead);
      if (token.value != 0) {
        let startIndex = actionIndex;
        if (token.extended > -1)
          actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
        actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
        if (!tokenizer.extend) {
          main2 = token;
          if (actionIndex > startIndex)
            break;
        }
      }
    }
    while (this.actions.length > actionIndex)
      this.actions.pop();
    if (lookAhead)
      stack.setLookAhead(lookAhead);
    if (!main2 && stack.pos == this.stream.end) {
      main2 = new CachedToken();
      main2.value = stack.p.parser.eofTerm;
      main2.start = main2.end = stack.pos;
      actionIndex = this.addActions(stack, main2.value, main2.end, actionIndex);
    }
    this.mainToken = main2;
    return this.actions;
  }
  getMainToken(stack) {
    if (this.mainToken)
      return this.mainToken;
    let main2 = new CachedToken(), { pos, p: p4 } = stack;
    main2.start = pos;
    main2.end = Math.min(pos + 1, p4.stream.end);
    main2.value = pos == p4.stream.end ? p4.parser.eofTerm : 0;
    return main2;
  }
  updateCachedToken(token, tokenizer, stack) {
    let start = this.stream.clipPos(stack.pos);
    tokenizer.token(this.stream.reset(start, token), stack);
    if (token.value > -1) {
      let { parser: parser4 } = stack.p;
      for (let i3 = 0; i3 < parser4.specialized.length; i3++)
        if (parser4.specialized[i3] == token.value) {
          let result2 = parser4.specializers[i3](this.stream.read(token.start, token.end), stack);
          if (result2 >= 0 && stack.p.parser.dialect.allows(result2 >> 1)) {
            if ((result2 & 1) == 0)
              token.value = result2 >> 1;
            else
              token.extended = result2 >> 1;
            break;
          }
        }
    } else {
      token.value = 0;
      token.end = this.stream.clipPos(start + 1);
    }
  }
  putAction(action, token, end, index2) {
    for (let i3 = 0; i3 < index2; i3 += 3)
      if (this.actions[i3] == action)
        return index2;
    this.actions[index2++] = action;
    this.actions[index2++] = token;
    this.actions[index2++] = end;
    return index2;
  }
  addActions(stack, token, end, index2) {
    let { state } = stack, { parser: parser4 } = stack.p, { data: data2 } = parser4;
    for (let set4 = 0; set4 < 2; set4++) {
      for (let i3 = parser4.stateSlot(
        state,
        set4 ? 2 : 1
        /* ParseState.Actions */
      ); ; i3 += 3) {
        if (data2[i3] == 65535) {
          if (data2[i3 + 1] == 1) {
            i3 = pair(data2, i3 + 2);
          } else {
            if (index2 == 0 && data2[i3 + 1] == 2)
              index2 = this.putAction(pair(data2, i3 + 2), token, end, index2);
            break;
          }
        }
        if (data2[i3] == token)
          index2 = this.putAction(pair(data2, i3 + 1), token, end, index2);
      }
    }
    return index2;
  }
};
var Parse = class {
  constructor(parser4, input, fragments, ranges) {
    this.parser = parser4;
    this.input = input;
    this.ranges = ranges;
    this.recovering = 0;
    this.nextStackID = 9812;
    this.minStackPos = 0;
    this.reused = [];
    this.stoppedAt = null;
    this.lastBigReductionStart = -1;
    this.lastBigReductionSize = 0;
    this.bigReductionCount = 0;
    this.stream = new InputStream(input, ranges);
    this.tokens = new TokenCache(parser4, this.stream);
    this.topTerm = parser4.top[1];
    let { from: from2 } = ranges[0];
    this.stacks = [Stack.start(this, parser4.top[0], from2)];
    this.fragments = fragments.length && this.stream.end - from2 > parser4.bufferLength * 4 ? new FragmentCursor(fragments, parser4.nodeSet) : null;
  }
  get parsedPos() {
    return this.minStackPos;
  }
  // Move the parser forward. This will process all parse stacks at
  // `this.pos` and try to advance them to a further position. If no
  // stack for such a position is found, it'll start error-recovery.
  //
  // When the parse is finished, this will return a syntax tree. When
  // not, it returns `null`.
  advance() {
    let stacks = this.stacks, pos = this.minStackPos;
    let newStacks = this.stacks = [];
    let stopped, stoppedTokens;
    if (this.bigReductionCount > 300 && stacks.length == 1) {
      let [s3] = stacks;
      while (s3.forceReduce() && s3.stack.length && s3.stack[s3.stack.length - 2] >= this.lastBigReductionStart) {
      }
      this.bigReductionCount = this.lastBigReductionSize = 0;
    }
    for (let i3 = 0; i3 < stacks.length; i3++) {
      let stack = stacks[i3];
      for (; ; ) {
        this.tokens.mainToken = null;
        if (stack.pos > pos) {
          newStacks.push(stack);
        } else if (this.advanceStack(stack, newStacks, stacks)) {
          continue;
        } else {
          if (!stopped) {
            stopped = [];
            stoppedTokens = [];
          }
          stopped.push(stack);
          let tok = this.tokens.getMainToken(stack);
          stoppedTokens.push(tok.value, tok.end);
        }
        break;
      }
    }
    if (!newStacks.length) {
      let finished = stopped && findFinished(stopped);
      if (finished) {
        if (verbose)
          console.log("Finish with " + this.stackID(finished));
        return this.stackToTree(finished);
      }
      if (this.parser.strict) {
        if (verbose && stopped)
          console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
        throw new SyntaxError("No parse at " + pos);
      }
      if (!this.recovering)
        this.recovering = 5;
    }
    if (this.recovering && stopped) {
      let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
      if (finished) {
        if (verbose)
          console.log("Force-finish " + this.stackID(finished));
        return this.stackToTree(finished.forceAll());
      }
    }
    if (this.recovering) {
      let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
      if (newStacks.length > maxRemaining) {
        newStacks.sort((a3, b3) => b3.score - a3.score);
        while (newStacks.length > maxRemaining)
          newStacks.pop();
      }
      if (newStacks.some((s3) => s3.reducePos > pos))
        this.recovering--;
    } else if (newStacks.length > 1) {
      outer: for (let i3 = 0; i3 < newStacks.length - 1; i3++) {
        let stack = newStacks[i3];
        for (let j = i3 + 1; j < newStacks.length; j++) {
          let other = newStacks[j];
          if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) {
            if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) {
              newStacks.splice(j--, 1);
            } else {
              newStacks.splice(i3--, 1);
              continue outer;
            }
          }
        }
      }
      if (newStacks.length > 12) {
        newStacks.sort((a3, b3) => b3.score - a3.score);
        newStacks.splice(
          12,
          newStacks.length - 12
          /* Rec.MaxStackCount */
        );
      }
    }
    this.minStackPos = newStacks[0].pos;
    for (let i3 = 1; i3 < newStacks.length; i3++)
      if (newStacks[i3].pos < this.minStackPos)
        this.minStackPos = newStacks[i3].pos;
    return null;
  }
  stopAt(pos) {
    if (this.stoppedAt != null && this.stoppedAt < pos)
      throw new RangeError("Can't move stoppedAt forward");
    this.stoppedAt = pos;
  }
  // Returns an updated version of the given stack, or null if the
  // stack can't advance normally. When `split` and `stacks` are
  // given, stacks split off by ambiguous operations will be pushed to
  // `split`, or added to `stacks` if they move `pos` forward.
  advanceStack(stack, stacks, split3) {
    let start = stack.pos, { parser: parser4 } = this;
    let base3 = verbose ? this.stackID(stack) + " -> " : "";
    if (this.stoppedAt != null && start > this.stoppedAt)
      return stack.forceReduce() ? stack : null;
    if (this.fragments) {
      let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
      for (let cached = this.fragments.nodeAt(start); cached; ) {
        let match2 = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser4.getGoto(stack.state, cached.type.id) : -1;
        if (match2 > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
          stack.useNode(cached, match2);
          if (verbose)
            console.log(base3 + this.stackID(stack) + ` (via reuse of ${parser4.getName(cached.type.id)})`);
          return true;
        }
        if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
          break;
        let inner = cached.children[0];
        if (inner instanceof Tree && cached.positions[0] == 0)
          cached = inner;
        else
          break;
      }
    }
    let defaultReduce = parser4.stateSlot(
      stack.state,
      4
      /* ParseState.DefaultReduce */
    );
    if (defaultReduce > 0) {
      stack.reduce(defaultReduce);
      if (verbose)
        console.log(base3 + this.stackID(stack) + ` (via always-reduce ${parser4.getName(
          defaultReduce & 65535
          /* Action.ValueMask */
        )})`);
      return true;
    }
    if (stack.stack.length >= 8400) {
      while (stack.stack.length > 6e3 && stack.forceReduce()) {
      }
    }
    let actions2 = this.tokens.getActions(stack);
    for (let i3 = 0; i3 < actions2.length; ) {
      let action = actions2[i3++], term = actions2[i3++], end = actions2[i3++];
      let last3 = i3 == actions2.length || !split3;
      let localStack = last3 ? stack : stack.split();
      let main2 = this.tokens.mainToken;
      localStack.apply(action, term, main2 ? main2.start : localStack.pos, end);
      if (verbose)
        console.log(base3 + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser4.getName(
          action & 65535
          /* Action.ValueMask */
        )}`} for ${parser4.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
      if (last3)
        return true;
      else if (localStack.pos > start)
        stacks.push(localStack);
      else
        split3.push(localStack);
    }
    return false;
  }
  // Advance a given stack forward as far as it will go. Returns the
  // (possibly updated) stack if it got stuck, or null if it moved
  // forward and was given to `pushStackDedup`.
  advanceFully(stack, newStacks) {
    let pos = stack.pos;
    for (; ; ) {
      if (!this.advanceStack(stack, null, null))
        return false;
      if (stack.pos > pos) {
        pushStackDedup(stack, newStacks);
        return true;
      }
    }
  }
  runRecovery(stacks, tokens, newStacks) {
    let finished = null, restarted = false;
    for (let i3 = 0; i3 < stacks.length; i3++) {
      let stack = stacks[i3], token = tokens[i3 << 1], tokenEnd = tokens[(i3 << 1) + 1];
      let base3 = verbose ? this.stackID(stack) + " -> " : "";
      if (stack.deadEnd) {
        if (restarted)
          continue;
        restarted = true;
        stack.restart();
        if (verbose)
          console.log(base3 + this.stackID(stack) + " (restarted)");
        let done = this.advanceFully(stack, newStacks);
        if (done)
          continue;
      }
      let force = stack.split(), forceBase = base3;
      for (let j = 0; j < 10 && force.forceReduce(); j++) {
        if (verbose)
          console.log(forceBase + this.stackID(force) + " (via force-reduce)");
        let done = this.advanceFully(force, newStacks);
        if (done)
          break;
        if (verbose)
          forceBase = this.stackID(force) + " -> ";
      }
      for (let insert4 of stack.recoverByInsert(token)) {
        if (verbose)
          console.log(base3 + this.stackID(insert4) + " (via recover-insert)");
        this.advanceFully(insert4, newStacks);
      }
      if (this.stream.end > stack.pos) {
        if (tokenEnd == stack.pos) {
          tokenEnd++;
          token = 0;
        }
        stack.recoverByDelete(token, tokenEnd);
        if (verbose)
          console.log(base3 + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
        pushStackDedup(stack, newStacks);
      } else if (!finished || finished.score < force.score) {
        finished = force;
      }
    }
    return finished;
  }
  // Convert the stack's buffer to a syntax tree.
  stackToTree(stack) {
    stack.close();
    return Tree.build({
      buffer: StackBufferCursor.create(stack),
      nodeSet: this.parser.nodeSet,
      topID: this.topTerm,
      maxBufferLength: this.parser.bufferLength,
      reused: this.reused,
      start: this.ranges[0].from,
      length: stack.pos - this.ranges[0].from,
      minRepeatType: this.parser.minRepeatTerm
    });
  }
  stackID(stack) {
    let id = (stackIDs || (stackIDs = /* @__PURE__ */ new WeakMap())).get(stack);
    if (!id)
      stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
    return id + stack;
  }
};
function pushStackDedup(stack, newStacks) {
  for (let i3 = 0; i3 < newStacks.length; i3++) {
    let other = newStacks[i3];
    if (other.pos == stack.pos && other.sameState(stack)) {
      if (newStacks[i3].score < stack.score)
        newStacks[i3] = stack;
      return;
    }
  }
  newStacks.push(stack);
}
var Dialect = class {
  constructor(source, flags, disabled) {
    this.source = source;
    this.flags = flags;
    this.disabled = disabled;
  }
  allows(term) {
    return !this.disabled || this.disabled[term] == 0;
  }
};
var LRParser = class _LRParser extends Parser2 {
  /**
  @internal
  */
  constructor(spec) {
    super();
    this.wrappers = [];
    if (spec.version != 14)
      throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14})`);
    let nodeNames = spec.nodeNames.split(" ");
    this.minRepeatTerm = nodeNames.length;
    for (let i3 = 0; i3 < spec.repeatNodeCount; i3++)
      nodeNames.push("");
    let topTerms = Object.keys(spec.topRules).map((r3) => spec.topRules[r3][1]);
    let nodeProps = [];
    for (let i3 = 0; i3 < nodeNames.length; i3++)
      nodeProps.push([]);
    function setProp(nodeID, prop2, value2) {
      nodeProps[nodeID].push([prop2, prop2.deserialize(String(value2))]);
    }
    if (spec.nodeProps)
      for (let propSpec of spec.nodeProps) {
        let prop2 = propSpec[0];
        if (typeof prop2 == "string")
          prop2 = NodeProp[prop2];
        for (let i3 = 1; i3 < propSpec.length; ) {
          let next2 = propSpec[i3++];
          if (next2 >= 0) {
            setProp(next2, prop2, propSpec[i3++]);
          } else {
            let value2 = propSpec[i3 + -next2];
            for (let j = -next2; j > 0; j--)
              setProp(propSpec[i3++], prop2, value2);
            i3++;
          }
        }
      }
    this.nodeSet = new NodeSet(nodeNames.map((name2, i3) => NodeType2.define({
      name: i3 >= this.minRepeatTerm ? void 0 : name2,
      id: i3,
      props: nodeProps[i3],
      top: topTerms.indexOf(i3) > -1,
      error: i3 == 0,
      skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i3) > -1
    })));
    if (spec.propSources)
      this.nodeSet = this.nodeSet.extend(...spec.propSources);
    this.strict = false;
    this.bufferLength = DefaultBufferLength;
    let tokenArray = decodeArray(spec.tokenData);
    this.context = spec.context;
    this.specializerSpecs = spec.specialized || [];
    this.specialized = new Uint16Array(this.specializerSpecs.length);
    for (let i3 = 0; i3 < this.specializerSpecs.length; i3++)
      this.specialized[i3] = this.specializerSpecs[i3].term;
    this.specializers = this.specializerSpecs.map(getSpecializer);
    this.states = decodeArray(spec.states, Uint32Array);
    this.data = decodeArray(spec.stateData);
    this.goto = decodeArray(spec.goto);
    this.maxTerm = spec.maxTerm;
    this.tokenizers = spec.tokenizers.map((value2) => typeof value2 == "number" ? new TokenGroup(tokenArray, value2) : value2);
    this.topRules = spec.topRules;
    this.dialects = spec.dialects || {};
    this.dynamicPrecedences = spec.dynamicPrecedences || null;
    this.tokenPrecTable = spec.tokenPrec;
    this.termNames = spec.termNames || null;
    this.maxNode = this.nodeSet.types.length - 1;
    this.dialect = this.parseDialect();
    this.top = this.topRules[Object.keys(this.topRules)[0]];
  }
  createParse(input, fragments, ranges) {
    let parse4 = new Parse(this, input, fragments, ranges);
    for (let w3 of this.wrappers)
      parse4 = w3(parse4, input, fragments, ranges);
    return parse4;
  }
  /**
  Get a goto table entry @internal
  */
  getGoto(state, term, loose = false) {
    let table2 = this.goto;
    if (term >= table2[0])
      return -1;
    for (let pos = table2[term + 1]; ; ) {
      let groupTag = table2[pos++], last3 = groupTag & 1;
      let target = table2[pos++];
      if (last3 && loose)
        return target;
      for (let end = pos + (groupTag >> 1); pos < end; pos++)
        if (table2[pos] == state)
          return target;
      if (last3)
        return -1;
    }
  }
  /**
  Check if this state has an action for a given terminal @internal
  */
  hasAction(state, terminal) {
    let data2 = this.data;
    for (let set4 = 0; set4 < 2; set4++) {
      for (let i3 = this.stateSlot(
        state,
        set4 ? 2 : 1
        /* ParseState.Actions */
      ), next2; ; i3 += 3) {
        if ((next2 = data2[i3]) == 65535) {
          if (data2[i3 + 1] == 1)
            next2 = data2[i3 = pair(data2, i3 + 2)];
          else if (data2[i3 + 1] == 2)
            return pair(data2, i3 + 2);
          else
            break;
        }
        if (next2 == terminal || next2 == 0)
          return pair(data2, i3 + 1);
      }
    }
    return 0;
  }
  /**
  @internal
  */
  stateSlot(state, slot) {
    return this.states[state * 6 + slot];
  }
  /**
  @internal
  */
  stateFlag(state, flag) {
    return (this.stateSlot(
      state,
      0
      /* ParseState.Flags */
    ) & flag) > 0;
  }
  /**
  @internal
  */
  validAction(state, action) {
    return !!this.allActions(state, (a3) => a3 == action ? true : null);
  }
  /**
  @internal
  */
  allActions(state, action) {
    let deflt = this.stateSlot(
      state,
      4
      /* ParseState.DefaultReduce */
    );
    let result2 = deflt ? action(deflt) : void 0;
    for (let i3 = this.stateSlot(
      state,
      1
      /* ParseState.Actions */
    ); result2 == null; i3 += 3) {
      if (this.data[i3] == 65535) {
        if (this.data[i3 + 1] == 1)
          i3 = pair(this.data, i3 + 2);
        else
          break;
      }
      result2 = action(pair(this.data, i3 + 1));
    }
    return result2;
  }
  /**
  Get the states that can follow this one through shift actions or
  goto jumps. @internal
  */
  nextStates(state) {
    let result2 = [];
    for (let i3 = this.stateSlot(
      state,
      1
      /* ParseState.Actions */
    ); ; i3 += 3) {
      if (this.data[i3] == 65535) {
        if (this.data[i3 + 1] == 1)
          i3 = pair(this.data, i3 + 2);
        else
          break;
      }
      if ((this.data[i3 + 2] & 65536 >> 16) == 0) {
        let value2 = this.data[i3 + 1];
        if (!result2.some((v3, i4) => i4 & 1 && v3 == value2))
          result2.push(this.data[i3], value2);
      }
    }
    return result2;
  }
  /**
  Configure the parser. Returns a new parser instance that has the
  given settings modified. Settings not provided in `config` are
  kept from the original parser.
  */
  configure(config3) {
    let copy2 = Object.assign(Object.create(_LRParser.prototype), this);
    if (config3.props)
      copy2.nodeSet = this.nodeSet.extend(...config3.props);
    if (config3.top) {
      let info = this.topRules[config3.top];
      if (!info)
        throw new RangeError(`Invalid top rule name ${config3.top}`);
      copy2.top = info;
    }
    if (config3.tokenizers)
      copy2.tokenizers = this.tokenizers.map((t3) => {
        let found2 = config3.tokenizers.find((r3) => r3.from == t3);
        return found2 ? found2.to : t3;
      });
    if (config3.specializers) {
      copy2.specializers = this.specializers.slice();
      copy2.specializerSpecs = this.specializerSpecs.map((s3, i3) => {
        let found2 = config3.specializers.find((r3) => r3.from == s3.external);
        if (!found2)
          return s3;
        let spec = Object.assign(Object.assign({}, s3), { external: found2.to });
        copy2.specializers[i3] = getSpecializer(spec);
        return spec;
      });
    }
    if (config3.contextTracker)
      copy2.context = config3.contextTracker;
    if (config3.dialect)
      copy2.dialect = this.parseDialect(config3.dialect);
    if (config3.strict != null)
      copy2.strict = config3.strict;
    if (config3.wrap)
      copy2.wrappers = copy2.wrappers.concat(config3.wrap);
    if (config3.bufferLength != null)
      copy2.bufferLength = config3.bufferLength;
    return copy2;
  }
  /**
  Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
  are registered for this parser.
  */
  hasWrappers() {
    return this.wrappers.length > 0;
  }
  /**
  Returns the name associated with a given term. This will only
  work for all terms when the parser was generated with the
  `--names` option. By default, only the names of tagged terms are
  stored.
  */
  getName(term) {
    return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
  }
  /**
  The eof term id is always allocated directly after the node
  types. @internal
  */
  get eofTerm() {
    return this.maxNode + 1;
  }
  /**
  The type of top node produced by the parser.
  */
  get topNode() {
    return this.nodeSet.types[this.top[1]];
  }
  /**
  @internal
  */
  dynamicPrecedence(term) {
    let prec2 = this.dynamicPrecedences;
    return prec2 == null ? 0 : prec2[term] || 0;
  }
  /**
  @internal
  */
  parseDialect(dialect) {
    let values2 = Object.keys(this.dialects), flags = values2.map(() => false);
    if (dialect)
      for (let part of dialect.split(" ")) {
        let id = values2.indexOf(part);
        if (id >= 0)
          flags[id] = true;
      }
    let disabled = null;
    for (let i3 = 0; i3 < values2.length; i3++)
      if (!flags[i3]) {
        for (let j = this.dialects[values2[i3]], id; (id = this.data[j++]) != 65535; )
          (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
      }
    return new Dialect(dialect, flags, disabled);
  }
  /**
  Used by the output of the parser generator. Not available to
  user code. @hide
  */
  static deserialize(spec) {
    return new _LRParser(spec);
  }
};
function pair(data2, off) {
  return data2[off] | data2[off + 1] << 16;
}
function findFinished(stacks) {
  let best = null;
  for (let stack of stacks) {
    let stopped = stack.p.stoppedAt;
    if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(
      stack.state,
      2
      /* StateFlag.Accepting */
    ) && (!best || best.score < stack.score))
      best = stack;
  }
  return best;
}
function getSpecializer(spec) {
  if (spec.external) {
    let mask = spec.extend ? 1 : 0;
    return (value2, stack) => spec.external(value2, stack) << 1 | mask;
  }
  return spec.get;
}

// node_modules/@lezer/json/dist/index.js
var jsonHighlighting = styleTags({
  String: tags.string,
  Number: tags.number,
  "True False": tags.bool,
  PropertyName: tags.propertyName,
  Null: tags.null,
  ", :": tags.separator,
  "[ ]": tags.squareBracket,
  "{ }": tags.brace
});
var parser2 = LRParser.deserialize({
  version: 14,
  states: "$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#ClOOQO'#Cr'#CrQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CtOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59W,59WO!iQPO,59WOVQPO,59QOqQPO'#CmO!nQPO,59`OOQO1G.k1G.kOVQPO'#CnO!vQPO,59aOOQO1G.r1G.rOOQO1G.l1G.lOOQO,59X,59XOOQO-E6k-E6kOOQO,59Y,59YOOQO-E6l-E6l",
  stateData: "#O~OeOS~OQSORSOSSOTSOWQO_ROgPO~OVXOgUO~O^[O~PVO[^O~O]_OVhX~OVaO~O]bO^iX~O^dO~O]_OVha~O]bO^ia~O",
  goto: "!kjPPPPPPkPPkqwPPPPk{!RPPP!XP!e!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",
  nodeNames: "\u26A0 JsonText True False Null Number String } { Object Property PropertyName : , ] [ Array",
  maxTerm: 25,
  nodeProps: [
    ["isolate", -2, 6, 11, ""],
    ["openedBy", 7, "{", 14, "["],
    ["closedBy", 8, "}", 15, "]"]
  ],
  propSources: [jsonHighlighting],
  skippedNodes: [0],
  repeatNodeCount: 2,
  tokenData: "(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oe~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Og~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zO]~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yO[~~'OO_~~'TO^~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",
  tokenizers: [0],
  topRules: { "JsonText": [0, 1] },
  tokenPrec: 0
});

// node_modules/@codemirror/lang-json/dist/index.js
var jsonParseLinter = () => (view) => {
  try {
    JSON.parse(view.state.doc.toString());
  } catch (e3) {
    if (!(e3 instanceof SyntaxError))
      throw e3;
    const pos = getErrorPosition(e3, view.state.doc);
    return [{
      from: pos,
      message: e3.message,
      severity: "error",
      to: pos
    }];
  }
  return [];
};
function getErrorPosition(error2, doc4) {
  let m3;
  if (m3 = error2.message.match(/at position (\d+)/))
    return Math.min(+m3[1], doc4.length);
  if (m3 = error2.message.match(/at line (\d+) column (\d+)/))
    return Math.min(doc4.line(+m3[1]).from + +m3[2] - 1, doc4.length);
  return 0;
}
var jsonLanguage = /* @__PURE__ */ LRLanguage.define({
  name: "json",
  parser: /* @__PURE__ */ parser2.configure({
    props: [
      /* @__PURE__ */ indentNodeProp.add({
        Object: /* @__PURE__ */ continuedIndent({ except: /^\s*\}/ }),
        Array: /* @__PURE__ */ continuedIndent({ except: /^\s*\]/ })
      }),
      /* @__PURE__ */ foldNodeProp.add({
        "Object Array": foldInside
      })
    ]
  }),
  languageData: {
    closeBrackets: { brackets: ["[", "{", '"'] },
    indentOnInput: /^\s*[\}\]]$/
  }
});
function json() {
  return new LanguageSupport(jsonLanguage);
}

// node_modules/codemirror-json-schema/dist/utils/debug.js
var import_loglevel = __toESM(require_loglevel(), 1);
import_loglevel.default.setLevel(true ? "silent" : "debug");
var debug = import_loglevel.default;

// node_modules/codemirror-json-schema/dist/constants.js
var TOKENS = {
  STRING: "String",
  NUMBER: "Number",
  TRUE: "True",
  FALSE: "False",
  NULL: "Null",
  OBJECT: "Object",
  ARRAY: "Array",
  PROPERTY: "Property",
  PROPERTY_NAME: "PropertyName",
  PROPERTY_COLON: "PropertyColon",
  // used in json5 grammar
  ITEM: "Item",
  // used in yaml grammar
  JSON_TEXT: "JsonText",
  INVALID: "\u26A0"
};
var YAML_TOKENS_MAPPING = {
  Pair: TOKENS.PROPERTY,
  Key: TOKENS.PROPERTY_NAME,
  BlockSequence: TOKENS.ARRAY,
  BlockMapping: TOKENS.OBJECT,
  FlowSequence: TOKENS.ARRAY,
  FlowMapping: TOKENS.OBJECT,
  QuotedLiteral: TOKENS.STRING,
  Literal: TOKENS.STRING,
  // best guess
  Stream: TOKENS.JSON_TEXT,
  Document: TOKENS.OBJECT
};
var JSON5_TOKENS_MAPPING = {
  File: TOKENS.JSON_TEXT
};
var PRIMITIVE_TYPES = [
  TOKENS.STRING,
  TOKENS.NUMBER,
  TOKENS.TRUE,
  TOKENS.FALSE,
  TOKENS.NULL
];
var COMPLEX_TYPES = [TOKENS.OBJECT, TOKENS.ARRAY, TOKENS.ITEM];
var MODES = {
  JSON5: "json5",
  JSON: "json4",
  YAML: "yaml"
};

// node_modules/codemirror-json-schema/dist/utils/json-pointers.js
var resolveTokenName = (nodeName, mode) => {
  var _a4, _b;
  switch (mode) {
    case MODES.YAML:
      return (_a4 = YAML_TOKENS_MAPPING[nodeName]) !== null && _a4 !== void 0 ? _a4 : nodeName;
    case MODES.JSON5:
      return (_b = JSON5_TOKENS_MAPPING[nodeName]) !== null && _b !== void 0 ? _b : nodeName;
    default:
      return nodeName;
  }
};
function getJsonPointerAt(docText, node, mode) {
  const path = [];
  for (let n4 = node; n4 === null || n4 === void 0 ? void 0 : n4.parent; n4 = n4.parent) {
    switch (resolveTokenName(n4.parent.name, mode)) {
      case TOKENS.PROPERTY: {
        const name2 = getMatchingChildNode(n4.parent, TOKENS.PROPERTY_NAME, mode);
        if (name2) {
          let word = getWord(docText, name2).replace(/[/~]/g, (v3) => v3 === "~" ? "~0" : "~1");
          path.unshift(word);
        }
        break;
      }
      case TOKENS.ARRAY: {
        if (isValueNode(n4, mode)) {
          const index2 = findNodeIndexInArrayNode(n4.parent, n4, mode);
          path.unshift(`${index2}`);
        }
        break;
      }
    }
  }
  if (path.length === 0) {
    return "";
  }
  return "/" + path.join("/");
}
var jsonPointerForPosition = (state, pos, side = -1, mode) => {
  return getJsonPointerAt(state.doc, syntaxTree(state).resolve(pos, side), mode);
};
var getJsonPointers = (state, mode) => {
  const tree = syntaxTree(state);
  const pointers = /* @__PURE__ */ new Map();
  tree.iterate({
    enter: (type) => {
      var _a4, _b, _c, _d, _e, _f, _g, _h;
      if ([TOKENS.PROPERTY_NAME, TOKENS.OBJECT].includes(resolveTokenName(type.name, mode))) {
        const pointer = getJsonPointerAt(state.doc, type.node, mode);
        const { from: keyFrom, to: keyTo } = type.node;
        if (!((_b = (_a4 = type.node) === null || _a4 === void 0 ? void 0 : _a4.nextSibling) === null || _b === void 0 ? void 0 : _b.node)) {
          pointers.set(pointer, { keyFrom, keyTo });
          return true;
        }
        const nextNode = mode === MODES.JSON ? (_d = (_c = type.node) === null || _c === void 0 ? void 0 : _c.nextSibling) === null || _d === void 0 ? void 0 : _d.node : (_h = (_g = (_f = (_e = type.node) === null || _e === void 0 ? void 0 : _e.nextSibling) === null || _f === void 0 ? void 0 : _f.node) === null || _g === void 0 ? void 0 : _g.nextSibling) === null || _h === void 0 ? void 0 : _h.node;
        if (!nextNode) {
          pointers.set(pointer, { keyFrom, keyTo });
          return true;
        }
        const { from: valueFrom, to: valueTo } = nextNode;
        pointers.set(pointer, { keyFrom, keyTo, valueFrom, valueTo });
        return true;
      }
    }
  });
  return pointers;
};

// node_modules/codemirror-json-schema/dist/utils/node.js
var getNodeAtPosition = (state, pos, side = -1) => {
  return syntaxTree(state).resolveInner(pos, side);
};
var stripSurroundingQuotes = (str) => {
  return str.replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
};
var surroundingDoubleQuotesToSingle = (str) => {
  return str.replace(/^"(.*)"$/, "'$1'");
};
var getWord = (doc4, node, stripQuotes = true, onlyEvenQuotes = true) => {
  const word = node ? doc4.sliceString(node.from, node.to) : "";
  if (!stripQuotes) {
    return word;
  }
  if (onlyEvenQuotes) {
    return stripSurroundingQuotes(word);
  }
  return word.replace(/(^["'])|(["']$)/g, "");
};
var isInvalidValueNode = (node, mode) => {
  var _a4, _b, _c, _d;
  return resolveTokenName(node.name, mode) === TOKENS.INVALID && (resolveTokenName((_b = (_a4 = node.prevSibling) === null || _a4 === void 0 ? void 0 : _a4.name) !== null && _b !== void 0 ? _b : "", mode) === TOKENS.PROPERTY_NAME || resolveTokenName((_d = (_c = node.prevSibling) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : "", mode) === TOKENS.PROPERTY_COLON);
};
var isPrimitiveValueNode = (node, mode) => {
  return PRIMITIVE_TYPES.includes(resolveTokenName(node.name, mode)) || isInvalidValueNode(node, mode);
};
var isValueNode = (node, mode) => {
  return [...PRIMITIVE_TYPES, ...COMPLEX_TYPES].includes(resolveTokenName(node.name, mode)) || isInvalidValueNode(node, mode);
};
var isPropertyNameNode = (node, mode) => {
  var _a4, _b, _c, _d, _e, _f;
  return resolveTokenName(node.name, mode) === TOKENS.PROPERTY_NAME || resolveTokenName(node.name, mode) === TOKENS.INVALID && (resolveTokenName((_b = (_a4 = node.prevSibling) === null || _a4 === void 0 ? void 0 : _a4.name) !== null && _b !== void 0 ? _b : "", mode) === TOKENS.PROPERTY || resolveTokenName((_d = (_c = node.prevSibling) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : "", mode) === "{") || // TODO: Can we make this work without checking for the mode?
  mode === MODES.YAML && resolveTokenName((_f = (_e = node.parent) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : "", mode) === TOKENS.OBJECT;
};
var getChildrenNodes = (node) => {
  const children2 = [];
  let child = node.firstChild;
  while (child) {
    if (child) {
      children2.push(child);
    }
    child = child === null || child === void 0 ? void 0 : child.nextSibling;
  }
  return children2;
};
var getMatchingChildrenNodes = (node, nodeName, mode) => {
  return getChildrenNodes(node).filter((n4) => resolveTokenName(n4.name, mode) === nodeName);
};
var getMatchingChildNode = (node, nodeName, mode) => {
  var _a4;
  return (_a4 = getChildrenNodes(node).find((n4) => resolveTokenName(n4.name, mode) === nodeName)) !== null && _a4 !== void 0 ? _a4 : null;
};
var getChildValueNode = (node, mode) => {
  return getChildrenNodes(node).find((n4) => isPrimitiveValueNode(n4, mode));
};
var getArrayNodeChildren = (node, mode) => {
  return getChildrenNodes(node).filter((n4) => PRIMITIVE_TYPES.includes(resolveTokenName(n4.name, mode)) || COMPLEX_TYPES.includes(resolveTokenName(n4.name, mode)));
};
var findNodeIndexInArrayNode = (arrayNode, valueNode, mode) => {
  return getArrayNodeChildren(arrayNode, mode).findIndex((nd) => nd.from === valueNode.from && nd.to === valueNode.to);
};
var getClosestNode = (node, nodeName, mode, depth2 = Infinity) => {
  let n4 = node;
  while (n4 && depth2 > 0) {
    if (resolveTokenName(n4.name, mode) === nodeName) {
      return n4;
    }
    n4 = n4.parent;
    depth2--;
  }
  return null;
};

// node_modules/codemirror-json-schema/dist/features/state.js
var schemaEffect = StateEffect.define();
var schemaStateField = StateField.define({
  create() {
  },
  update(schema7, tr2) {
    for (const e3 of tr2.effects) {
      if (e3.is(schemaEffect)) {
        return e3.value;
      }
    }
    return schema7;
  }
});
var getJSONSchema = (state) => {
  return state.field(schemaStateField);
};
var stateExtensions = (schema7) => [
  schemaStateField.init(() => schema7)
];

// node_modules/json-schema-library/dist/module/lib/config/strings.js
var strings_default = {
  // validation errors
  AdditionalItemsError: "Array at `{{pointer}}` may not have an additional item `{{key}}`",
  AdditionalPropertiesError: "Additional property `{{property}}` on `{{pointer}}` does not match schema `{{schema}}`",
  AllOfError: "Value `{{value}}` at `{{pointer}}` does not match schema of `{{allOf}}`",
  AnyOfError: "Value `{{value}}` at `{{pointer}}` does not match any schema of `{{anyOf}}`",
  ConstError: "Expected value at `{{pointer}}` to be `{{expected}}`, but value given is `{{value}}`",
  containsAnyError: "The array at `{{pointer}}` must contain at least one item",
  ContainsArrayError: "The property at `{{pointer}}` must not be an array",
  ContainsError: "The array at `{{pointer}}` must contain an element that matches `{{schema}}`",
  EnumError: "Expected given value `{{value}}` in `{{pointer}}` to be one of `{{values}}`",
  ForbiddenPropertyError: "Property name `{{property}}` at `{{pointer}}` is not allowed",
  FormatDateError: "Value `{{value}}` at `{{pointer}}` is not a valid date",
  FormatDateTimeError: "Value `{{value}}` at `{{pointer}}` is not a valid date-time",
  FormatEmailError: "Value `{{value}}` at `{{pointer}}` is not a valid email",
  FormatHostnameError: "Value `{{value}}` at `{{pointer}}` is not a valid hostname",
  FormatIPV4Error: "Value `{{value}}` at `{{pointer}}` is not a valid IPv4 address",
  FormatIPV4LeadingZeroError: "IPv4 addresses starting with zero are invalid, since they are interpreted as octals",
  FormatIPV6Error: "Value `{{value}}` at `{{pointer}}` is not a valid IPv6 address",
  FormatIPV6LeadingZeroError: "IPv6 addresses starting with zero are invalid, since they are interpreted as octals",
  FormatJsonPointerError: "Value `{{value}}` at `{{pointer}}` is not a valid json-pointer",
  FormatRegExError: "Value `{{value}}` at `{{pointer}}` is not a valid regular expression",
  FormatTimeError: "Value `{{value}}` at `{{pointer}}` is not a valid time",
  FormatURIError: "Value `{{value}}` at `{{pointer}}` is not a valid uri",
  FormatURIReferenceError: "Value `{{value}}` at `{{pointer}}` is not a valid uri-reference",
  FormatURITemplateError: "Value `{{value}}` at `{{pointer}}` is not a valid uri-template",
  FormatURLError: "Value `{{value}}` at `{{pointer}}` is not a valid url",
  InvalidDataError: "No value may be specified in `{{pointer}}`",
  InvalidPropertyNameError: "Invalid property name `{{property}}` at `{{pointer}}`",
  MaximumError: "Value in `{{pointer}}` is `{{length}}`, but should be `{{maximum}}` at maximum",
  MaxItemsError: "Too many items in `{{pointer}}`, should be `{{maximum}}` at most, but got `{{length}}`",
  MaxLengthError: "Value `{{pointer}}` should have a maximum length of `{{maxLength}}`, but got `{{length}}`.",
  MaxPropertiesError: "Too many properties in `{{pointer}}`, should be `{{maximum}}` at most, but got `{{length}}`",
  MinimumError: "Value in `{{pointer}}` is `{{length}}`, but should be `{{minimum}}` at minimum",
  MinItemsError: "Too few items in `{{pointer}}`, should be at least `{{minItems}}`, but got `{{length}}`",
  MinItemsOneError: "At least one item is required in `{{pointer}}`",
  MinLengthError: "Value `{{pointer}}` should have a minimum length of `{{minLength}}`, but got `{{length}}`.",
  MinLengthOneError: "A value is required in `{{pointer}}`",
  MinPropertiesError: "Too few properties in `{{pointer}}`, should be at least `{{minimum}}`, but got `{{length}}`",
  MissingDependencyError: "The required propery '{{missingProperty}}' in `{{pointer}}` is missing",
  MissingOneOfPropertyError: "Value at `{{pointer}}` property: `{{property}}`",
  MultipleOfError: "Expected `{{value}}` in `{{pointer}}` to be multiple of `{{multipleOf}}`",
  MultipleOneOfError: "Value `{{value}}` should not match multiple schemas in oneOf `{{matches}}`",
  NoAdditionalPropertiesError: "Additional property `{{property}}` in `{{pointer}}` is not allowed",
  NotError: "Value `{{value}}` at pointer should not match schema `{{not}}`",
  OneOfError: "Value `{{value}}` in `{{pointer}}` does not match any given oneof schema",
  OneOfPropertyError: "Failed finding a matching oneOfProperty schema in `{{pointer}}` where `{{property}}` matches `{{value}}`",
  PatternError: "Value in `{{pointer}}` should match `{{description}}`, but received `{{received}}`",
  PatternPropertiesError: "Property `{{key}}` does not match any patterns in `{{pointer}}`. Valid patterns are: {{patterns}}",
  RequiredPropertyError: "The required property `{{key}}` is missing at `{{pointer}}`",
  SchemaWarning: "Failed retrieving a schema from '{{pointer}}' to key '{{key}}'",
  TypeError: "Expected `{{value}}` ({{received}}) in `{{pointer}}` to be of type `{{expected}}`",
  UndefinedValueError: "Value must not be undefined in `{{pointer}}`",
  UniqueItemsError: "Items in array must be unique. Value `{{value}}` in `{{pointer}}` is a duplicate of {{duplicatePointer}}.",
  UnknownPropertyError: "Could not find a valid schema for property `{{pointer}}` within object",
  ValueNotEmptyError: "A value for `{{property}}` is required at `{{pointer}}`"
};

// node_modules/json-schema-library/dist/module/lib/getTypeOf.js
var toString6 = Object.prototype.toString;
function getTypeOf(value2) {
  const type = toString6.call(value2).match(/\s([^\]]+)\]/).pop().toLowerCase();
  if (type === "file") {
    return "object";
  }
  return type;
}

// node_modules/json-schema-library/dist/module/lib/utils/render.js
var OBJECT_TYPE = "object";
var ARRAY_TYPE = "array";
function render2(template3, data2 = {}) {
  return template3.replace(/\{\{\w+\}\}/g, (match2) => {
    const key2 = match2.replace(/[{}]/g, "");
    const variable = data2[key2];
    const variableType = getTypeOf(variable);
    if (variableType === OBJECT_TYPE || variableType === ARRAY_TYPE) {
      return JSON.stringify(variable);
    }
    return variable;
  });
}

// node_modules/json-schema-library/dist/module/lib/utils/__.js
function __(keyword2, data2, fallback = keyword2) {
  var _a4;
  const template3 = (_a4 = strings_default[keyword2]) !== null && _a4 !== void 0 ? _a4 : fallback;
  return render2(template3, data2);
}

// node_modules/json-schema-library/dist/module/lib/utils/createCustomError.js
function dashCase(text3) {
  return text3.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
function createError(name2, data2) {
  return {
    type: "error",
    name: name2,
    code: dashCase(name2),
    message: __(name2, data2),
    data: data2
  };
}
function createCustomError(name2) {
  return createError.bind(null, name2);
}

// node_modules/json-schema-library/dist/module/lib/utils/flattenArray.js
function flattenArray(list2, result2 = []) {
  for (let i3 = 0; i3 < list2.length; i3 += 1) {
    const item = list2[i3];
    if (Array.isArray(item)) {
      flattenArray(item, result2);
    } else {
      result2.push(item);
    }
  }
  return result2;
}

// node_modules/json-schema-library/dist/module/lib/config/settings.js
var settings_default = {
  DECLARATOR_ONEOF: "oneOfProperty",
  GET_TEMPLATE_RECURSION_LIMIT: 1,
  propertyBlacklist: ["_id"],
  templateDefaultOptions: {
    addOptionalProps: false,
    removeInvalidData: false,
    extendDefaults: true
  }
};

// node_modules/json-schema-library/dist/module/lib/schema/createOneOfSchemaResult.js
function createOneOfSchemaResult(schema7, oneOfSchema, oneOfIndex) {
  const childSchema = { ...oneOfSchema };
  Object.defineProperty(childSchema, "getOneOfOrigin", {
    enumerable: false,
    value: () => ({
      index: oneOfIndex,
      schema: schema7
    })
  });
  return childSchema;
}

// node_modules/json-schema-library/dist/module/lib/types.js
function isJsonError(error2) {
  return (error2 === null || error2 === void 0 ? void 0 : error2.type) === "error";
}

// node_modules/json-schema-library/dist/module/lib/utils/filter.js
function isPromise2(obj) {
  return obj instanceof Promise;
}
function errorOrPromise(error2) {
  return isJsonError(error2) || isPromise2(error2);
}

// node_modules/json-schema-library/dist/module/lib/features/oneOf.js
var { DECLARATOR_ONEOF } = settings_default;
function resolveOneOf(draft, data2, schema7 = draft.rootSchema, pointer = "#") {
  if (data2 != null && schema7[DECLARATOR_ONEOF]) {
    const errors4 = [];
    const oneOfProperty = schema7[DECLARATOR_ONEOF];
    const oneOfValue = data2[schema7[DECLARATOR_ONEOF]];
    if (oneOfValue === void 0) {
      return draft.errors.missingOneOfPropertyError({
        property: oneOfProperty,
        pointer,
        schema: schema7,
        value: data2
      });
    }
    for (let i3 = 0; i3 < schema7.oneOf.length; i3 += 1) {
      const one2 = draft.resolveRef(schema7.oneOf[i3]);
      const oneOfPropertySchema = draft.step(oneOfProperty, one2, data2, pointer);
      if (isJsonError(oneOfPropertySchema)) {
        return oneOfPropertySchema;
      }
      let result2 = flattenArray(draft.validate(oneOfValue, oneOfPropertySchema, pointer));
      result2 = result2.filter(errorOrPromise);
      if (result2.length > 0) {
        errors4.push(...result2);
      } else {
        return createOneOfSchemaResult(schema7, one2, i3);
      }
    }
    return draft.errors.oneOfPropertyError({
      property: oneOfProperty,
      value: oneOfValue,
      pointer,
      schema: schema7,
      errors: errors4
    });
  }
  const matches3 = [];
  const errors3 = [];
  for (let i3 = 0; i3 < schema7.oneOf.length; i3 += 1) {
    const one2 = draft.resolveRef(schema7.oneOf[i3]);
    let result2 = flattenArray(draft.validate(data2, one2, pointer));
    result2 = result2.filter(errorOrPromise);
    if (result2.length > 0) {
      errors3.push(...result2);
    } else {
      matches3.push({ index: i3, schema: one2 });
    }
  }
  if (matches3.length === 1) {
    return createOneOfSchemaResult(schema7, matches3[0].schema, matches3[0].index);
  }
  if (matches3.length > 1) {
    return draft.errors.multipleOneOfError({
      value: data2,
      pointer,
      schema: schema7,
      matches: matches3
    });
  }
  return draft.errors.oneOfError({
    value: JSON.stringify(data2),
    pointer,
    schema: schema7,
    oneOf: schema7.oneOf,
    errors: errors3
  });
}
function fuzzyObjectValue(draft, one2, data2, pointer) {
  if (data2 == null || one2.properties == null) {
    return -1;
  }
  let value2 = 0;
  const keys5 = Object.keys(one2.properties);
  for (let i3 = 0; i3 < keys5.length; i3 += 1) {
    const key2 = keys5[i3];
    if (data2[key2] != null && draft.isValid(data2[key2], one2.properties[key2], pointer)) {
      value2 += 1;
    }
  }
  return value2;
}
function resolveOneOfFuzzy(draft, data2, schema7 = draft.rootSchema, pointer = "#") {
  if (data2 != null && schema7[DECLARATOR_ONEOF]) {
    const errors3 = [];
    const oneOfProperty = schema7[DECLARATOR_ONEOF];
    const oneOfValue = data2[schema7[DECLARATOR_ONEOF]];
    if (oneOfValue === void 0) {
      return draft.errors.missingOneOfPropertyError({
        property: oneOfProperty,
        pointer,
        schema: schema7,
        value: data2
      });
    }
    for (let i3 = 0; i3 < schema7.oneOf.length; i3 += 1) {
      const one2 = draft.resolveRef(schema7.oneOf[i3]);
      const oneOfPropertySchema = draft.step(oneOfProperty, one2, data2, pointer);
      if (isJsonError(oneOfPropertySchema)) {
        return oneOfPropertySchema;
      }
      let result2 = flattenArray(draft.validate(oneOfValue, oneOfPropertySchema, pointer));
      result2 = result2.filter(errorOrPromise);
      if (result2.length > 0) {
        errors3.push(...result2);
      } else {
        return createOneOfSchemaResult(schema7, one2, i3);
      }
    }
    return draft.errors.oneOfPropertyError({
      property: oneOfProperty,
      value: oneOfValue,
      pointer,
      schema: schema7,
      errors: errors3
    });
  }
  const matches3 = [];
  for (let i3 = 0; i3 < schema7.oneOf.length; i3 += 1) {
    const one2 = draft.resolveRef(schema7.oneOf[i3]);
    if (draft.isValid(data2, one2, pointer)) {
      matches3.push({ schema: one2, index: i3 });
    }
  }
  if (matches3.length === 1) {
    return createOneOfSchemaResult(schema7, matches3[0].schema, matches3[0].index);
  }
  if (getTypeOf(data2) === "object") {
    let schemaOfItem;
    let schemaOfIndex = -1;
    let fuzzyGreatest = 0;
    for (let i3 = 0; i3 < schema7.oneOf.length; i3 += 1) {
      const one2 = draft.resolveRef(schema7.oneOf[i3]);
      const fuzzyValue = fuzzyObjectValue(draft, one2, data2);
      if (fuzzyGreatest < fuzzyValue) {
        fuzzyGreatest = fuzzyValue;
        schemaOfItem = schema7.oneOf[i3];
        schemaOfIndex = i3;
      }
    }
    if (schemaOfItem === void 0) {
      return draft.errors.oneOfError({
        value: JSON.stringify(data2),
        pointer,
        schema: schema7,
        oneOf: schema7.oneOf
      });
    }
    return createOneOfSchemaResult(schema7, schemaOfItem, schemaOfIndex);
  }
  if (matches3.length > 1) {
    return draft.errors.multipleOneOfError({ matches: matches3, pointer, schema: schema7, value: data2 });
  }
  return draft.errors.oneOfError({
    value: JSON.stringify(data2),
    pointer,
    schema: schema7,
    oneOf: schema7.oneOf
  });
}
var validateOneOf = (draft, schema7, value2, pointer) => {
  if (Array.isArray(schema7.oneOf)) {
    const schemaOrError = draft.resolveOneOf(value2, schema7, pointer);
    if (isJsonError(schemaOrError)) {
      return schemaOrError;
    }
  }
};

// node_modules/json-schema-library/dist/module/lib/utils/merge.js
var import_deepmerge = __toESM(require_cjs());
var overwriteMerge = (destinationArray, sourceArray) => sourceArray;
var merge_default = (a3, b3) => (0, import_deepmerge.default)(a3, b3, { arrayMerge: overwriteMerge });
var mergeUniqueItems = (destinationArray, sourceArray) => {
  const all2 = destinationArray.concat(sourceArray);
  return all2.filter((item, pos) => all2.indexOf(item) === pos);
};
var mergeArraysUnique = (a3, b3) => (0, import_deepmerge.default)(a3, b3, { arrayMerge: mergeUniqueItems });

// node_modules/json-schema-library/dist/module/lib/mergeSchema.js
function mergeSchema(a3, b3) {
  const aType = getTypeOf(a3);
  const bType = getTypeOf(b3);
  if (aType !== bType) {
    return a3;
  }
  const result2 = mergeArraysUnique(a3, b3);
  if (a3.getOneOfOrigin) {
    Object.defineProperty(result2, "getOneOfOrigin", {
      enumerable: false,
      value: a3.getOneOfOrigin
    });
  } else if (b3.getOneOfOrigin) {
    Object.defineProperty(result2, "getOneOfOrigin", {
      enumerable: false,
      value: b3.getOneOfOrigin
    });
  }
  return result2;
}

// node_modules/json-schema-library/dist/module/lib/utils/omit.js
function omit(object2, ...keysToOmit) {
  const result2 = {};
  Object.keys(object2).forEach((key2) => {
    if (!keysToOmit.includes(key2)) {
      result2[key2] = object2[key2];
    }
  });
  if (object2.getOneOfOrigin) {
    Object.defineProperty(result2, "getOneOfOrigin", {
      enumerable: false,
      value: object2.getOneOfOrigin
    });
  }
  return result2;
}

// node_modules/fast-copy/dist/esm/index.mjs
var toStringFunction = Function.prototype.toString;
var create3 = Object.create;
var toStringObject = Object.prototype.toString;
var LegacyCache = (
  /** @class */
  function() {
    function LegacyCache2() {
      this._keys = [];
      this._values = [];
    }
    LegacyCache2.prototype.has = function(key2) {
      return !!~this._keys.indexOf(key2);
    };
    LegacyCache2.prototype.get = function(key2) {
      return this._values[this._keys.indexOf(key2)];
    };
    LegacyCache2.prototype.set = function(key2, value2) {
      this._keys.push(key2);
      this._values.push(value2);
    };
    return LegacyCache2;
  }()
);
function createCacheLegacy() {
  return new LegacyCache();
}
function createCacheModern() {
  return /* @__PURE__ */ new WeakMap();
}
var createCache = typeof WeakMap !== "undefined" ? createCacheModern : createCacheLegacy;
function getCleanClone(prototype) {
  if (!prototype) {
    return create3(null);
  }
  var Constructor = prototype.constructor;
  if (Constructor === Object) {
    return prototype === Object.prototype ? {} : create3(prototype);
  }
  if (Constructor && ~toStringFunction.call(Constructor).indexOf("[native code]")) {
    try {
      return new Constructor();
    } catch (_a4) {
    }
  }
  return create3(prototype);
}
function getRegExpFlagsLegacy(regExp) {
  var flags = "";
  if (regExp.global) {
    flags += "g";
  }
  if (regExp.ignoreCase) {
    flags += "i";
  }
  if (regExp.multiline) {
    flags += "m";
  }
  if (regExp.unicode) {
    flags += "u";
  }
  if (regExp.sticky) {
    flags += "y";
  }
  return flags;
}
function getRegExpFlagsModern(regExp) {
  return regExp.flags;
}
var getRegExpFlags = /test/g.flags === "g" ? getRegExpFlagsModern : getRegExpFlagsLegacy;
function getTagLegacy(value2) {
  var type = toStringObject.call(value2);
  return type.substring(8, type.length - 1);
}
function getTagModern(value2) {
  return value2[Symbol.toStringTag] || getTagLegacy(value2);
}
var getTag = typeof Symbol !== "undefined" ? getTagModern : getTagLegacy;
var defineProperty2 = Object.defineProperty;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var _a2 = Object.prototype;
var hasOwnProperty2 = _a2.hasOwnProperty;
var propertyIsEnumerable = _a2.propertyIsEnumerable;
var SUPPORTS_SYMBOL = typeof getOwnPropertySymbols === "function";
function getStrictPropertiesModern(object2) {
  return getOwnPropertyNames(object2).concat(getOwnPropertySymbols(object2));
}
var getStrictProperties = SUPPORTS_SYMBOL ? getStrictPropertiesModern : getOwnPropertyNames;
function copyOwnPropertiesStrict(value2, clone3, state) {
  var properties = getStrictProperties(value2);
  for (var index2 = 0, length_1 = properties.length, property2 = void 0, descriptor = void 0; index2 < length_1; ++index2) {
    property2 = properties[index2];
    if (property2 === "callee" || property2 === "caller") {
      continue;
    }
    descriptor = getOwnPropertyDescriptor(value2, property2);
    if (!descriptor) {
      clone3[property2] = state.copier(value2[property2], state);
      continue;
    }
    if (!descriptor.get && !descriptor.set) {
      descriptor.value = state.copier(descriptor.value, state);
    }
    try {
      defineProperty2(clone3, property2, descriptor);
    } catch (error2) {
      clone3[property2] = descriptor.value;
    }
  }
  return clone3;
}
function copyArrayLoose(array, state) {
  var clone3 = new state.Constructor();
  state.cache.set(array, clone3);
  for (var index2 = 0, length_2 = array.length; index2 < length_2; ++index2) {
    clone3[index2] = state.copier(array[index2], state);
  }
  return clone3;
}
function copyArrayStrict(array, state) {
  var clone3 = new state.Constructor();
  state.cache.set(array, clone3);
  return copyOwnPropertiesStrict(array, clone3, state);
}
function copyArrayBuffer(arrayBuffer, _state) {
  return arrayBuffer.slice(0);
}
function copyBlob(blob, _state) {
  return blob.slice(0, blob.size, blob.type);
}
function copyDataView(dataView, state) {
  return new state.Constructor(copyArrayBuffer(dataView.buffer));
}
function copyDate(date, state) {
  return new state.Constructor(date.getTime());
}
function copyMapLoose(map5, state) {
  var clone3 = new state.Constructor();
  state.cache.set(map5, clone3);
  map5.forEach(function(value2, key2) {
    clone3.set(key2, state.copier(value2, state));
  });
  return clone3;
}
function copyMapStrict(map5, state) {
  return copyOwnPropertiesStrict(map5, copyMapLoose(map5, state), state);
}
function copyObjectLooseLegacy(object2, state) {
  var clone3 = getCleanClone(state.prototype);
  state.cache.set(object2, clone3);
  for (var key2 in object2) {
    if (hasOwnProperty2.call(object2, key2)) {
      clone3[key2] = state.copier(object2[key2], state);
    }
  }
  return clone3;
}
function copyObjectLooseModern(object2, state) {
  var clone3 = getCleanClone(state.prototype);
  state.cache.set(object2, clone3);
  for (var key2 in object2) {
    if (hasOwnProperty2.call(object2, key2)) {
      clone3[key2] = state.copier(object2[key2], state);
    }
  }
  var symbols = getOwnPropertySymbols(object2);
  for (var index2 = 0, length_3 = symbols.length, symbol = void 0; index2 < length_3; ++index2) {
    symbol = symbols[index2];
    if (propertyIsEnumerable.call(object2, symbol)) {
      clone3[symbol] = state.copier(object2[symbol], state);
    }
  }
  return clone3;
}
var copyObjectLoose = SUPPORTS_SYMBOL ? copyObjectLooseModern : copyObjectLooseLegacy;
function copyObjectStrict(object2, state) {
  var clone3 = getCleanClone(state.prototype);
  state.cache.set(object2, clone3);
  return copyOwnPropertiesStrict(object2, clone3, state);
}
function copyPrimitiveWrapper(primitiveObject, state) {
  return new state.Constructor(primitiveObject.valueOf());
}
function copyRegExp(regExp, state) {
  var clone3 = new state.Constructor(regExp.source, getRegExpFlags(regExp));
  clone3.lastIndex = regExp.lastIndex;
  return clone3;
}
function copySelf(value2, _state) {
  return value2;
}
function copySetLoose(set4, state) {
  var clone3 = new state.Constructor();
  state.cache.set(set4, clone3);
  set4.forEach(function(value2) {
    clone3.add(state.copier(value2, state));
  });
  return clone3;
}
function copySetStrict(set4, state) {
  return copyOwnPropertiesStrict(set4, copySetLoose(set4, state), state);
}
var isArray = Array.isArray;
var assign3 = Object.assign;
var getPrototypeOf = Object.getPrototypeOf || function(obj) {
  return obj.__proto__;
};
var DEFAULT_LOOSE_OPTIONS = {
  array: copyArrayLoose,
  arrayBuffer: copyArrayBuffer,
  blob: copyBlob,
  dataView: copyDataView,
  date: copyDate,
  error: copySelf,
  map: copyMapLoose,
  object: copyObjectLoose,
  regExp: copyRegExp,
  set: copySetLoose
};
var DEFAULT_STRICT_OPTIONS = assign3({}, DEFAULT_LOOSE_OPTIONS, {
  array: copyArrayStrict,
  map: copyMapStrict,
  object: copyObjectStrict,
  set: copySetStrict
});
function getTagSpecificCopiers(options2) {
  return {
    Arguments: options2.object,
    Array: options2.array,
    ArrayBuffer: options2.arrayBuffer,
    Blob: options2.blob,
    Boolean: copyPrimitiveWrapper,
    DataView: options2.dataView,
    Date: options2.date,
    Error: options2.error,
    Float32Array: options2.arrayBuffer,
    Float64Array: options2.arrayBuffer,
    Int8Array: options2.arrayBuffer,
    Int16Array: options2.arrayBuffer,
    Int32Array: options2.arrayBuffer,
    Map: options2.map,
    Number: copyPrimitiveWrapper,
    Object: options2.object,
    Promise: copySelf,
    RegExp: options2.regExp,
    Set: options2.set,
    String: copyPrimitiveWrapper,
    WeakMap: copySelf,
    WeakSet: copySelf,
    Uint8Array: options2.arrayBuffer,
    Uint8ClampedArray: options2.arrayBuffer,
    Uint16Array: options2.arrayBuffer,
    Uint32Array: options2.arrayBuffer,
    Uint64Array: options2.arrayBuffer
  };
}
function createCopier(options2) {
  var normalizedOptions = assign3({}, DEFAULT_LOOSE_OPTIONS, options2);
  var tagSpecificCopiers = getTagSpecificCopiers(normalizedOptions);
  var array = tagSpecificCopiers.Array, object2 = tagSpecificCopiers.Object;
  function copier(value2, state) {
    state.prototype = state.Constructor = void 0;
    if (!value2 || typeof value2 !== "object") {
      return value2;
    }
    if (state.cache.has(value2)) {
      return state.cache.get(value2);
    }
    state.prototype = getPrototypeOf(value2);
    state.Constructor = state.prototype && state.prototype.constructor;
    if (!state.Constructor || state.Constructor === Object) {
      return object2(value2, state);
    }
    if (isArray(value2)) {
      return array(value2, state);
    }
    var tagSpecificCopier = tagSpecificCopiers[getTag(value2)];
    if (tagSpecificCopier) {
      return tagSpecificCopier(value2, state);
    }
    return typeof value2.then === "function" ? value2 : object2(value2, state);
  }
  return function copy2(value2) {
    return copier(value2, {
      Constructor: void 0,
      cache: createCache(),
      copier,
      prototype: void 0
    });
  };
}
function createStrictCopier(options2) {
  return createCopier(assign3({}, DEFAULT_STRICT_OPTIONS, options2));
}
var copyStrict = createStrictCopier({});
var index = createCopier({});

// node_modules/json-schema-library/dist/module/lib/utils/copy.js
var copy_default = index;

// node_modules/json-schema-library/dist/module/lib/features/if.js
function resolveIfSchema(draft, schema7, data2) {
  if (schema7.if == null) {
    return void 0;
  }
  if (schema7.if === false) {
    return schema7.else;
  }
  if (schema7.if && (schema7.then || schema7.else)) {
    const ifErrors = draft.validate(data2, draft.resolveRef(schema7.if));
    if (ifErrors.length === 0 && schema7.then) {
      return draft.resolveRef(schema7.then);
    }
    if (ifErrors.length !== 0 && schema7.else) {
      return draft.resolveRef(schema7.else);
    }
  }
}
var validateIf = (draft, schema7, value2, pointer) => {
  const resolvedSchema = resolveIfSchema(draft, schema7, value2);
  if (resolvedSchema) {
    return draft.validate(value2, resolvedSchema, pointer);
  }
};

// node_modules/json-schema-library/dist/module/lib/features/allOf.js
function resolveSchema(draft, schemaToResolve, data2) {
  var _a4;
  const schema7 = { ...(_a4 = draft.resolveRef(schemaToResolve)) !== null && _a4 !== void 0 ? _a4 : {} };
  const ifSchema = resolveIfSchema(draft, schema7, data2);
  if (ifSchema) {
    return ifSchema;
  }
  return omit(schema7, "if", "then", "else");
}
function resolveAllOf(draft, data2, schema7 = draft.rootSchema) {
  let mergedSchema = copy_default(schema7);
  for (let i3 = 0; i3 < schema7.allOf.length; i3 += 1) {
    const allOfSchema = resolveSchema(draft, schema7.allOf[i3], data2);
    mergedSchema = mergeSchema(mergedSchema, allOfSchema);
  }
  delete mergedSchema.allOf;
  return mergedSchema;
}
function mergeAllOfSchema(draft, schema7) {
  const { allOf } = schema7;
  if (!Array.isArray(allOf) || allOf.length === 0) {
    return;
  }
  let resolvedSchema = {};
  allOf.forEach((subschema) => {
    resolvedSchema = mergeSchema(resolvedSchema, draft.resolveRef(subschema));
  });
  return resolvedSchema;
}
var validateAllOf = (draft, schema7, value2, pointer) => {
  const { allOf } = schema7;
  if (!Array.isArray(allOf) || allOf.length === 0) {
    return;
  }
  const errors3 = [];
  schema7.allOf.forEach((subSchema) => {
    errors3.push(...draft.validate(value2, subSchema, pointer));
  });
  return errors3;
};

// node_modules/json-schema-library/dist/module/lib/resolveRef.strict.js
function resolveRef(schema7, rootSchema) {
  if (schema7 == null || schema7.$ref == null) {
    return schema7;
  }
  if (schema7.getRoot) {
    const resolvedSchema2 = schema7.getRoot().getRef(schema7);
    return resolvedSchema2;
  }
  const resolvedSchema = rootSchema.getRef(schema7);
  return resolvedSchema;
}

// node_modules/json-schema-library/dist/module/lib/resolveRef.merge.js
function resolveRefMerge(schema7, rootSchema) {
  if (schema7 == null || schema7.$ref == null) {
    return schema7;
  }
  const resolvedSchema = rootSchema.getRef(schema7);
  const mergedSchema = Object.assign({}, resolvedSchema, schema7);
  delete mergedSchema.$ref;
  Object.defineProperty(mergedSchema, "__ref", { enumerable: false, value: schema7.__ref });
  Object.defineProperty(mergedSchema, "getRoot", { enumerable: false, value: schema7.getRoot });
  return mergedSchema;
}

// node_modules/json-schema-library/dist/module/lib/utils/uniqueItems.js
function uniqueItems(list2) {
  return list2.filter((item, index2) => list2.indexOf(item) === index2);
}

// node_modules/json-schema-library/dist/module/lib/utils/isObject.js
function isObject4(v3) {
  return getTypeOf(v3) === "object";
}

// node_modules/json-schema-library/dist/module/lib/features/dependencies.js
function resolveDependencies(draft, schema7, data2) {
  const { dependencies } = schema7;
  if (!isObject4(dependencies) || !isObject4(data2)) {
    return;
  }
  let updated = false;
  let resolvedSchema = { required: [] };
  Object.keys(dependencies).forEach((prop2) => {
    var _a4, _b;
    if (data2[prop2] == null && !(((_a4 = schema7.required) === null || _a4 === void 0 ? void 0 : _a4.includes(prop2)) || ((_b = resolvedSchema.required) === null || _b === void 0 ? void 0 : _b.includes(prop2)))) {
      return;
    }
    const dependency = dependencies[prop2];
    if (Array.isArray(dependency)) {
      updated = true;
      resolvedSchema.required.push(...dependency);
      return;
    }
    if (isObject4(dependency)) {
      updated = true;
      resolvedSchema = mergeSchema(resolvedSchema, draft.resolveRef(dependency));
      return;
    }
  });
  if (updated) {
    resolvedSchema.required = uniqueItems(resolvedSchema.required);
    return resolvedSchema;
  }
}
var validateDependencies = (draft, schema7, value2, pointer) => {
  if (getTypeOf(schema7.dependencies) !== "object") {
    return void 0;
  }
  const errors3 = [];
  Object.keys(value2).forEach((property2) => {
    if (schema7.dependencies[property2] === void 0) {
      return;
    }
    if (schema7.dependencies[property2] === true) {
      return;
    }
    if (schema7.dependencies[property2] === false) {
      errors3.push(draft.errors.missingDependencyError({ pointer, schema: schema7, value: value2 }));
      return;
    }
    let dependencyErrors;
    const type = getTypeOf(schema7.dependencies[property2]);
    if (type === "array") {
      dependencyErrors = schema7.dependencies[property2].filter((dependency) => value2[dependency] === void 0).map((missingProperty) => draft.errors.missingDependencyError({ missingProperty, pointer, schema: schema7, value: value2 }));
    } else if (type === "object") {
      dependencyErrors = draft.validate(value2, schema7.dependencies[property2], pointer);
    } else {
      throw new Error(`Invalid dependency definition for ${pointer}/${property2}. Must be string[] or schema`);
    }
    errors3.push(...dependencyErrors);
  });
  return errors3.length > 0 ? errors3 : void 0;
};

// node_modules/json-schema-library/dist/module/lib/features/anyOf.js
function mergeValidAnyOfSchema(draft, schema7, data2) {
  if (!Array.isArray(schema7.anyOf) || schema7.anyOf.length === 0) {
    return;
  }
  let resolvedSchema;
  schema7.anyOf.forEach((anySchema) => {
    anySchema = draft.resolveRef(anySchema);
    if (draft.isValid(data2, anySchema)) {
      resolvedSchema = resolvedSchema ? mergeSchema(resolvedSchema, anySchema) : anySchema;
    }
  });
  return resolvedSchema;
}
function resolveAnyOf(draft, data2, schema7 = draft.rootSchema, pointer = "#") {
  const { anyOf } = schema7;
  if (!Array.isArray(anyOf) || anyOf.length === 0) {
    return schema7;
  }
  const resolvedSchema = mergeValidAnyOfSchema(draft, schema7, data2);
  if (resolvedSchema == null) {
    return draft.errors.anyOfError({ pointer, schema: schema7, value: data2, anyOf: JSON.stringify(anyOf) });
  }
  const mergedSchema = mergeSchema(schema7, resolvedSchema);
  return omit(mergedSchema, "anyOf");
}
var validateAnyOf = (draft, schema7, value2, pointer) => {
  if (!Array.isArray(schema7.anyOf) || schema7.anyOf.length === 0) {
    return void 0;
  }
  for (let i3 = 0; i3 < schema7.anyOf.length; i3 += 1) {
    if (draft.isValid(value2, schema7.anyOf[i3])) {
      return void 0;
    }
  }
  return draft.errors.anyOfError({ pointer, schema: schema7, value: value2, anyOf: schema7.anyOf });
};

// node_modules/json-schema-library/dist/module/lib/resolveDynamicSchema.js
var toOmit = ["allOf", "anyOf", "oneOf", "dependencies", "if", "then", "else"];
var dynamicProperties = ["allOf", "anyOf", "oneOf", "dependencies", "if"];
function isDynamicSchema(schema7) {
  const givenProps = Object.keys(schema7);
  return dynamicProperties.findIndex((prop2) => givenProps.includes(prop2)) !== -1;
}
function resolveDynamicSchema(draft, schema7, data2, pointer) {
  let resolvedSchema;
  let error2;
  schema7 = draft.resolveRef(schema7);
  if (schema7.oneOf) {
    const oneOfSchema = resolveOneOfFuzzy(draft, data2, schema7, pointer);
    if (isJsonError(oneOfSchema)) {
      error2 = oneOfSchema;
    } else if (oneOfSchema) {
      resolvedSchema = mergeSchema(resolvedSchema !== null && resolvedSchema !== void 0 ? resolvedSchema : {}, oneOfSchema);
    }
  }
  if (Array.isArray(schema7.allOf)) {
    const allOf = schema7.allOf.map((s3) => {
      if (isDynamicSchema(s3)) {
        let result2 = resolveDynamicSchema(draft, s3, data2, pointer);
        if (result2) {
          result2 = mergeSchema(s3, result2);
          return omit(result2, ...toOmit);
        }
        return void 0;
      }
      return s3;
    });
    if (allOf.length > 0) {
      const allOfSchema = mergeAllOfSchema(draft, { allOf });
      resolvedSchema = mergeSchema(resolvedSchema !== null && resolvedSchema !== void 0 ? resolvedSchema : {}, allOfSchema);
    }
  }
  const anyOfSchema = mergeValidAnyOfSchema(draft, schema7, data2);
  if (anyOfSchema) {
    resolvedSchema = mergeSchema(resolvedSchema !== null && resolvedSchema !== void 0 ? resolvedSchema : {}, anyOfSchema);
  }
  const dependenciesSchema = resolveDependencies(draft, schema7, data2);
  if (dependenciesSchema) {
    resolvedSchema = mergeSchema(resolvedSchema !== null && resolvedSchema !== void 0 ? resolvedSchema : {}, dependenciesSchema);
  }
  const ifSchema = resolveIfSchema(draft, schema7, data2);
  if (ifSchema) {
    resolvedSchema = mergeSchema(resolvedSchema !== null && resolvedSchema !== void 0 ? resolvedSchema : {}, ifSchema);
  }
  if (resolvedSchema == null) {
    return error2;
  }
  const nestedSchema = resolveDynamicSchema(draft, resolvedSchema, data2, pointer);
  if (nestedSchema) {
    resolvedSchema = mergeSchema(resolvedSchema, nestedSchema);
  }
  return omit(resolvedSchema, ...toOmit);
}

// node_modules/json-schema-library/dist/module/lib/reduceSchema.js
var toOmit2 = ["allOf", "anyOf", "oneOf", "dependencies", "if", "then", "else"];
function reduceSchema(draft, schema7, data2, pointer) {
  let resolvedSchema = resolveDynamicSchema(draft, schema7, data2, pointer);
  if (resolvedSchema) {
    resolvedSchema = mergeSchema(schema7, resolvedSchema);
    return omit(resolvedSchema, ...toOmit2);
  }
  return schema7;
}

// node_modules/json-schema-library/dist/module/lib/draft/index.js
var Draft = class {
  constructor(config3, schema7) {
    this.remotes = {};
    this.errors = {};
    this.typeKeywords = {};
    this.validateKeyword = {};
    this.validateType = {};
    this.validateFormat = {};
    this.config = config3;
    this.typeKeywords = copy_default(config3.typeKeywords);
    this.validateKeyword = Object.assign({}, config3.validateKeyword);
    this.validateType = Object.assign({}, config3.validateType);
    this.validateFormat = Object.assign({}, config3.validateFormat);
    this.errors = Object.assign({}, config3.errors);
    this.setSchema(schema7);
  }
  get rootSchema() {
    return this.__rootSchema;
  }
  set rootSchema(rootSchema) {
    if (rootSchema == null) {
      return;
    }
    this.__rootSchema = this.config.compileSchema(this, rootSchema);
  }
  /**
   * register a json-schema to be referenced from another json-schema
   * @param url - base-url of json-schema (aka id)
   * @param schema - json-schema root
   */
  addRemoteSchema(url2, schema7) {
    this.config.addRemoteSchema(this, url2, schema7);
  }
  compileSchema(schema7) {
    var _a4;
    return this.config.compileSchema(this, schema7, (_a4 = this.rootSchema) !== null && _a4 !== void 0 ? _a4 : schema7);
  }
  createSchemaOf(data2) {
    return this.config.createSchemaOf(data2);
  }
  /**
   * Iterates over data, retrieving its schema
   *
   * @param data - the data to iterate
   * @param callback - will be called with (schema, data, pointer) on each item
   * @param [schema] - the schema matching the data. Defaults to rootSchema
   * @param [pointer] - pointer to current data. Default to rootPointer
   */
  each(data2, callback, schema7, pointer) {
    return this.config.each(this, data2, callback, schema7, pointer);
  }
  eachSchema(callback, schema7 = this.rootSchema) {
    return this.config.eachSchema(schema7, callback);
  }
  getChildSchemaSelection(property2, schema7) {
    return this.config.getChildSchemaSelection(this, property2, schema7);
  }
  /**
   * Returns the json-schema of a data-json-pointer.
   *
   * To resolve dynamic schema where the type of json-schema is evaluated by
   * its value, a data object has to be passed in options.
   *
   * Per default this function will return `undefined` for valid properties that
   * do not have a defined schema. Use the option `withSchemaWarning: true` to
   * receive an error with `code: schema-warning` containing the location of its
   * last evaluated json-schema.
   *
   * Notes
   *      - uses draft.step to walk through data and schema
   *
   * @param draft
   * @param pointer - json pointer in data to get the json schema for
   * @param [options.data] - the data object, which includes the json pointers value. This is optional, as
   *    long as no oneOf, anyOf, etc statement is part of the pointers schema
   * @param [options.schema] - the json schema to iterate. Defaults to draft.rootSchema
   * @param [options.withSchemaWarning] - if true returns an error instead of `undefined` for valid properties missing a schema definition
   * @return resolved json-schema object of requested json-pointer location
   */
  getSchema(options2) {
    return this.config.getSchema(this, options2);
  }
  /**
   * Create data object matching the given schema
   *
   * @param [data] - optional template data
   * @param [schema] - json schema, defaults to rootSchema
   * @return created template data
   */
  getTemplate(data2, schema7, opts = this.config.templateDefaultOptions) {
    return this.config.getTemplate(this, data2, schema7, opts);
  }
  isValid(data2, schema7, pointer) {
    return this.config.isValid(this, data2, schema7, pointer);
  }
  resolveAnyOf(data2, schema7, pointer) {
    return this.config.resolveAnyOf(this, data2, schema7, pointer);
  }
  resolveAllOf(data2, schema7) {
    return this.config.resolveAllOf(this, data2, schema7);
  }
  resolveRef(schema7) {
    return this.config.resolveRef(schema7, this.rootSchema);
  }
  resolveOneOf(data2, schema7, pointer) {
    return this.config.resolveOneOf(this, data2, schema7, pointer);
  }
  setSchema(schema7) {
    this.rootSchema = schema7;
  }
  /**
   * Returns the json-schema of the given object property or array item.
   * e.g. it steps by one key into the data
   *
   *  This helper determines the location of the property within the schema (additional properties, oneOf, ...) and
   *  returns the correct schema.
   *
   * @param  key       - property-name or array-index
   * @param  schema    - json schema of current data
   * @param  data      - parent of key
   * @param  [pointer] - pointer to schema and data (parent of key)
   * @return Schema or Error if failed resolving key
   */
  step(key2, schema7, data2, pointer) {
    return this.config.step(this, key2, schema7, data2, pointer);
  }
  /**
   * Validate data by a json schema
   *
   * @param value - value to validate
   * @param [schema] - json schema, defaults to rootSchema
   * @param [pointer] - json pointer pointing to value (used for error-messages only)
   * @return list of errors or empty
   */
  validate(data2, schema7, pointer) {
    return this.config.validate(this, data2, schema7, pointer);
  }
};

// node_modules/json-schema-library/dist/module/lib/addRemoteSchema.js
function addRemoteSchema(draft, url2, schema7) {
  schema7.id = schema7.id || url2;
  draft.remotes[url2] = draft.compileSchema(schema7);
}

// node_modules/json-schema-library/dist/module/lib/eachSchema.js
var import_json_pointer3 = __toESM(require_jsonPointer());

// node_modules/json-schema-library/dist/module/lib/schema/getTypeDefs.js
var import_json_pointer2 = __toESM(require_jsonPointer());

// node_modules/@sagold/json-query/dist/module/lib/parser/index.js
var import_W3CEBNF = __toESM(require_W3CEBNF());

// node_modules/@sagold/json-query/dist/module/lib/parser/jsonQueryGrammar.js
var propertyRegex = "[^?/{}*,()#]+";
var jsonQueryGrammar = `
root ::= ("#" recursion | recursion | (query | pattern) recursion* | "#" SEP? | SEP)
recursion ::= (SEP query | pattern)*

query ::= (ESC escaped ESC | property | all | any | regex) typecheck? lookahead?
property ::= ${propertyRegex}
regex ::= "{" [^}]+ "}"
SEP ::= "/"
all ::= "**"
any ::= "*"

typecheck ::= "?:" ("value" | "boolean" | "string" | "number" | "object" | "array")
lookahead ::= "?" expression ((andExpr | orExpr) expression)*
andExpr ::= S? "&&" S?
orExpr ::= S? "||" S?

expression ::= (exprProperty | ESC escaped ESC) ((isnot | is) (exprProperty | regex | ESC escaped ESC))*
exprProperty ::= [a-zA-Z0-9-_ $]+
escaped ::= [^"]+
is ::= ":"
isnot ::= ":!"
ESC ::= '"'

pattern ::= S? "(" (SEP query | pattern (orPattern? pattern)*)* ")" quantifier? S? lookahead?
quantifier ::= "+" | "*" | [0-9]+
orPattern ::= S? "," S?

S ::= [ ]*
`;

// node_modules/@sagold/json-query/dist/module/lib/parser/index.js
var parser3 = new import_W3CEBNF.default.Parser(jsonQueryGrammar);
var parse = (query2) => parser3.getAST(query2);

// node_modules/@sagold/json-query/dist/module/lib/interpreter/keys.js
var VALUE_INDEX = 0;
var POINTER_INDEX = 3;

// node_modules/@sagold/json-query/dist/module/lib/interpreter/nodes.js
var join2 = (a3, b3) => `${a3}/${b3}`;
var toString7 = Object.prototype.toString;
var rContainer = /Object|Array/;
var isContainer = (v3) => rContainer.test(toString7.call(v3));
var getTypeOf2 = (v3) => toString7.call(v3).match(/\s([^\]]+)\]/).pop().toLowerCase();
function nodeAsRegex(node) {
  return new RegExp(node.text.replace(/(^{|}$)/g, ""));
}
function forEach2(parent, callback) {
  if (Array.isArray(parent)) {
    parent.forEach(callback);
  } else if (Object.prototype.toString.call(parent) === "[object Object]") {
    Object.keys(parent).forEach(function(key2) {
      callback(parent[key2], key2, parent);
    });
  }
}
function getKeys(value2) {
  if (Array.isArray(value2)) {
    return value2.map(function(value3, index2) {
      return `${index2}`;
    });
  }
  if (Object.prototype.toString.call(value2) === "[object Object]") {
    return Object.keys(value2);
  }
  return [];
}
var cache3 = {
  mem: [],
  get(entry, prop2) {
    const v3 = entry[VALUE_INDEX][prop2];
    if (cache3.mem.includes(v3)) {
      return void 0;
    }
    if (isContainer(v3)) {
      cache3.mem.push(v3);
    }
    return [v3, prop2, entry[VALUE_INDEX], join2(entry[POINTER_INDEX], prop2)];
  },
  reset() {
    cache3.mem.length = 0;
  }
};
var expand = {
  any(node, entry) {
    const value2 = entry[VALUE_INDEX];
    return getKeys(value2).map((prop2) => [
      value2[prop2],
      prop2,
      value2,
      join2(entry[POINTER_INDEX], prop2)
    ]);
  },
  all(node, entry) {
    const result2 = [entry];
    forEach2(entry[VALUE_INDEX], (value2, prop2) => {
      const childEntry = cache3.get(entry, prop2);
      childEntry && result2.push(...expand.all(node, childEntry));
    });
    return result2;
  },
  regex(node, entry) {
    const regex = nodeAsRegex(node);
    const value2 = entry[VALUE_INDEX];
    return getKeys(value2).filter((prop2) => regex.test(prop2)).map((prop2) => [
      value2[prop2],
      prop2,
      value2,
      join2(entry[POINTER_INDEX], prop2)
    ]);
  }
};
var select = {
  // alias to property (but escaped)
  escaped: (node, entry) => select.property(node, entry),
  property: (node, entry) => {
    const prop2 = node.text;
    if (entry[VALUE_INDEX] && entry[VALUE_INDEX][prop2] !== void 0) {
      return [
        entry[VALUE_INDEX][prop2],
        prop2,
        entry[VALUE_INDEX],
        join2(entry[POINTER_INDEX], prop2)
      ];
    }
  },
  typecheck: (node, entry) => {
    const checkedTyped = node.text.replace(/^\?:/, "");
    if (checkedTyped === "value") {
      return isContainer(entry[VALUE_INDEX]) ? void 0 : entry;
    }
    const type = getTypeOf2(entry[VALUE_INDEX]);
    if (type === checkedTyped) {
      return entry;
    }
  },
  lookahead: (node, entry) => {
    let valid2 = true;
    let or2 = false;
    node.children.forEach((expr) => {
      if (expr.type === "expression") {
        const isValid2 = select.expression(expr, entry) !== void 0;
        valid2 = or2 === true ? valid2 || isValid2 : valid2 && isValid2;
      } else {
        or2 = expr.type === "orExpr";
      }
    });
    return valid2 ? entry : void 0;
  },
  expression: (node, entry) => {
    const prop2 = node.children[0].text;
    const cmp4 = node.children[1];
    const test2 = node.children[2];
    const value2 = entry[VALUE_INDEX];
    if (isContainer(value2) === false) {
      return void 0;
    }
    return expressionMatches(value2[prop2], cmp4, test2) ? entry : void 0;
  }
};
function expressionMatches(value2, cmp4, test2) {
  if (cmp4 === void 0) {
    return value2 !== void 0;
  }
  let valid2;
  const valueString = `${value2}`;
  if (test2.type === "regex") {
    const regex = nodeAsRegex(test2);
    valid2 = regex.test(valueString);
  } else {
    valid2 = valueString === test2.text;
  }
  if (cmp4.type === "isnot") {
    valid2 = valid2 === false && value2 !== void 0;
  }
  return valid2;
}

// node_modules/@sagold/json-query/dist/module/lib/interpreter/index.js
function collect(func, input, node, pointer) {
  const result2 = [];
  for (let i3 = 0, l3 = input.length; i3 < l3; i3 += 1) {
    result2.push(...func(node, input[i3], node, pointer));
  }
  return result2;
}
function reduce2(func, input, node, pointer) {
  const result2 = [];
  for (let i3 = 0, l3 = input.length; i3 < l3; i3 += 1) {
    const output = func(node, input[i3], pointer);
    if (output) {
      result2.push(output);
    }
  }
  return result2;
}
function query(data2, ast, pointer) {
  let result2 = data2;
  ast.children.forEach((node) => {
    if (expand[node.type]) {
      result2 = collect(expand[node.type], result2, node, pointer);
    } else if (select[node.type]) {
      result2 = reduce2(select[node.type], result2, node, pointer);
    } else {
      throw new Error(`Unknown filter ${node.type}`);
    }
  });
  return result2;
}
function runPatternOnce(inputSet, ast, pointer) {
  const resultingSet = [];
  let workingSet = inputSet;
  ast.children.forEach((node) => {
    if (node.type === "orPattern") {
      resultingSet.push(...workingSet);
      workingSet = inputSet;
      return;
    }
    workingSet = runNode(workingSet, node, pointer);
  });
  resultingSet.push(...workingSet);
  return resultingSet;
}
function getIterationCount(quantifier) {
  if (quantifier == null) {
    return 1;
  }
  if (quantifier === "*" || quantifier === "+") {
    return Infinity;
  }
  const count = parseInt(quantifier);
  return isNaN(count) ? 1 : count;
}
function pattern(data2, ast, pointer) {
  const result2 = [];
  const quantifier = ast.children.find((node) => node.type === "quantifier");
  const iterationCount = getIterationCount(quantifier && quantifier.text);
  let workingSet = data2;
  if (quantifier && quantifier.text === "*") {
    result2.push(...workingSet);
  }
  let count = 0;
  while (workingSet.length > 0 && count < iterationCount) {
    workingSet = runPatternOnce(workingSet, ast, pointer);
    result2.push(...workingSet);
    count += 1;
  }
  return result2;
}
function skip(data2, ast, pointer) {
  let result2 = data2;
  ast.children.forEach((n4) => result2 = runNode(result2, n4, pointer));
  return result2;
}
function runNode(data2, ast, pointer) {
  let result2;
  if (ast.type === "query") {
    result2 = query(data2, ast, pointer);
  } else if (ast.type === "pattern") {
    result2 = pattern(data2, ast, pointer);
  } else {
    result2 = skip(data2, ast, pointer);
  }
  cache3.reset();
  cache3.mem.push(data2);
  return result2;
}
function run(data2, ast) {
  cache3.reset();
  cache3.mem.push(data2);
  return runNode([[data2, null, null, "#"]], ast);
}

// node_modules/@sagold/json-query/dist/module/lib/get.js
var returnTypes = {
  value: (r3) => r3.map((e3) => e3[VALUE_INDEX]),
  pointer: (r3) => r3.map((e3) => e3[POINTER_INDEX]),
  all: (r3) => r3,
  map: (r3) => {
    const map5 = {};
    r3.forEach((e3) => map5[e3[POINTER_INDEX]] = e3[VALUE_INDEX]);
    return map5;
  }
};
var ReturnType;
(function(ReturnType2) {
  ReturnType2["POINTER"] = "pointer";
  ReturnType2["VALUE"] = "value";
  ReturnType2["ALL"] = "all";
  ReturnType2["MAP"] = "map";
})(ReturnType || (ReturnType = {}));
get2.POINTER = ReturnType.POINTER;
get2.VALUE = ReturnType.VALUE;
get2.ALL = ReturnType.ALL;
get2.MAP = ReturnType.MAP;
function get2(data2, queryString, returnType = ReturnType.VALUE) {
  if (queryString == null) {
    return [];
  }
  queryString = queryString.replace(/(\/$)/g, "");
  if (queryString === "") {
    queryString = "#";
  }
  const ast = parse(queryString);
  if (ast == null) {
    throw new Error(`empty ast for '${queryString}'`);
  }
  if (ast.rest !== "") {
    throw new Error(`Failed parsing queryString from: '${ast.rest}'`);
  }
  const result2 = run(data2, ast);
  if (typeof returnType === "function") {
    return result2.map((r3) => returnType(...r3));
  } else if (returnTypes[returnType]) {
    return returnTypes[returnType](result2);
  }
  return result2;
}

// node_modules/@sagold/json-query/dist/module/lib/split.js
var skip2 = ["root", "recursion"];
function buildPath(node, path = []) {
  if (skip2.includes(node.type)) {
    node.children.forEach((n4) => buildPath(n4, path));
    return path;
  }
  path.push(node.text);
  return path;
}
function split2(queryString) {
  if (queryString == null || queryString === "") {
    return [];
  }
  const ast = parse(queryString);
  return buildPath(ast);
}

// node_modules/@sagold/json-query/dist/module/lib/set.js
var cp = (v3) => JSON.parse(JSON.stringify(v3));
var toString8 = Object.prototype.toString;
var getType = (v3) => toString8.call(v3).match(/\s([^\]]+)\]/).pop().toLowerCase();
var isProperty = new RegExp(`^("[^"]+"|${propertyRegex})$`);
var ignoreTypes = ["string", "number", "boolean", "null"];
var isArray2 = /^\[\d*\]$/;
var arrayHasIndex = /^\[(\d+)\]$/;
var isEscaped = /^".+"$/;
var isArrayProp = /(^\[\d*\]$|^\d+$)/;
function convertToIndex(index2) {
  return parseInt(index2.replace(/^(\[|\]$)/, ""));
}
function removeEscape(property2) {
  return isEscaped.test(property2) ? property2.replace(/(^"|"$)/g, "") : property2;
}
function insert3(array, index2, value2) {
  if (array.length <= index2) {
    array[index2] = value2;
  } else {
    array.splice(index2, 0, value2);
  }
}
function select2(workingSet, query2) {
  const nextSet = [];
  workingSet.forEach((d3) => nextSet.push(...get2(d3[0], query2, ReturnType.ALL)));
  return nextSet;
}
function addToArray(result2, index2, value2, force) {
  const target = result2[0];
  if (/^\[\]$/.test(index2)) {
    target.push(value2);
    const i3 = target.length - 1;
    return [target[i3], i3, target, `${result2[3]}/${i3}}`];
  }
  if (force == null && getType(target[index2]) === "object" && getType(value2) === "object") {
    Object.assign(target[index2], value2);
    return [target[index2], index2, target, `${result2[3]}/${index2}}`];
  }
  if (force === set.INSERT_ITEMS || force == null && arrayHasIndex.test(index2)) {
    const arrayIndex = convertToIndex(index2);
    insert3(target, arrayIndex, value2);
    return [
      target[arrayIndex],
      arrayIndex,
      target,
      `${result2[3]}/${arrayIndex}}`
    ];
  }
  if (force === set.REPLACE_ITEMS || force == null) {
    const arrayIndex = convertToIndex(index2);
    target[arrayIndex] = value2;
    return [
      target[arrayIndex],
      arrayIndex,
      target,
      `${result2[3]}/${arrayIndex}}`
    ];
  }
  throw new Error(`Unknown array index '${index2}' with force-option '${force}'`);
}
function create4(workingSet, query2, keyIsArray, force) {
  query2 = removeEscape(query2);
  return workingSet.filter((o3) => {
    if (Array.isArray(o3[0]) && isArrayProp.test(query2)) {
      return true;
    }
    return ignoreTypes.includes(getType(o3[0][query2])) === false;
  }).map((r3) => {
    const container = keyIsArray ? [] : {};
    const o3 = r3[0];
    const containerType = getType(container);
    const itemType = getType(o3[query2]);
    if (Array.isArray(o3) && itemType !== containerType) {
      return addToArray(r3, query2, container, force);
    }
    o3[query2] = o3[query2] || container;
    return [o3[query2], query2, o3, `${r3[3]}/${query2}`];
  });
}
var InsertMode;
(function(InsertMode2) {
  InsertMode2["REPLACE_ITEMS"] = "replace";
  InsertMode2["INSERT_ITEMS"] = "insert";
})(InsertMode || (InsertMode = {}));
set.REPLACE_ITEMS = InsertMode.REPLACE_ITEMS;
set.INSERT_ITEMS = InsertMode.INSERT_ITEMS;
function set(data2, queryString, value2, force) {
  if (queryString == null) {
    return cp(data2);
  }
  queryString = queryString.replace(/(\/$)/g, "");
  if (queryString === "") {
    return cp(value2);
  }
  const result2 = cp(data2);
  let workingSet = [[result2, null, null, "#"]];
  const path = split2(queryString);
  const property2 = path.pop();
  const arrayWithoutIndex = isArray2.test(property2) && arrayHasIndex.test(property2) === false;
  if (isProperty.test(property2) === false || arrayWithoutIndex) {
    throw new Error(`Unsupported query '${queryString}' ending with non-property`);
  }
  path.forEach((query2, index2) => {
    if ("__proto__" === query2 || "prototyped" === query2 || "constructor" === query2) {
      return;
    }
    if (isProperty.test(query2) === false) {
      workingSet = select2(workingSet, query2);
      return;
    }
    const nextKey = index2 >= path.length - 1 ? property2 : path[index2 + 1];
    const insertArray = isArrayProp.test(nextKey);
    workingSet = create4(workingSet, query2, insertArray, force);
  });
  workingSet.forEach((r3) => {
    let targetValue = value2;
    if (getType(value2) === "function") {
      targetValue = value2(r3[3], property2, r3[0], `${r3[3]}/${property2}`);
    }
    const d3 = r3[0];
    if (Array.isArray(d3)) {
      addToArray(r3, property2, targetValue, force);
    } else {
      const unescapedProp = removeEscape(property2);
      if ("__proto__" === unescapedProp || "prototyped" === unescapedProp || "constructor" === unescapedProp) {
        return;
      }
      d3[unescapedProp] = targetValue;
    }
  });
  return result2;
}

// node_modules/@sagold/json-query/dist/module/lib/remove.js
var import_json_pointer = __toESM(require_jsonPointer());

// node_modules/json-schema-library/dist/module/lib/schema/types.js
var Types = {
  $ref: {
    type: false
  },
  allOf: {
    type: false,
    definitions: ["allOf/*"]
  },
  anyOf: {
    type: false,
    definitions: ["anyOf/*"]
  },
  array: {
    type: true,
    // ignore additionalItems:TypeDef, when items:TypeDef
    definitions: [
      "allOf/*",
      "anyOf/*",
      "oneOf/*",
      "not",
      "items",
      "items/*",
      "additionalItems"
    ],
    validationKeywords: ["minItems", "maxItems", "uniqueItems"],
    keywords: ["items", "additionalItems", "minItems", "maxItems", "uniqueItems"]
  },
  boolean: {
    type: true
  },
  enum: {
    type: false
  },
  integer: {
    type: true,
    definitions: ["allOf/*", "anyOf/*", "oneOf/*", "not"],
    validationKeywords: ["minimum", "maximum", "multipleOf"]
  },
  not: {
    type: false,
    definitions: ["not"]
  },
  number: {
    type: true,
    definitions: ["allOf/*", "anyOf/*", "oneOf/*", "not"],
    validationKeywords: ["minimum", "maximum", "multipleOf"]
  },
  null: {
    type: true
  },
  object: {
    type: true,
    // patternProperties also validate properties
    // dependencies:(string, TypeDef) extend current TypeDef
    // additional Properties validate only remaining properties (after properties & pattern)
    definitions: [
      "allOf/*",
      "anyOf/*",
      "oneOf/*",
      "not",
      "properties/*",
      "additionalProperties",
      "patternProperties/*",
      "dependencies/*"
    ],
    validationKeywords: ["minProperties", "maxProperties", "required"],
    keywords: [
      "properties",
      "additionalProperties",
      "patternProperties",
      "dependencies",
      "minProperties",
      "maxProperties",
      "required"
    ]
  },
  oneOf: {
    type: false,
    definitions: ["oneOf/*"]
  },
  string: {
    type: true,
    definitions: ["allOf/*", "anyOf/*", "oneOf/*", "not"],
    validationKeywords: ["minLength", "maxLength", "pattern"]
  }
};
var types_default = Types;

// node_modules/json-schema-library/dist/module/lib/schema/getTypeId.js
var typeKeywords = Object.keys(types_default).filter((id) => types_default[id].type === false);
var hasOwnProperty3 = Object.prototype.hasOwnProperty;
function getTypeId(schema7) {
  if (isObject4(schema7) === false) {
    return void 0;
  }
  if (schema7.enum) {
    return "enum";
  }
  const type = schema7.type;
  if (Array.isArray(type) || types_default[type]) {
    return type;
  }
  const ids = typeKeywords.filter((type2) => schema7[type2]);
  if (ids.length === 1) {
    return ids[0];
  }
  if (ids.length === 0) {
    for (let i3 = 0, l3 = types_default.object.keywords.length; i3 < l3; i3 += 1) {
      const keyword2 = types_default.object.keywords[i3];
      if (hasOwnProperty3.call(schema7, keyword2)) {
        return "object";
      }
    }
    for (let i3 = 0, l3 = types_default.array.keywords.length; i3 < l3; i3 += 1) {
      const keyword2 = types_default.array.keywords[i3];
      if (hasOwnProperty3.call(schema7, keyword2)) {
        return "array";
      }
    }
    return void 0;
  }
  throw new Error(`Mutiple typeIds [${ids.join(", ")}] matched in ${JSON.stringify(schema7)}`);
}

// node_modules/json-schema-library/dist/module/lib/schema/getTypeDefs.js
function getTypeDefs(schema7) {
  const defs = [];
  const id = getTypeId(schema7);
  if (id == null) {
    return defs;
  }
  let type;
  if (Array.isArray(id)) {
    type = {};
    for (let i3 = 0, l3 = id.length; i3 < l3; i3 += 1) {
      Object.assign(type, types_default[id[i3]]);
    }
  } else {
    type = types_default[id];
  }
  if (type.definitions == null) {
    return defs;
  }
  type.definitions.forEach((query2) => {
    get2(schema7, query2, (value2, key2, parent, pointer) => {
      if (isObject4(value2) && getTypeId(value2)) {
        defs.push({ pointer: import_json_pointer2.default.join(import_json_pointer2.default.split(pointer), false), def: value2 });
      }
    });
  });
  return defs;
}

// node_modules/json-schema-library/dist/module/lib/eachSchema.js
function nextTypeDefs(schema7, pointer) {
  if (this.callback(schema7, pointer) === true) {
    return;
  }
  const defs = getTypeDefs(schema7);
  defs.forEach((next2) => this.nextTypeDefs(next2.def, import_json_pointer3.default.join(pointer, next2.pointer, false)));
}
function eachDefinition(walk, schema7, pointer, key2 = "definitions") {
  const defs = schema7[key2];
  Object.keys(defs).forEach((defId) => {
    if (defs[defId] === false || isObject4(defs[defId])) {
      walk.nextTypeDefs(defs[defId], import_json_pointer3.default.join(pointer, key2, defId, false));
      return;
    }
  });
}
function eachSchema(schema7, callback, pointer = "#") {
  const walk = { callback, nextTypeDefs };
  walk.nextTypeDefs(schema7, pointer);
  if (schema7.definitions != null) {
    walk.callback = (defschema, schemaPointer) => {
      callback(defschema, schemaPointer);
      if (defschema.definitions != null) {
        eachDefinition(walk, defschema, schemaPointer);
      }
    };
    eachDefinition(walk, schema7, pointer);
  }
  if (schema7.$defs != null) {
    walk.callback = (defschema, schemaPointer) => {
      callback(defschema, schemaPointer);
      if (defschema.definitions != null) {
        eachDefinition(walk, defschema, schemaPointer);
      }
    };
    eachDefinition(walk, schema7, pointer, "$defs");
  }
}

// node_modules/json-schema-library/dist/module/lib/compile/joinScope.js
var suffixes = /(#|\/)+$/;
var trailingHash = /#$/;
var isDomain = /^[^:]+:\/\/[^/]+\//;
var trailingFragments = /\/[^/]*$/;
var idAndPointer = /#.*$/;
function joinScope(previous, id) {
  if (previous == null && id == null) {
    return "#";
  }
  if (id == null) {
    return previous.replace(trailingHash, "");
  }
  if (previous == null) {
    return id.replace(trailingHash, "");
  }
  if (id[0] === "#") {
    return `${previous.replace(idAndPointer, "")}${id.replace(suffixes, "")}`;
  }
  if (isDomain.test(id)) {
    return id.replace(trailingHash, "");
  }
  return `${previous.replace(trailingFragments, "")}/${id.replace(trailingHash, "")}`;
}

// node_modules/json-schema-library/dist/module/lib/compile/getRef.js
var import_json_pointer4 = __toESM(require_jsonPointer());

// node_modules/json-schema-library/dist/module/lib/compile/splitRef.js
var suffixes2 = /(#|\/)+$/g;
var emptyValues = ["", null, "#"];
function splitRef($ref) {
  if (emptyValues.includes($ref)) {
    return [];
  }
  $ref = $ref.replace(suffixes2, "");
  if ($ref.indexOf("#") === -1) {
    return [$ref.replace(suffixes2, "")];
  }
  if ($ref.indexOf("#") === 0) {
    return [$ref.replace(suffixes2, "")];
  }
  const result2 = $ref.split("#");
  result2[0] = result2[0].replace(suffixes2, "");
  result2[1] = `#${result2[1].replace(suffixes2, "")}`;
  return result2;
}

// node_modules/json-schema-library/dist/module/lib/compile/getRef.js
var suffixes3 = /(#|\/)+$/g;
var isObject5 = (val) => getTypeOf(val) === "object";
function getRef(context, rootSchema, $ref) {
  if (isObject5($ref)) {
    $ref = $ref.__ref || $ref.$ref;
  }
  if ($ref == null) {
    return rootSchema;
  }
  let schema7;
  const $remote = $ref.replace(suffixes3, "");
  if (context.remotes[$remote]) {
    schema7 = context.remotes[$remote];
    if (schema7 && schema7.$ref) {
      return getRef(context, rootSchema, schema7.$ref);
    }
    return schema7;
  }
  if (context.ids[$ref]) {
    schema7 = (0, import_json_pointer4.get)(rootSchema, context.ids[$ref]);
    if (schema7 && schema7.$ref) {
      return getRef(context, rootSchema, schema7.$ref);
    }
    return schema7;
  }
  const fragments = splitRef($ref);
  if (fragments.length === 0) {
    return rootSchema;
  }
  if (fragments.length === 1) {
    $ref = fragments[0];
    if (context.remotes[$ref]) {
      schema7 = context.remotes[$ref];
      return getRef(context, rootSchema, schema7.$ref);
    }
    if (context.ids[$ref]) {
      schema7 = (0, import_json_pointer4.get)(rootSchema, context.ids[$ref]);
      if (schema7 && schema7.$ref) {
        return getRef(context, rootSchema, schema7.$ref);
      }
      return schema7;
    }
  }
  if (fragments.length === 2) {
    const base3 = fragments[0];
    $ref = fragments[1];
    if (context.remotes[base3]) {
      if (context.remotes[base3].getRef) {
        return context.remotes[base3].getRef($ref);
      }
      return getRef(context, context.remotes[base3], $ref);
    }
    if (context.ids[base3]) {
      return getRef(context, (0, import_json_pointer4.get)(rootSchema, context.ids[base3]), $ref);
    }
  }
  schema7 = (0, import_json_pointer4.get)(rootSchema, context.ids[$ref] || $ref);
  if (schema7 && schema7.$ref) {
    return getRef(context, rootSchema, schema7.$ref);
  }
  return schema7;
}

// node_modules/json-schema-library/dist/module/lib/compile/index.js
var import_json_pointer5 = __toESM(require_jsonPointer());
var COMPILED = "__compiled";
var COMPILED_REF = "__ref";
var GET_REF = "getRef";
var GET_ROOT = "getRoot";
var suffixes4 = /(#|\/)+$/g;
function compileSchema(draft, schemaToCompile, rootSchema = schemaToCompile, force = false) {
  if (!schemaToCompile || schemaToCompile[COMPILED] !== void 0) {
    return schemaToCompile;
  }
  const context = { ids: {}, remotes: draft.remotes };
  const rootSchemaAsString = JSON.stringify(schemaToCompile);
  const compiledSchema = JSON.parse(rootSchemaAsString);
  Object.defineProperty(compiledSchema, COMPILED, { enumerable: false, value: true });
  Object.defineProperty(compiledSchema, GET_REF, {
    enumerable: false,
    value: getRef.bind(null, context, compiledSchema)
  });
  if (force === false && rootSchemaAsString.includes("$ref") === false) {
    return compiledSchema;
  }
  if (schemaToCompile !== rootSchema) {
    Object.defineProperty(compiledSchema, "definitions", {
      enumerable: false,
      value: Object.assign({}, rootSchema.definitions, rootSchema.$defs, schemaToCompile.definitions, schemaToCompile.$defs)
    });
  }
  const scopes = {};
  const getRoot2 = () => compiledSchema;
  eachSchema(compiledSchema, (schema7, pointer) => {
    var _a4;
    if (schema7.id) {
      if (schema7.id.startsWith("http") && /(allOf|anyOf|oneOf)\/\d+$/.test(pointer)) {
        const parentPointer2 = pointer.replace(/\/(allOf|anyOf|oneOf)\/\d+$/, "");
        const parentSchema = (0, import_json_pointer5.get)(compiledSchema, parentPointer2);
        schema7.id = (_a4 = parentSchema.id) !== null && _a4 !== void 0 ? _a4 : schema7.id;
      }
      context.ids[schema7.id.replace(suffixes4, "")] = pointer;
    }
    pointer = `#${pointer}`.replace(/##+/, "#");
    const previousPointer = pointer.replace(/\/[^/]+$/, "");
    const parentPointer = pointer.replace(/\/[^/]+\/[^/]+$/, "");
    const previousScope = scopes[previousPointer] || scopes[parentPointer];
    const scope = joinScope(previousScope, schema7.id);
    scopes[pointer] = scope;
    if (context.ids[scope] == null) {
      context.ids[scope] = pointer;
    }
    if (schema7.$ref && !schema7[COMPILED_REF]) {
      Object.defineProperty(schema7, COMPILED_REF, {
        enumerable: false,
        value: joinScope(scope, schema7.$ref)
      });
      Object.defineProperty(schema7, GET_ROOT, { enumerable: false, value: getRoot2 });
    }
  });
  return compiledSchema;
}

// node_modules/json-schema-library/dist/module/lib/compileSchema.js
var compileSchema_default = compileSchema;

// node_modules/json-schema-library/dist/module/lib/each.js
function each2(draft, data2, callback, schema7 = draft.rootSchema, pointer = "#") {
  schema7 = draft.resolveRef(schema7);
  callback(schema7, data2, pointer);
  const dataType = getTypeOf(data2);
  if (dataType === "object") {
    Object.keys(data2).forEach((key2) => {
      const nextSchema = draft.step(key2, schema7, data2, pointer);
      const next2 = data2[key2];
      draft.each(next2, callback, nextSchema, `${pointer}/${key2}`);
    });
  } else if (dataType === "array") {
    data2.forEach((next2, key2) => {
      const nextSchema = draft.step(key2, schema7, data2, pointer);
      draft.each(next2, callback, nextSchema, `${pointer}/${key2}`);
    });
  }
}

// node_modules/json-schema-library/dist/module/lib/validation/errors.js
var errors = {
  additionalItemsError: createCustomError("AdditionalItemsError"),
  additionalPropertiesError: createCustomError("AdditionalPropertiesError"),
  anyOfError: createCustomError("AnyOfError"),
  allOfError: createCustomError("AllOfError"),
  constError: createCustomError("ConstError"),
  containsError: createCustomError("ContainsError"),
  containsArrayError: createCustomError("ContainsArrayError"),
  containsAnyError: createCustomError("ContainsAnyError"),
  enumError: createCustomError("EnumError"),
  forbiddenPropertyError: createCustomError("ForbiddenPropertyError"),
  formatURLError: createCustomError("FormatURLError"),
  formatURIError: createCustomError("FormatURIError"),
  formatURIReferenceError: createCustomError("FormatURIReferenceError"),
  formatURITemplateError: createCustomError("FormatURITemplateError"),
  formatDateError: createCustomError("FormatDateError"),
  formatDateTimeError: createCustomError("FormatDateTimeError"),
  formatEmailError: createCustomError("FormatEmailError"),
  formatHostnameError: createCustomError("FormatHostnameError"),
  formatIPV4Error: createCustomError("FormatIPV4Error"),
  formatIPV4LeadingZeroError: createCustomError("FormatIPV4LeadingZeroError"),
  formatIPV6Error: createCustomError("FormatIPV6Error"),
  formatIPV6LeadingZeroError: createCustomError("FormatIPV6LeadingZeroError"),
  formatJsonPointerError: createCustomError("FormatJsonPointerError"),
  formatRegExError: createCustomError("FormatRegExError"),
  formatTimeError: createCustomError("FormatTimeError"),
  invalidSchemaError: createCustomError("InvalidSchemaError"),
  invalidDataError: createCustomError("InvalidDataError"),
  invalidTypeError: createCustomError("InvalidTypeError"),
  invalidPropertyNameError: createCustomError("InvalidPropertyNameError"),
  maximumError: createCustomError("MaximumError"),
  maxItemsError: createCustomError("MaxItemsError"),
  maxLengthError: createCustomError("MaxLengthError"),
  maxPropertiesError: createCustomError("MaxPropertiesError"),
  minimumError: createCustomError("MinimumError"),
  minItemsError: createCustomError("MinItemsError"),
  minItemsOneError: createCustomError("MinItemsOneError"),
  minLengthError: createCustomError("MinLengthError"),
  minLengthOneError: createCustomError("MinLengthOneError"),
  minPropertiesError: createCustomError("MinPropertiesError"),
  missingDependencyError: createCustomError("MissingDependencyError"),
  missingOneOfPropertyError: createCustomError("MissingOneOfPropertyError"),
  multipleOfError: createCustomError("MultipleOfError"),
  multipleOneOfError: createCustomError("MultipleOneOfError"),
  noAdditionalPropertiesError: createCustomError("NoAdditionalPropertiesError"),
  notError: createCustomError("NotError"),
  oneOfError: createCustomError("OneOfError"),
  oneOfPropertyError: createCustomError("OneOfPropertyError"),
  patternError: createCustomError("PatternError"),
  patternPropertiesError: createCustomError("PatternPropertiesError"),
  requiredPropertyError: createCustomError("RequiredPropertyError"),
  schemaWarning: createCustomError("SchemaWarning"),
  typeError: createCustomError("TypeError"),
  undefinedValueError: createCustomError("UndefinedValueError"),
  uniqueItemsError: createCustomError("UniqueItemsError"),
  unknownPropertyError: createCustomError("UnknownPropertyError"),
  valueNotEmptyError: createCustomError("ValueNotEmptyError")
};
var errors_default = errors;

// node_modules/json-schema-library/dist/module/lib/validation/format.js
var import_valid_url = __toESM(require_valid_url());
var import_smtp_address_parser = __toESM(require_lib());
var isValidDateTime = new RegExp("^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\\.[0-9]+)?(([Zz])|([\\+|\\-]([01][0-9]|2[0-3]):[0-5][0-9]))$");
var isValidIPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
var isValidIPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i;
var isValidHostname = /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/;
var matchDate = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var matchTime = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i;
var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var isValidJsonPointer = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var isValidRelativeJsonPointer = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
var isValidURIRef = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var isValidURITemplate = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
var formatValidators = {
  date: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    const matches3 = value2.match(matchDate);
    if (!matches3) {
      return draft.errors.formatDateTimeError({ value: value2, pointer, schema: schema7 });
    }
    const year = +matches3[1];
    const month = +matches3[2];
    const day = +matches3[3];
    const isLeapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    if (month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear ? 29 : DAYS[month])) {
      return void 0;
    }
    return draft.errors.formatDateError({ value: value2, pointer, schema: schema7 });
  },
  "date-time": (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (value2 === "" || isValidDateTime.test(value2)) {
      if (new Date(value2).toString() === "Invalid Date") {
        return draft.errors.formatDateTimeError({ value: value2, pointer, schema: schema7 });
      }
      return void 0;
    }
    return draft.errors.formatDateTimeError({ value: value2, pointer, schema: schema7 });
  },
  email: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (value2[0] === '"') {
      return draft.errors.formatEmailError({ value: value2, pointer, schema: schema7 });
    }
    const [name2, host, ...rest2] = value2.split("@");
    if (!name2 || !host || rest2.length !== 0 || name2.length > 64 || host.length > 253) {
      return draft.errors.formatEmailError({ value: value2, pointer, schema: schema7 });
    }
    if (name2[0] === "." || name2.endsWith(".") || name2.includes("..")) {
      return draft.errors.formatEmailError({ value: value2, pointer, schema: schema7 });
    }
    if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name2)) {
      return draft.errors.formatEmailError({ value: value2, pointer, schema: schema7 });
    }
    if (!host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part))) {
      return draft.errors.formatEmailError({ value: value2, pointer, schema: schema7 });
    }
    return void 0;
  },
  /**
   * @draft 7
   * [RFC6531] https://json-schema.org/draft-07/json-schema-validation.html#RFC6531
   */
  "idn-email": (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    try {
      (0, import_smtp_address_parser.parse)(value2);
      return void 0;
    } catch (e3) {
      return draft.errors.formatEmailError({ value: value2, pointer, schema: schema7 });
    }
  },
  hostname: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string") {
      return void 0;
    }
    if (value2 === "" || isValidHostname.test(value2)) {
      return void 0;
    }
    return draft.errors.formatHostnameError({ value: value2, pointer, schema: schema7 });
  },
  ipv4: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (value2 && value2[0] === "0") {
      return draft.errors.formatIPV4LeadingZeroError({ value: value2, pointer, schema: schema7 });
    }
    if (value2.length <= 15 && isValidIPV4.test(value2)) {
      return void 0;
    }
    return draft.errors.formatIPV4Error({ value: value2, pointer, schema: schema7 });
  },
  ipv6: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (value2 && value2[0] === "0") {
      return draft.errors.formatIPV6LeadingZeroError({ value: value2, pointer, schema: schema7 });
    }
    if (value2.length <= 45 && isValidIPV6.test(value2)) {
      return void 0;
    }
    return draft.errors.formatIPV6Error({ value: value2, pointer, schema: schema7 });
  },
  "json-pointer": (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (isValidJsonPointer.test(value2)) {
      return void 0;
    }
    return draft.errors.formatJsonPointerError({ value: value2, pointer, schema: schema7 });
  },
  "relative-json-pointer": (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (isValidRelativeJsonPointer.test(value2)) {
      return void 0;
    }
    return draft.errors.formatJsonPointerError({ value: value2, pointer, schema: schema7 });
  },
  regex: (draft, schema7, value2, pointer) => {
    if (typeof value2 === "string" && /\\Z$/.test(value2) === false) {
      try {
        new RegExp(value2);
        return void 0;
      } catch (e3) {
      }
      return draft.errors.formatRegExError({ value: value2, pointer, schema: schema7 });
    }
    if (typeof value2 === "object" || typeof value2 === "number" || Array.isArray(value2)) {
      return void 0;
    }
    return draft.errors.formatRegExError({ value: value2, pointer, schema: schema7 });
  },
  // hh:mm:ss.sTZD
  // https://opis.io/json-schema/2.x/formats.html
  // regex https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html
  time: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    const matches3 = value2.match(matchTime);
    return matches3 ? void 0 : draft.errors.formatDateTimeError({ value: value2, pointer, schema: schema7 });
  },
  uri: (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (import_valid_url.default.isUri(value2)) {
      return void 0;
    }
    return draft.errors.formatURIError({ value: value2, pointer, schema: schema7 });
  },
  "uri-reference": (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (isValidURIRef.test(value2)) {
      return void 0;
    }
    return draft.errors.formatURIReferenceError({ value: value2, pointer, schema: schema7 });
  },
  "uri-template": (draft, schema7, value2, pointer) => {
    if (typeof value2 !== "string" || value2 === "") {
      return void 0;
    }
    if (isValidURITemplate.test(value2)) {
      return void 0;
    }
    return draft.errors.formatURITemplateError({ value: value2, pointer, schema: schema7 });
  },
  url: (draft, schema7, value2, pointer) => {
    if (value2 === "" || import_valid_url.default.isWebUri(value2)) {
      return void 0;
    }
    return draft.errors.formatURLError({ value: value2, pointer, schema: schema7 });
  }
};
var format_default = formatValidators;

// node_modules/json-schema-library/dist/module/lib/getSchema.js
var import_json_pointer6 = __toESM(require_jsonPointer());
var emptyObject = {};
function getSchema(draft, options2 = emptyObject) {
  const { pointer = "#", data: data2, schema: schema7 = draft.rootSchema, withSchemaWarning = false } = options2;
  const path = import_json_pointer6.default.split(pointer);
  const result2 = _getSchema(draft, draft.resolveRef(schema7), path, "#", data2);
  if (!withSchemaWarning && (result2 === null || result2 === void 0 ? void 0 : result2.code) === "schema-warning") {
    return void 0;
  }
  return result2;
}
function _getSchema(draft, schema7, path, pointer, data2 = emptyObject) {
  if (path.length === 0) {
    return draft.resolveRef(schema7);
  }
  const key2 = path.shift();
  schema7 = draft.step(key2, schema7, data2, pointer);
  if (isJsonError(schema7)) {
    return schema7;
  }
  data2 = data2[key2];
  return _getSchema(draft, schema7, path, `${pointer}/${key2}`, data2);
}

// node_modules/json-schema-library/dist/module/lib/utils/isEmpty.js
function isEmpty2(v3) {
  const type = getTypeOf(v3);
  switch (type) {
    case "string":
    case "array":
      return (v3 === null || v3 === void 0 ? void 0 : v3.length) === 0;
    case "null":
    case "undefined":
      return true;
    case "object":
      return Object.keys(v3).length === 0;
    default:
      return false;
  }
}

// node_modules/json-schema-library/dist/module/lib/getTemplate.js
var defaultOptions2 = settings_default.templateDefaultOptions;
var cache4;
function shouldResolveRef(schema7, pointer) {
  const { $ref } = schema7;
  if ($ref == null) {
    return true;
  }
  const value2 = cache4[pointer] == null || cache4[pointer][$ref] == null ? 0 : cache4[pointer][$ref];
  return value2 < settings_default.GET_TEMPLATE_RECURSION_LIMIT;
}
function resolveRef2(draft, schema7, pointer) {
  const { $ref } = schema7;
  if ($ref == null) {
    return schema7;
  }
  cache4[pointer] = cache4[pointer] || {};
  cache4[pointer][$ref] = cache4[pointer][$ref] || 0;
  cache4[pointer][$ref] += 1;
  return draft.resolveRef(schema7);
}
function convertValue(type, value2) {
  if (type === "string") {
    return JSON.stringify(value2);
  } else if (typeof value2 !== "string") {
    return null;
  }
  try {
    value2 = JSON.parse(value2);
    if (typeof value2 === type) {
      return value2;
    }
  } catch (e3) {
  }
  return null;
}
function createTemplateSchema(draft, schema7, data2, pointer, opts) {
  if (getTypeOf(schema7) !== "object") {
    return Object.assign({ pointer }, schema7);
  }
  if (shouldResolveRef(schema7, pointer) === false && data2 == null) {
    return false;
  }
  let templateSchema = copy_default(resolveRef2(draft, schema7, pointer));
  if (Array.isArray(schema7.anyOf) && schema7.anyOf.length > 0) {
    if (shouldResolveRef(schema7.anyOf[0], `${pointer}/anyOf/0`)) {
      const resolvedAnyOf = resolveRef2(draft, schema7.anyOf[0], `${pointer}/anyOf/0`);
      templateSchema = merge_default(templateSchema, resolvedAnyOf);
      templateSchema.pointer = schema7.anyOf[0].$ref || templateSchema.pointer;
    }
    delete templateSchema.anyOf;
  }
  if (Array.isArray(schema7.allOf)) {
    const mayResolve = schema7.allOf.map((allOf, index2) => shouldResolveRef(allOf, `${pointer}/allOf/${index2}`)).reduceRight((next2, before2) => next2 && before2, true);
    if (mayResolve) {
      const allOf = [];
      let extendedData = copy_default(data2);
      for (let i3 = 0; i3 < schema7.allOf.length; i3 += 1) {
        allOf.push(resolveSchema(draft, schema7.allOf[i3], extendedData));
        extendedData = getTemplate(draft, extendedData, { type: schema7.type, ...allOf[i3] }, `${pointer}/allOf/${i3}`, opts);
      }
      const resolvedSchema = mergeAllOfSchema(draft, { allOf });
      if (resolvedSchema) {
        templateSchema = mergeSchema(templateSchema, resolvedSchema);
      }
    }
  }
  templateSchema.pointer = templateSchema.pointer || schema7.$ref || pointer;
  return templateSchema;
}
var isJsonSchema = (template3) => template3 && typeof template3 === "object";
function getTemplate(draft, data2, _schema, pointer, opts) {
  var _a4;
  if (_schema == null) {
    throw new Error(`getTemplate: missing schema for data: ${JSON.stringify(data2)}`);
  }
  if (pointer == null) {
    throw new Error("Missing pointer");
  }
  let schema7 = createTemplateSchema(draft, _schema, data2, pointer, opts);
  if (!isJsonSchema(schema7)) {
    return void 0;
  }
  pointer = schema7.pointer;
  if (schema7 === null || schema7 === void 0 ? void 0 : schema7.const) {
    return schema7.const;
  }
  if (Array.isArray(schema7.oneOf)) {
    if (isEmpty2(data2)) {
      const type2 = schema7.oneOf[0].type || schema7.type || schema7.const && typeof schema7.const || getTypeOf(data2);
      schema7 = { ...schema7.oneOf[0], type: type2 };
    } else {
      const resolvedSchema = resolveOneOfFuzzy(draft, data2, schema7);
      if (isJsonError(resolvedSchema)) {
        if (data2 != null && opts.removeInvalidData !== true) {
          return data2;
        }
        schema7 = schema7.oneOf[0];
        data2 = void 0;
      } else {
        resolvedSchema.type = (_a4 = resolvedSchema.type) !== null && _a4 !== void 0 ? _a4 : schema7.type;
        schema7 = resolvedSchema;
      }
    }
  }
  if (!isJsonSchema(schema7) || schema7.type == null) {
    return void 0;
  }
  if (data2 instanceof File) {
    return data2;
  }
  const type = Array.isArray(schema7.type) ? selectType(schema7.type, data2, schema7.default) : schema7.type;
  const javascriptTypeOfData = getTypeOf(data2);
  if (data2 != null && javascriptTypeOfData !== type && !(javascriptTypeOfData === "number" && type === "integer")) {
    data2 = convertValue(type, data2);
  }
  if (TYPE[type] == null) {
    if (opts.removeInvalidData) {
      return void 0;
    }
    return data2;
  }
  const templateData = TYPE[type](draft, schema7, data2, pointer, opts);
  return templateData;
}
function selectType(types2, data2, defaultValue) {
  if (data2 == void 0) {
    if (defaultValue != null) {
      const defaultType = getTypeOf(defaultValue);
      if (types2.includes(defaultType)) {
        return defaultType;
      }
    }
    return types2[0];
  }
  const dataType = getTypeOf(data2);
  if (types2.includes(dataType)) {
    return dataType;
  }
  return types2[0];
}
var TYPE = {
  null: (draft, schema7, data2) => getDefault(schema7, data2, null),
  string: (draft, schema7, data2) => getDefault(schema7, data2, ""),
  number: (draft, schema7, data2) => getDefault(schema7, data2, 0),
  integer: (draft, schema7, data2) => getDefault(schema7, data2, 0),
  boolean: (draft, schema7, data2) => getDefault(schema7, data2, false),
  object: (draft, schema7, data2, pointer, opts) => {
    var _a4;
    const template3 = schema7.default === void 0 ? {} : schema7.default;
    const d3 = {};
    const required2 = opts.extendDefaults === false && schema7.default !== void 0 ? [] : (_a4 = schema7.required) !== null && _a4 !== void 0 ? _a4 : [];
    if (schema7.properties) {
      Object.keys(schema7.properties).forEach((key2) => {
        const value2 = data2 == null || data2[key2] == null ? template3[key2] : data2[key2];
        const isRequired = required2.includes(key2);
        if (value2 != null || isRequired || opts.addOptionalProps) {
          d3[key2] = getTemplate(draft, value2, schema7.properties[key2], `${pointer}/properties/${key2}`, opts);
        }
      });
    }
    let dependenciesSchema = resolveDependencies(draft, schema7, d3);
    if (dependenciesSchema) {
      dependenciesSchema = mergeSchema(schema7, dependenciesSchema);
      delete dependenciesSchema.dependencies;
      const dependencyData = getTemplate(draft, data2, dependenciesSchema, `${pointer}/dependencies`, opts);
      Object.assign(d3, dependencyData);
    }
    if (data2) {
      if (opts.removeInvalidData === true && (schema7.additionalProperties === false || getTypeOf(schema7.additionalProperties) === "object")) {
        if (getTypeOf(schema7.additionalProperties) === "object") {
          Object.keys(data2).forEach((key2) => {
            if (d3[key2] == null) {
              if (draft.isValid(data2[key2], schema7.additionalProperties)) {
                d3[key2] = data2[key2];
              }
            }
          });
        }
      } else {
        Object.keys(data2).forEach((key2) => d3[key2] == null && (d3[key2] = data2[key2]));
      }
    }
    const ifSchema = resolveIfSchema(draft, schema7, d3);
    if (ifSchema) {
      const additionalData = getTemplate(draft, d3, { type: "object", ...ifSchema }, pointer, opts);
      Object.assign(d3, additionalData);
    }
    return d3;
  },
  // build array type of items, ignores additionalItems
  array: (draft, schema7, data2, pointer, opts) => {
    var _a4, _b;
    if (schema7.items == null) {
      return data2 || [];
    }
    const template3 = schema7.default === void 0 ? [] : schema7.default;
    const d3 = data2 || template3;
    const minItems = opts.extendDefaults === false && schema7.default !== void 0 ? 0 : schema7.minItems || 0;
    if (Array.isArray(schema7.items)) {
      for (let i3 = 0, l3 = Math.max(minItems !== null && minItems !== void 0 ? minItems : 0, (_b = (_a4 = schema7.items) === null || _a4 === void 0 ? void 0 : _a4.length) !== null && _b !== void 0 ? _b : 0); i3 < l3; i3 += 1) {
        d3[i3] = getTemplate(draft, d3[i3] == null ? template3[i3] : d3[i3], schema7.items[i3], `${pointer}/items/${i3}`, opts);
      }
      return d3;
    }
    if (getTypeOf(schema7.items) !== "object") {
      return d3;
    }
    const templateSchema = createTemplateSchema(draft, schema7.items, data2, pointer, opts);
    if (templateSchema === false) {
      return d3;
    }
    pointer = templateSchema.pointer || pointer;
    if (templateSchema.oneOf && d3.length === 0) {
      const oneOfSchema = templateSchema.oneOf[0];
      for (let i3 = 0; i3 < minItems; i3 += 1) {
        d3[i3] = getTemplate(draft, d3[i3] == null ? template3[i3] : d3[i3], oneOfSchema, `${pointer}/oneOf/0`, opts);
      }
      return d3;
    }
    if (templateSchema.oneOf && d3.length > 0) {
      const itemCount = Math.max(minItems, d3.length);
      for (let i3 = 0; i3 < itemCount; i3 += 1) {
        let value2 = d3[i3] == null ? template3[i3] : d3[i3];
        let one2 = resolveOneOfFuzzy(draft, value2, templateSchema);
        if (one2 == null || isJsonError(one2)) {
          if (value2 != null && opts.removeInvalidData !== true) {
            d3[i3] = value2;
          } else {
            value2 = void 0;
            one2 = templateSchema.oneOf[0];
            d3[i3] = getTemplate(draft, value2, one2, `${pointer}/oneOf/${i3}`, opts);
          }
        } else {
          d3[i3] = getTemplate(draft, value2, one2, `${pointer}/oneOf/${i3}`, opts);
        }
      }
      return d3;
    }
    if (templateSchema.type) {
      for (let i3 = 0, l3 = Math.max(minItems, d3.length); i3 < l3; i3 += 1) {
        d3[i3] = getTemplate(draft, d3[i3] == null ? template3[i3] : d3[i3], templateSchema, `${pointer}/items`, opts);
      }
      return d3;
    }
    return d3;
  }
};
function getDefault(schema7, templateValue, initValue) {
  if (templateValue != null) {
    return templateValue;
  } else if (schema7.const) {
    return schema7.const;
  } else if (schema7.default === void 0 && Array.isArray(schema7.enum)) {
    return schema7.enum[0];
  } else if (schema7.default === void 0) {
    return initValue;
  }
  return schema7.default;
}
var getTemplate_default = (draft, data2, schema7 = draft.rootSchema, opts) => {
  cache4 = {};
  if (opts) {
    return getTemplate(draft, data2, schema7, "#", { ...defaultOptions2, ...opts });
  }
  return getTemplate(draft, data2, schema7, "#", defaultOptions2);
};

// node_modules/json-schema-library/dist/module/lib/isValid.js
function isValid(draft, value2, schema7 = draft.rootSchema, pointer = "#") {
  return draft.validate(value2, schema7, pointer).length === 0;
}

// node_modules/json-schema-library/dist/module/lib/utils/punycode.ucs2decode.js
function ucs2decode(string3) {
  const output = [];
  let counter3 = 0;
  const length = string3.length;
  while (counter3 < length) {
    const value2 = string3.charCodeAt(counter3++);
    if (value2 >= 55296 && value2 <= 56319 && counter3 < length) {
      const extra = string3.charCodeAt(counter3++);
      if ((extra & 64512) == 56320) {
        output.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output.push(value2);
        counter3--;
      }
    } else {
      output.push(value2);
    }
  }
  return output;
}

// node_modules/json-schema-library/dist/module/lib/utils/getPrecision.js
function getPrecision(value2) {
  const string3 = `${value2}`;
  const index2 = string3.indexOf(".");
  return index2 === -1 ? 0 : string3.length - (index2 + 1);
}

// node_modules/json-schema-library/dist/module/lib/validation/keyword.js
var import_fast_deep_equal = __toESM(require_fast_deep_equal());
var hasOwnProperty4 = Object.prototype.hasOwnProperty;
var hasProperty = (value2, property2) => !(value2[property2] === void 0 || !hasOwnProperty4.call(value2, property2));
var KeywordValidation = {
  additionalProperties: (draft, schema7, value2, pointer) => {
    if (schema7.additionalProperties === true || schema7.additionalProperties == null) {
      return void 0;
    }
    if (getTypeOf(schema7.patternProperties) === "object" && schema7.additionalProperties === false) {
      return void 0;
    }
    const errors3 = [];
    let receivedProperties = Object.keys(value2).filter((prop2) => settings_default.propertyBlacklist.includes(prop2) === false);
    const expectedProperties = Object.keys(schema7.properties || {});
    if (getTypeOf(schema7.patternProperties) === "object") {
      const patterns = Object.keys(schema7.patternProperties).map((pattern2) => new RegExp(pattern2));
      receivedProperties = receivedProperties.filter((prop2) => {
        for (let i3 = 0; i3 < patterns.length; i3 += 1) {
          if (patterns[i3].test(prop2)) {
            return false;
          }
        }
        return true;
      });
    }
    for (let i3 = 0, l3 = receivedProperties.length; i3 < l3; i3 += 1) {
      const property2 = receivedProperties[i3];
      if (expectedProperties.indexOf(property2) === -1) {
        const additionalIsObject = isObject4(schema7.additionalProperties);
        if (additionalIsObject && Array.isArray(schema7.additionalProperties.oneOf)) {
          const result2 = draft.resolveOneOf(value2[property2], schema7.additionalProperties, `${pointer}/${property2}`);
          if (isJsonError(result2)) {
            errors3.push(draft.errors.additionalPropertiesError({
              pointer,
              schema: schema7.additionalProperties,
              value: value2,
              property: receivedProperties[i3],
              properties: expectedProperties,
              // pass all validation errors
              errors: result2.data.errors
            }));
          } else {
            errors3.push(...draft.validate(value2[property2], result2, pointer));
          }
        } else if (additionalIsObject) {
          errors3.push(...draft.validate(value2[property2], schema7.additionalProperties, `${pointer}/${property2}`));
        } else {
          errors3.push(draft.errors.noAdditionalPropertiesError({
            pointer,
            schema: schema7,
            value: value2,
            property: receivedProperties[i3],
            properties: expectedProperties
          }));
        }
      }
    }
    return errors3;
  },
  allOf: validateAllOf,
  anyOf: validateAnyOf,
  dependencies: validateDependencies,
  enum: (draft, schema7, value2, pointer) => {
    const type = getTypeOf(value2);
    if (type === "object" || type === "array") {
      const valueStr = JSON.stringify(value2);
      for (let i3 = 0; i3 < schema7.enum.length; i3 += 1) {
        if (JSON.stringify(schema7.enum[i3]) === valueStr) {
          return void 0;
        }
      }
    } else if (schema7.enum.includes(value2)) {
      return void 0;
    }
    return draft.errors.enumError({ pointer, schema: schema7, value: value2, values: schema7.enum });
  },
  format: (draft, schema7, value2, pointer) => {
    if (draft.validateFormat[schema7.format]) {
      const errors3 = draft.validateFormat[schema7.format](draft, schema7, value2, pointer);
      return errors3;
    }
    return void 0;
  },
  items: (draft, schema7, value2, pointer) => {
    if (schema7.items === false) {
      if (Array.isArray(value2) && value2.length === 0) {
        return void 0;
      }
      return draft.errors.invalidDataError({ pointer, value: value2, schema: schema7 });
    }
    const errors3 = [];
    for (let i3 = 0; i3 < value2.length; i3 += 1) {
      const itemData = value2[i3];
      const itemSchema = draft.step(i3, schema7, value2, pointer);
      if (isJsonError(itemSchema)) {
        return [itemSchema];
      }
      const itemErrors = draft.validate(itemData, itemSchema, `${pointer}/${i3}`);
      errors3.push(...itemErrors);
    }
    return errors3;
  },
  maximum: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.maximum)) {
      return void 0;
    }
    if (schema7.maximum && schema7.maximum < value2) {
      return draft.errors.maximumError({
        maximum: schema7.maximum,
        length: value2,
        value: value2,
        pointer,
        schema: schema7
      });
    }
    if (schema7.maximum && schema7.exclusiveMaximum === true && schema7.maximum === value2) {
      return draft.errors.maximumError({
        maximum: schema7.maximum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  maxItems: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.maxItems)) {
      return void 0;
    }
    if (schema7.maxItems < value2.length) {
      return draft.errors.maxItemsError({
        maximum: schema7.maxItems,
        length: value2.length,
        schema: schema7,
        value: value2,
        pointer
      });
    }
    return void 0;
  },
  maxLength: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.maxLength)) {
      return void 0;
    }
    const lengthOfString = ucs2decode(value2).length;
    if (schema7.maxLength < lengthOfString) {
      return draft.errors.maxLengthError({
        maxLength: schema7.maxLength,
        length: lengthOfString,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  maxProperties: (draft, schema7, value2, pointer) => {
    const propertyCount = Object.keys(value2).length;
    if (isNaN(schema7.maxProperties) === false && schema7.maxProperties < propertyCount) {
      return draft.errors.maxPropertiesError({
        maxProperties: schema7.maxProperties,
        length: propertyCount,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  minLength: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.minLength)) {
      return void 0;
    }
    const lengthOfString = ucs2decode(value2).length;
    if (schema7.minLength > lengthOfString) {
      if (schema7.minLength === 1) {
        return draft.errors.minLengthOneError({
          minLength: schema7.minLength,
          length: lengthOfString,
          pointer,
          schema: schema7,
          value: value2
        });
      }
      return draft.errors.minLengthError({
        minLength: schema7.minLength,
        length: lengthOfString,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  minimum: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.minimum)) {
      return void 0;
    }
    if (schema7.minimum > value2) {
      return draft.errors.minimumError({
        minimum: schema7.minimum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    if (schema7.exclusiveMinimum === true && schema7.minimum === value2) {
      return draft.errors.minimumError({
        minimum: schema7.minimum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  minItems: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.minItems)) {
      return void 0;
    }
    if (schema7.minItems > value2.length) {
      if (schema7.minItems === 1) {
        return draft.errors.minItemsOneError({
          minItems: schema7.minItems,
          length: value2.length,
          pointer,
          schema: schema7,
          value: value2
        });
      }
      return draft.errors.minItemsError({
        minItems: schema7.minItems,
        length: value2.length,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  minProperties: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.minProperties)) {
      return void 0;
    }
    const propertyCount = Object.keys(value2).length;
    if (schema7.minProperties > propertyCount) {
      return draft.errors.minPropertiesError({
        minProperties: schema7.minProperties,
        length: propertyCount,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  multipleOf: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.multipleOf) || typeof value2 !== "number") {
      return void 0;
    }
    const valuePrecision = getPrecision(value2);
    const multiplePrecision = getPrecision(schema7.multipleOf);
    if (valuePrecision > multiplePrecision) {
      return draft.errors.multipleOfError({
        multipleOf: schema7.multipleOf,
        value: value2,
        pointer,
        schema: schema7
      });
    }
    const precision = Math.pow(10, multiplePrecision);
    const val = Math.round(value2 * precision);
    const multiple = Math.round(schema7.multipleOf * precision);
    if (val % multiple / precision !== 0) {
      return draft.errors.multipleOfError({
        multipleOf: schema7.multipleOf,
        value: value2,
        pointer,
        schema: schema7
      });
    }
    return void 0;
  },
  not: (draft, schema7, value2, pointer) => {
    const errors3 = [];
    if (draft.validate(value2, schema7.not, pointer).length === 0) {
      errors3.push(draft.errors.notError({ value: value2, not: schema7.not, pointer, schema: schema7 }));
    }
    return errors3;
  },
  oneOf: validateOneOf,
  pattern: (draft, schema7, value2, pointer) => {
    const pattern2 = new RegExp(schema7.pattern, "u");
    if (pattern2.test(value2) === false) {
      return draft.errors.patternError({
        pattern: schema7.pattern,
        description: schema7.patternExample || schema7.pattern,
        received: value2,
        schema: schema7,
        value: value2,
        pointer
      });
    }
    return void 0;
  },
  patternProperties: (draft, schema7, value2, pointer) => {
    const properties = schema7.properties || {};
    const pp = schema7.patternProperties;
    if (getTypeOf(pp) !== "object") {
      return void 0;
    }
    const errors3 = [];
    const keys5 = Object.keys(value2);
    const patterns = Object.keys(pp).map((expr) => ({
      regex: new RegExp(expr),
      patternSchema: pp[expr]
    }));
    keys5.forEach((key2) => {
      let patternFound = false;
      for (let i3 = 0, l3 = patterns.length; i3 < l3; i3 += 1) {
        if (patterns[i3].regex.test(key2)) {
          patternFound = true;
          const valErrors = draft.validate(value2[key2], patterns[i3].patternSchema, `${pointer}/${key2}`);
          if (valErrors && valErrors.length > 0) {
            errors3.push(...valErrors);
          }
        }
      }
      if (properties[key2]) {
        return;
      }
      if (patternFound === false && schema7.additionalProperties === false) {
        errors3.push(draft.errors.patternPropertiesError({
          key: key2,
          pointer,
          schema: schema7,
          value: value2,
          patterns: Object.keys(pp).join(",")
        }));
      }
    });
    return errors3;
  },
  properties: (draft, schema7, value2, pointer) => {
    const errors3 = [];
    const keys5 = Object.keys(schema7.properties || {});
    for (let i3 = 0; i3 < keys5.length; i3 += 1) {
      const key2 = keys5[i3];
      if (hasProperty(value2, key2)) {
        const itemSchema = draft.step(key2, schema7, value2, pointer);
        const keyErrors = draft.validate(value2[key2], itemSchema, `${pointer}/${key2}`);
        errors3.push(...keyErrors);
      }
    }
    return errors3;
  },
  // @todo move to separate file: this is custom keyword validation for JsonEditor.properties keyword
  propertiesRequired: (draft, schema7, value2, pointer) => {
    const errors3 = [];
    const keys5 = Object.keys(schema7.properties || {});
    for (let i3 = 0; i3 < keys5.length; i3 += 1) {
      const key2 = keys5[i3];
      if (value2[key2] === void 0) {
        errors3.push(draft.errors.requiredPropertyError({ key: key2, pointer, schema: schema7, value: value2 }));
      } else {
        const itemSchema = draft.step(key2, schema7, value2, pointer);
        const keyErrors = draft.validate(value2[key2], itemSchema, `${pointer}/${key2}`);
        errors3.push(...keyErrors);
      }
    }
    return errors3;
  },
  required: (draft, schema7, value2, pointer) => {
    if (Array.isArray(schema7.required) === false) {
      return void 0;
    }
    return schema7.required.map((property2) => {
      if (!hasProperty(value2, property2)) {
        return draft.errors.requiredPropertyError({
          key: property2,
          pointer,
          schema: schema7,
          value: value2
        });
      }
      return void 0;
    });
  },
  // @todo move to separate file: this is custom keyword validation for JsonEditor.required keyword
  requiredNotEmpty: (draft, schema7, value2, pointer) => {
    if (Array.isArray(schema7.required) === false) {
      return void 0;
    }
    return schema7.required.map((property2) => {
      if (value2[property2] == null || value2[property2] === "") {
        return draft.errors.valueNotEmptyError({
          property: property2,
          pointer: `${pointer}/${property2}`,
          schema: schema7,
          value: value2
        });
      }
      return void 0;
    });
  },
  uniqueItems: (draft, schema7, value2, pointer) => {
    if ((Array.isArray(value2) && schema7.uniqueItems) === false) {
      return void 0;
    }
    const duplicates = [];
    const errors3 = [];
    value2.forEach((item, index2) => {
      for (let i3 = index2 + 1; i3 < value2.length; i3 += 1) {
        if ((0, import_fast_deep_equal.default)(item, value2[i3]) && !duplicates.includes(i3)) {
          errors3.push(draft.errors.uniqueItemsError({
            pointer: `${pointer}/${i3}`,
            duplicatePointer: `${pointer}/${index2}`,
            arrayPointer: pointer,
            value: JSON.stringify(item),
            schema: schema7
          }));
          duplicates.push(i3);
        }
      }
    });
    return errors3;
  }
};
var keyword_default = KeywordValidation;

// node_modules/json-schema-library/dist/module/lib/createSchemaOf.js
function createSchemaOf(data2) {
  if (data2 === void 0) {
    return void 0;
  }
  const schema7 = {
    type: getTypeOf(data2)
  };
  if (schema7.type === "object" && isObject4(data2)) {
    schema7.properties = {};
    Object.keys(data2).forEach((key2) => schema7.properties[key2] = createSchemaOf(data2[key2]));
  }
  if (schema7.type === "array" && Array.isArray(data2)) {
    if (data2.length === 1) {
      schema7.items = createSchemaOf(data2[0]);
    } else {
      schema7.items = data2.map(createSchemaOf);
    }
  }
  return schema7;
}

// node_modules/json-schema-library/dist/module/lib/step.js
var stepType = {
  array: (draft, key2, schema7, data2, pointer) => {
    const itemValue = data2 === null || data2 === void 0 ? void 0 : data2[key2];
    const itemsType = getTypeOf(schema7.items);
    if (itemsType === "object") {
      return reduceSchema(draft, schema7.items, itemValue, `${pointer}/${key2}`) || draft.resolveRef(schema7.items);
    }
    if (itemsType === "array") {
      if (schema7.items[key2] === true) {
        return createSchemaOf(itemValue);
      }
      if (schema7.items[key2] === false) {
        return draft.errors.invalidDataError({
          key: key2,
          value: itemValue,
          pointer,
          schema: schema7
        });
      }
      if (schema7.items[key2]) {
        return draft.resolveRef(schema7.items[key2]);
      }
      if (schema7.additionalItems === false) {
        return draft.errors.additionalItemsError({
          key: key2,
          value: itemValue,
          pointer,
          schema: schema7
        });
      }
      if (schema7.additionalItems === true || schema7.additionalItems === void 0) {
        return createSchemaOf(itemValue);
      }
      if (getTypeOf(schema7.additionalItems) === "object") {
        return schema7.additionalItems;
      }
      throw new Error(`Invalid schema ${JSON.stringify(schema7, null, 2)} for ${JSON.stringify(data2, null, 2)}`);
    }
    if (schema7.additionalItems !== false && itemValue) {
      return createSchemaOf(itemValue);
    }
    return new Error(`Invalid array schema for ${key2} at ${pointer}`);
  },
  object: (draft, key2, schema7, data2, pointer) => {
    var _a4;
    schema7 = reduceSchema(draft, schema7, data2, pointer);
    const property2 = (_a4 = schema7 === null || schema7 === void 0 ? void 0 : schema7.properties) === null || _a4 === void 0 ? void 0 : _a4[key2];
    if (property2 !== void 0) {
      if (property2 === false) {
        return draft.errors.forbiddenPropertyError({
          property: key2,
          value: data2,
          pointer,
          schema: schema7
        });
      } else if (property2 === true) {
        return createSchemaOf(data2 === null || data2 === void 0 ? void 0 : data2[key2]);
      }
      const targetSchema = draft.resolveRef(property2);
      if (isJsonError(targetSchema)) {
        return targetSchema;
      }
      if (targetSchema && Array.isArray(targetSchema.oneOf)) {
        const resolvedSchema = draft.resolveOneOf(data2[key2], targetSchema, `${pointer}/${key2}`);
        for (const p4 in targetSchema) {
          if (p4 !== "oneOf" && resolvedSchema[p4] === void 0) {
            resolvedSchema[p4] = targetSchema[p4];
          }
        }
        return resolvedSchema;
      }
      if (targetSchema) {
        return targetSchema;
      }
    }
    const { patternProperties } = schema7;
    if (getTypeOf(patternProperties) === "object") {
      let regex;
      const patterns = Object.keys(patternProperties);
      for (let i3 = 0, l3 = patterns.length; i3 < l3; i3 += 1) {
        regex = new RegExp(patterns[i3]);
        if (regex.test(key2)) {
          return patternProperties[patterns[i3]];
        }
      }
    }
    const { additionalProperties } = schema7;
    if (getTypeOf(additionalProperties) === "object") {
      return schema7.additionalProperties;
    }
    if (data2 && (additionalProperties === void 0 || additionalProperties === true)) {
      return createSchemaOf(data2[key2]);
    }
    return draft.errors.unknownPropertyError({
      property: key2,
      value: data2,
      pointer: `${pointer}`,
      schema: schema7
    });
  }
};
function step(draft, key2, schema7, data2, pointer = "#") {
  var _a4;
  const typeOfData = getTypeOf(data2);
  let schemaType = (_a4 = schema7.type) !== null && _a4 !== void 0 ? _a4 : typeOfData;
  if (Array.isArray(schemaType)) {
    if (!schemaType.includes(typeOfData)) {
      return draft.errors.typeError({
        value: data2,
        pointer,
        expected: schema7.type,
        received: typeOfData,
        schema: schema7
      });
    }
    schemaType = typeOfData;
  }
  const stepFunction = stepType[schemaType];
  if (stepFunction) {
    const schemaResult = stepFunction(draft, `${key2}`, schema7, data2, pointer);
    if (schemaResult === void 0) {
      return draft.errors.schemaWarning({
        pointer,
        value: data2,
        schema: schema7,
        key: key2
      });
    }
    return schemaResult;
  }
  return new Error(`Unsupported schema type ${schema7.type} for key ${key2}`);
}

// node_modules/json-schema-library/dist/module/lib/getChildSchemaSelection.js
function getChildSchemaSelection(draft, property2, schema7 = draft.rootSchema) {
  var _a4;
  if (schema7.oneOf) {
    return schema7.oneOf.map((item) => draft.resolveRef(item));
  }
  if ((_a4 = schema7.items) === null || _a4 === void 0 ? void 0 : _a4.oneOf) {
    return schema7.items.oneOf.map((item) => draft.resolveRef(item));
  }
  const result2 = draft.step(property2, schema7, {}, "#");
  if (isJsonError(result2)) {
    return result2;
  }
  return [result2];
}

// node_modules/json-schema-library/dist/module/lib/validation/type.js
var typeValidators = {
  array: (draft, schema7, value2, pointer) => draft.typeKeywords.array.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  object: (draft, schema7, value2, pointer) => draft.typeKeywords.object.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  string: (draft, schema7, value2, pointer) => draft.typeKeywords.string.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  integer: (draft, schema7, value2, pointer) => draft.typeKeywords.number.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  number: (draft, schema7, value2, pointer) => draft.typeKeywords.number.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  boolean: (draft, schema7, value2, pointer) => draft.typeKeywords.boolean.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  null: (draft, schema7, value2, pointer) => draft.typeKeywords.null.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer))
};
var type_default = typeValidators;

// node_modules/json-schema-library/dist/module/lib/validate.js
var import_fast_deep_equal2 = __toESM(require_fast_deep_equal());
function getJsonSchemaType(value2, expectedType) {
  const jsType = getTypeOf(value2);
  if (jsType === "number" && (expectedType === "integer" || Array.isArray(expectedType) && expectedType.includes("integer"))) {
    return Number.isInteger(value2) || isNaN(value2) ? "integer" : "number";
  }
  return jsType;
}
function validate2(draft, value2, schema7 = draft.rootSchema, pointer = "#") {
  schema7 = draft.resolveRef(schema7);
  if (getTypeOf(schema7) === "boolean") {
    if (schema7) {
      return [];
    }
    return [draft.errors.invalidDataError({ pointer, schema: schema7, value: value2 })];
  }
  if (isJsonError(schema7)) {
    return [schema7];
  }
  if (schema7.const !== void 0) {
    if ((0, import_fast_deep_equal2.default)(schema7.const, value2)) {
      return [];
    }
    return [draft.errors.constError({ pointer, schema: schema7, value: value2, expected: schema7.const })];
  }
  const receivedType = getJsonSchemaType(value2, schema7.type);
  const expectedType = schema7.type || receivedType;
  if (receivedType !== expectedType && (!Array.isArray(expectedType) || !expectedType.includes(receivedType))) {
    return [
      draft.errors.typeError({
        pointer,
        schema: schema7,
        value: value2,
        received: receivedType,
        expected: expectedType
      })
    ];
  }
  if (draft.validateType[receivedType] == null) {
    return [draft.errors.invalidTypeError({ pointer, schema: schema7, value: value2, receivedType })];
  }
  const errors3 = flattenArray(draft.validateType[receivedType](draft, schema7, value2, pointer));
  return errors3.filter(errorOrPromise);
}

// node_modules/json-schema-library/dist/module/lib/draft04/index.js
var draft04Config = {
  typeKeywords: {
    array: [
      "allOf",
      "anyOf",
      "enum",
      "items",
      "maxItems",
      "minItems",
      "not",
      "oneOf",
      "uniqueItems"
    ],
    boolean: ["enum", "not", "allOf", "anyOf", "oneOf"],
    object: [
      "additionalProperties",
      "dependencies",
      "enum",
      "format",
      "minProperties",
      "maxProperties",
      "patternProperties",
      "properties",
      "required",
      "not",
      "oneOf",
      "allOf",
      "anyOf"
    ],
    string: [
      "allOf",
      "anyOf",
      "enum",
      "format",
      "maxLength",
      "minLength",
      "not",
      "oneOf",
      "pattern"
    ],
    number: [
      "allOf",
      "anyOf",
      "enum",
      "format",
      "maximum",
      "minimum",
      "multipleOf",
      "not",
      "oneOf"
    ],
    null: ["allOf", "anyOf", "enum", "format", "not", "oneOf"]
  },
  validateKeyword: keyword_default,
  validateType: type_default,
  validateFormat: format_default,
  errors: errors_default,
  addRemoteSchema,
  compileSchema: compileSchema_default,
  createSchemaOf,
  each: each2,
  eachSchema,
  getChildSchemaSelection,
  getSchema,
  getTemplate: getTemplate_default,
  isValid,
  resolveAllOf,
  resolveAnyOf,
  resolveOneOf,
  resolveRef,
  step,
  validate: validate2,
  templateDefaultOptions: settings_default.templateDefaultOptions
};
var Draft04 = class extends Draft {
  constructor(schema7, config3 = {}) {
    super(merge_default(draft04Config, config3), schema7);
  }
};

// node_modules/json-schema-library/dist/module/lib/draft06/compile/index.js
var import_json_pointer7 = __toESM(require_jsonPointer());
var COMPILED2 = "__compiled";
var COMPILED_REF2 = "__ref";
var GET_REF2 = "getRef";
var GET_ROOT2 = "getRoot";
var suffixes5 = /(#|\/)+$/g;
function compileSchema2(draft, schemaToCompile, rootSchema = schemaToCompile, force = false) {
  if (schemaToCompile === true || schemaToCompile === false || schemaToCompile === void 0) {
    return schemaToCompile;
  }
  if (schemaToCompile[COMPILED2] !== void 0) {
    return schemaToCompile;
  }
  const context = { ids: {}, remotes: draft.remotes };
  const rootSchemaAsString = JSON.stringify(schemaToCompile);
  const compiledSchema = JSON.parse(rootSchemaAsString);
  Object.defineProperty(compiledSchema, COMPILED2, { enumerable: false, value: true });
  Object.defineProperty(compiledSchema, GET_REF2, {
    enumerable: false,
    value: getRef.bind(null, context, compiledSchema)
  });
  if (force === false && rootSchemaAsString.includes("$ref") === false) {
    return compiledSchema;
  }
  if (compiledSchema !== rootSchema) {
    Object.defineProperty(compiledSchema, "$defs", {
      enumerable: true,
      value: Object.assign({}, rootSchema.definitions, rootSchema.$defs, compiledSchema.definitions, compiledSchema.$defs)
    });
  }
  const scopes = {};
  const getRoot2 = () => compiledSchema;
  eachSchema(compiledSchema, (schema7, pointer) => {
    var _a4;
    if (schema7.$id) {
      if (schema7.$id.startsWith("http") && /(allOf|anyOf|oneOf)\/\d+$/.test(pointer)) {
        const parentPointer2 = pointer.replace(/\/(allOf|anyOf|oneOf)\/\d+$/, "");
        const parentSchema = (0, import_json_pointer7.get)(compiledSchema, parentPointer2);
        schema7.$id = (_a4 = parentSchema.$id) !== null && _a4 !== void 0 ? _a4 : schema7.$id;
      }
      context.ids[schema7.$id.replace(suffixes5, "")] = pointer;
    }
    pointer = `#${pointer}`.replace(/##+/, "#");
    const previousPointer = pointer.replace(/\/[^/]+$/, "");
    const parentPointer = pointer.replace(/\/[^/]+\/[^/]+$/, "");
    const previousScope = scopes[previousPointer] || scopes[parentPointer];
    const scope = joinScope(previousScope, schema7.$id);
    scopes[pointer] = scope;
    if (context.ids[scope] == null) {
      context.ids[scope] = pointer;
    }
    if (schema7.$ref && !schema7[COMPILED_REF2]) {
      Object.defineProperty(schema7, COMPILED_REF2, {
        enumerable: false,
        value: joinScope(scope, schema7.$ref)
      });
      Object.defineProperty(schema7, GET_ROOT2, { enumerable: false, value: getRoot2 });
    }
  });
  return compiledSchema;
}

// node_modules/json-schema-library/dist/module/lib/draft06/validation/keyword.js
var KeywordValidation2 = {
  ...keyword_default,
  // @draft >= 6
  contains: (draft, schema7, value2, pointer) => {
    if (schema7.contains === false) {
      return draft.errors.containsArrayError({ pointer, value: value2, schema: schema7 });
    }
    if (schema7.contains === true) {
      if (Array.isArray(value2) && value2.length === 0) {
        return draft.errors.containsAnyError({ pointer, value: value2, schema: schema7 });
      }
      return void 0;
    }
    if (getTypeOf(schema7.contains) !== "object") {
      return void 0;
    }
    for (let i3 = 0; i3 < value2.length; i3 += 1) {
      if (draft.isValid(value2[i3], schema7.contains)) {
        return void 0;
      }
    }
    return draft.errors.containsError({ pointer, schema: schema7, value: value2 });
  },
  exclusiveMaximum: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.exclusiveMaximum)) {
      return void 0;
    }
    if (schema7.exclusiveMaximum <= value2) {
      return draft.errors.maximumError({
        maximum: schema7.exclusiveMaximum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  exclusiveMinimum: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.exclusiveMinimum)) {
      return void 0;
    }
    if (schema7.exclusiveMinimum >= value2) {
      return draft.errors.minimumError({
        minimum: schema7.exclusiveMinimum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  // @feature if-then-else
  if: validateIf,
  maximum: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.maximum)) {
      return void 0;
    }
    if (schema7.maximum && schema7.maximum < value2) {
      return draft.errors.maximumError({
        maximum: schema7.maximum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  minimum: (draft, schema7, value2, pointer) => {
    if (isNaN(schema7.minimum)) {
      return void 0;
    }
    if (schema7.minimum > value2) {
      return draft.errors.minimumError({
        minimum: schema7.minimum,
        length: value2,
        pointer,
        schema: schema7,
        value: value2
      });
    }
    return void 0;
  },
  patternProperties: (draft, schema7, value2, pointer) => {
    const properties = schema7.properties || {};
    const pp = schema7.patternProperties;
    if (getTypeOf(pp) !== "object") {
      return void 0;
    }
    const errors3 = [];
    const keys5 = Object.keys(value2);
    const patterns = Object.keys(pp).map((expr) => ({
      regex: new RegExp(expr),
      patternSchema: pp[expr]
    }));
    keys5.forEach((key2) => {
      let patternFound = false;
      for (let i3 = 0, l3 = patterns.length; i3 < l3; i3 += 1) {
        if (patterns[i3].regex.test(key2)) {
          patternFound = true;
          if (patterns[i3].patternSchema === false) {
            errors3.push(draft.errors.patternPropertiesError({
              key: key2,
              pointer,
              patterns: Object.keys(pp).join(","),
              schema: schema7,
              value: value2
            }));
            return;
          }
          const valErrors = draft.validate(value2[key2], patterns[i3].patternSchema, `${pointer}/${key2}`);
          if (valErrors && valErrors.length > 0) {
            errors3.push(...valErrors);
          }
        }
      }
      if (properties[key2]) {
        return;
      }
      if (patternFound === false && schema7.additionalProperties === false) {
        errors3.push(draft.errors.patternPropertiesError({
          key: key2,
          pointer,
          patterns: Object.keys(pp).join(","),
          schema: schema7,
          value: value2
        }));
      }
    });
    return errors3;
  },
  // @draft >= 6
  propertyNames: (draft, schema7, value2, pointer) => {
    if (schema7.propertyNames === false) {
      if (Object.keys(value2).length === 0) {
        return void 0;
      }
      return draft.errors.invalidPropertyNameError({
        property: Object.keys(value2),
        pointer,
        value: value2,
        schema: schema7
      });
    }
    if (schema7.propertyNames === true) {
      return void 0;
    }
    if (getTypeOf(schema7.propertyNames) !== "object") {
      return void 0;
    }
    const errors3 = [];
    const properties = Object.keys(value2);
    const propertySchema = { ...schema7.propertyNames, type: "string" };
    properties.forEach((prop2) => {
      const validationResult = draft.validate(prop2, propertySchema, `${pointer}/${prop2}`);
      if (validationResult.length > 0) {
        errors3.push(draft.errors.invalidPropertyNameError({
          property: prop2,
          pointer,
          validationError: validationResult[0],
          value: value2[prop2],
          schema: schema7
        }));
      }
    });
    return errors3;
  }
};
var keyword_default2 = KeywordValidation2;

// node_modules/json-schema-library/dist/module/lib/draft06/validation/type.js
var validationType = {
  array: (draft, schema7, value2, pointer) => draft.typeKeywords.array.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  object: (draft, schema7, value2, pointer) => draft.typeKeywords.object.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  string: (draft, schema7, value2, pointer) => draft.typeKeywords.string.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  integer: (draft, schema7, value2, pointer) => draft.typeKeywords.number.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  number: (draft, schema7, value2, pointer) => draft.typeKeywords.number.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  boolean: (draft, schema7, value2, pointer) => draft.typeKeywords.boolean.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer)),
  null: (draft, schema7, value2, pointer) => draft.typeKeywords.null.filter((key2) => schema7 && schema7[key2] != null).map((key2) => draft.validateKeyword[key2](draft, schema7, value2, pointer))
};
var type_default2 = validationType;

// node_modules/json-schema-library/dist/module/lib/draft06/index.js
var draft06Config = {
  typeKeywords: {
    array: [
      "allOf",
      "anyOf",
      "contains",
      "enum",
      "if",
      "items",
      "maxItems",
      "minItems",
      "not",
      "oneOf",
      "uniqueItems"
    ],
    boolean: ["allOf", "anyOf", "enum", "not", "oneOf"],
    object: [
      "additionalProperties",
      "allOf",
      "anyOf",
      "dependencies",
      "enum",
      "format",
      "if",
      "maxProperties",
      "minProperties",
      "not",
      "oneOf",
      "patternProperties",
      "properties",
      "propertyNames",
      "required"
    ],
    string: [
      "allOf",
      "anyOf",
      "enum",
      "format",
      "if",
      "maxLength",
      "minLength",
      "not",
      "oneOf",
      "pattern"
    ],
    number: [
      "enum",
      "exclusiveMaximum",
      "exclusiveMinimum",
      "format",
      "maximum",
      "minimum",
      "multipleOf",
      "not",
      "oneOf",
      "allOf",
      "anyOf",
      "if"
    ],
    null: ["allOf", "anyOf", "enum", "format", "not", "oneOf"]
  },
  validateKeyword: keyword_default2,
  validateType: type_default2,
  validateFormat: format_default,
  errors: errors_default,
  addRemoteSchema,
  compileSchema: compileSchema2,
  createSchemaOf,
  each: each2,
  eachSchema,
  getChildSchemaSelection,
  getSchema,
  getTemplate: getTemplate_default,
  isValid,
  resolveAllOf,
  resolveAnyOf,
  resolveOneOf,
  resolveRef,
  step,
  validate: validate2,
  templateDefaultOptions: settings_default.templateDefaultOptions
};

// node_modules/json-schema-library/dist/module/lib/draft07/index.js
var draft07Config = {
  typeKeywords: {
    array: [
      "allOf",
      "anyOf",
      "contains",
      "enum",
      "if",
      "items",
      "maxItems",
      "minItems",
      "not",
      "oneOf",
      "uniqueItems"
    ],
    boolean: ["allOf", "anyOf", "enum", "not", "oneOf"],
    object: [
      "additionalProperties",
      "allOf",
      "anyOf",
      "dependencies",
      "enum",
      "format",
      "if",
      "maxProperties",
      "minProperties",
      "not",
      "oneOf",
      "patternProperties",
      "properties",
      "propertyNames",
      "required"
    ],
    string: [
      "allOf",
      "anyOf",
      "enum",
      "format",
      "if",
      "maxLength",
      "minLength",
      "not",
      "oneOf",
      "pattern"
    ],
    number: [
      "allOf",
      "anyOf",
      "enum",
      "exclusiveMaximum",
      "exclusiveMinimum",
      "format",
      "if",
      "maximum",
      "minimum",
      "multipleOf",
      "not",
      "oneOf"
    ],
    null: ["allOf", "anyOf", "enum", "format", "not", "oneOf"]
  },
  validateKeyword: keyword_default2,
  validateType: type_default2,
  validateFormat: format_default,
  errors: errors_default,
  addRemoteSchema,
  compileSchema: compileSchema2,
  createSchemaOf,
  each: each2,
  eachSchema,
  getChildSchemaSelection,
  getSchema,
  getTemplate: getTemplate_default,
  isValid,
  resolveAllOf,
  resolveAnyOf,
  resolveOneOf,
  resolveRef,
  step,
  validate: validate2,
  templateDefaultOptions: settings_default.templateDefaultOptions
};
var Draft07 = class extends Draft {
  constructor(schema7, config3 = {}) {
    super(merge_default(draft07Config, config3), schema7);
  }
};

// node_modules/json-schema-library/dist/module/lib/jsoneditor/index.js
var draftJsonEditorConfig = {
  ...draft07Config,
  resolveOneOf: resolveOneOfFuzzy,
  resolveRef: resolveRefMerge
};

// node_modules/codemirror-json-schema/dist/utils/dom.js
function el(tagName, attributes, children2 = []) {
  const e3 = document.createElement(tagName);
  Object.entries(attributes).forEach(([k2, v3]) => {
    if (k2 === "text") {
      e3.innerText = v3;
      return;
    }
    if (k2 === "inner") {
      e3.innerHTML = v3;
      return;
    }
    e3.setAttribute(k2, v3);
  });
  children2.forEach((c3) => e3.appendChild(c3));
  return e3;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/common/utils.mjs
var utils_exports = {};
__export(utils_exports, {
  arrayReplaceAt: () => arrayReplaceAt,
  assign: () => assign4,
  escapeHtml: () => escapeHtml,
  escapeRE: () => escapeRE,
  fromCodePoint: () => fromCodePoint3,
  has: () => has3,
  isMdAsciiPunct: () => isMdAsciiPunct,
  isPunctChar: () => isPunctChar,
  isSpace: () => isSpace,
  isString: () => isString3,
  isValidEntityCode: () => isValidEntityCode,
  isWhiteSpace: () => isWhiteSpace,
  lib: () => lib,
  normalizeReference: () => normalizeReference,
  unescapeAll: () => unescapeAll,
  unescapeMd: () => unescapeMd
});

// node_modules/codemirror-json-schema/node_modules/mdurl/index.mjs
var mdurl_exports = {};
__export(mdurl_exports, {
  decode: () => decode_default,
  encode: () => encode_default,
  format: () => format,
  parse: () => parse_default
});

// node_modules/codemirror-json-schema/node_modules/mdurl/lib/decode.mjs
var decodeCache = {};
function getDecodeCache(exclude) {
  let cache5 = decodeCache[exclude];
  if (cache5) {
    return cache5;
  }
  cache5 = decodeCache[exclude] = [];
  for (let i3 = 0; i3 < 128; i3++) {
    const ch = String.fromCharCode(i3);
    cache5.push(ch);
  }
  for (let i3 = 0; i3 < exclude.length; i3++) {
    const ch = exclude.charCodeAt(i3);
    cache5[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
  }
  return cache5;
}
function decode(string3, exclude) {
  if (typeof exclude !== "string") {
    exclude = decode.defaultChars;
  }
  const cache5 = getDecodeCache(exclude);
  return string3.replace(/(%[a-f0-9]{2})+/gi, function(seq2) {
    let result2 = "";
    for (let i3 = 0, l3 = seq2.length; i3 < l3; i3 += 3) {
      const b1 = parseInt(seq2.slice(i3 + 1, i3 + 3), 16);
      if (b1 < 128) {
        result2 += cache5[b1];
        continue;
      }
      if ((b1 & 224) === 192 && i3 + 3 < l3) {
        const b22 = parseInt(seq2.slice(i3 + 4, i3 + 6), 16);
        if ((b22 & 192) === 128) {
          const chr = b1 << 6 & 1984 | b22 & 63;
          if (chr < 128) {
            result2 += "\uFFFD\uFFFD";
          } else {
            result2 += String.fromCharCode(chr);
          }
          i3 += 3;
          continue;
        }
      }
      if ((b1 & 240) === 224 && i3 + 6 < l3) {
        const b22 = parseInt(seq2.slice(i3 + 4, i3 + 6), 16);
        const b3 = parseInt(seq2.slice(i3 + 7, i3 + 9), 16);
        if ((b22 & 192) === 128 && (b3 & 192) === 128) {
          const chr = b1 << 12 & 61440 | b22 << 6 & 4032 | b3 & 63;
          if (chr < 2048 || chr >= 55296 && chr <= 57343) {
            result2 += "\uFFFD\uFFFD\uFFFD";
          } else {
            result2 += String.fromCharCode(chr);
          }
          i3 += 6;
          continue;
        }
      }
      if ((b1 & 248) === 240 && i3 + 9 < l3) {
        const b22 = parseInt(seq2.slice(i3 + 4, i3 + 6), 16);
        const b3 = parseInt(seq2.slice(i3 + 7, i3 + 9), 16);
        const b4 = parseInt(seq2.slice(i3 + 10, i3 + 12), 16);
        if ((b22 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
          let chr = b1 << 18 & 1835008 | b22 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
          if (chr < 65536 || chr > 1114111) {
            result2 += "\uFFFD\uFFFD\uFFFD\uFFFD";
          } else {
            chr -= 65536;
            result2 += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
          }
          i3 += 9;
          continue;
        }
      }
      result2 += "\uFFFD";
    }
    return result2;
  });
}
decode.defaultChars = ";/?:@&=+$,#";
decode.componentChars = "";
var decode_default = decode;

// node_modules/codemirror-json-schema/node_modules/mdurl/lib/encode.mjs
var encodeCache = {};
function getEncodeCache(exclude) {
  let cache5 = encodeCache[exclude];
  if (cache5) {
    return cache5;
  }
  cache5 = encodeCache[exclude] = [];
  for (let i3 = 0; i3 < 128; i3++) {
    const ch = String.fromCharCode(i3);
    if (/^[0-9a-z]$/i.test(ch)) {
      cache5.push(ch);
    } else {
      cache5.push("%" + ("0" + i3.toString(16).toUpperCase()).slice(-2));
    }
  }
  for (let i3 = 0; i3 < exclude.length; i3++) {
    cache5[exclude.charCodeAt(i3)] = exclude[i3];
  }
  return cache5;
}
function encode(string3, exclude, keepEscaped) {
  if (typeof exclude !== "string") {
    keepEscaped = exclude;
    exclude = encode.defaultChars;
  }
  if (typeof keepEscaped === "undefined") {
    keepEscaped = true;
  }
  const cache5 = getEncodeCache(exclude);
  let result2 = "";
  for (let i3 = 0, l3 = string3.length; i3 < l3; i3++) {
    const code2 = string3.charCodeAt(i3);
    if (keepEscaped && code2 === 37 && i3 + 2 < l3) {
      if (/^[0-9a-f]{2}$/i.test(string3.slice(i3 + 1, i3 + 3))) {
        result2 += string3.slice(i3, i3 + 3);
        i3 += 2;
        continue;
      }
    }
    if (code2 < 128) {
      result2 += cache5[code2];
      continue;
    }
    if (code2 >= 55296 && code2 <= 57343) {
      if (code2 >= 55296 && code2 <= 56319 && i3 + 1 < l3) {
        const nextCode = string3.charCodeAt(i3 + 1);
        if (nextCode >= 56320 && nextCode <= 57343) {
          result2 += encodeURIComponent(string3[i3] + string3[i3 + 1]);
          i3++;
          continue;
        }
      }
      result2 += "%EF%BF%BD";
      continue;
    }
    result2 += encodeURIComponent(string3[i3]);
  }
  return result2;
}
encode.defaultChars = ";/?:@&=+$,-_.!~*'()#";
encode.componentChars = "-_.!~*'()";
var encode_default = encode;

// node_modules/codemirror-json-schema/node_modules/mdurl/lib/format.mjs
function format(url2) {
  let result2 = "";
  result2 += url2.protocol || "";
  result2 += url2.slashes ? "//" : "";
  result2 += url2.auth ? url2.auth + "@" : "";
  if (url2.hostname && url2.hostname.indexOf(":") !== -1) {
    result2 += "[" + url2.hostname + "]";
  } else {
    result2 += url2.hostname || "";
  }
  result2 += url2.port ? ":" + url2.port : "";
  result2 += url2.pathname || "";
  result2 += url2.search || "";
  result2 += url2.hash || "";
  return result2;
}

// node_modules/codemirror-json-schema/node_modules/mdurl/lib/parse.mjs
function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.pathname = null;
}
var protocolPattern = /^([a-z0-9.+-]+:)/i;
var portPattern = /:[0-9]*$/;
var simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
var delims = ["<", ">", '"', "`", " ", "\r", "\n", "	"];
var unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
var autoEscape = ["'"].concat(unwise);
var nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
var hostEndingChars = ["/", "?", "#"];
var hostnameMaxLen = 255;
var hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
var hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
var hostlessProtocol = {
  javascript: true,
  "javascript:": true
};
var slashedProtocol = {
  http: true,
  https: true,
  ftp: true,
  gopher: true,
  file: true,
  "http:": true,
  "https:": true,
  "ftp:": true,
  "gopher:": true,
  "file:": true
};
function urlParse(url2, slashesDenoteHost) {
  if (url2 && url2 instanceof Url) return url2;
  const u3 = new Url();
  u3.parse(url2, slashesDenoteHost);
  return u3;
}
Url.prototype.parse = function(url2, slashesDenoteHost) {
  let lowerProto, hec, slashes;
  let rest2 = url2;
  rest2 = rest2.trim();
  if (!slashesDenoteHost && url2.split("#").length === 1) {
    const simplePath = simplePathPattern.exec(rest2);
    if (simplePath) {
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
      }
      return this;
    }
  }
  let proto = protocolPattern.exec(rest2);
  if (proto) {
    proto = proto[0];
    lowerProto = proto.toLowerCase();
    this.protocol = proto;
    rest2 = rest2.substr(proto.length);
  }
  if (slashesDenoteHost || proto || rest2.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    slashes = rest2.substr(0, 2) === "//";
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest2 = rest2.substr(2);
      this.slashes = true;
    }
  }
  if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
    let hostEnd = -1;
    for (let i3 = 0; i3 < hostEndingChars.length; i3++) {
      hec = rest2.indexOf(hostEndingChars[i3]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    let auth, atSign;
    if (hostEnd === -1) {
      atSign = rest2.lastIndexOf("@");
    } else {
      atSign = rest2.lastIndexOf("@", hostEnd);
    }
    if (atSign !== -1) {
      auth = rest2.slice(0, atSign);
      rest2 = rest2.slice(atSign + 1);
      this.auth = auth;
    }
    hostEnd = -1;
    for (let i3 = 0; i3 < nonHostChars.length; i3++) {
      hec = rest2.indexOf(nonHostChars[i3]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    if (hostEnd === -1) {
      hostEnd = rest2.length;
    }
    if (rest2[hostEnd - 1] === ":") {
      hostEnd--;
    }
    const host = rest2.slice(0, hostEnd);
    rest2 = rest2.slice(hostEnd);
    this.parseHost(host);
    this.hostname = this.hostname || "";
    const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
    if (!ipv6Hostname) {
      const hostparts = this.hostname.split(/\./);
      for (let i3 = 0, l3 = hostparts.length; i3 < l3; i3++) {
        const part = hostparts[i3];
        if (!part) {
          continue;
        }
        if (!part.match(hostnamePartPattern)) {
          let newpart = "";
          for (let j = 0, k2 = part.length; j < k2; j++) {
            if (part.charCodeAt(j) > 127) {
              newpart += "x";
            } else {
              newpart += part[j];
            }
          }
          if (!newpart.match(hostnamePartPattern)) {
            const validParts = hostparts.slice(0, i3);
            const notHost = hostparts.slice(i3 + 1);
            const bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest2 = notHost.join(".") + rest2;
            }
            this.hostname = validParts.join(".");
            break;
          }
        }
      }
    }
    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = "";
    }
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
    }
  }
  const hash = rest2.indexOf("#");
  if (hash !== -1) {
    this.hash = rest2.substr(hash);
    rest2 = rest2.slice(0, hash);
  }
  const qm = rest2.indexOf("?");
  if (qm !== -1) {
    this.search = rest2.substr(qm);
    rest2 = rest2.slice(0, qm);
  }
  if (rest2) {
    this.pathname = rest2;
  }
  if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
    this.pathname = "";
  }
  return this;
};
Url.prototype.parseHost = function(host) {
  let port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ":") {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) {
    this.hostname = host;
  }
};
var parse_default = urlParse;

// node_modules/codemirror-json-schema/node_modules/uc.micro/index.mjs
var uc_exports = {};
__export(uc_exports, {
  Any: () => regex_default,
  Cc: () => regex_default2,
  Cf: () => regex_default3,
  P: () => regex_default4,
  S: () => regex_default5,
  Z: () => regex_default6
});

// node_modules/codemirror-json-schema/node_modules/uc.micro/properties/Any/regex.mjs
var regex_default = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;

// node_modules/codemirror-json-schema/node_modules/uc.micro/categories/Cc/regex.mjs
var regex_default2 = /[\0-\x1F\x7F-\x9F]/;

// node_modules/codemirror-json-schema/node_modules/uc.micro/categories/Cf/regex.mjs
var regex_default3 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;

// node_modules/codemirror-json-schema/node_modules/uc.micro/categories/P/regex.mjs
var regex_default4 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;

// node_modules/codemirror-json-schema/node_modules/uc.micro/categories/S/regex.mjs
var regex_default5 = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/;

// node_modules/codemirror-json-schema/node_modules/uc.micro/categories/Z/regex.mjs
var regex_default6 = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;

// node_modules/codemirror-json-schema/node_modules/entities/lib/esm/generated/decode-data-html.js
var decode_data_html_default = new Uint16Array(
  // prettier-ignore
  '\u1D41<\xD5\u0131\u028A\u049D\u057B\u05D0\u0675\u06DE\u07A2\u07D6\u080F\u0A4A\u0A91\u0DA1\u0E6D\u0F09\u0F26\u10CA\u1228\u12E1\u1415\u149D\u14C3\u14DF\u1525\0\0\0\0\0\0\u156B\u16CD\u198D\u1C12\u1DDD\u1F7E\u2060\u21B0\u228D\u23C0\u23FB\u2442\u2824\u2912\u2D08\u2E48\u2FCE\u3016\u32BA\u3639\u37AC\u38FE\u3A28\u3A71\u3AE0\u3B2E\u0800EMabcfglmnoprstu\\bfms\x7F\x84\x8B\x90\x95\x98\xA6\xB3\xB9\xC8\xCFlig\u803B\xC6\u40C6P\u803B&\u4026cute\u803B\xC1\u40C1reve;\u4102\u0100iyx}rc\u803B\xC2\u40C2;\u4410r;\uC000\u{1D504}rave\u803B\xC0\u40C0pha;\u4391acr;\u4100d;\u6A53\u0100gp\x9D\xA1on;\u4104f;\uC000\u{1D538}plyFunction;\u6061ing\u803B\xC5\u40C5\u0100cs\xBE\xC3r;\uC000\u{1D49C}ign;\u6254ilde\u803B\xC3\u40C3ml\u803B\xC4\u40C4\u0400aceforsu\xE5\xFB\xFE\u0117\u011C\u0122\u0127\u012A\u0100cr\xEA\xF2kslash;\u6216\u0176\xF6\xF8;\u6AE7ed;\u6306y;\u4411\u0180crt\u0105\u010B\u0114ause;\u6235noullis;\u612Ca;\u4392r;\uC000\u{1D505}pf;\uC000\u{1D539}eve;\u42D8c\xF2\u0113mpeq;\u624E\u0700HOacdefhilorsu\u014D\u0151\u0156\u0180\u019E\u01A2\u01B5\u01B7\u01BA\u01DC\u0215\u0273\u0278\u027Ecy;\u4427PY\u803B\xA9\u40A9\u0180cpy\u015D\u0162\u017Aute;\u4106\u0100;i\u0167\u0168\u62D2talDifferentialD;\u6145leys;\u612D\u0200aeio\u0189\u018E\u0194\u0198ron;\u410Cdil\u803B\xC7\u40C7rc;\u4108nint;\u6230ot;\u410A\u0100dn\u01A7\u01ADilla;\u40B8terDot;\u40B7\xF2\u017Fi;\u43A7rcle\u0200DMPT\u01C7\u01CB\u01D1\u01D6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01E2\u01F8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020FoubleQuote;\u601Duote;\u6019\u0200lnpu\u021E\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6A74\u0180git\u022F\u0236\u023Aruent;\u6261nt;\u622FourIntegral;\u622E\u0100fr\u024C\u024E;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6A2Fcr;\uC000\u{1D49E}p\u0100;C\u0284\u0285\u62D3ap;\u624D\u0580DJSZacefios\u02A0\u02AC\u02B0\u02B4\u02B8\u02CB\u02D7\u02E1\u02E6\u0333\u048D\u0100;o\u0179\u02A5trahd;\u6911cy;\u4402cy;\u4405cy;\u440F\u0180grs\u02BF\u02C4\u02C7ger;\u6021r;\u61A1hv;\u6AE4\u0100ay\u02D0\u02D5ron;\u410E;\u4414l\u0100;t\u02DD\u02DE\u6207a;\u4394r;\uC000\u{1D507}\u0100af\u02EB\u0327\u0100cm\u02F0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031Ccute;\u40B4o\u0174\u030B\u030D;\u42D9bleAcute;\u42DDrave;\u4060ilde;\u42DCond;\u62C4ferentialD;\u6146\u0470\u033D\0\0\0\u0342\u0354\0\u0405f;\uC000\u{1D53B}\u0180;DE\u0348\u0349\u034D\u40A8ot;\u60DCqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03CF\u03E2\u03F8ontourIntegra\xEC\u0239o\u0274\u0379\0\0\u037B\xBB\u0349nArrow;\u61D3\u0100eo\u0387\u03A4ft\u0180ART\u0390\u0396\u03A1rrow;\u61D0ightArrow;\u61D4e\xE5\u02CAng\u0100LR\u03AB\u03C4eft\u0100AR\u03B3\u03B9rrow;\u67F8ightArrow;\u67FAightArrow;\u67F9ight\u0100AT\u03D8\u03DErrow;\u61D2ee;\u62A8p\u0241\u03E9\0\0\u03EFrrow;\u61D1ownArrow;\u61D5erticalBar;\u6225n\u0300ABLRTa\u0412\u042A\u0430\u045E\u047F\u037Crrow\u0180;BU\u041D\u041E\u0422\u6193ar;\u6913pArrow;\u61F5reve;\u4311eft\u02D2\u043A\0\u0446\0\u0450ightVector;\u6950eeVector;\u695Eector\u0100;B\u0459\u045A\u61BDar;\u6956ight\u01D4\u0467\0\u0471eeVector;\u695Fector\u0100;B\u047A\u047B\u61C1ar;\u6957ee\u0100;A\u0486\u0487\u62A4rrow;\u61A7\u0100ct\u0492\u0497r;\uC000\u{1D49F}rok;\u4110\u0800NTacdfglmopqstux\u04BD\u04C0\u04C4\u04CB\u04DE\u04E2\u04E7\u04EE\u04F5\u0521\u052F\u0536\u0552\u055D\u0560\u0565G;\u414AH\u803B\xD0\u40D0cute\u803B\xC9\u40C9\u0180aiy\u04D2\u04D7\u04DCron;\u411Arc\u803B\xCA\u40CA;\u442Dot;\u4116r;\uC000\u{1D508}rave\u803B\xC8\u40C8ement;\u6208\u0100ap\u04FA\u04FEcr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65FBerySmallSquare;\u65AB\u0100gp\u0526\u052Aon;\u4118f;\uC000\u{1D53C}silon;\u4395u\u0100ai\u053C\u0549l\u0100;T\u0542\u0543\u6A75ilde;\u6242librium;\u61CC\u0100ci\u0557\u055Ar;\u6130m;\u6A73a;\u4397ml\u803B\xCB\u40CB\u0100ip\u056A\u056Fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058D\u05B2\u05CCy;\u4424r;\uC000\u{1D509}lled\u0253\u0597\0\0\u05A3mallSquare;\u65FCerySmallSquare;\u65AA\u0370\u05BA\0\u05BF\0\0\u05C4f;\uC000\u{1D53D}All;\u6200riertrf;\u6131c\xF2\u05CB\u0600JTabcdfgorst\u05E8\u05EC\u05EF\u05FA\u0600\u0612\u0616\u061B\u061D\u0623\u066C\u0672cy;\u4403\u803B>\u403Emma\u0100;d\u05F7\u05F8\u4393;\u43DCreve;\u411E\u0180eiy\u0607\u060C\u0610dil;\u4122rc;\u411C;\u4413ot;\u4120r;\uC000\u{1D50A};\u62D9pf;\uC000\u{1D53E}eater\u0300EFGLST\u0635\u0644\u064E\u0656\u065B\u0666qual\u0100;L\u063E\u063F\u6265ess;\u62DBullEqual;\u6267reater;\u6AA2ess;\u6277lantEqual;\u6A7Eilde;\u6273cr;\uC000\u{1D4A2};\u626B\u0400Aacfiosu\u0685\u068B\u0696\u069B\u069E\u06AA\u06BE\u06CARDcy;\u442A\u0100ct\u0690\u0694ek;\u42C7;\u405Eirc;\u4124r;\u610ClbertSpace;\u610B\u01F0\u06AF\0\u06B2f;\u610DizontalLine;\u6500\u0100ct\u06C3\u06C5\xF2\u06A9rok;\u4126mp\u0144\u06D0\u06D8ownHum\xF0\u012Fqual;\u624F\u0700EJOacdfgmnostu\u06FA\u06FE\u0703\u0707\u070E\u071A\u071E\u0721\u0728\u0744\u0778\u078B\u078F\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803B\xCD\u40CD\u0100iy\u0713\u0718rc\u803B\xCE\u40CE;\u4418ot;\u4130r;\u6111rave\u803B\xCC\u40CC\u0180;ap\u0720\u072F\u073F\u0100cg\u0734\u0737r;\u412AinaryI;\u6148lie\xF3\u03DD\u01F4\u0749\0\u0762\u0100;e\u074D\u074E\u622C\u0100gr\u0753\u0758ral;\u622Bsection;\u62C2isible\u0100CT\u076C\u0772omma;\u6063imes;\u6062\u0180gpt\u077F\u0783\u0788on;\u412Ef;\uC000\u{1D540}a;\u4399cr;\u6110ilde;\u4128\u01EB\u079A\0\u079Ecy;\u4406l\u803B\xCF\u40CF\u0280cfosu\u07AC\u07B7\u07BC\u07C2\u07D0\u0100iy\u07B1\u07B5rc;\u4134;\u4419r;\uC000\u{1D50D}pf;\uC000\u{1D541}\u01E3\u07C7\0\u07CCr;\uC000\u{1D4A5}rcy;\u4408kcy;\u4404\u0380HJacfos\u07E4\u07E8\u07EC\u07F1\u07FD\u0802\u0808cy;\u4425cy;\u440Cppa;\u439A\u0100ey\u07F6\u07FBdil;\u4136;\u441Ar;\uC000\u{1D50E}pf;\uC000\u{1D542}cr;\uC000\u{1D4A6}\u0580JTaceflmost\u0825\u0829\u082C\u0850\u0863\u09B3\u09B8\u09C7\u09CD\u0A37\u0A47cy;\u4409\u803B<\u403C\u0280cmnpr\u0837\u083C\u0841\u0844\u084Dute;\u4139bda;\u439Bg;\u67EAlacetrf;\u6112r;\u619E\u0180aey\u0857\u085C\u0861ron;\u413Ddil;\u413B;\u441B\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087E\u08A9\u08B1\u08E0\u08E6\u08FC\u092F\u095B\u0390\u096A\u0100nr\u0883\u088FgleBracket;\u67E8row\u0180;BR\u0899\u089A\u089E\u6190ar;\u61E4ightArrow;\u61C6eiling;\u6308o\u01F5\u08B7\0\u08C3bleBracket;\u67E6n\u01D4\u08C8\0\u08D2eeVector;\u6961ector\u0100;B\u08DB\u08DC\u61C3ar;\u6959loor;\u630Aight\u0100AV\u08EF\u08F5rrow;\u6194ector;\u694E\u0100er\u0901\u0917e\u0180;AV\u0909\u090A\u0910\u62A3rrow;\u61A4ector;\u695Aiangle\u0180;BE\u0924\u0925\u0929\u62B2ar;\u69CFqual;\u62B4p\u0180DTV\u0937\u0942\u094CownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61BFar;\u6958ector\u0100;B\u0965\u0966\u61BCar;\u6952ight\xE1\u039Cs\u0300EFGLST\u097E\u098B\u0995\u099D\u09A2\u09ADqualGreater;\u62DAullEqual;\u6266reater;\u6276ess;\u6AA1lantEqual;\u6A7Dilde;\u6272r;\uC000\u{1D50F}\u0100;e\u09BD\u09BE\u62D8ftarrow;\u61DAidot;\u413F\u0180npw\u09D4\u0A16\u0A1Bg\u0200LRlr\u09DE\u09F7\u0A02\u0A10eft\u0100AR\u09E6\u09ECrrow;\u67F5ightArrow;\u67F7ightArrow;\u67F6eft\u0100ar\u03B3\u0A0Aight\xE1\u03BFight\xE1\u03CAf;\uC000\u{1D543}er\u0100LR\u0A22\u0A2CeftArrow;\u6199ightArrow;\u6198\u0180cht\u0A3E\u0A40\u0A42\xF2\u084C;\u61B0rok;\u4141;\u626A\u0400acefiosu\u0A5A\u0A5D\u0A60\u0A77\u0A7C\u0A85\u0A8B\u0A8Ep;\u6905y;\u441C\u0100dl\u0A65\u0A6FiumSpace;\u605Flintrf;\u6133r;\uC000\u{1D510}nusPlus;\u6213pf;\uC000\u{1D544}c\xF2\u0A76;\u439C\u0480Jacefostu\u0AA3\u0AA7\u0AAD\u0AC0\u0B14\u0B19\u0D91\u0D97\u0D9Ecy;\u440Acute;\u4143\u0180aey\u0AB4\u0AB9\u0ABEron;\u4147dil;\u4145;\u441D\u0180gsw\u0AC7\u0AF0\u0B0Eative\u0180MTV\u0AD3\u0ADF\u0AE8ediumSpace;\u600Bhi\u0100cn\u0AE6\u0AD8\xEB\u0AD9eryThi\xEE\u0AD9ted\u0100GL\u0AF8\u0B06reaterGreate\xF2\u0673essLes\xF3\u0A48Line;\u400Ar;\uC000\u{1D511}\u0200Bnpt\u0B22\u0B28\u0B37\u0B3Areak;\u6060BreakingSpace;\u40A0f;\u6115\u0680;CDEGHLNPRSTV\u0B55\u0B56\u0B6A\u0B7C\u0BA1\u0BEB\u0C04\u0C5E\u0C84\u0CA6\u0CD8\u0D61\u0D85\u6AEC\u0100ou\u0B5B\u0B64ngruent;\u6262pCap;\u626DoubleVerticalBar;\u6226\u0180lqx\u0B83\u0B8A\u0B9Bement;\u6209ual\u0100;T\u0B92\u0B93\u6260ilde;\uC000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0BB6\u0BB7\u0BBD\u0BC9\u0BD3\u0BD8\u0BE5\u626Fqual;\u6271ullEqual;\uC000\u2267\u0338reater;\uC000\u226B\u0338ess;\u6279lantEqual;\uC000\u2A7E\u0338ilde;\u6275ump\u0144\u0BF2\u0BFDownHump;\uC000\u224E\u0338qual;\uC000\u224F\u0338e\u0100fs\u0C0A\u0C27tTriangle\u0180;BE\u0C1A\u0C1B\u0C21\u62EAar;\uC000\u29CF\u0338qual;\u62ECs\u0300;EGLST\u0C35\u0C36\u0C3C\u0C44\u0C4B\u0C58\u626Equal;\u6270reater;\u6278ess;\uC000\u226A\u0338lantEqual;\uC000\u2A7D\u0338ilde;\u6274ested\u0100GL\u0C68\u0C79reaterGreater;\uC000\u2AA2\u0338essLess;\uC000\u2AA1\u0338recedes\u0180;ES\u0C92\u0C93\u0C9B\u6280qual;\uC000\u2AAF\u0338lantEqual;\u62E0\u0100ei\u0CAB\u0CB9verseElement;\u620CghtTriangle\u0180;BE\u0CCB\u0CCC\u0CD2\u62EBar;\uC000\u29D0\u0338qual;\u62ED\u0100qu\u0CDD\u0D0CuareSu\u0100bp\u0CE8\u0CF9set\u0100;E\u0CF0\u0CF3\uC000\u228F\u0338qual;\u62E2erset\u0100;E\u0D03\u0D06\uC000\u2290\u0338qual;\u62E3\u0180bcp\u0D13\u0D24\u0D4Eset\u0100;E\u0D1B\u0D1E\uC000\u2282\u20D2qual;\u6288ceeds\u0200;EST\u0D32\u0D33\u0D3B\u0D46\u6281qual;\uC000\u2AB0\u0338lantEqual;\u62E1ilde;\uC000\u227F\u0338erset\u0100;E\u0D58\u0D5B\uC000\u2283\u20D2qual;\u6289ilde\u0200;EFT\u0D6E\u0D6F\u0D75\u0D7F\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uC000\u{1D4A9}ilde\u803B\xD1\u40D1;\u439D\u0700Eacdfgmoprstuv\u0DBD\u0DC2\u0DC9\u0DD5\u0DDB\u0DE0\u0DE7\u0DFC\u0E02\u0E20\u0E22\u0E32\u0E3F\u0E44lig;\u4152cute\u803B\xD3\u40D3\u0100iy\u0DCE\u0DD3rc\u803B\xD4\u40D4;\u441Eblac;\u4150r;\uC000\u{1D512}rave\u803B\xD2\u40D2\u0180aei\u0DEE\u0DF2\u0DF6cr;\u414Cga;\u43A9cron;\u439Fpf;\uC000\u{1D546}enCurly\u0100DQ\u0E0E\u0E1AoubleQuote;\u601Cuote;\u6018;\u6A54\u0100cl\u0E27\u0E2Cr;\uC000\u{1D4AA}ash\u803B\xD8\u40D8i\u016C\u0E37\u0E3Cde\u803B\xD5\u40D5es;\u6A37ml\u803B\xD6\u40D6er\u0100BP\u0E4B\u0E60\u0100ar\u0E50\u0E53r;\u603Eac\u0100ek\u0E5A\u0E5C;\u63DEet;\u63B4arenthesis;\u63DC\u0480acfhilors\u0E7F\u0E87\u0E8A\u0E8F\u0E92\u0E94\u0E9D\u0EB0\u0EFCrtialD;\u6202y;\u441Fr;\uC000\u{1D513}i;\u43A6;\u43A0usMinus;\u40B1\u0100ip\u0EA2\u0EADncareplan\xE5\u069Df;\u6119\u0200;eio\u0EB9\u0EBA\u0EE0\u0EE4\u6ABBcedes\u0200;EST\u0EC8\u0EC9\u0ECF\u0EDA\u627Aqual;\u6AAFlantEqual;\u627Cilde;\u627Eme;\u6033\u0100dp\u0EE9\u0EEEuct;\u620Fortion\u0100;a\u0225\u0EF9l;\u621D\u0100ci\u0F01\u0F06r;\uC000\u{1D4AB};\u43A8\u0200Ufos\u0F11\u0F16\u0F1B\u0F1FOT\u803B"\u4022r;\uC000\u{1D514}pf;\u611Acr;\uC000\u{1D4AC}\u0600BEacefhiorsu\u0F3E\u0F43\u0F47\u0F60\u0F73\u0FA7\u0FAA\u0FAD\u1096\u10A9\u10B4\u10BEarr;\u6910G\u803B\xAE\u40AE\u0180cnr\u0F4E\u0F53\u0F56ute;\u4154g;\u67EBr\u0100;t\u0F5C\u0F5D\u61A0l;\u6916\u0180aey\u0F67\u0F6C\u0F71ron;\u4158dil;\u4156;\u4420\u0100;v\u0F78\u0F79\u611Cerse\u0100EU\u0F82\u0F99\u0100lq\u0F87\u0F8Eement;\u620Builibrium;\u61CBpEquilibrium;\u696Fr\xBB\u0F79o;\u43A1ght\u0400ACDFTUVa\u0FC1\u0FEB\u0FF3\u1022\u1028\u105B\u1087\u03D8\u0100nr\u0FC6\u0FD2gleBracket;\u67E9row\u0180;BL\u0FDC\u0FDD\u0FE1\u6192ar;\u61E5eftArrow;\u61C4eiling;\u6309o\u01F5\u0FF9\0\u1005bleBracket;\u67E7n\u01D4\u100A\0\u1014eeVector;\u695Dector\u0100;B\u101D\u101E\u61C2ar;\u6955loor;\u630B\u0100er\u102D\u1043e\u0180;AV\u1035\u1036\u103C\u62A2rrow;\u61A6ector;\u695Biangle\u0180;BE\u1050\u1051\u1055\u62B3ar;\u69D0qual;\u62B5p\u0180DTV\u1063\u106E\u1078ownVector;\u694FeeVector;\u695Cector\u0100;B\u1082\u1083\u61BEar;\u6954ector\u0100;B\u1091\u1092\u61C0ar;\u6953\u0100pu\u109B\u109Ef;\u611DndImplies;\u6970ightarrow;\u61DB\u0100ch\u10B9\u10BCr;\u611B;\u61B1leDelayed;\u69F4\u0680HOacfhimoqstu\u10E4\u10F1\u10F7\u10FD\u1119\u111E\u1151\u1156\u1161\u1167\u11B5\u11BB\u11BF\u0100Cc\u10E9\u10EEHcy;\u4429y;\u4428FTcy;\u442Ccute;\u415A\u0280;aeiy\u1108\u1109\u110E\u1113\u1117\u6ABCron;\u4160dil;\u415Erc;\u415C;\u4421r;\uC000\u{1D516}ort\u0200DLRU\u112A\u1134\u113E\u1149ownArrow\xBB\u041EeftArrow\xBB\u089AightArrow\xBB\u0FDDpArrow;\u6191gma;\u43A3allCircle;\u6218pf;\uC000\u{1D54A}\u0272\u116D\0\0\u1170t;\u621Aare\u0200;ISU\u117B\u117C\u1189\u11AF\u65A1ntersection;\u6293u\u0100bp\u118F\u119Eset\u0100;E\u1197\u1198\u628Fqual;\u6291erset\u0100;E\u11A8\u11A9\u6290qual;\u6292nion;\u6294cr;\uC000\u{1D4AE}ar;\u62C6\u0200bcmp\u11C8\u11DB\u1209\u120B\u0100;s\u11CD\u11CE\u62D0et\u0100;E\u11CD\u11D5qual;\u6286\u0100ch\u11E0\u1205eeds\u0200;EST\u11ED\u11EE\u11F4\u11FF\u627Bqual;\u6AB0lantEqual;\u627Dilde;\u627FTh\xE1\u0F8C;\u6211\u0180;es\u1212\u1213\u1223\u62D1rset\u0100;E\u121C\u121D\u6283qual;\u6287et\xBB\u1213\u0580HRSacfhiors\u123E\u1244\u1249\u1255\u125E\u1271\u1276\u129F\u12C2\u12C8\u12D1ORN\u803B\xDE\u40DEADE;\u6122\u0100Hc\u124E\u1252cy;\u440By;\u4426\u0100bu\u125A\u125C;\u4009;\u43A4\u0180aey\u1265\u126A\u126Fron;\u4164dil;\u4162;\u4422r;\uC000\u{1D517}\u0100ei\u127B\u1289\u01F2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128E\u1298kSpace;\uC000\u205F\u200ASpace;\u6009lde\u0200;EFT\u12AB\u12AC\u12B2\u12BC\u623Cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uC000\u{1D54B}ipleDot;\u60DB\u0100ct\u12D6\u12DBr;\uC000\u{1D4AF}rok;\u4166\u0AE1\u12F7\u130E\u131A\u1326\0\u132C\u1331\0\0\0\0\0\u1338\u133D\u1377\u1385\0\u13FF\u1404\u140A\u1410\u0100cr\u12FB\u1301ute\u803B\xDA\u40DAr\u0100;o\u1307\u1308\u619Fcir;\u6949r\u01E3\u1313\0\u1316y;\u440Eve;\u416C\u0100iy\u131E\u1323rc\u803B\xDB\u40DB;\u4423blac;\u4170r;\uC000\u{1D518}rave\u803B\xD9\u40D9acr;\u416A\u0100di\u1341\u1369er\u0100BP\u1348\u135D\u0100ar\u134D\u1350r;\u405Fac\u0100ek\u1357\u1359;\u63DFet;\u63B5arenthesis;\u63DDon\u0100;P\u1370\u1371\u62C3lus;\u628E\u0100gp\u137B\u137Fon;\u4172f;\uC000\u{1D54C}\u0400ADETadps\u1395\u13AE\u13B8\u13C4\u03E8\u13D2\u13D7\u13F3rrow\u0180;BD\u1150\u13A0\u13A4ar;\u6912ownArrow;\u61C5ownArrow;\u6195quilibrium;\u696Eee\u0100;A\u13CB\u13CC\u62A5rrow;\u61A5own\xE1\u03F3er\u0100LR\u13DE\u13E8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13F9\u13FA\u43D2on;\u43A5ing;\u416Ecr;\uC000\u{1D4B0}ilde;\u4168ml\u803B\xDC\u40DC\u0480Dbcdefosv\u1427\u142C\u1430\u1433\u143E\u1485\u148A\u1490\u1496ash;\u62ABar;\u6AEBy;\u4412ash\u0100;l\u143B\u143C\u62A9;\u6AE6\u0100er\u1443\u1445;\u62C1\u0180bty\u144C\u1450\u147Aar;\u6016\u0100;i\u144F\u1455cal\u0200BLST\u1461\u1465\u146A\u1474ar;\u6223ine;\u407Ceparator;\u6758ilde;\u6240ThinSpace;\u600Ar;\uC000\u{1D519}pf;\uC000\u{1D54D}cr;\uC000\u{1D4B1}dash;\u62AA\u0280cefos\u14A7\u14AC\u14B1\u14B6\u14BCirc;\u4174dge;\u62C0r;\uC000\u{1D51A}pf;\uC000\u{1D54E}cr;\uC000\u{1D4B2}\u0200fios\u14CB\u14D0\u14D2\u14D8r;\uC000\u{1D51B};\u439Epf;\uC000\u{1D54F}cr;\uC000\u{1D4B3}\u0480AIUacfosu\u14F1\u14F5\u14F9\u14FD\u1504\u150F\u1514\u151A\u1520cy;\u442Fcy;\u4407cy;\u442Ecute\u803B\xDD\u40DD\u0100iy\u1509\u150Drc;\u4176;\u442Br;\uC000\u{1D51C}pf;\uC000\u{1D550}cr;\uC000\u{1D4B4}ml;\u4178\u0400Hacdefos\u1535\u1539\u153F\u154B\u154F\u155D\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417D;\u4417ot;\u417B\u01F2\u1554\0\u155BoWidt\xE8\u0AD9a;\u4396r;\u6128pf;\u6124cr;\uC000\u{1D4B5}\u0BE1\u1583\u158A\u1590\0\u15B0\u15B6\u15BF\0\0\0\0\u15C6\u15DB\u15EB\u165F\u166D\0\u1695\u169B\u16B2\u16B9\0\u16BEcute\u803B\xE1\u40E1reve;\u4103\u0300;Ediuy\u159C\u159D\u15A1\u15A3\u15A8\u15AD\u623E;\uC000\u223E\u0333;\u623Frc\u803B\xE2\u40E2te\u80BB\xB4\u0306;\u4430lig\u803B\xE6\u40E6\u0100;r\xB2\u15BA;\uC000\u{1D51E}rave\u803B\xE0\u40E0\u0100ep\u15CA\u15D6\u0100fp\u15CF\u15D4sym;\u6135\xE8\u15D3ha;\u43B1\u0100ap\u15DFc\u0100cl\u15E4\u15E7r;\u4101g;\u6A3F\u0264\u15F0\0\0\u160A\u0280;adsv\u15FA\u15FB\u15FF\u1601\u1607\u6227nd;\u6A55;\u6A5Clope;\u6A58;\u6A5A\u0380;elmrsz\u1618\u1619\u161B\u161E\u163F\u164F\u1659\u6220;\u69A4e\xBB\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163A\u163C\u163E;\u69A8;\u69A9;\u69AA;\u69AB;\u69AC;\u69AD;\u69AE;\u69AFt\u0100;v\u1645\u1646\u621Fb\u0100;d\u164C\u164D\u62BE;\u699D\u0100pt\u1654\u1657h;\u6222\xBB\xB9arr;\u637C\u0100gp\u1663\u1667on;\u4105f;\uC000\u{1D552}\u0380;Eaeiop\u12C1\u167B\u167D\u1682\u1684\u1687\u168A;\u6A70cir;\u6A6F;\u624Ad;\u624Bs;\u4027rox\u0100;e\u12C1\u1692\xF1\u1683ing\u803B\xE5\u40E5\u0180cty\u16A1\u16A6\u16A8r;\uC000\u{1D4B6};\u402Amp\u0100;e\u12C1\u16AF\xF1\u0288ilde\u803B\xE3\u40E3ml\u803B\xE4\u40E4\u0100ci\u16C2\u16C8onin\xF4\u0272nt;\u6A11\u0800Nabcdefiklnoprsu\u16ED\u16F1\u1730\u173C\u1743\u1748\u1778\u177D\u17E0\u17E6\u1839\u1850\u170D\u193D\u1948\u1970ot;\u6AED\u0100cr\u16F6\u171Ek\u0200ceps\u1700\u1705\u170D\u1713ong;\u624Cpsilon;\u43F6rime;\u6035im\u0100;e\u171A\u171B\u623Dq;\u62CD\u0176\u1722\u1726ee;\u62BDed\u0100;g\u172C\u172D\u6305e\xBB\u172Drk\u0100;t\u135C\u1737brk;\u63B6\u0100oy\u1701\u1741;\u4431quo;\u601E\u0280cmprt\u1753\u175B\u1761\u1764\u1768aus\u0100;e\u010A\u0109ptyv;\u69B0s\xE9\u170Cno\xF5\u0113\u0180ahw\u176F\u1771\u1773;\u43B2;\u6136een;\u626Cr;\uC000\u{1D51F}g\u0380costuvw\u178D\u179D\u17B3\u17C1\u17D5\u17DB\u17DE\u0180aiu\u1794\u1796\u179A\xF0\u0760rc;\u65EFp\xBB\u1371\u0180dpt\u17A4\u17A8\u17ADot;\u6A00lus;\u6A01imes;\u6A02\u0271\u17B9\0\0\u17BEcup;\u6A06ar;\u6605riangle\u0100du\u17CD\u17D2own;\u65BDp;\u65B3plus;\u6A04e\xE5\u1444\xE5\u14ADarow;\u690D\u0180ako\u17ED\u1826\u1835\u0100cn\u17F2\u1823k\u0180lst\u17FA\u05AB\u1802ozenge;\u69EBriangle\u0200;dlr\u1812\u1813\u1818\u181D\u65B4own;\u65BEeft;\u65C2ight;\u65B8k;\u6423\u01B1\u182B\0\u1833\u01B2\u182F\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183E\u184D\u0100;q\u1843\u1846\uC000=\u20E5uiv;\uC000\u2261\u20E5t;\u6310\u0200ptwx\u1859\u185E\u1867\u186Cf;\uC000\u{1D553}\u0100;t\u13CB\u1863om\xBB\u13CCtie;\u62C8\u0600DHUVbdhmptuv\u1885\u1896\u18AA\u18BB\u18D7\u18DB\u18EC\u18FF\u1905\u190A\u1910\u1921\u0200LRlr\u188E\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18A1\u18A2\u18A4\u18A6\u18A8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18B3\u18B5\u18B7\u18B9;\u655D;\u655A;\u655C;\u6559\u0380;HLRhlr\u18CA\u18CB\u18CD\u18CF\u18D1\u18D3\u18D5\u6551;\u656C;\u6563;\u6560;\u656B;\u6562;\u655Fox;\u69C9\u0200LRlr\u18E4\u18E6\u18E8\u18EA;\u6555;\u6552;\u6510;\u650C\u0280;DUdu\u06BD\u18F7\u18F9\u18FB\u18FD;\u6565;\u6568;\u652C;\u6534inus;\u629Flus;\u629Eimes;\u62A0\u0200LRlr\u1919\u191B\u191D\u191F;\u655B;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193B\u6502;\u656A;\u6561;\u655E;\u653C;\u6524;\u651C\u0100ev\u0123\u1942bar\u803B\xA6\u40A6\u0200ceio\u1951\u1956\u195A\u1960r;\uC000\u{1D4B7}mi;\u604Fm\u0100;e\u171A\u171Cl\u0180;bh\u1968\u1969\u196B\u405C;\u69C5sub;\u67C8\u016C\u1974\u197El\u0100;e\u1979\u197A\u6022t\xBB\u197Ap\u0180;Ee\u012F\u1985\u1987;\u6AAE\u0100;q\u06DC\u06DB\u0CE1\u19A7\0\u19E8\u1A11\u1A15\u1A32\0\u1A37\u1A50\0\0\u1AB4\0\0\u1AC1\0\0\u1B21\u1B2E\u1B4D\u1B52\0\u1BFD\0\u1C0C\u0180cpr\u19AD\u19B2\u19DDute;\u4107\u0300;abcds\u19BF\u19C0\u19C4\u19CA\u19D5\u19D9\u6229nd;\u6A44rcup;\u6A49\u0100au\u19CF\u19D2p;\u6A4Bp;\u6A47ot;\u6A40;\uC000\u2229\uFE00\u0100eo\u19E2\u19E5t;\u6041\xEE\u0693\u0200aeiu\u19F0\u19FB\u1A01\u1A05\u01F0\u19F5\0\u19F8s;\u6A4Don;\u410Ddil\u803B\xE7\u40E7rc;\u4109ps\u0100;s\u1A0C\u1A0D\u6A4Cm;\u6A50ot;\u410B\u0180dmn\u1A1B\u1A20\u1A26il\u80BB\xB8\u01ADptyv;\u69B2t\u8100\xA2;e\u1A2D\u1A2E\u40A2r\xE4\u01B2r;\uC000\u{1D520}\u0180cei\u1A3D\u1A40\u1A4Dy;\u4447ck\u0100;m\u1A47\u1A48\u6713ark\xBB\u1A48;\u43C7r\u0380;Ecefms\u1A5F\u1A60\u1A62\u1A6B\u1AA4\u1AAA\u1AAE\u65CB;\u69C3\u0180;el\u1A69\u1A6A\u1A6D\u42C6q;\u6257e\u0261\u1A74\0\0\u1A88rrow\u0100lr\u1A7C\u1A81eft;\u61BAight;\u61BB\u0280RSacd\u1A92\u1A94\u1A96\u1A9A\u1A9F\xBB\u0F47;\u64C8st;\u629Birc;\u629Aash;\u629Dnint;\u6A10id;\u6AEFcir;\u69C2ubs\u0100;u\u1ABB\u1ABC\u6663it\xBB\u1ABC\u02EC\u1AC7\u1AD4\u1AFA\0\u1B0Aon\u0100;e\u1ACD\u1ACE\u403A\u0100;q\xC7\xC6\u026D\u1AD9\0\0\u1AE2a\u0100;t\u1ADE\u1ADF\u402C;\u4040\u0180;fl\u1AE8\u1AE9\u1AEB\u6201\xEE\u1160e\u0100mx\u1AF1\u1AF6ent\xBB\u1AE9e\xF3\u024D\u01E7\u1AFE\0\u1B07\u0100;d\u12BB\u1B02ot;\u6A6Dn\xF4\u0246\u0180fry\u1B10\u1B14\u1B17;\uC000\u{1D554}o\xE4\u0254\u8100\xA9;s\u0155\u1B1Dr;\u6117\u0100ao\u1B25\u1B29rr;\u61B5ss;\u6717\u0100cu\u1B32\u1B37r;\uC000\u{1D4B8}\u0100bp\u1B3C\u1B44\u0100;e\u1B41\u1B42\u6ACF;\u6AD1\u0100;e\u1B49\u1B4A\u6AD0;\u6AD2dot;\u62EF\u0380delprvw\u1B60\u1B6C\u1B77\u1B82\u1BAC\u1BD4\u1BF9arr\u0100lr\u1B68\u1B6A;\u6938;\u6935\u0270\u1B72\0\0\u1B75r;\u62DEc;\u62DFarr\u0100;p\u1B7F\u1B80\u61B6;\u693D\u0300;bcdos\u1B8F\u1B90\u1B96\u1BA1\u1BA5\u1BA8\u622Arcap;\u6A48\u0100au\u1B9B\u1B9Ep;\u6A46p;\u6A4Aot;\u628Dr;\u6A45;\uC000\u222A\uFE00\u0200alrv\u1BB5\u1BBF\u1BDE\u1BE3rr\u0100;m\u1BBC\u1BBD\u61B7;\u693Cy\u0180evw\u1BC7\u1BD4\u1BD8q\u0270\u1BCE\0\0\u1BD2re\xE3\u1B73u\xE3\u1B75ee;\u62CEedge;\u62CFen\u803B\xA4\u40A4earrow\u0100lr\u1BEE\u1BF3eft\xBB\u1B80ight\xBB\u1BBDe\xE4\u1BDD\u0100ci\u1C01\u1C07onin\xF4\u01F7nt;\u6231lcty;\u632D\u0980AHabcdefhijlorstuwz\u1C38\u1C3B\u1C3F\u1C5D\u1C69\u1C75\u1C8A\u1C9E\u1CAC\u1CB7\u1CFB\u1CFF\u1D0D\u1D7B\u1D91\u1DAB\u1DBB\u1DC6\u1DCDr\xF2\u0381ar;\u6965\u0200glrs\u1C48\u1C4D\u1C52\u1C54ger;\u6020eth;\u6138\xF2\u1133h\u0100;v\u1C5A\u1C5B\u6010\xBB\u090A\u016B\u1C61\u1C67arow;\u690Fa\xE3\u0315\u0100ay\u1C6E\u1C73ron;\u410F;\u4434\u0180;ao\u0332\u1C7C\u1C84\u0100gr\u02BF\u1C81r;\u61CAtseq;\u6A77\u0180glm\u1C91\u1C94\u1C98\u803B\xB0\u40B0ta;\u43B4ptyv;\u69B1\u0100ir\u1CA3\u1CA8sht;\u697F;\uC000\u{1D521}ar\u0100lr\u1CB3\u1CB5\xBB\u08DC\xBB\u101E\u0280aegsv\u1CC2\u0378\u1CD6\u1CDC\u1CE0m\u0180;os\u0326\u1CCA\u1CD4nd\u0100;s\u0326\u1CD1uit;\u6666amma;\u43DDin;\u62F2\u0180;io\u1CE7\u1CE8\u1CF8\u40F7de\u8100\xF7;o\u1CE7\u1CF0ntimes;\u62C7n\xF8\u1CF7cy;\u4452c\u026F\u1D06\0\0\u1D0Arn;\u631Eop;\u630D\u0280lptuw\u1D18\u1D1D\u1D22\u1D49\u1D55lar;\u4024f;\uC000\u{1D555}\u0280;emps\u030B\u1D2D\u1D37\u1D3D\u1D42q\u0100;d\u0352\u1D33ot;\u6251inus;\u6238lus;\u6214quare;\u62A1blebarwedg\xE5\xFAn\u0180adh\u112E\u1D5D\u1D67ownarrow\xF3\u1C83arpoon\u0100lr\u1D72\u1D76ef\xF4\u1CB4igh\xF4\u1CB6\u0162\u1D7F\u1D85karo\xF7\u0F42\u026F\u1D8A\0\0\u1D8Ern;\u631Fop;\u630C\u0180cot\u1D98\u1DA3\u1DA6\u0100ry\u1D9D\u1DA1;\uC000\u{1D4B9};\u4455l;\u69F6rok;\u4111\u0100dr\u1DB0\u1DB4ot;\u62F1i\u0100;f\u1DBA\u1816\u65BF\u0100ah\u1DC0\u1DC3r\xF2\u0429a\xF2\u0FA6angle;\u69A6\u0100ci\u1DD2\u1DD5y;\u445Fgrarr;\u67FF\u0900Dacdefglmnopqrstux\u1E01\u1E09\u1E19\u1E38\u0578\u1E3C\u1E49\u1E61\u1E7E\u1EA5\u1EAF\u1EBD\u1EE1\u1F2A\u1F37\u1F44\u1F4E\u1F5A\u0100Do\u1E06\u1D34o\xF4\u1C89\u0100cs\u1E0E\u1E14ute\u803B\xE9\u40E9ter;\u6A6E\u0200aioy\u1E22\u1E27\u1E31\u1E36ron;\u411Br\u0100;c\u1E2D\u1E2E\u6256\u803B\xEA\u40EAlon;\u6255;\u444Dot;\u4117\u0100Dr\u1E41\u1E45ot;\u6252;\uC000\u{1D522}\u0180;rs\u1E50\u1E51\u1E57\u6A9Aave\u803B\xE8\u40E8\u0100;d\u1E5C\u1E5D\u6A96ot;\u6A98\u0200;ils\u1E6A\u1E6B\u1E72\u1E74\u6A99nters;\u63E7;\u6113\u0100;d\u1E79\u1E7A\u6A95ot;\u6A97\u0180aps\u1E85\u1E89\u1E97cr;\u4113ty\u0180;sv\u1E92\u1E93\u1E95\u6205et\xBB\u1E93p\u01001;\u1E9D\u1EA4\u0133\u1EA1\u1EA3;\u6004;\u6005\u6003\u0100gs\u1EAA\u1EAC;\u414Bp;\u6002\u0100gp\u1EB4\u1EB8on;\u4119f;\uC000\u{1D556}\u0180als\u1EC4\u1ECE\u1ED2r\u0100;s\u1ECA\u1ECB\u62D5l;\u69E3us;\u6A71i\u0180;lv\u1EDA\u1EDB\u1EDF\u43B5on\xBB\u1EDB;\u43F5\u0200csuv\u1EEA\u1EF3\u1F0B\u1F23\u0100io\u1EEF\u1E31rc\xBB\u1E2E\u0269\u1EF9\0\0\u1EFB\xED\u0548ant\u0100gl\u1F02\u1F06tr\xBB\u1E5Dess\xBB\u1E7A\u0180aei\u1F12\u1F16\u1F1Als;\u403Dst;\u625Fv\u0100;D\u0235\u1F20D;\u6A78parsl;\u69E5\u0100Da\u1F2F\u1F33ot;\u6253rr;\u6971\u0180cdi\u1F3E\u1F41\u1EF8r;\u612Fo\xF4\u0352\u0100ah\u1F49\u1F4B;\u43B7\u803B\xF0\u40F0\u0100mr\u1F53\u1F57l\u803B\xEB\u40EBo;\u60AC\u0180cip\u1F61\u1F64\u1F67l;\u4021s\xF4\u056E\u0100eo\u1F6C\u1F74ctatio\xEE\u0559nential\xE5\u0579\u09E1\u1F92\0\u1F9E\0\u1FA1\u1FA7\0\0\u1FC6\u1FCC\0\u1FD3\0\u1FE6\u1FEA\u2000\0\u2008\u205Allingdotse\xF1\u1E44y;\u4444male;\u6640\u0180ilr\u1FAD\u1FB3\u1FC1lig;\u8000\uFB03\u0269\u1FB9\0\0\u1FBDg;\u8000\uFB00ig;\u8000\uFB04;\uC000\u{1D523}lig;\u8000\uFB01lig;\uC000fj\u0180alt\u1FD9\u1FDC\u1FE1t;\u666Dig;\u8000\uFB02ns;\u65B1of;\u4192\u01F0\u1FEE\0\u1FF3f;\uC000\u{1D557}\u0100ak\u05BF\u1FF7\u0100;v\u1FFC\u1FFD\u62D4;\u6AD9artint;\u6A0D\u0100ao\u200C\u2055\u0100cs\u2011\u2052\u03B1\u201A\u2030\u2038\u2045\u2048\0\u2050\u03B2\u2022\u2025\u2027\u202A\u202C\0\u202E\u803B\xBD\u40BD;\u6153\u803B\xBC\u40BC;\u6155;\u6159;\u615B\u01B3\u2034\0\u2036;\u6154;\u6156\u02B4\u203E\u2041\0\0\u2043\u803B\xBE\u40BE;\u6157;\u615C5;\u6158\u01B6\u204C\0\u204E;\u615A;\u615D8;\u615El;\u6044wn;\u6322cr;\uC000\u{1D4BB}\u0880Eabcdefgijlnorstv\u2082\u2089\u209F\u20A5\u20B0\u20B4\u20F0\u20F5\u20FA\u20FF\u2103\u2112\u2138\u0317\u213E\u2152\u219E\u0100;l\u064D\u2087;\u6A8C\u0180cmp\u2090\u2095\u209Dute;\u41F5ma\u0100;d\u209C\u1CDA\u43B3;\u6A86reve;\u411F\u0100iy\u20AA\u20AErc;\u411D;\u4433ot;\u4121\u0200;lqs\u063E\u0642\u20BD\u20C9\u0180;qs\u063E\u064C\u20C4lan\xF4\u0665\u0200;cdl\u0665\u20D2\u20D5\u20E5c;\u6AA9ot\u0100;o\u20DC\u20DD\u6A80\u0100;l\u20E2\u20E3\u6A82;\u6A84\u0100;e\u20EA\u20ED\uC000\u22DB\uFE00s;\u6A94r;\uC000\u{1D524}\u0100;g\u0673\u061Bmel;\u6137cy;\u4453\u0200;Eaj\u065A\u210C\u210E\u2110;\u6A92;\u6AA5;\u6AA4\u0200Eaes\u211B\u211D\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6A8Arox\xBB\u2124\u0100;q\u212E\u212F\u6A88\u0100;q\u212E\u211Bim;\u62E7pf;\uC000\u{1D558}\u0100ci\u2143\u2146r;\u610Am\u0180;el\u066B\u214E\u2150;\u6A8E;\u6A90\u8300>;cdlqr\u05EE\u2160\u216A\u216E\u2173\u2179\u0100ci\u2165\u2167;\u6AA7r;\u6A7Aot;\u62D7Par;\u6995uest;\u6A7C\u0280adels\u2184\u216A\u2190\u0656\u219B\u01F0\u2189\0\u218Epro\xF8\u209Er;\u6978q\u0100lq\u063F\u2196les\xF3\u2088i\xED\u066B\u0100en\u21A3\u21ADrtneqq;\uC000\u2269\uFE00\xC5\u21AA\u0500Aabcefkosy\u21C4\u21C7\u21F1\u21F5\u21FA\u2218\u221D\u222F\u2268\u227Dr\xF2\u03A0\u0200ilmr\u21D0\u21D4\u21D7\u21DBrs\xF0\u1484f\xBB\u2024il\xF4\u06A9\u0100dr\u21E0\u21E4cy;\u444A\u0180;cw\u08F4\u21EB\u21EFir;\u6948;\u61ADar;\u610Firc;\u4125\u0180alr\u2201\u220E\u2213rts\u0100;u\u2209\u220A\u6665it\xBB\u220Alip;\u6026con;\u62B9r;\uC000\u{1D525}s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223A\u223E\u2243\u225E\u2263rr;\u61FFtht;\u623Bk\u0100lr\u2249\u2253eftarrow;\u61A9ightarrow;\u61AAf;\uC000\u{1D559}bar;\u6015\u0180clt\u226F\u2274\u2278r;\uC000\u{1D4BD}as\xE8\u21F4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xBB\u1C5B\u0AE1\u22A3\0\u22AA\0\u22B8\u22C5\u22CE\0\u22D5\u22F3\0\0\u22F8\u2322\u2367\u2362\u237F\0\u2386\u23AA\u23B4cute\u803B\xED\u40ED\u0180;iy\u0771\u22B0\u22B5rc\u803B\xEE\u40EE;\u4438\u0100cx\u22BC\u22BFy;\u4435cl\u803B\xA1\u40A1\u0100fr\u039F\u22C9;\uC000\u{1D526}rave\u803B\xEC\u40EC\u0200;ino\u073E\u22DD\u22E9\u22EE\u0100in\u22E2\u22E6nt;\u6A0Ct;\u622Dfin;\u69DCta;\u6129lig;\u4133\u0180aop\u22FE\u231A\u231D\u0180cgt\u2305\u2308\u2317r;\u412B\u0180elp\u071F\u230F\u2313in\xE5\u078Ear\xF4\u0720h;\u4131f;\u62B7ed;\u41B5\u0280;cfot\u04F4\u232C\u2331\u233D\u2341are;\u6105in\u0100;t\u2338\u2339\u621Eie;\u69DDdo\xF4\u2319\u0280;celp\u0757\u234C\u2350\u235B\u2361al;\u62BA\u0100gr\u2355\u2359er\xF3\u1563\xE3\u234Darhk;\u6A17rod;\u6A3C\u0200cgpt\u236F\u2372\u2376\u237By;\u4451on;\u412Ff;\uC000\u{1D55A}a;\u43B9uest\u803B\xBF\u40BF\u0100ci\u238A\u238Fr;\uC000\u{1D4BE}n\u0280;Edsv\u04F4\u239B\u239D\u23A1\u04F3;\u62F9ot;\u62F5\u0100;v\u23A6\u23A7\u62F4;\u62F3\u0100;i\u0777\u23AElde;\u4129\u01EB\u23B8\0\u23BCcy;\u4456l\u803B\xEF\u40EF\u0300cfmosu\u23CC\u23D7\u23DC\u23E1\u23E7\u23F5\u0100iy\u23D1\u23D5rc;\u4135;\u4439r;\uC000\u{1D527}ath;\u4237pf;\uC000\u{1D55B}\u01E3\u23EC\0\u23F1r;\uC000\u{1D4BF}rcy;\u4458kcy;\u4454\u0400acfghjos\u240B\u2416\u2422\u2427\u242D\u2431\u2435\u243Bppa\u0100;v\u2413\u2414\u43BA;\u43F0\u0100ey\u241B\u2420dil;\u4137;\u443Ar;\uC000\u{1D528}reen;\u4138cy;\u4445cy;\u445Cpf;\uC000\u{1D55C}cr;\uC000\u{1D4C0}\u0B80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248D\u2491\u250E\u253D\u255A\u2580\u264E\u265E\u2665\u2679\u267D\u269A\u26B2\u26D8\u275D\u2768\u278B\u27C0\u2801\u2812\u0180art\u2477\u247A\u247Cr\xF2\u09C6\xF2\u0395ail;\u691Barr;\u690E\u0100;g\u0994\u248B;\u6A8Bar;\u6962\u0963\u24A5\0\u24AA\0\u24B1\0\0\0\0\0\u24B5\u24BA\0\u24C6\u24C8\u24CD\0\u24F9ute;\u413Amptyv;\u69B4ra\xEE\u084Cbda;\u43BBg\u0180;dl\u088E\u24C1\u24C3;\u6991\xE5\u088E;\u6A85uo\u803B\xAB\u40ABr\u0400;bfhlpst\u0899\u24DE\u24E6\u24E9\u24EB\u24EE\u24F1\u24F5\u0100;f\u089D\u24E3s;\u691Fs;\u691D\xEB\u2252p;\u61ABl;\u6939im;\u6973l;\u61A2\u0180;ae\u24FF\u2500\u2504\u6AABil;\u6919\u0100;s\u2509\u250A\u6AAD;\uC000\u2AAD\uFE00\u0180abr\u2515\u2519\u251Drr;\u690Crk;\u6772\u0100ak\u2522\u252Cc\u0100ek\u2528\u252A;\u407B;\u405B\u0100es\u2531\u2533;\u698Bl\u0100du\u2539\u253B;\u698F;\u698D\u0200aeuy\u2546\u254B\u2556\u2558ron;\u413E\u0100di\u2550\u2554il;\u413C\xEC\u08B0\xE2\u2529;\u443B\u0200cqrs\u2563\u2566\u256D\u257Da;\u6936uo\u0100;r\u0E19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694Bh;\u61B2\u0280;fgqs\u258B\u258C\u0989\u25F3\u25FF\u6264t\u0280ahlrt\u2598\u25A4\u25B7\u25C2\u25E8rrow\u0100;t\u0899\u25A1a\xE9\u24F6arpoon\u0100du\u25AF\u25B4own\xBB\u045Ap\xBB\u0966eftarrows;\u61C7ight\u0180ahs\u25CD\u25D6\u25DErrow\u0100;s\u08F4\u08A7arpoon\xF3\u0F98quigarro\xF7\u21F0hreetimes;\u62CB\u0180;qs\u258B\u0993\u25FAlan\xF4\u09AC\u0280;cdgs\u09AC\u260A\u260D\u261D\u2628c;\u6AA8ot\u0100;o\u2614\u2615\u6A7F\u0100;r\u261A\u261B\u6A81;\u6A83\u0100;e\u2622\u2625\uC000\u22DA\uFE00s;\u6A93\u0280adegs\u2633\u2639\u263D\u2649\u264Bppro\xF8\u24C6ot;\u62D6q\u0100gq\u2643\u2645\xF4\u0989gt\xF2\u248C\xF4\u099Bi\xED\u09B2\u0180ilr\u2655\u08E1\u265Asht;\u697C;\uC000\u{1D529}\u0100;E\u099C\u2663;\u6A91\u0161\u2669\u2676r\u0100du\u25B2\u266E\u0100;l\u0965\u2673;\u696Alk;\u6584cy;\u4459\u0280;acht\u0A48\u2688\u268B\u2691\u2696r\xF2\u25C1orne\xF2\u1D08ard;\u696Bri;\u65FA\u0100io\u269F\u26A4dot;\u4140ust\u0100;a\u26AC\u26AD\u63B0che\xBB\u26AD\u0200Eaes\u26BB\u26BD\u26C9\u26D4;\u6268p\u0100;p\u26C3\u26C4\u6A89rox\xBB\u26C4\u0100;q\u26CE\u26CF\u6A87\u0100;q\u26CE\u26BBim;\u62E6\u0400abnoptwz\u26E9\u26F4\u26F7\u271A\u272F\u2741\u2747\u2750\u0100nr\u26EE\u26F1g;\u67ECr;\u61FDr\xEB\u08C1g\u0180lmr\u26FF\u270D\u2714eft\u0100ar\u09E6\u2707ight\xE1\u09F2apsto;\u67FCight\xE1\u09FDparrow\u0100lr\u2725\u2729ef\xF4\u24EDight;\u61AC\u0180afl\u2736\u2739\u273Dr;\u6985;\uC000\u{1D55D}us;\u6A2Dimes;\u6A34\u0161\u274B\u274Fst;\u6217\xE1\u134E\u0180;ef\u2757\u2758\u1800\u65CAnge\xBB\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277C\u2785\u2787r\xF2\u08A8orne\xF2\u1D8Car\u0100;d\u0F98\u2783;\u696D;\u600Eri;\u62BF\u0300achiqt\u2798\u279D\u0A40\u27A2\u27AE\u27BBquo;\u6039r;\uC000\u{1D4C1}m\u0180;eg\u09B2\u27AA\u27AC;\u6A8D;\u6A8F\u0100bu\u252A\u27B3o\u0100;r\u0E1F\u27B9;\u601Arok;\u4142\u8400<;cdhilqr\u082B\u27D2\u2639\u27DC\u27E0\u27E5\u27EA\u27F0\u0100ci\u27D7\u27D9;\u6AA6r;\u6A79re\xE5\u25F2mes;\u62C9arr;\u6976uest;\u6A7B\u0100Pi\u27F5\u27F9ar;\u6996\u0180;ef\u2800\u092D\u181B\u65C3r\u0100du\u2807\u280Dshar;\u694Ahar;\u6966\u0100en\u2817\u2821rtneqq;\uC000\u2268\uFE00\xC5\u281E\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288E\u2893\u28A0\u28A5\u28A8\u28DA\u28E2\u28E4\u0A83\u28F3\u2902Dot;\u623A\u0200clpr\u284E\u2852\u2863\u287Dr\u803B\xAF\u40AF\u0100et\u2857\u2859;\u6642\u0100;e\u285E\u285F\u6720se\xBB\u285F\u0100;s\u103B\u2868to\u0200;dlu\u103B\u2873\u2877\u287Bow\xEE\u048Cef\xF4\u090F\xF0\u13D1ker;\u65AE\u0100oy\u2887\u288Cmma;\u6A29;\u443Cash;\u6014asuredangle\xBB\u1626r;\uC000\u{1D52A}o;\u6127\u0180cdn\u28AF\u28B4\u28C9ro\u803B\xB5\u40B5\u0200;acd\u1464\u28BD\u28C0\u28C4s\xF4\u16A7ir;\u6AF0ot\u80BB\xB7\u01B5us\u0180;bd\u28D2\u1903\u28D3\u6212\u0100;u\u1D3C\u28D8;\u6A2A\u0163\u28DE\u28E1p;\u6ADB\xF2\u2212\xF0\u0A81\u0100dp\u28E9\u28EEels;\u62A7f;\uC000\u{1D55E}\u0100ct\u28F8\u28FDr;\uC000\u{1D4C2}pos\xBB\u159D\u0180;lm\u2909\u290A\u290D\u43BCtimap;\u62B8\u0C00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297E\u2989\u2998\u29DA\u29E9\u2A15\u2A1A\u2A58\u2A5D\u2A83\u2A95\u2AA4\u2AA8\u2B04\u2B07\u2B44\u2B7F\u2BAE\u2C34\u2C67\u2C7C\u2CE9\u0100gt\u2947\u294B;\uC000\u22D9\u0338\u0100;v\u2950\u0BCF\uC000\u226B\u20D2\u0180elt\u295A\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61CDightarrow;\u61CE;\uC000\u22D8\u0338\u0100;v\u297B\u0C47\uC000\u226A\u20D2ightarrow;\u61CF\u0100Dd\u298E\u2993ash;\u62AFash;\u62AE\u0280bcnpt\u29A3\u29A7\u29AC\u29B1\u29CCla\xBB\u02DEute;\u4144g;\uC000\u2220\u20D2\u0280;Eiop\u0D84\u29BC\u29C0\u29C5\u29C8;\uC000\u2A70\u0338d;\uC000\u224B\u0338s;\u4149ro\xF8\u0D84ur\u0100;a\u29D3\u29D4\u666El\u0100;s\u29D3\u0B38\u01F3\u29DF\0\u29E3p\u80BB\xA0\u0B37mp\u0100;e\u0BF9\u0C00\u0280aeouy\u29F4\u29FE\u2A03\u2A10\u2A13\u01F0\u29F9\0\u29FB;\u6A43on;\u4148dil;\u4146ng\u0100;d\u0D7E\u2A0Aot;\uC000\u2A6D\u0338p;\u6A42;\u443Dash;\u6013\u0380;Aadqsx\u0B92\u2A29\u2A2D\u2A3B\u2A41\u2A45\u2A50rr;\u61D7r\u0100hr\u2A33\u2A36k;\u6924\u0100;o\u13F2\u13F0ot;\uC000\u2250\u0338ui\xF6\u0B63\u0100ei\u2A4A\u2A4Ear;\u6928\xED\u0B98ist\u0100;s\u0BA0\u0B9Fr;\uC000\u{1D52B}\u0200Eest\u0BC5\u2A66\u2A79\u2A7C\u0180;qs\u0BBC\u2A6D\u0BE1\u0180;qs\u0BBC\u0BC5\u2A74lan\xF4\u0BE2i\xED\u0BEA\u0100;r\u0BB6\u2A81\xBB\u0BB7\u0180Aap\u2A8A\u2A8D\u2A91r\xF2\u2971rr;\u61AEar;\u6AF2\u0180;sv\u0F8D\u2A9C\u0F8C\u0100;d\u2AA1\u2AA2\u62FC;\u62FAcy;\u445A\u0380AEadest\u2AB7\u2ABA\u2ABE\u2AC2\u2AC5\u2AF6\u2AF9r\xF2\u2966;\uC000\u2266\u0338rr;\u619Ar;\u6025\u0200;fqs\u0C3B\u2ACE\u2AE3\u2AEFt\u0100ar\u2AD4\u2AD9rro\xF7\u2AC1ightarro\xF7\u2A90\u0180;qs\u0C3B\u2ABA\u2AEAlan\xF4\u0C55\u0100;s\u0C55\u2AF4\xBB\u0C36i\xED\u0C5D\u0100;r\u0C35\u2AFEi\u0100;e\u0C1A\u0C25i\xE4\u0D90\u0100pt\u2B0C\u2B11f;\uC000\u{1D55F}\u8180\xAC;in\u2B19\u2B1A\u2B36\u40ACn\u0200;Edv\u0B89\u2B24\u2B28\u2B2E;\uC000\u22F9\u0338ot;\uC000\u22F5\u0338\u01E1\u0B89\u2B33\u2B35;\u62F7;\u62F6i\u0100;v\u0CB8\u2B3C\u01E1\u0CB8\u2B41\u2B43;\u62FE;\u62FD\u0180aor\u2B4B\u2B63\u2B69r\u0200;ast\u0B7B\u2B55\u2B5A\u2B5Flle\xEC\u0B7Bl;\uC000\u2AFD\u20E5;\uC000\u2202\u0338lint;\u6A14\u0180;ce\u0C92\u2B70\u2B73u\xE5\u0CA5\u0100;c\u0C98\u2B78\u0100;e\u0C92\u2B7D\xF1\u0C98\u0200Aait\u2B88\u2B8B\u2B9D\u2BA7r\xF2\u2988rr\u0180;cw\u2B94\u2B95\u2B99\u619B;\uC000\u2933\u0338;\uC000\u219D\u0338ghtarrow\xBB\u2B95ri\u0100;e\u0CCB\u0CD6\u0380chimpqu\u2BBD\u2BCD\u2BD9\u2B04\u0B78\u2BE4\u2BEF\u0200;cer\u0D32\u2BC6\u0D37\u2BC9u\xE5\u0D45;\uC000\u{1D4C3}ort\u026D\u2B05\0\0\u2BD6ar\xE1\u2B56m\u0100;e\u0D6E\u2BDF\u0100;q\u0D74\u0D73su\u0100bp\u2BEB\u2BED\xE5\u0CF8\xE5\u0D0B\u0180bcp\u2BF6\u2C11\u2C19\u0200;Ees\u2BFF\u2C00\u0D22\u2C04\u6284;\uC000\u2AC5\u0338et\u0100;e\u0D1B\u2C0Bq\u0100;q\u0D23\u2C00c\u0100;e\u0D32\u2C17\xF1\u0D38\u0200;Ees\u2C22\u2C23\u0D5F\u2C27\u6285;\uC000\u2AC6\u0338et\u0100;e\u0D58\u2C2Eq\u0100;q\u0D60\u2C23\u0200gilr\u2C3D\u2C3F\u2C45\u2C47\xEC\u0BD7lde\u803B\xF1\u40F1\xE7\u0C43iangle\u0100lr\u2C52\u2C5Ceft\u0100;e\u0C1A\u2C5A\xF1\u0C26ight\u0100;e\u0CCB\u2C65\xF1\u0CD7\u0100;m\u2C6C\u2C6D\u43BD\u0180;es\u2C74\u2C75\u2C79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2C8F\u2C94\u2C99\u2C9E\u2CA3\u2CB0\u2CB6\u2CD3\u2CE3ash;\u62ADarr;\u6904p;\uC000\u224D\u20D2ash;\u62AC\u0100et\u2CA8\u2CAC;\uC000\u2265\u20D2;\uC000>\u20D2nfin;\u69DE\u0180Aet\u2CBD\u2CC1\u2CC5rr;\u6902;\uC000\u2264\u20D2\u0100;r\u2CCA\u2CCD\uC000<\u20D2ie;\uC000\u22B4\u20D2\u0100At\u2CD8\u2CDCrr;\u6903rie;\uC000\u22B5\u20D2im;\uC000\u223C\u20D2\u0180Aan\u2CF0\u2CF4\u2D02rr;\u61D6r\u0100hr\u2CFA\u2CFDk;\u6923\u0100;o\u13E7\u13E5ear;\u6927\u1253\u1A95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2D2D\0\u2D38\u2D48\u2D60\u2D65\u2D72\u2D84\u1B07\0\0\u2D8D\u2DAB\0\u2DC8\u2DCE\0\u2DDC\u2E19\u2E2B\u2E3E\u2E43\u0100cs\u2D31\u1A97ute\u803B\xF3\u40F3\u0100iy\u2D3C\u2D45r\u0100;c\u1A9E\u2D42\u803B\xF4\u40F4;\u443E\u0280abios\u1AA0\u2D52\u2D57\u01C8\u2D5Alac;\u4151v;\u6A38old;\u69BClig;\u4153\u0100cr\u2D69\u2D6Dir;\u69BF;\uC000\u{1D52C}\u036F\u2D79\0\0\u2D7C\0\u2D82n;\u42DBave\u803B\xF2\u40F2;\u69C1\u0100bm\u2D88\u0DF4ar;\u69B5\u0200acit\u2D95\u2D98\u2DA5\u2DA8r\xF2\u1A80\u0100ir\u2D9D\u2DA0r;\u69BEoss;\u69BBn\xE5\u0E52;\u69C0\u0180aei\u2DB1\u2DB5\u2DB9cr;\u414Dga;\u43C9\u0180cdn\u2DC0\u2DC5\u01CDron;\u43BF;\u69B6pf;\uC000\u{1D560}\u0180ael\u2DD4\u2DD7\u01D2r;\u69B7rp;\u69B9\u0380;adiosv\u2DEA\u2DEB\u2DEE\u2E08\u2E0D\u2E10\u2E16\u6228r\xF2\u1A86\u0200;efm\u2DF7\u2DF8\u2E02\u2E05\u6A5Dr\u0100;o\u2DFE\u2DFF\u6134f\xBB\u2DFF\u803B\xAA\u40AA\u803B\xBA\u40BAgof;\u62B6r;\u6A56lope;\u6A57;\u6A5B\u0180clo\u2E1F\u2E21\u2E27\xF2\u2E01ash\u803B\xF8\u40F8l;\u6298i\u016C\u2E2F\u2E34de\u803B\xF5\u40F5es\u0100;a\u01DB\u2E3As;\u6A36ml\u803B\xF6\u40F6bar;\u633D\u0AE1\u2E5E\0\u2E7D\0\u2E80\u2E9D\0\u2EA2\u2EB9\0\0\u2ECB\u0E9C\0\u2F13\0\0\u2F2B\u2FBC\0\u2FC8r\u0200;ast\u0403\u2E67\u2E72\u0E85\u8100\xB6;l\u2E6D\u2E6E\u40B6le\xEC\u0403\u0269\u2E78\0\0\u2E7Bm;\u6AF3;\u6AFDy;\u443Fr\u0280cimpt\u2E8B\u2E8F\u2E93\u1865\u2E97nt;\u4025od;\u402Eil;\u6030enk;\u6031r;\uC000\u{1D52D}\u0180imo\u2EA8\u2EB0\u2EB4\u0100;v\u2EAD\u2EAE\u43C6;\u43D5ma\xF4\u0A76ne;\u660E\u0180;tv\u2EBF\u2EC0\u2EC8\u43C0chfork\xBB\u1FFD;\u43D6\u0100au\u2ECF\u2EDFn\u0100ck\u2ED5\u2EDDk\u0100;h\u21F4\u2EDB;\u610E\xF6\u21F4s\u0480;abcdemst\u2EF3\u2EF4\u1908\u2EF9\u2EFD\u2F04\u2F06\u2F0A\u2F0E\u402Bcir;\u6A23ir;\u6A22\u0100ou\u1D40\u2F02;\u6A25;\u6A72n\u80BB\xB1\u0E9Dim;\u6A26wo;\u6A27\u0180ipu\u2F19\u2F20\u2F25ntint;\u6A15f;\uC000\u{1D561}nd\u803B\xA3\u40A3\u0500;Eaceinosu\u0EC8\u2F3F\u2F41\u2F44\u2F47\u2F81\u2F89\u2F92\u2F7E\u2FB6;\u6AB3p;\u6AB7u\xE5\u0ED9\u0100;c\u0ECE\u2F4C\u0300;acens\u0EC8\u2F59\u2F5F\u2F66\u2F68\u2F7Eppro\xF8\u2F43urlye\xF1\u0ED9\xF1\u0ECE\u0180aes\u2F6F\u2F76\u2F7Approx;\u6AB9qq;\u6AB5im;\u62E8i\xED\u0EDFme\u0100;s\u2F88\u0EAE\u6032\u0180Eas\u2F78\u2F90\u2F7A\xF0\u2F75\u0180dfp\u0EEC\u2F99\u2FAF\u0180als\u2FA0\u2FA5\u2FAAlar;\u632Eine;\u6312urf;\u6313\u0100;t\u0EFB\u2FB4\xEF\u0EFBrel;\u62B0\u0100ci\u2FC0\u2FC5r;\uC000\u{1D4C5};\u43C8ncsp;\u6008\u0300fiopsu\u2FDA\u22E2\u2FDF\u2FE5\u2FEB\u2FF1r;\uC000\u{1D52E}pf;\uC000\u{1D562}rime;\u6057cr;\uC000\u{1D4C6}\u0180aeo\u2FF8\u3009\u3013t\u0100ei\u2FFE\u3005rnion\xF3\u06B0nt;\u6A16st\u0100;e\u3010\u3011\u403F\xF1\u1F19\xF4\u0F14\u0A80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30E0\u310E\u312B\u3147\u3162\u3172\u318E\u3206\u3215\u3224\u3229\u3258\u326E\u3272\u3290\u32B0\u32B7\u0180art\u3047\u304A\u304Cr\xF2\u10B3\xF2\u03DDail;\u691Car\xF2\u1C65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307F\u308F\u3094\u30CC\u0100eu\u306D\u3071;\uC000\u223D\u0331te;\u4155i\xE3\u116Emptyv;\u69B3g\u0200;del\u0FD1\u3089\u308B\u308D;\u6992;\u69A5\xE5\u0FD1uo\u803B\xBB\u40BBr\u0580;abcfhlpstw\u0FDC\u30AC\u30AF\u30B7\u30B9\u30BC\u30BE\u30C0\u30C3\u30C7\u30CAp;\u6975\u0100;f\u0FE0\u30B4s;\u6920;\u6933s;\u691E\xEB\u225D\xF0\u272El;\u6945im;\u6974l;\u61A3;\u619D\u0100ai\u30D1\u30D5il;\u691Ao\u0100;n\u30DB\u30DC\u6236al\xF3\u0F1E\u0180abr\u30E7\u30EA\u30EEr\xF2\u17E5rk;\u6773\u0100ak\u30F3\u30FDc\u0100ek\u30F9\u30FB;\u407D;\u405D\u0100es\u3102\u3104;\u698Cl\u0100du\u310A\u310C;\u698E;\u6990\u0200aeuy\u3117\u311C\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xEC\u0FF2\xE2\u30FA;\u4440\u0200clqs\u3134\u3137\u313D\u3144a;\u6937dhar;\u6969uo\u0100;r\u020E\u020Dh;\u61B3\u0180acg\u314E\u315F\u0F44l\u0200;ips\u0F78\u3158\u315B\u109Cn\xE5\u10BBar\xF4\u0FA9t;\u65AD\u0180ilr\u3169\u1023\u316Esht;\u697D;\uC000\u{1D52F}\u0100ao\u3177\u3186r\u0100du\u317D\u317F\xBB\u047B\u0100;l\u1091\u3184;\u696C\u0100;v\u318B\u318C\u43C1;\u43F1\u0180gns\u3195\u31F9\u31FCht\u0300ahlrst\u31A4\u31B0\u31C2\u31D8\u31E4\u31EErrow\u0100;t\u0FDC\u31ADa\xE9\u30C8arpoon\u0100du\u31BB\u31BFow\xEE\u317Ep\xBB\u1092eft\u0100ah\u31CA\u31D0rrow\xF3\u0FEAarpoon\xF3\u0551ightarrows;\u61C9quigarro\xF7\u30CBhreetimes;\u62CCg;\u42DAingdotse\xF1\u1F32\u0180ahm\u320D\u3210\u3213r\xF2\u0FEAa\xF2\u0551;\u600Foust\u0100;a\u321E\u321F\u63B1che\xBB\u321Fmid;\u6AEE\u0200abpt\u3232\u323D\u3240\u3252\u0100nr\u3237\u323Ag;\u67EDr;\u61FEr\xEB\u1003\u0180afl\u3247\u324A\u324Er;\u6986;\uC000\u{1D563}us;\u6A2Eimes;\u6A35\u0100ap\u325D\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6A12ar\xF2\u31E3\u0200achq\u327B\u3280\u10BC\u3285quo;\u603Ar;\uC000\u{1D4C7}\u0100bu\u30FB\u328Ao\u0100;r\u0214\u0213\u0180hir\u3297\u329B\u32A0re\xE5\u31F8mes;\u62CAi\u0200;efl\u32AA\u1059\u1821\u32AB\u65B9tri;\u69CEluhar;\u6968;\u611E\u0D61\u32D5\u32DB\u32DF\u332C\u3338\u3371\0\u337A\u33A4\0\0\u33EC\u33F0\0\u3428\u3448\u345A\u34AD\u34B1\u34CA\u34F1\0\u3616\0\0\u3633cute;\u415Bqu\xEF\u27BA\u0500;Eaceinpsy\u11ED\u32F3\u32F5\u32FF\u3302\u330B\u330F\u331F\u3326\u3329;\u6AB4\u01F0\u32FA\0\u32FC;\u6AB8on;\u4161u\xE5\u11FE\u0100;d\u11F3\u3307il;\u415Frc;\u415D\u0180Eas\u3316\u3318\u331B;\u6AB6p;\u6ABAim;\u62E9olint;\u6A13i\xED\u1204;\u4441ot\u0180;be\u3334\u1D47\u3335\u62C5;\u6A66\u0380Aacmstx\u3346\u334A\u3357\u335B\u335E\u3363\u336Drr;\u61D8r\u0100hr\u3350\u3352\xEB\u2228\u0100;o\u0A36\u0A34t\u803B\xA7\u40A7i;\u403Bwar;\u6929m\u0100in\u3369\xF0nu\xF3\xF1t;\u6736r\u0100;o\u3376\u2055\uC000\u{1D530}\u0200acoy\u3382\u3386\u3391\u33A0rp;\u666F\u0100hy\u338B\u338Fcy;\u4449;\u4448rt\u026D\u3399\0\0\u339Ci\xE4\u1464ara\xEC\u2E6F\u803B\xAD\u40AD\u0100gm\u33A8\u33B4ma\u0180;fv\u33B1\u33B2\u33B2\u43C3;\u43C2\u0400;deglnpr\u12AB\u33C5\u33C9\u33CE\u33D6\u33DE\u33E1\u33E6ot;\u6A6A\u0100;q\u12B1\u12B0\u0100;E\u33D3\u33D4\u6A9E;\u6AA0\u0100;E\u33DB\u33DC\u6A9D;\u6A9Fe;\u6246lus;\u6A24arr;\u6972ar\xF2\u113D\u0200aeit\u33F8\u3408\u340F\u3417\u0100ls\u33FD\u3404lsetm\xE9\u336Ahp;\u6A33parsl;\u69E4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341C\u341D\u6AAA\u0100;s\u3422\u3423\u6AAC;\uC000\u2AAC\uFE00\u0180flp\u342E\u3433\u3442tcy;\u444C\u0100;b\u3438\u3439\u402F\u0100;a\u343E\u343F\u69C4r;\u633Ff;\uC000\u{1D564}a\u0100dr\u344D\u0402es\u0100;u\u3454\u3455\u6660it\xBB\u3455\u0180csu\u3460\u3479\u349F\u0100au\u3465\u346Fp\u0100;s\u1188\u346B;\uC000\u2293\uFE00p\u0100;s\u11B4\u3475;\uC000\u2294\uFE00u\u0100bp\u347F\u348F\u0180;es\u1197\u119C\u3486et\u0100;e\u1197\u348D\xF1\u119D\u0180;es\u11A8\u11AD\u3496et\u0100;e\u11A8\u349D\xF1\u11AE\u0180;af\u117B\u34A6\u05B0r\u0165\u34AB\u05B1\xBB\u117Car\xF2\u1148\u0200cemt\u34B9\u34BE\u34C2\u34C5r;\uC000\u{1D4C8}tm\xEE\xF1i\xEC\u3415ar\xE6\u11BE\u0100ar\u34CE\u34D5r\u0100;f\u34D4\u17BF\u6606\u0100an\u34DA\u34EDight\u0100ep\u34E3\u34EApsilo\xEE\u1EE0h\xE9\u2EAFs\xBB\u2852\u0280bcmnp\u34FB\u355E\u1209\u358B\u358E\u0480;Edemnprs\u350E\u350F\u3511\u3515\u351E\u3523\u352C\u3531\u3536\u6282;\u6AC5ot;\u6ABD\u0100;d\u11DA\u351Aot;\u6AC3ult;\u6AC1\u0100Ee\u3528\u352A;\u6ACB;\u628Alus;\u6ABFarr;\u6979\u0180eiu\u353D\u3552\u3555t\u0180;en\u350E\u3545\u354Bq\u0100;q\u11DA\u350Feq\u0100;q\u352B\u3528m;\u6AC7\u0100bp\u355A\u355C;\u6AD5;\u6AD3c\u0300;acens\u11ED\u356C\u3572\u3579\u357B\u3326ppro\xF8\u32FAurlye\xF1\u11FE\xF1\u11F3\u0180aes\u3582\u3588\u331Bppro\xF8\u331Aq\xF1\u3317g;\u666A\u0680123;Edehlmnps\u35A9\u35AC\u35AF\u121C\u35B2\u35B4\u35C0\u35C9\u35D5\u35DA\u35DF\u35E8\u35ED\u803B\xB9\u40B9\u803B\xB2\u40B2\u803B\xB3\u40B3;\u6AC6\u0100os\u35B9\u35BCt;\u6ABEub;\u6AD8\u0100;d\u1222\u35C5ot;\u6AC4s\u0100ou\u35CF\u35D2l;\u67C9b;\u6AD7arr;\u697Bult;\u6AC2\u0100Ee\u35E4\u35E6;\u6ACC;\u628Blus;\u6AC0\u0180eiu\u35F4\u3609\u360Ct\u0180;en\u121C\u35FC\u3602q\u0100;q\u1222\u35B2eq\u0100;q\u35E7\u35E4m;\u6AC8\u0100bp\u3611\u3613;\u6AD4;\u6AD6\u0180Aan\u361C\u3620\u362Drr;\u61D9r\u0100hr\u3626\u3628\xEB\u222E\u0100;o\u0A2B\u0A29war;\u692Alig\u803B\xDF\u40DF\u0BE1\u3651\u365D\u3660\u12CE\u3673\u3679\0\u367E\u36C2\0\0\0\0\0\u36DB\u3703\0\u3709\u376C\0\0\0\u3787\u0272\u3656\0\0\u365Bget;\u6316;\u43C4r\xEB\u0E5F\u0180aey\u3666\u366B\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uC000\u{1D531}\u0200eiko\u3686\u369D\u36B5\u36BC\u01F2\u368B\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369B\u43B8ym;\u43D1\u0100cn\u36A2\u36B2k\u0100as\u36A8\u36AEppro\xF8\u12C1im\xBB\u12ACs\xF0\u129E\u0100as\u36BA\u36AE\xF0\u12C1rn\u803B\xFE\u40FE\u01EC\u031F\u36C6\u22E7es\u8180\xD7;bd\u36CF\u36D0\u36D8\u40D7\u0100;a\u190F\u36D5r;\u6A31;\u6A30\u0180eps\u36E1\u36E3\u3700\xE1\u2A4D\u0200;bcf\u0486\u36EC\u36F0\u36F4ot;\u6336ir;\u6AF1\u0100;o\u36F9\u36FC\uC000\u{1D565}rk;\u6ADA\xE1\u3362rime;\u6034\u0180aip\u370F\u3712\u3764d\xE5\u1248\u0380adempst\u3721\u374D\u3740\u3751\u3757\u375C\u375Fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65B5own\xBB\u1DBBeft\u0100;e\u2800\u373E\xF1\u092E;\u625Cight\u0100;e\u32AA\u374B\xF1\u105Aot;\u65ECinus;\u6A3Alus;\u6A39b;\u69CDime;\u6A3Bezium;\u63E2\u0180cht\u3772\u377D\u3781\u0100ry\u3777\u377B;\uC000\u{1D4C9};\u4446cy;\u445Brok;\u4167\u0100io\u378B\u378Ex\xF4\u1777head\u0100lr\u3797\u37A0eftarro\xF7\u084Fightarrow\xBB\u0F5D\u0900AHabcdfghlmoprstuw\u37D0\u37D3\u37D7\u37E4\u37F0\u37FC\u380E\u381C\u3823\u3834\u3851\u385D\u386B\u38A9\u38CC\u38D2\u38EA\u38F6r\xF2\u03EDar;\u6963\u0100cr\u37DC\u37E2ute\u803B\xFA\u40FA\xF2\u1150r\u01E3\u37EA\0\u37EDy;\u445Eve;\u416D\u0100iy\u37F5\u37FArc\u803B\xFB\u40FB;\u4443\u0180abh\u3803\u3806\u380Br\xF2\u13ADlac;\u4171a\xF2\u13C3\u0100ir\u3813\u3818sht;\u697E;\uC000\u{1D532}rave\u803B\xF9\u40F9\u0161\u3827\u3831r\u0100lr\u382C\u382E\xBB\u0957\xBB\u1083lk;\u6580\u0100ct\u3839\u384D\u026F\u383F\0\0\u384Arn\u0100;e\u3845\u3846\u631Cr\xBB\u3846op;\u630Fri;\u65F8\u0100al\u3856\u385Acr;\u416B\u80BB\xA8\u0349\u0100gp\u3862\u3866on;\u4173f;\uC000\u{1D566}\u0300adhlsu\u114B\u3878\u387D\u1372\u3891\u38A0own\xE1\u13B3arpoon\u0100lr\u3888\u388Cef\xF4\u382Digh\xF4\u382Fi\u0180;hl\u3899\u389A\u389C\u43C5\xBB\u13FAon\xBB\u389Aparrows;\u61C8\u0180cit\u38B0\u38C4\u38C8\u026F\u38B6\0\0\u38C1rn\u0100;e\u38BC\u38BD\u631Dr\xBB\u38BDop;\u630Eng;\u416Fri;\u65F9cr;\uC000\u{1D4CA}\u0180dir\u38D9\u38DD\u38E2ot;\u62F0lde;\u4169i\u0100;f\u3730\u38E8\xBB\u1813\u0100am\u38EF\u38F2r\xF2\u38A8l\u803B\xFC\u40FCangle;\u69A7\u0780ABDacdeflnoprsz\u391C\u391F\u3929\u392D\u39B5\u39B8\u39BD\u39DF\u39E4\u39E8\u39F3\u39F9\u39FD\u3A01\u3A20r\xF2\u03F7ar\u0100;v\u3926\u3927\u6AE8;\u6AE9as\xE8\u03E1\u0100nr\u3932\u3937grt;\u699C\u0380eknprst\u34E3\u3946\u394B\u3952\u395D\u3964\u3996app\xE1\u2415othin\xE7\u1E96\u0180hir\u34EB\u2EC8\u3959op\xF4\u2FB5\u0100;h\u13B7\u3962\xEF\u318D\u0100iu\u3969\u396Dgm\xE1\u33B3\u0100bp\u3972\u3984setneq\u0100;q\u397D\u3980\uC000\u228A\uFE00;\uC000\u2ACB\uFE00setneq\u0100;q\u398F\u3992\uC000\u228B\uFE00;\uC000\u2ACC\uFE00\u0100hr\u399B\u399Fet\xE1\u369Ciangle\u0100lr\u39AA\u39AFeft\xBB\u0925ight\xBB\u1051y;\u4432ash\xBB\u1036\u0180elr\u39C4\u39D2\u39D7\u0180;be\u2DEA\u39CB\u39CFar;\u62BBq;\u625Alip;\u62EE\u0100bt\u39DC\u1468a\xF2\u1469r;\uC000\u{1D533}tr\xE9\u39AEsu\u0100bp\u39EF\u39F1\xBB\u0D1C\xBB\u0D59pf;\uC000\u{1D567}ro\xF0\u0EFBtr\xE9\u39B4\u0100cu\u3A06\u3A0Br;\uC000\u{1D4CB}\u0100bp\u3A10\u3A18n\u0100Ee\u3980\u3A16\xBB\u397En\u0100Ee\u3992\u3A1E\xBB\u3990igzag;\u699A\u0380cefoprs\u3A36\u3A3B\u3A56\u3A5B\u3A54\u3A61\u3A6Airc;\u4175\u0100di\u3A40\u3A51\u0100bg\u3A45\u3A49ar;\u6A5Fe\u0100;q\u15FA\u3A4F;\u6259erp;\u6118r;\uC000\u{1D534}pf;\uC000\u{1D568}\u0100;e\u1479\u3A66at\xE8\u1479cr;\uC000\u{1D4CC}\u0AE3\u178E\u3A87\0\u3A8B\0\u3A90\u3A9B\0\0\u3A9D\u3AA8\u3AAB\u3AAF\0\0\u3AC3\u3ACE\0\u3AD8\u17DC\u17DFtr\xE9\u17D1r;\uC000\u{1D535}\u0100Aa\u3A94\u3A97r\xF2\u03C3r\xF2\u09F6;\u43BE\u0100Aa\u3AA1\u3AA4r\xF2\u03B8r\xF2\u09EBa\xF0\u2713is;\u62FB\u0180dpt\u17A4\u3AB5\u3ABE\u0100fl\u3ABA\u17A9;\uC000\u{1D569}im\xE5\u17B2\u0100Aa\u3AC7\u3ACAr\xF2\u03CEr\xF2\u0A01\u0100cq\u3AD2\u17B8r;\uC000\u{1D4CD}\u0100pt\u17D6\u3ADCr\xE9\u17D4\u0400acefiosu\u3AF0\u3AFD\u3B08\u3B0C\u3B11\u3B15\u3B1B\u3B21c\u0100uy\u3AF6\u3AFBte\u803B\xFD\u40FD;\u444F\u0100iy\u3B02\u3B06rc;\u4177;\u444Bn\u803B\xA5\u40A5r;\uC000\u{1D536}cy;\u4457pf;\uC000\u{1D56A}cr;\uC000\u{1D4CE}\u0100cm\u3B26\u3B29y;\u444El\u803B\xFF\u40FF\u0500acdefhiosw\u3B42\u3B48\u3B54\u3B58\u3B64\u3B69\u3B6D\u3B74\u3B7A\u3B80cute;\u417A\u0100ay\u3B4D\u3B52ron;\u417E;\u4437ot;\u417C\u0100et\u3B5D\u3B61tr\xE6\u155Fa;\u43B6r;\uC000\u{1D537}cy;\u4436grarr;\u61DDpf;\uC000\u{1D56B}cr;\uC000\u{1D4CF}\u0100jn\u3B85\u3B87;\u600Dj;\u600C'.split("").map((c3) => c3.charCodeAt(0))
);

// node_modules/codemirror-json-schema/node_modules/entities/lib/esm/generated/decode-data-xml.js
var decode_data_xml_default = new Uint16Array(
  // prettier-ignore
  "\u0200aglq	\x1B\u026D\0\0p;\u4026os;\u4027t;\u403Et;\u403Cuot;\u4022".split("").map((c3) => c3.charCodeAt(0))
);

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

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

// node_modules/codemirror-json-schema/node_modules/entities/lib/esm/generated/encode-html.js
function restoreDiff(arr) {
  for (let i3 = 1; i3 < arr.length; i3++) {
    arr[i3][0] += arr[i3 - 1][0] + 1;
  }
  return arr;
}
var encode_html_default = new Map(/* @__PURE__ */ restoreDiff([[9, "&Tab;"], [0, "&NewLine;"], [22, "&excl;"], [0, "&quot;"], [0, "&num;"], [0, "&dollar;"], [0, "&percnt;"], [0, "&amp;"], [0, "&apos;"], [0, "&lpar;"], [0, "&rpar;"], [0, "&ast;"], [0, "&plus;"], [0, "&comma;"], [1, "&period;"], [0, "&sol;"], [10, "&colon;"], [0, "&semi;"], [0, { v: "&lt;", n: 8402, o: "&nvlt;" }], [0, { v: "&equals;", n: 8421, o: "&bne;" }], [0, { v: "&gt;", n: 8402, o: "&nvgt;" }], [0, "&quest;"], [0, "&commat;"], [26, "&lbrack;"], [0, "&bsol;"], [0, "&rbrack;"], [0, "&Hat;"], [0, "&lowbar;"], [0, "&DiacriticalGrave;"], [5, { n: 106, o: "&fjlig;" }], [20, "&lbrace;"], [0, "&verbar;"], [0, "&rbrace;"], [34, "&nbsp;"], [0, "&iexcl;"], [0, "&cent;"], [0, "&pound;"], [0, "&curren;"], [0, "&yen;"], [0, "&brvbar;"], [0, "&sect;"], [0, "&die;"], [0, "&copy;"], [0, "&ordf;"], [0, "&laquo;"], [0, "&not;"], [0, "&shy;"], [0, "&circledR;"], [0, "&macr;"], [0, "&deg;"], [0, "&PlusMinus;"], [0, "&sup2;"], [0, "&sup3;"], [0, "&acute;"], [0, "&micro;"], [0, "&para;"], [0, "&centerdot;"], [0, "&cedil;"], [0, "&sup1;"], [0, "&ordm;"], [0, "&raquo;"], [0, "&frac14;"], [0, "&frac12;"], [0, "&frac34;"], [0, "&iquest;"], [0, "&Agrave;"], [0, "&Aacute;"], [0, "&Acirc;"], [0, "&Atilde;"], [0, "&Auml;"], [0, "&angst;"], [0, "&AElig;"], [0, "&Ccedil;"], [0, "&Egrave;"], [0, "&Eacute;"], [0, "&Ecirc;"], [0, "&Euml;"], [0, "&Igrave;"], [0, "&Iacute;"], [0, "&Icirc;"], [0, "&Iuml;"], [0, "&ETH;"], [0, "&Ntilde;"], [0, "&Ograve;"], [0, "&Oacute;"], [0, "&Ocirc;"], [0, "&Otilde;"], [0, "&Ouml;"], [0, "&times;"], [0, "&Oslash;"], [0, "&Ugrave;"], [0, "&Uacute;"], [0, "&Ucirc;"], [0, "&Uuml;"], [0, "&Yacute;"], [0, "&THORN;"], [0, "&szlig;"], [0, "&agrave;"], [0, "&aacute;"], [0, "&acirc;"], [0, "&atilde;"], [0, "&auml;"], [0, "&aring;"], [0, "&aelig;"], [0, "&ccedil;"], [0, "&egrave;"], [0, "&eacute;"], [0, "&ecirc;"], [0, "&euml;"], [0, "&igrave;"], [0, "&iacute;"], [0, "&icirc;"], [0, "&iuml;"], [0, "&eth;"], [0, "&ntilde;"], [0, "&ograve;"], [0, "&oacute;"], [0, "&ocirc;"], [0, "&otilde;"], [0, "&ouml;"], [0, "&div;"], [0, "&oslash;"], [0, "&ugrave;"], [0, "&uacute;"], [0, "&ucirc;"], [0, "&uuml;"], [0, "&yacute;"], [0, "&thorn;"], [0, "&yuml;"], [0, "&Amacr;"], [0, "&amacr;"], [0, "&Abreve;"], [0, "&abreve;"], [0, "&Aogon;"], [0, "&aogon;"], [0, "&Cacute;"], [0, "&cacute;"], [0, "&Ccirc;"], [0, "&ccirc;"], [0, "&Cdot;"], [0, "&cdot;"], [0, "&Ccaron;"], [0, "&ccaron;"], [0, "&Dcaron;"], [0, "&dcaron;"], [0, "&Dstrok;"], [0, "&dstrok;"], [0, "&Emacr;"], [0, "&emacr;"], [2, "&Edot;"], [0, "&edot;"], [0, "&Eogon;"], [0, "&eogon;"], [0, "&Ecaron;"], [0, "&ecaron;"], [0, "&Gcirc;"], [0, "&gcirc;"], [0, "&Gbreve;"], [0, "&gbreve;"], [0, "&Gdot;"], [0, "&gdot;"], [0, "&Gcedil;"], [1, "&Hcirc;"], [0, "&hcirc;"], [0, "&Hstrok;"], [0, "&hstrok;"], [0, "&Itilde;"], [0, "&itilde;"], [0, "&Imacr;"], [0, "&imacr;"], [2, "&Iogon;"], [0, "&iogon;"], [0, "&Idot;"], [0, "&imath;"], [0, "&IJlig;"], [0, "&ijlig;"], [0, "&Jcirc;"], [0, "&jcirc;"], [0, "&Kcedil;"], [0, "&kcedil;"], [0, "&kgreen;"], [0, "&Lacute;"], [0, "&lacute;"], [0, "&Lcedil;"], [0, "&lcedil;"], [0, "&Lcaron;"], [0, "&lcaron;"], [0, "&Lmidot;"], [0, "&lmidot;"], [0, "&Lstrok;"], [0, "&lstrok;"], [0, "&Nacute;"], [0, "&nacute;"], [0, "&Ncedil;"], [0, "&ncedil;"], [0, "&Ncaron;"], [0, "&ncaron;"], [0, "&napos;"], [0, "&ENG;"], [0, "&eng;"], [0, "&Omacr;"], [0, "&omacr;"], [2, "&Odblac;"], [0, "&odblac;"], [0, "&OElig;"], [0, "&oelig;"], [0, "&Racute;"], [0, "&racute;"], [0, "&Rcedil;"], [0, "&rcedil;"], [0, "&Rcaron;"], [0, "&rcaron;"], [0, "&Sacute;"], [0, "&sacute;"], [0, "&Scirc;"], [0, "&scirc;"], [0, "&Scedil;"], [0, "&scedil;"], [0, "&Scaron;"], [0, "&scaron;"], [0, "&Tcedil;"], [0, "&tcedil;"], [0, "&Tcaron;"], [0, "&tcaron;"], [0, "&Tstrok;"], [0, "&tstrok;"], [0, "&Utilde;"], [0, "&utilde;"], [0, "&Umacr;"], [0, "&umacr;"], [0, "&Ubreve;"], [0, "&ubreve;"], [0, "&Uring;"], [0, "&uring;"], [0, "&Udblac;"], [0, "&udblac;"], [0, "&Uogon;"], [0, "&uogon;"], [0, "&Wcirc;"], [0, "&wcirc;"], [0, "&Ycirc;"], [0, "&ycirc;"], [0, "&Yuml;"], [0, "&Zacute;"], [0, "&zacute;"], [0, "&Zdot;"], [0, "&zdot;"], [0, "&Zcaron;"], [0, "&zcaron;"], [19, "&fnof;"], [34, "&imped;"], [63, "&gacute;"], [65, "&jmath;"], [142, "&circ;"], [0, "&caron;"], [16, "&breve;"], [0, "&DiacriticalDot;"], [0, "&ring;"], [0, "&ogon;"], [0, "&DiacriticalTilde;"], [0, "&dblac;"], [51, "&DownBreve;"], [127, "&Alpha;"], [0, "&Beta;"], [0, "&Gamma;"], [0, "&Delta;"], [0, "&Epsilon;"], [0, "&Zeta;"], [0, "&Eta;"], [0, "&Theta;"], [0, "&Iota;"], [0, "&Kappa;"], [0, "&Lambda;"], [0, "&Mu;"], [0, "&Nu;"], [0, "&Xi;"], [0, "&Omicron;"], [0, "&Pi;"], [0, "&Rho;"], [1, "&Sigma;"], [0, "&Tau;"], [0, "&Upsilon;"], [0, "&Phi;"], [0, "&Chi;"], [0, "&Psi;"], [0, "&ohm;"], [7, "&alpha;"], [0, "&beta;"], [0, "&gamma;"], [0, "&delta;"], [0, "&epsi;"], [0, "&zeta;"], [0, "&eta;"], [0, "&theta;"], [0, "&iota;"], [0, "&kappa;"], [0, "&lambda;"], [0, "&mu;"], [0, "&nu;"], [0, "&xi;"], [0, "&omicron;"], [0, "&pi;"], [0, "&rho;"], [0, "&sigmaf;"], [0, "&sigma;"], [0, "&tau;"], [0, "&upsi;"], [0, "&phi;"], [0, "&chi;"], [0, "&psi;"], [0, "&omega;"], [7, "&thetasym;"], [0, "&Upsi;"], [2, "&phiv;"], [0, "&piv;"], [5, "&Gammad;"], [0, "&digamma;"], [18, "&kappav;"], [0, "&rhov;"], [3, "&epsiv;"], [0, "&backepsilon;"], [10, "&IOcy;"], [0, "&DJcy;"], [0, "&GJcy;"], [0, "&Jukcy;"], [0, "&DScy;"], [0, "&Iukcy;"], [0, "&YIcy;"], [0, "&Jsercy;"], [0, "&LJcy;"], [0, "&NJcy;"], [0, "&TSHcy;"], [0, "&KJcy;"], [1, "&Ubrcy;"], [0, "&DZcy;"], [0, "&Acy;"], [0, "&Bcy;"], [0, "&Vcy;"], [0, "&Gcy;"], [0, "&Dcy;"], [0, "&IEcy;"], [0, "&ZHcy;"], [0, "&Zcy;"], [0, "&Icy;"], [0, "&Jcy;"], [0, "&Kcy;"], [0, "&Lcy;"], [0, "&Mcy;"], [0, "&Ncy;"], [0, "&Ocy;"], [0, "&Pcy;"], [0, "&Rcy;"], [0, "&Scy;"], [0, "&Tcy;"], [0, "&Ucy;"], [0, "&Fcy;"], [0, "&KHcy;"], [0, "&TScy;"], [0, "&CHcy;"], [0, "&SHcy;"], [0, "&SHCHcy;"], [0, "&HARDcy;"], [0, "&Ycy;"], [0, "&SOFTcy;"], [0, "&Ecy;"], [0, "&YUcy;"], [0, "&YAcy;"], [0, "&acy;"], [0, "&bcy;"], [0, "&vcy;"], [0, "&gcy;"], [0, "&dcy;"], [0, "&iecy;"], [0, "&zhcy;"], [0, "&zcy;"], [0, "&icy;"], [0, "&jcy;"], [0, "&kcy;"], [0, "&lcy;"], [0, "&mcy;"], [0, "&ncy;"], [0, "&ocy;"], [0, "&pcy;"], [0, "&rcy;"], [0, "&scy;"], [0, "&tcy;"], [0, "&ucy;"], [0, "&fcy;"], [0, "&khcy;"], [0, "&tscy;"], [0, "&chcy;"], [0, "&shcy;"], [0, "&shchcy;"], [0, "&hardcy;"], [0, "&ycy;"], [0, "&softcy;"], [0, "&ecy;"], [0, "&yucy;"], [0, "&yacy;"], [1, "&iocy;"], [0, "&djcy;"], [0, "&gjcy;"], [0, "&jukcy;"], [0, "&dscy;"], [0, "&iukcy;"], [0, "&yicy;"], [0, "&jsercy;"], [0, "&ljcy;"], [0, "&njcy;"], [0, "&tshcy;"], [0, "&kjcy;"], [1, "&ubrcy;"], [0, "&dzcy;"], [7074, "&ensp;"], [0, "&emsp;"], [0, "&emsp13;"], [0, "&emsp14;"], [1, "&numsp;"], [0, "&puncsp;"], [0, "&ThinSpace;"], [0, "&hairsp;"], [0, "&NegativeMediumSpace;"], [0, "&zwnj;"], [0, "&zwj;"], [0, "&lrm;"], [0, "&rlm;"], [0, "&dash;"], [2, "&ndash;"], [0, "&mdash;"], [0, "&horbar;"], [0, "&Verbar;"], [1, "&lsquo;"], [0, "&CloseCurlyQuote;"], [0, "&lsquor;"], [1, "&ldquo;"], [0, "&CloseCurlyDoubleQuote;"], [0, "&bdquo;"], [1, "&dagger;"], [0, "&Dagger;"], [0, "&bull;"], [2, "&nldr;"], [0, "&hellip;"], [9, "&permil;"], [0, "&pertenk;"], [0, "&prime;"], [0, "&Prime;"], [0, "&tprime;"], [0, "&backprime;"], [3, "&lsaquo;"], [0, "&rsaquo;"], [3, "&oline;"], [2, "&caret;"], [1, "&hybull;"], [0, "&frasl;"], [10, "&bsemi;"], [7, "&qprime;"], [7, { v: "&MediumSpace;", n: 8202, o: "&ThickSpace;" }], [0, "&NoBreak;"], [0, "&af;"], [0, "&InvisibleTimes;"], [0, "&ic;"], [72, "&euro;"], [46, "&tdot;"], [0, "&DotDot;"], [37, "&complexes;"], [2, "&incare;"], [4, "&gscr;"], [0, "&hamilt;"], [0, "&Hfr;"], [0, "&Hopf;"], [0, "&planckh;"], [0, "&hbar;"], [0, "&imagline;"], [0, "&Ifr;"], [0, "&lagran;"], [0, "&ell;"], [1, "&naturals;"], [0, "&numero;"], [0, "&copysr;"], [0, "&weierp;"], [0, "&Popf;"], [0, "&Qopf;"], [0, "&realine;"], [0, "&real;"], [0, "&reals;"], [0, "&rx;"], [3, "&trade;"], [1, "&integers;"], [2, "&mho;"], [0, "&zeetrf;"], [0, "&iiota;"], [2, "&bernou;"], [0, "&Cayleys;"], [1, "&escr;"], [0, "&Escr;"], [0, "&Fouriertrf;"], [1, "&Mellintrf;"], [0, "&order;"], [0, "&alefsym;"], [0, "&beth;"], [0, "&gimel;"], [0, "&daleth;"], [12, "&CapitalDifferentialD;"], [0, "&dd;"], [0, "&ee;"], [0, "&ii;"], [10, "&frac13;"], [0, "&frac23;"], [0, "&frac15;"], [0, "&frac25;"], [0, "&frac35;"], [0, "&frac45;"], [0, "&frac16;"], [0, "&frac56;"], [0, "&frac18;"], [0, "&frac38;"], [0, "&frac58;"], [0, "&frac78;"], [49, "&larr;"], [0, "&ShortUpArrow;"], [0, "&rarr;"], [0, "&darr;"], [0, "&harr;"], [0, "&updownarrow;"], [0, "&nwarr;"], [0, "&nearr;"], [0, "&LowerRightArrow;"], [0, "&LowerLeftArrow;"], [0, "&nlarr;"], [0, "&nrarr;"], [1, { v: "&rarrw;", n: 824, o: "&nrarrw;" }], [0, "&Larr;"], [0, "&Uarr;"], [0, "&Rarr;"], [0, "&Darr;"], [0, "&larrtl;"], [0, "&rarrtl;"], [0, "&LeftTeeArrow;"], [0, "&mapstoup;"], [0, "&map;"], [0, "&DownTeeArrow;"], [1, "&hookleftarrow;"], [0, "&hookrightarrow;"], [0, "&larrlp;"], [0, "&looparrowright;"], [0, "&harrw;"], [0, "&nharr;"], [1, "&lsh;"], [0, "&rsh;"], [0, "&ldsh;"], [0, "&rdsh;"], [1, "&crarr;"], [0, "&cularr;"], [0, "&curarr;"], [2, "&circlearrowleft;"], [0, "&circlearrowright;"], [0, "&leftharpoonup;"], [0, "&DownLeftVector;"], [0, "&RightUpVector;"], [0, "&LeftUpVector;"], [0, "&rharu;"], [0, "&DownRightVector;"], [0, "&dharr;"], [0, "&dharl;"], [0, "&RightArrowLeftArrow;"], [0, "&udarr;"], [0, "&LeftArrowRightArrow;"], [0, "&leftleftarrows;"], [0, "&upuparrows;"], [0, "&rightrightarrows;"], [0, "&ddarr;"], [0, "&leftrightharpoons;"], [0, "&Equilibrium;"], [0, "&nlArr;"], [0, "&nhArr;"], [0, "&nrArr;"], [0, "&DoubleLeftArrow;"], [0, "&DoubleUpArrow;"], [0, "&DoubleRightArrow;"], [0, "&dArr;"], [0, "&DoubleLeftRightArrow;"], [0, "&DoubleUpDownArrow;"], [0, "&nwArr;"], [0, "&neArr;"], [0, "&seArr;"], [0, "&swArr;"], [0, "&lAarr;"], [0, "&rAarr;"], [1, "&zigrarr;"], [6, "&larrb;"], [0, "&rarrb;"], [15, "&DownArrowUpArrow;"], [7, "&loarr;"], [0, "&roarr;"], [0, "&hoarr;"], [0, "&forall;"], [0, "&comp;"], [0, { v: "&part;", n: 824, o: "&npart;" }], [0, "&exist;"], [0, "&nexist;"], [0, "&empty;"], [1, "&Del;"], [0, "&Element;"], [0, "&NotElement;"], [1, "&ni;"], [0, "&notni;"], [2, "&prod;"], [0, "&coprod;"], [0, "&sum;"], [0, "&minus;"], [0, "&MinusPlus;"], [0, "&dotplus;"], [1, "&Backslash;"], [0, "&lowast;"], [0, "&compfn;"], [1, "&radic;"], [2, "&prop;"], [0, "&infin;"], [0, "&angrt;"], [0, { v: "&ang;", n: 8402, o: "&nang;" }], [0, "&angmsd;"], [0, "&angsph;"], [0, "&mid;"], [0, "&nmid;"], [0, "&DoubleVerticalBar;"], [0, "&NotDoubleVerticalBar;"], [0, "&and;"], [0, "&or;"], [0, { v: "&cap;", n: 65024, o: "&caps;" }], [0, { v: "&cup;", n: 65024, o: "&cups;" }], [0, "&int;"], [0, "&Int;"], [0, "&iiint;"], [0, "&conint;"], [0, "&Conint;"], [0, "&Cconint;"], [0, "&cwint;"], [0, "&ClockwiseContourIntegral;"], [0, "&awconint;"], [0, "&there4;"], [0, "&becaus;"], [0, "&ratio;"], [0, "&Colon;"], [0, "&dotminus;"], [1, "&mDDot;"], [0, "&homtht;"], [0, { v: "&sim;", n: 8402, o: "&nvsim;" }], [0, { v: "&backsim;", n: 817, o: "&race;" }], [0, { v: "&ac;", n: 819, o: "&acE;" }], [0, "&acd;"], [0, "&VerticalTilde;"], [0, "&NotTilde;"], [0, { v: "&eqsim;", n: 824, o: "&nesim;" }], [0, "&sime;"], [0, "&NotTildeEqual;"], [0, "&cong;"], [0, "&simne;"], [0, "&ncong;"], [0, "&ap;"], [0, "&nap;"], [0, "&ape;"], [0, { v: "&apid;", n: 824, o: "&napid;" }], [0, "&backcong;"], [0, { v: "&asympeq;", n: 8402, o: "&nvap;" }], [0, { v: "&bump;", n: 824, o: "&nbump;" }], [0, { v: "&bumpe;", n: 824, o: "&nbumpe;" }], [0, { v: "&doteq;", n: 824, o: "&nedot;" }], [0, "&doteqdot;"], [0, "&efDot;"], [0, "&erDot;"], [0, "&Assign;"], [0, "&ecolon;"], [0, "&ecir;"], [0, "&circeq;"], [1, "&wedgeq;"], [0, "&veeeq;"], [1, "&triangleq;"], [2, "&equest;"], [0, "&ne;"], [0, { v: "&Congruent;", n: 8421, o: "&bnequiv;" }], [0, "&nequiv;"], [1, { v: "&le;", n: 8402, o: "&nvle;" }], [0, { v: "&ge;", n: 8402, o: "&nvge;" }], [0, { v: "&lE;", n: 824, o: "&nlE;" }], [0, { v: "&gE;", n: 824, o: "&ngE;" }], [0, { v: "&lnE;", n: 65024, o: "&lvertneqq;" }], [0, { v: "&gnE;", n: 65024, o: "&gvertneqq;" }], [0, { v: "&ll;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nLtv;"], [7577, "&nLt;"]])) }], [0, { v: "&gg;", n: new Map(/* @__PURE__ */ restoreDiff([[824, "&nGtv;"], [7577, "&nGt;"]])) }], [0, "&between;"], [0, "&NotCupCap;"], [0, "&nless;"], [0, "&ngt;"], [0, "&nle;"], [0, "&nge;"], [0, "&lesssim;"], [0, "&GreaterTilde;"], [0, "&nlsim;"], [0, "&ngsim;"], [0, "&LessGreater;"], [0, "&gl;"], [0, "&NotLessGreater;"], [0, "&NotGreaterLess;"], [0, "&pr;"], [0, "&sc;"], [0, "&prcue;"], [0, "&sccue;"], [0, "&PrecedesTilde;"], [0, { v: "&scsim;", n: 824, o: "&NotSucceedsTilde;" }], [0, "&NotPrecedes;"], [0, "&NotSucceeds;"], [0, { v: "&sub;", n: 8402, o: "&NotSubset;" }], [0, { v: "&sup;", n: 8402, o: "&NotSuperset;" }], [0, "&nsub;"], [0, "&nsup;"], [0, "&sube;"], [0, "&supe;"], [0, "&NotSubsetEqual;"], [0, "&NotSupersetEqual;"], [0, { v: "&subne;", n: 65024, o: "&varsubsetneq;" }], [0, { v: "&supne;", n: 65024, o: "&varsupsetneq;" }], [1, "&cupdot;"], [0, "&UnionPlus;"], [0, { v: "&sqsub;", n: 824, o: "&NotSquareSubset;" }], [0, { v: "&sqsup;", n: 824, o: "&NotSquareSuperset;" }], [0, "&sqsube;"], [0, "&sqsupe;"], [0, { v: "&sqcap;", n: 65024, o: "&sqcaps;" }], [0, { v: "&sqcup;", n: 65024, o: "&sqcups;" }], [0, "&CirclePlus;"], [0, "&CircleMinus;"], [0, "&CircleTimes;"], [0, "&osol;"], [0, "&CircleDot;"], [0, "&circledcirc;"], [0, "&circledast;"], [1, "&circleddash;"], [0, "&boxplus;"], [0, "&boxminus;"], [0, "&boxtimes;"], [0, "&dotsquare;"], [0, "&RightTee;"], [0, "&dashv;"], [0, "&DownTee;"], [0, "&bot;"], [1, "&models;"], [0, "&DoubleRightTee;"], [0, "&Vdash;"], [0, "&Vvdash;"], [0, "&VDash;"], [0, "&nvdash;"], [0, "&nvDash;"], [0, "&nVdash;"], [0, "&nVDash;"], [0, "&prurel;"], [1, "&LeftTriangle;"], [0, "&RightTriangle;"], [0, { v: "&LeftTriangleEqual;", n: 8402, o: "&nvltrie;" }], [0, { v: "&RightTriangleEqual;", n: 8402, o: "&nvrtrie;" }], [0, "&origof;"], [0, "&imof;"], [0, "&multimap;"], [0, "&hercon;"], [0, "&intcal;"], [0, "&veebar;"], [1, "&barvee;"], [0, "&angrtvb;"], [0, "&lrtri;"], [0, "&bigwedge;"], [0, "&bigvee;"], [0, "&bigcap;"], [0, "&bigcup;"], [0, "&diam;"], [0, "&sdot;"], [0, "&sstarf;"], [0, "&divideontimes;"], [0, "&bowtie;"], [0, "&ltimes;"], [0, "&rtimes;"], [0, "&leftthreetimes;"], [0, "&rightthreetimes;"], [0, "&backsimeq;"], [0, "&curlyvee;"], [0, "&curlywedge;"], [0, "&Sub;"], [0, "&Sup;"], [0, "&Cap;"], [0, "&Cup;"], [0, "&fork;"], [0, "&epar;"], [0, "&lessdot;"], [0, "&gtdot;"], [0, { v: "&Ll;", n: 824, o: "&nLl;" }], [0, { v: "&Gg;", n: 824, o: "&nGg;" }], [0, { v: "&leg;", n: 65024, o: "&lesg;" }], [0, { v: "&gel;", n: 65024, o: "&gesl;" }], [2, "&cuepr;"], [0, "&cuesc;"], [0, "&NotPrecedesSlantEqual;"], [0, "&NotSucceedsSlantEqual;"], [0, "&NotSquareSubsetEqual;"], [0, "&NotSquareSupersetEqual;"], [2, "&lnsim;"], [0, "&gnsim;"], [0, "&precnsim;"], [0, "&scnsim;"], [0, "&nltri;"], [0, "&NotRightTriangle;"], [0, "&nltrie;"], [0, "&NotRightTriangleEqual;"], [0, "&vellip;"], [0, "&ctdot;"], [0, "&utdot;"], [0, "&dtdot;"], [0, "&disin;"], [0, "&isinsv;"], [0, "&isins;"], [0, { v: "&isindot;", n: 824, o: "&notindot;" }], [0, "&notinvc;"], [0, "&notinvb;"], [1, { v: "&isinE;", n: 824, o: "&notinE;" }], [0, "&nisd;"], [0, "&xnis;"], [0, "&nis;"], [0, "&notnivc;"], [0, "&notnivb;"], [6, "&barwed;"], [0, "&Barwed;"], [1, "&lceil;"], [0, "&rceil;"], [0, "&LeftFloor;"], [0, "&rfloor;"], [0, "&drcrop;"], [0, "&dlcrop;"], [0, "&urcrop;"], [0, "&ulcrop;"], [0, "&bnot;"], [1, "&profline;"], [0, "&profsurf;"], [1, "&telrec;"], [0, "&target;"], [5, "&ulcorn;"], [0, "&urcorn;"], [0, "&dlcorn;"], [0, "&drcorn;"], [2, "&frown;"], [0, "&smile;"], [9, "&cylcty;"], [0, "&profalar;"], [7, "&topbot;"], [6, "&ovbar;"], [1, "&solbar;"], [60, "&angzarr;"], [51, "&lmoustache;"], [0, "&rmoustache;"], [2, "&OverBracket;"], [0, "&bbrk;"], [0, "&bbrktbrk;"], [37, "&OverParenthesis;"], [0, "&UnderParenthesis;"], [0, "&OverBrace;"], [0, "&UnderBrace;"], [2, "&trpezium;"], [4, "&elinters;"], [59, "&blank;"], [164, "&circledS;"], [55, "&boxh;"], [1, "&boxv;"], [9, "&boxdr;"], [3, "&boxdl;"], [3, "&boxur;"], [3, "&boxul;"], [3, "&boxvr;"], [7, "&boxvl;"], [7, "&boxhd;"], [7, "&boxhu;"], [7, "&boxvh;"], [19, "&boxH;"], [0, "&boxV;"], [0, "&boxdR;"], [0, "&boxDr;"], [0, "&boxDR;"], [0, "&boxdL;"], [0, "&boxDl;"], [0, "&boxDL;"], [0, "&boxuR;"], [0, "&boxUr;"], [0, "&boxUR;"], [0, "&boxuL;"], [0, "&boxUl;"], [0, "&boxUL;"], [0, "&boxvR;"], [0, "&boxVr;"], [0, "&boxVR;"], [0, "&boxvL;"], [0, "&boxVl;"], [0, "&boxVL;"], [0, "&boxHd;"], [0, "&boxhD;"], [0, "&boxHD;"], [0, "&boxHu;"], [0, "&boxhU;"], [0, "&boxHU;"], [0, "&boxvH;"], [0, "&boxVh;"], [0, "&boxVH;"], [19, "&uhblk;"], [3, "&lhblk;"], [3, "&block;"], [8, "&blk14;"], [0, "&blk12;"], [0, "&blk34;"], [13, "&square;"], [8, "&blacksquare;"], [0, "&EmptyVerySmallSquare;"], [1, "&rect;"], [0, "&marker;"], [2, "&fltns;"], [1, "&bigtriangleup;"], [0, "&blacktriangle;"], [0, "&triangle;"], [2, "&blacktriangleright;"], [0, "&rtri;"], [3, "&bigtriangledown;"], [0, "&blacktriangledown;"], [0, "&dtri;"], [2, "&blacktriangleleft;"], [0, "&ltri;"], [6, "&loz;"], [0, "&cir;"], [32, "&tridot;"], [2, "&bigcirc;"], [8, "&ultri;"], [0, "&urtri;"], [0, "&lltri;"], [0, "&EmptySmallSquare;"], [0, "&FilledSmallSquare;"], [8, "&bigstar;"], [0, "&star;"], [7, "&phone;"], [49, "&female;"], [1, "&male;"], [29, "&spades;"], [2, "&clubs;"], [1, "&hearts;"], [0, "&diamondsuit;"], [3, "&sung;"], [2, "&flat;"], [0, "&natural;"], [0, "&sharp;"], [163, "&check;"], [3, "&cross;"], [8, "&malt;"], [21, "&sext;"], [33, "&VerticalSeparator;"], [25, "&lbbrk;"], [0, "&rbbrk;"], [84, "&bsolhsub;"], [0, "&suphsol;"], [28, "&LeftDoubleBracket;"], [0, "&RightDoubleBracket;"], [0, "&lang;"], [0, "&rang;"], [0, "&Lang;"], [0, "&Rang;"], [0, "&loang;"], [0, "&roang;"], [7, "&longleftarrow;"], [0, "&longrightarrow;"], [0, "&longleftrightarrow;"], [0, "&DoubleLongLeftArrow;"], [0, "&DoubleLongRightArrow;"], [0, "&DoubleLongLeftRightArrow;"], [1, "&longmapsto;"], [2, "&dzigrarr;"], [258, "&nvlArr;"], [0, "&nvrArr;"], [0, "&nvHarr;"], [0, "&Map;"], [6, "&lbarr;"], [0, "&bkarow;"], [0, "&lBarr;"], [0, "&dbkarow;"], [0, "&drbkarow;"], [0, "&DDotrahd;"], [0, "&UpArrowBar;"], [0, "&DownArrowBar;"], [2, "&Rarrtl;"], [2, "&latail;"], [0, "&ratail;"], [0, "&lAtail;"], [0, "&rAtail;"], [0, "&larrfs;"], [0, "&rarrfs;"], [0, "&larrbfs;"], [0, "&rarrbfs;"], [2, "&nwarhk;"], [0, "&nearhk;"], [0, "&hksearow;"], [0, "&hkswarow;"], [0, "&nwnear;"], [0, "&nesear;"], [0, "&seswar;"], [0, "&swnwar;"], [8, { v: "&rarrc;", n: 824, o: "&nrarrc;" }], [1, "&cudarrr;"], [0, "&ldca;"], [0, "&rdca;"], [0, "&cudarrl;"], [0, "&larrpl;"], [2, "&curarrm;"], [0, "&cularrp;"], [7, "&rarrpl;"], [2, "&harrcir;"], [0, "&Uarrocir;"], [0, "&lurdshar;"], [0, "&ldrushar;"], [2, "&LeftRightVector;"], [0, "&RightUpDownVector;"], [0, "&DownLeftRightVector;"], [0, "&LeftUpDownVector;"], [0, "&LeftVectorBar;"], [0, "&RightVectorBar;"], [0, "&RightUpVectorBar;"], [0, "&RightDownVectorBar;"], [0, "&DownLeftVectorBar;"], [0, "&DownRightVectorBar;"], [0, "&LeftUpVectorBar;"], [0, "&LeftDownVectorBar;"], [0, "&LeftTeeVector;"], [0, "&RightTeeVector;"], [0, "&RightUpTeeVector;"], [0, "&RightDownTeeVector;"], [0, "&DownLeftTeeVector;"], [0, "&DownRightTeeVector;"], [0, "&LeftUpTeeVector;"], [0, "&LeftDownTeeVector;"], [0, "&lHar;"], [0, "&uHar;"], [0, "&rHar;"], [0, "&dHar;"], [0, "&luruhar;"], [0, "&ldrdhar;"], [0, "&ruluhar;"], [0, "&rdldhar;"], [0, "&lharul;"], [0, "&llhard;"], [0, "&rharul;"], [0, "&lrhard;"], [0, "&udhar;"], [0, "&duhar;"], [0, "&RoundImplies;"], [0, "&erarr;"], [0, "&simrarr;"], [0, "&larrsim;"], [0, "&rarrsim;"], [0, "&rarrap;"], [0, "&ltlarr;"], [1, "&gtrarr;"], [0, "&subrarr;"], [1, "&suplarr;"], [0, "&lfisht;"], [0, "&rfisht;"], [0, "&ufisht;"], [0, "&dfisht;"], [5, "&lopar;"], [0, "&ropar;"], [4, "&lbrke;"], [0, "&rbrke;"], [0, "&lbrkslu;"], [0, "&rbrksld;"], [0, "&lbrksld;"], [0, "&rbrkslu;"], [0, "&langd;"], [0, "&rangd;"], [0, "&lparlt;"], [0, "&rpargt;"], [0, "&gtlPar;"], [0, "&ltrPar;"], [3, "&vzigzag;"], [1, "&vangrt;"], [0, "&angrtvbd;"], [6, "&ange;"], [0, "&range;"], [0, "&dwangle;"], [0, "&uwangle;"], [0, "&angmsdaa;"], [0, "&angmsdab;"], [0, "&angmsdac;"], [0, "&angmsdad;"], [0, "&angmsdae;"], [0, "&angmsdaf;"], [0, "&angmsdag;"], [0, "&angmsdah;"], [0, "&bemptyv;"], [0, "&demptyv;"], [0, "&cemptyv;"], [0, "&raemptyv;"], [0, "&laemptyv;"], [0, "&ohbar;"], [0, "&omid;"], [0, "&opar;"], [1, "&operp;"], [1, "&olcross;"], [0, "&odsold;"], [1, "&olcir;"], [0, "&ofcir;"], [0, "&olt;"], [0, "&ogt;"], [0, "&cirscir;"], [0, "&cirE;"], [0, "&solb;"], [0, "&bsolb;"], [3, "&boxbox;"], [3, "&trisb;"], [0, "&rtriltri;"], [0, { v: "&LeftTriangleBar;", n: 824, o: "&NotLeftTriangleBar;" }], [0, { v: "&RightTriangleBar;", n: 824, o: "&NotRightTriangleBar;" }], [11, "&iinfin;"], [0, "&infintie;"], [0, "&nvinfin;"], [4, "&eparsl;"], [0, "&smeparsl;"], [0, "&eqvparsl;"], [5, "&blacklozenge;"], [8, "&RuleDelayed;"], [1, "&dsol;"], [9, "&bigodot;"], [0, "&bigoplus;"], [0, "&bigotimes;"], [1, "&biguplus;"], [1, "&bigsqcup;"], [5, "&iiiint;"], [0, "&fpartint;"], [2, "&cirfnint;"], [0, "&awint;"], [0, "&rppolint;"], [0, "&scpolint;"], [0, "&npolint;"], [0, "&pointint;"], [0, "&quatint;"], [0, "&intlarhk;"], [10, "&pluscir;"], [0, "&plusacir;"], [0, "&simplus;"], [0, "&plusdu;"], [0, "&plussim;"], [0, "&plustwo;"], [1, "&mcomma;"], [0, "&minusdu;"], [2, "&loplus;"], [0, "&roplus;"], [0, "&Cross;"], [0, "&timesd;"], [0, "&timesbar;"], [1, "&smashp;"], [0, "&lotimes;"], [0, "&rotimes;"], [0, "&otimesas;"], [0, "&Otimes;"], [0, "&odiv;"], [0, "&triplus;"], [0, "&triminus;"], [0, "&tritime;"], [0, "&intprod;"], [2, "&amalg;"], [0, "&capdot;"], [1, "&ncup;"], [0, "&ncap;"], [0, "&capand;"], [0, "&cupor;"], [0, "&cupcap;"], [0, "&capcup;"], [0, "&cupbrcap;"], [0, "&capbrcup;"], [0, "&cupcup;"], [0, "&capcap;"], [0, "&ccups;"], [0, "&ccaps;"], [2, "&ccupssm;"], [2, "&And;"], [0, "&Or;"], [0, "&andand;"], [0, "&oror;"], [0, "&orslope;"], [0, "&andslope;"], [1, "&andv;"], [0, "&orv;"], [0, "&andd;"], [0, "&ord;"], [1, "&wedbar;"], [6, "&sdote;"], [3, "&simdot;"], [2, { v: "&congdot;", n: 824, o: "&ncongdot;" }], [0, "&easter;"], [0, "&apacir;"], [0, { v: "&apE;", n: 824, o: "&napE;" }], [0, "&eplus;"], [0, "&pluse;"], [0, "&Esim;"], [0, "&Colone;"], [0, "&Equal;"], [1, "&ddotseq;"], [0, "&equivDD;"], [0, "&ltcir;"], [0, "&gtcir;"], [0, "&ltquest;"], [0, "&gtquest;"], [0, { v: "&leqslant;", n: 824, o: "&nleqslant;" }], [0, { v: "&geqslant;", n: 824, o: "&ngeqslant;" }], [0, "&lesdot;"], [0, "&gesdot;"], [0, "&lesdoto;"], [0, "&gesdoto;"], [0, "&lesdotor;"], [0, "&gesdotol;"], [0, "&lap;"], [0, "&gap;"], [0, "&lne;"], [0, "&gne;"], [0, "&lnap;"], [0, "&gnap;"], [0, "&lEg;"], [0, "&gEl;"], [0, "&lsime;"], [0, "&gsime;"], [0, "&lsimg;"], [0, "&gsiml;"], [0, "&lgE;"], [0, "&glE;"], [0, "&lesges;"], [0, "&gesles;"], [0, "&els;"], [0, "&egs;"], [0, "&elsdot;"], [0, "&egsdot;"], [0, "&el;"], [0, "&eg;"], [2, "&siml;"], [0, "&simg;"], [0, "&simlE;"], [0, "&simgE;"], [0, { v: "&LessLess;", n: 824, o: "&NotNestedLessLess;" }], [0, { v: "&GreaterGreater;", n: 824, o: "&NotNestedGreaterGreater;" }], [1, "&glj;"], [0, "&gla;"], [0, "&ltcc;"], [0, "&gtcc;"], [0, "&lescc;"], [0, "&gescc;"], [0, "&smt;"], [0, "&lat;"], [0, { v: "&smte;", n: 65024, o: "&smtes;" }], [0, { v: "&late;", n: 65024, o: "&lates;" }], [0, "&bumpE;"], [0, { v: "&PrecedesEqual;", n: 824, o: "&NotPrecedesEqual;" }], [0, { v: "&sce;", n: 824, o: "&NotSucceedsEqual;" }], [2, "&prE;"], [0, "&scE;"], [0, "&precneqq;"], [0, "&scnE;"], [0, "&prap;"], [0, "&scap;"], [0, "&precnapprox;"], [0, "&scnap;"], [0, "&Pr;"], [0, "&Sc;"], [0, "&subdot;"], [0, "&supdot;"], [0, "&subplus;"], [0, "&supplus;"], [0, "&submult;"], [0, "&supmult;"], [0, "&subedot;"], [0, "&supedot;"], [0, { v: "&subE;", n: 824, o: "&nsubE;" }], [0, { v: "&supE;", n: 824, o: "&nsupE;" }], [0, "&subsim;"], [0, "&supsim;"], [2, { v: "&subnE;", n: 65024, o: "&varsubsetneqq;" }], [0, { v: "&supnE;", n: 65024, o: "&varsupsetneqq;" }], [2, "&csub;"], [0, "&csup;"], [0, "&csube;"], [0, "&csupe;"], [0, "&subsup;"], [0, "&supsub;"], [0, "&subsub;"], [0, "&supsup;"], [0, "&suphsub;"], [0, "&supdsub;"], [0, "&forkv;"], [0, "&topfork;"], [0, "&mlcp;"], [8, "&Dashv;"], [1, "&Vdashl;"], [0, "&Barv;"], [0, "&vBar;"], [0, "&vBarv;"], [1, "&Vbar;"], [0, "&Not;"], [0, "&bNot;"], [0, "&rnmid;"], [0, "&cirmid;"], [0, "&midcir;"], [0, "&topcir;"], [0, "&nhpar;"], [0, "&parsim;"], [9, { v: "&parsl;", n: 8421, o: "&nparsl;" }], [44343, { n: new Map(/* @__PURE__ */ restoreDiff([[56476, "&Ascr;"], [1, "&Cscr;"], [0, "&Dscr;"], [2, "&Gscr;"], [2, "&Jscr;"], [0, "&Kscr;"], [2, "&Nscr;"], [0, "&Oscr;"], [0, "&Pscr;"], [0, "&Qscr;"], [1, "&Sscr;"], [0, "&Tscr;"], [0, "&Uscr;"], [0, "&Vscr;"], [0, "&Wscr;"], [0, "&Xscr;"], [0, "&Yscr;"], [0, "&Zscr;"], [0, "&ascr;"], [0, "&bscr;"], [0, "&cscr;"], [0, "&dscr;"], [1, "&fscr;"], [1, "&hscr;"], [0, "&iscr;"], [0, "&jscr;"], [0, "&kscr;"], [0, "&lscr;"], [0, "&mscr;"], [0, "&nscr;"], [1, "&pscr;"], [0, "&qscr;"], [0, "&rscr;"], [0, "&sscr;"], [0, "&tscr;"], [0, "&uscr;"], [0, "&vscr;"], [0, "&wscr;"], [0, "&xscr;"], [0, "&yscr;"], [0, "&zscr;"], [52, "&Afr;"], [0, "&Bfr;"], [1, "&Dfr;"], [0, "&Efr;"], [0, "&Ffr;"], [0, "&Gfr;"], [2, "&Jfr;"], [0, "&Kfr;"], [0, "&Lfr;"], [0, "&Mfr;"], [0, "&Nfr;"], [0, "&Ofr;"], [0, "&Pfr;"], [0, "&Qfr;"], [1, "&Sfr;"], [0, "&Tfr;"], [0, "&Ufr;"], [0, "&Vfr;"], [0, "&Wfr;"], [0, "&Xfr;"], [0, "&Yfr;"], [1, "&afr;"], [0, "&bfr;"], [0, "&cfr;"], [0, "&dfr;"], [0, "&efr;"], [0, "&ffr;"], [0, "&gfr;"], [0, "&hfr;"], [0, "&ifr;"], [0, "&jfr;"], [0, "&kfr;"], [0, "&lfr;"], [0, "&mfr;"], [0, "&nfr;"], [0, "&ofr;"], [0, "&pfr;"], [0, "&qfr;"], [0, "&rfr;"], [0, "&sfr;"], [0, "&tfr;"], [0, "&ufr;"], [0, "&vfr;"], [0, "&wfr;"], [0, "&xfr;"], [0, "&yfr;"], [0, "&zfr;"], [0, "&Aopf;"], [0, "&Bopf;"], [1, "&Dopf;"], [0, "&Eopf;"], [0, "&Fopf;"], [0, "&Gopf;"], [1, "&Iopf;"], [0, "&Jopf;"], [0, "&Kopf;"], [0, "&Lopf;"], [0, "&Mopf;"], [1, "&Oopf;"], [3, "&Sopf;"], [0, "&Topf;"], [0, "&Uopf;"], [0, "&Vopf;"], [0, "&Wopf;"], [0, "&Xopf;"], [0, "&Yopf;"], [1, "&aopf;"], [0, "&bopf;"], [0, "&copf;"], [0, "&dopf;"], [0, "&eopf;"], [0, "&fopf;"], [0, "&gopf;"], [0, "&hopf;"], [0, "&iopf;"], [0, "&jopf;"], [0, "&kopf;"], [0, "&lopf;"], [0, "&mopf;"], [0, "&nopf;"], [0, "&oopf;"], [0, "&popf;"], [0, "&qopf;"], [0, "&ropf;"], [0, "&sopf;"], [0, "&topf;"], [0, "&uopf;"], [0, "&vopf;"], [0, "&wopf;"], [0, "&xopf;"], [0, "&yopf;"], [0, "&zopf;"]])) }], [8906, "&fflig;"], [0, "&filig;"], [0, "&fllig;"], [0, "&ffilig;"], [0, "&ffllig;"]]));

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

// node_modules/codemirror-json-schema/node_modules/entities/lib/esm/index.js
var EntityLevel;
(function(EntityLevel2) {
  EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
  EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
})(EntityLevel || (EntityLevel = {}));
var EncodingMode;
(function(EncodingMode2) {
  EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
  EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
  EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
  EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
  EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
})(EncodingMode || (EncodingMode = {}));

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/common/utils.mjs
function _class(obj) {
  return Object.prototype.toString.call(obj);
}
function isString3(obj) {
  return _class(obj) === "[object String]";
}
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function has3(object2, key2) {
  return _hasOwnProperty.call(object2, key2);
}
function assign4(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    if (typeof source !== "object") {
      throw new TypeError(source + "must be object");
    }
    Object.keys(source).forEach(function(key2) {
      obj[key2] = source[key2];
    });
  });
  return obj;
}
function arrayReplaceAt(src, pos, newElements) {
  return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
}
function isValidEntityCode(c3) {
  if (c3 >= 55296 && c3 <= 57343) {
    return false;
  }
  if (c3 >= 64976 && c3 <= 65007) {
    return false;
  }
  if ((c3 & 65535) === 65535 || (c3 & 65535) === 65534) {
    return false;
  }
  if (c3 >= 0 && c3 <= 8) {
    return false;
  }
  if (c3 === 11) {
    return false;
  }
  if (c3 >= 14 && c3 <= 31) {
    return false;
  }
  if (c3 >= 127 && c3 <= 159) {
    return false;
  }
  if (c3 > 1114111) {
    return false;
  }
  return true;
}
function fromCodePoint3(c3) {
  if (c3 > 65535) {
    c3 -= 65536;
    const surrogate1 = 55296 + (c3 >> 10);
    const surrogate2 = 56320 + (c3 & 1023);
    return String.fromCharCode(surrogate1, surrogate2);
  }
  return String.fromCharCode(c3);
}
var UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
var ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
var UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, "gi");
var DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;
function replaceEntityPattern(match2, name2) {
  if (name2.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE.test(name2)) {
    const code2 = name2[1].toLowerCase() === "x" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
    if (isValidEntityCode(code2)) {
      return fromCodePoint3(code2);
    }
    return match2;
  }
  const decoded = decodeHTML(match2);
  if (decoded !== match2) {
    return decoded;
  }
  return match2;
}
function unescapeMd(str) {
  if (str.indexOf("\\") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_MD_RE, "$1");
}
function unescapeAll(str) {
  if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_ALL_RE, function(match2, escaped, entity2) {
    if (escaped) {
      return escaped;
    }
    return replaceEntityPattern(match2, entity2);
  });
}
var HTML_ESCAPE_TEST_RE = /[&<>"]/;
var HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
var HTML_REPLACEMENTS = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;"
};
function replaceUnsafeChar(ch) {
  return HTML_REPLACEMENTS[ch];
}
function escapeHtml(str) {
  if (HTML_ESCAPE_TEST_RE.test(str)) {
    return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
  }
  return str;
}
var REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
function escapeRE(str) {
  return str.replace(REGEXP_ESCAPE_RE, "\\$&");
}
function isSpace(code2) {
  switch (code2) {
    case 9:
    case 32:
      return true;
  }
  return false;
}
function isWhiteSpace(code2) {
  if (code2 >= 8192 && code2 <= 8202) {
    return true;
  }
  switch (code2) {
    case 9:
    // \t
    case 10:
    // \n
    case 11:
    // \v
    case 12:
    // \f
    case 13:
    // \r
    case 32:
    case 160:
    case 5760:
    case 8239:
    case 8287:
    case 12288:
      return true;
  }
  return false;
}
function isPunctChar(ch) {
  return regex_default4.test(ch) || regex_default5.test(ch);
}
function isMdAsciiPunct(ch) {
  switch (ch) {
    case 33:
    case 34:
    case 35:
    case 36:
    case 37:
    case 38:
    case 39:
    case 40:
    case 41:
    case 42:
    case 43:
    case 44:
    case 45:
    case 46:
    case 47:
    case 58:
    case 59:
    case 60:
    case 61:
    case 62:
    case 63:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 124:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
function normalizeReference(str) {
  str = str.trim().replace(/\s+/g, " ");
  if ("\u1E9E".toLowerCase() === "\u1E7E") {
    str = str.replace(/ẞ/g, "\xDF");
  }
  return str.toLowerCase().toUpperCase();
}
var lib = { mdurl: mdurl_exports, ucmicro: uc_exports };

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/helpers/index.mjs
var helpers_exports = {};
__export(helpers_exports, {
  parseLinkDestination: () => parseLinkDestination,
  parseLinkLabel: () => parseLinkLabel,
  parseLinkTitle: () => parseLinkTitle
});

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/helpers/parse_link_label.mjs
function parseLinkLabel(state, start, disableNested) {
  let level, found2, marker, prevPos;
  const max3 = state.posMax;
  const oldPos = state.pos;
  state.pos = start + 1;
  level = 1;
  while (state.pos < max3) {
    marker = state.src.charCodeAt(state.pos);
    if (marker === 93) {
      level--;
      if (level === 0) {
        found2 = true;
        break;
      }
    }
    prevPos = state.pos;
    state.md.inline.skipToken(state);
    if (marker === 91) {
      if (prevPos === state.pos - 1) {
        level++;
      } else if (disableNested) {
        state.pos = oldPos;
        return -1;
      }
    }
  }
  let labelEnd = -1;
  if (found2) {
    labelEnd = state.pos;
  }
  state.pos = oldPos;
  return labelEnd;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/helpers/parse_link_destination.mjs
function parseLinkDestination(str, start, max3) {
  let code2;
  let pos = start;
  const result2 = {
    ok: false,
    pos: 0,
    str: ""
  };
  if (str.charCodeAt(pos) === 60) {
    pos++;
    while (pos < max3) {
      code2 = str.charCodeAt(pos);
      if (code2 === 10) {
        return result2;
      }
      if (code2 === 60) {
        return result2;
      }
      if (code2 === 62) {
        result2.pos = pos + 1;
        result2.str = unescapeAll(str.slice(start + 1, pos));
        result2.ok = true;
        return result2;
      }
      if (code2 === 92 && pos + 1 < max3) {
        pos += 2;
        continue;
      }
      pos++;
    }
    return result2;
  }
  let level = 0;
  while (pos < max3) {
    code2 = str.charCodeAt(pos);
    if (code2 === 32) {
      break;
    }
    if (code2 < 32 || code2 === 127) {
      break;
    }
    if (code2 === 92 && pos + 1 < max3) {
      if (str.charCodeAt(pos + 1) === 32) {
        break;
      }
      pos += 2;
      continue;
    }
    if (code2 === 40) {
      level++;
      if (level > 32) {
        return result2;
      }
    }
    if (code2 === 41) {
      if (level === 0) {
        break;
      }
      level--;
    }
    pos++;
  }
  if (start === pos) {
    return result2;
  }
  if (level !== 0) {
    return result2;
  }
  result2.str = unescapeAll(str.slice(start, pos));
  result2.pos = pos;
  result2.ok = true;
  return result2;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/helpers/parse_link_title.mjs
function parseLinkTitle(str, start, max3, prev_state) {
  let code2;
  let pos = start;
  const state = {
    // if `true`, this is a valid link title
    ok: false,
    // if `true`, this link can be continued on the next line
    can_continue: false,
    // if `ok`, it's the position of the first character after the closing marker
    pos: 0,
    // if `ok`, it's the unescaped title
    str: "",
    // expected closing marker character code
    marker: 0
  };
  if (prev_state) {
    state.str = prev_state.str;
    state.marker = prev_state.marker;
  } else {
    if (pos >= max3) {
      return state;
    }
    let marker = str.charCodeAt(pos);
    if (marker !== 34 && marker !== 39 && marker !== 40) {
      return state;
    }
    start++;
    pos++;
    if (marker === 40) {
      marker = 41;
    }
    state.marker = marker;
  }
  while (pos < max3) {
    code2 = str.charCodeAt(pos);
    if (code2 === state.marker) {
      state.pos = pos + 1;
      state.str += unescapeAll(str.slice(start, pos));
      state.ok = true;
      return state;
    } else if (code2 === 40 && state.marker === 41) {
      return state;
    } else if (code2 === 92 && pos + 1 < max3) {
      pos++;
    }
    pos++;
  }
  state.can_continue = true;
  state.str += unescapeAll(str.slice(start, pos));
  return state;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/renderer.mjs
var default_rules = {};
default_rules.code_inline = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  return "<code" + slf.renderAttrs(token) + ">" + escapeHtml(token.content) + "</code>";
};
default_rules.code_block = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  return "<pre" + slf.renderAttrs(token) + "><code>" + escapeHtml(tokens[idx].content) + "</code></pre>\n";
};
default_rules.fence = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  const info = token.info ? unescapeAll(token.info).trim() : "";
  let langName = "";
  let langAttrs = "";
  if (info) {
    const arr = info.split(/(\s+)/g);
    langName = arr[0];
    langAttrs = arr.slice(2).join("");
  }
  let highlighted;
  if (options2.highlight) {
    highlighted = options2.highlight(token.content, langName, langAttrs) || escapeHtml(token.content);
  } else {
    highlighted = escapeHtml(token.content);
  }
  if (highlighted.indexOf("<pre") === 0) {
    return highlighted + "\n";
  }
  if (info) {
    const i3 = token.attrIndex("class");
    const tmpAttrs = token.attrs ? token.attrs.slice() : [];
    if (i3 < 0) {
      tmpAttrs.push(["class", options2.langPrefix + langName]);
    } else {
      tmpAttrs[i3] = tmpAttrs[i3].slice();
      tmpAttrs[i3][1] += " " + options2.langPrefix + langName;
    }
    const tmpToken = {
      attrs: tmpAttrs
    };
    return `<pre><code${slf.renderAttrs(tmpToken)}>${highlighted}</code></pre>
`;
  }
  return `<pre><code${slf.renderAttrs(token)}>${highlighted}</code></pre>
`;
};
default_rules.image = function(tokens, idx, options2, env, slf) {
  const token = tokens[idx];
  token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText(token.children, options2, env);
  return slf.renderToken(tokens, idx, options2);
};
default_rules.hardbreak = function(tokens, idx, options2) {
  return options2.xhtmlOut ? "<br />\n" : "<br>\n";
};
default_rules.softbreak = function(tokens, idx, options2) {
  return options2.breaks ? options2.xhtmlOut ? "<br />\n" : "<br>\n" : "\n";
};
default_rules.text = function(tokens, idx) {
  return escapeHtml(tokens[idx].content);
};
default_rules.html_block = function(tokens, idx) {
  return tokens[idx].content;
};
default_rules.html_inline = function(tokens, idx) {
  return tokens[idx].content;
};
function Renderer2() {
  this.rules = assign4({}, default_rules);
}
Renderer2.prototype.renderAttrs = function renderAttrs(token) {
  let i3, l3, result2;
  if (!token.attrs) {
    return "";
  }
  result2 = "";
  for (i3 = 0, l3 = token.attrs.length; i3 < l3; i3++) {
    result2 += " " + escapeHtml(token.attrs[i3][0]) + '="' + escapeHtml(token.attrs[i3][1]) + '"';
  }
  return result2;
};
Renderer2.prototype.renderToken = function renderToken(tokens, idx, options2) {
  const token = tokens[idx];
  let result2 = "";
  if (token.hidden) {
    return "";
  }
  if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) {
    result2 += "\n";
  }
  result2 += (token.nesting === -1 ? "</" : "<") + token.tag;
  result2 += this.renderAttrs(token);
  if (token.nesting === 0 && options2.xhtmlOut) {
    result2 += " /";
  }
  let needLf = false;
  if (token.block) {
    needLf = true;
    if (token.nesting === 1) {
      if (idx + 1 < tokens.length) {
        const nextToken = tokens[idx + 1];
        if (nextToken.type === "inline" || nextToken.hidden) {
          needLf = false;
        } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
          needLf = false;
        }
      }
    }
  }
  result2 += needLf ? ">\n" : ">";
  return result2;
};
Renderer2.prototype.renderInline = function(tokens, options2, env) {
  let result2 = "";
  const rules = this.rules;
  for (let i3 = 0, len = tokens.length; i3 < len; i3++) {
    const type = tokens[i3].type;
    if (typeof rules[type] !== "undefined") {
      result2 += rules[type](tokens, i3, options2, env, this);
    } else {
      result2 += this.renderToken(tokens, i3, options2);
    }
  }
  return result2;
};
Renderer2.prototype.renderInlineAsText = function(tokens, options2, env) {
  let result2 = "";
  for (let i3 = 0, len = tokens.length; i3 < len; i3++) {
    switch (tokens[i3].type) {
      case "text":
        result2 += tokens[i3].content;
        break;
      case "image":
        result2 += this.renderInlineAsText(tokens[i3].children, options2, env);
        break;
      case "html_inline":
      case "html_block":
        result2 += tokens[i3].content;
        break;
      case "softbreak":
      case "hardbreak":
        result2 += "\n";
        break;
      default:
    }
  }
  return result2;
};
Renderer2.prototype.render = function(tokens, options2, env) {
  let result2 = "";
  const rules = this.rules;
  for (let i3 = 0, len = tokens.length; i3 < len; i3++) {
    const type = tokens[i3].type;
    if (type === "inline") {
      result2 += this.renderInline(tokens[i3].children, options2, env);
    } else if (typeof rules[type] !== "undefined") {
      result2 += rules[type](tokens, i3, options2, env, this);
    } else {
      result2 += this.renderToken(tokens, i3, options2, env);
    }
  }
  return result2;
};
var renderer_default = Renderer2;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/ruler.mjs
function Ruler() {
  this.__rules__ = [];
  this.__cache__ = null;
}
Ruler.prototype.__find__ = function(name2) {
  for (let i3 = 0; i3 < this.__rules__.length; i3++) {
    if (this.__rules__[i3].name === name2) {
      return i3;
    }
  }
  return -1;
};
Ruler.prototype.__compile__ = function() {
  const self2 = this;
  const chains = [""];
  self2.__rules__.forEach(function(rule) {
    if (!rule.enabled) {
      return;
    }
    rule.alt.forEach(function(altName) {
      if (chains.indexOf(altName) < 0) {
        chains.push(altName);
      }
    });
  });
  self2.__cache__ = {};
  chains.forEach(function(chain3) {
    self2.__cache__[chain3] = [];
    self2.__rules__.forEach(function(rule) {
      if (!rule.enabled) {
        return;
      }
      if (chain3 && rule.alt.indexOf(chain3) < 0) {
        return;
      }
      self2.__cache__[chain3].push(rule.fn);
    });
  });
};
Ruler.prototype.at = function(name2, fn, options2) {
  const index2 = this.__find__(name2);
  const opt = options2 || {};
  if (index2 === -1) {
    throw new Error("Parser rule not found: " + name2);
  }
  this.__rules__[index2].fn = fn;
  this.__rules__[index2].alt = opt.alt || [];
  this.__cache__ = null;
};
Ruler.prototype.before = function(beforeName, ruleName, fn, options2) {
  const index2 = this.__find__(beforeName);
  const opt = options2 || {};
  if (index2 === -1) {
    throw new Error("Parser rule not found: " + beforeName);
  }
  this.__rules__.splice(index2, 0, {
    name: ruleName,
    enabled: true,
    fn,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.after = function(afterName, ruleName, fn, options2) {
  const index2 = this.__find__(afterName);
  const opt = options2 || {};
  if (index2 === -1) {
    throw new Error("Parser rule not found: " + afterName);
  }
  this.__rules__.splice(index2 + 1, 0, {
    name: ruleName,
    enabled: true,
    fn,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.push = function(ruleName, fn, options2) {
  const opt = options2 || {};
  this.__rules__.push({
    name: ruleName,
    enabled: true,
    fn,
    alt: opt.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.enable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result2 = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = true;
    result2.push(name2);
  }, this);
  this.__cache__ = null;
  return result2;
};
Ruler.prototype.enableOnly = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  this.__rules__.forEach(function(rule) {
    rule.enabled = false;
  });
  this.enable(list2, ignoreInvalid);
};
Ruler.prototype.disable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result2 = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = false;
    result2.push(name2);
  }, this);
  this.__cache__ = null;
  return result2;
};
Ruler.prototype.getRules = function(chainName) {
  if (this.__cache__ === null) {
    this.__compile__();
  }
  return this.__cache__[chainName] || [];
};
var ruler_default = Ruler;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/token.mjs
function Token(type, tag, nesting) {
  this.type = type;
  this.tag = tag;
  this.attrs = null;
  this.map = null;
  this.nesting = nesting;
  this.level = 0;
  this.children = null;
  this.content = "";
  this.markup = "";
  this.info = "";
  this.meta = null;
  this.block = false;
  this.hidden = false;
}
Token.prototype.attrIndex = function attrIndex(name2) {
  if (!this.attrs) {
    return -1;
  }
  const attrs2 = this.attrs;
  for (let i3 = 0, len = attrs2.length; i3 < len; i3++) {
    if (attrs2[i3][0] === name2) {
      return i3;
    }
  }
  return -1;
};
Token.prototype.attrPush = function attrPush(attrData) {
  if (this.attrs) {
    this.attrs.push(attrData);
  } else {
    this.attrs = [attrData];
  }
};
Token.prototype.attrSet = function attrSet(name2, value2) {
  const idx = this.attrIndex(name2);
  const attrData = [name2, value2];
  if (idx < 0) {
    this.attrPush(attrData);
  } else {
    this.attrs[idx] = attrData;
  }
};
Token.prototype.attrGet = function attrGet(name2) {
  const idx = this.attrIndex(name2);
  let value2 = null;
  if (idx >= 0) {
    value2 = this.attrs[idx][1];
  }
  return value2;
};
Token.prototype.attrJoin = function attrJoin(name2, value2) {
  const idx = this.attrIndex(name2);
  if (idx < 0) {
    this.attrPush([name2, value2]);
  } else {
    this.attrs[idx][1] = this.attrs[idx][1] + " " + value2;
  }
};
var token_default = Token;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/state_core.mjs
function StateCore(src, md2, env) {
  this.src = src;
  this.env = env;
  this.tokens = [];
  this.inlineMode = false;
  this.md = md2;
}
StateCore.prototype.Token = token_default;
var state_core_default = StateCore;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/normalize.mjs
var NEWLINES_RE = /\r\n?|\n/g;
var NULL_RE = /\0/g;
function normalize(state) {
  let str;
  str = state.src.replace(NEWLINES_RE, "\n");
  str = str.replace(NULL_RE, "\uFFFD");
  state.src = str;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/block.mjs
function block2(state) {
  let token;
  if (state.inlineMode) {
    token = new state.Token("inline", "", 0);
    token.content = state.src;
    token.map = [0, 1];
    token.children = [];
    state.tokens.push(token);
  } else {
    state.md.block.parse(state.src, state.md, state.env, state.tokens);
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/inline.mjs
function inline2(state) {
  const tokens = state.tokens;
  for (let i3 = 0, l3 = tokens.length; i3 < l3; i3++) {
    const tok = tokens[i3];
    if (tok.type === "inline") {
      state.md.inline.parse(tok.content, state.md, state.env, tok.children);
    }
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/linkify.mjs
function isLinkOpen(str) {
  return /^<a[>\s]/i.test(str);
}
function isLinkClose(str) {
  return /^<\/a\s*>/i.test(str);
}
function linkify(state) {
  const blockTokens = state.tokens;
  if (!state.md.options.linkify) {
    return;
  }
  for (let j = 0, l3 = blockTokens.length; j < l3; j++) {
    if (blockTokens[j].type !== "inline" || !state.md.linkify.pretest(blockTokens[j].content)) {
      continue;
    }
    let tokens = blockTokens[j].children;
    let htmlLinkLevel = 0;
    for (let i3 = tokens.length - 1; i3 >= 0; i3--) {
      const currentToken = tokens[i3];
      if (currentToken.type === "link_close") {
        i3--;
        while (tokens[i3].level !== currentToken.level && tokens[i3].type !== "link_open") {
          i3--;
        }
        continue;
      }
      if (currentToken.type === "html_inline") {
        if (isLinkOpen(currentToken.content) && htmlLinkLevel > 0) {
          htmlLinkLevel--;
        }
        if (isLinkClose(currentToken.content)) {
          htmlLinkLevel++;
        }
      }
      if (htmlLinkLevel > 0) {
        continue;
      }
      if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
        const text3 = currentToken.content;
        let links = state.md.linkify.match(text3);
        const nodes2 = [];
        let level = currentToken.level;
        let lastPos = 0;
        if (links.length > 0 && links[0].index === 0 && i3 > 0 && tokens[i3 - 1].type === "text_special") {
          links = links.slice(1);
        }
        for (let ln = 0; ln < links.length; ln++) {
          const url2 = links[ln].url;
          const fullUrl = state.md.normalizeLink(url2);
          if (!state.md.validateLink(fullUrl)) {
            continue;
          }
          let urlText = links[ln].text;
          if (!links[ln].schema) {
            urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
          } else if (links[ln].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
            urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
          } else {
            urlText = state.md.normalizeLinkText(urlText);
          }
          const pos = links[ln].index;
          if (pos > lastPos) {
            const token = new state.Token("text", "", 0);
            token.content = text3.slice(lastPos, pos);
            token.level = level;
            nodes2.push(token);
          }
          const token_o = new state.Token("link_open", "a", 1);
          token_o.attrs = [["href", fullUrl]];
          token_o.level = level++;
          token_o.markup = "linkify";
          token_o.info = "auto";
          nodes2.push(token_o);
          const token_t = new state.Token("text", "", 0);
          token_t.content = urlText;
          token_t.level = level;
          nodes2.push(token_t);
          const token_c = new state.Token("link_close", "a", -1);
          token_c.level = --level;
          token_c.markup = "linkify";
          token_c.info = "auto";
          nodes2.push(token_c);
          lastPos = links[ln].lastIndex;
        }
        if (lastPos < text3.length) {
          const token = new state.Token("text", "", 0);
          token.content = text3.slice(lastPos);
          token.level = level;
          nodes2.push(token);
        }
        blockTokens[j].children = tokens = arrayReplaceAt(tokens, i3, nodes2);
      }
    }
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/replacements.mjs
var RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
var SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
var SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
var SCOPED_ABBR = {
  c: "\xA9",
  r: "\xAE",
  tm: "\u2122"
};
function replaceFn(match2, name2) {
  return SCOPED_ABBR[name2.toLowerCase()];
}
function replace_scoped(inlineTokens) {
  let inside_autolink = 0;
  for (let i3 = inlineTokens.length - 1; i3 >= 0; i3--) {
    const token = inlineTokens[i3];
    if (token.type === "text" && !inside_autolink) {
      token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
    }
    if (token.type === "link_open" && token.info === "auto") {
      inside_autolink--;
    }
    if (token.type === "link_close" && token.info === "auto") {
      inside_autolink++;
    }
  }
}
function replace_rare(inlineTokens) {
  let inside_autolink = 0;
  for (let i3 = inlineTokens.length - 1; i3 >= 0; i3--) {
    const token = inlineTokens[i3];
    if (token.type === "text" && !inside_autolink) {
      if (RARE_RE.test(token.content)) {
        token.content = token.content.replace(/\+-/g, "\xB1").replace(/\.{2,}/g, "\u2026").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1\u2014").replace(/(^|\s)--(?=\s|$)/mg, "$1\u2013").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1\u2013");
      }
    }
    if (token.type === "link_open" && token.info === "auto") {
      inside_autolink--;
    }
    if (token.type === "link_close" && token.info === "auto") {
      inside_autolink++;
    }
  }
}
function replace3(state) {
  let blkIdx;
  if (!state.md.options.typographer) {
    return;
  }
  for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline") {
      continue;
    }
    if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
      replace_scoped(state.tokens[blkIdx].children);
    }
    if (RARE_RE.test(state.tokens[blkIdx].content)) {
      replace_rare(state.tokens[blkIdx].children);
    }
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/smartquotes.mjs
var QUOTE_TEST_RE = /['"]/;
var QUOTE_RE = /['"]/g;
var APOSTROPHE = "\u2019";
function replaceAt(str, index2, ch) {
  return str.slice(0, index2) + ch + str.slice(index2 + 1);
}
function process_inlines(tokens, state) {
  let j;
  const stack = [];
  for (let i3 = 0; i3 < tokens.length; i3++) {
    const token = tokens[i3];
    const thisLevel = tokens[i3].level;
    for (j = stack.length - 1; j >= 0; j--) {
      if (stack[j].level <= thisLevel) {
        break;
      }
    }
    stack.length = j + 1;
    if (token.type !== "text") {
      continue;
    }
    let text3 = token.content;
    let pos = 0;
    let max3 = text3.length;
    OUTER:
      while (pos < max3) {
        QUOTE_RE.lastIndex = pos;
        const t3 = QUOTE_RE.exec(text3);
        if (!t3) {
          break;
        }
        let canOpen = true;
        let canClose = true;
        pos = t3.index + 1;
        const isSingle = t3[0] === "'";
        let lastChar = 32;
        if (t3.index - 1 >= 0) {
          lastChar = text3.charCodeAt(t3.index - 1);
        } else {
          for (j = i3 - 1; j >= 0; j--) {
            if (tokens[j].type === "softbreak" || tokens[j].type === "hardbreak") break;
            if (!tokens[j].content) continue;
            lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1);
            break;
          }
        }
        let nextChar2 = 32;
        if (pos < max3) {
          nextChar2 = text3.charCodeAt(pos);
        } else {
          for (j = i3 + 1; j < tokens.length; j++) {
            if (tokens[j].type === "softbreak" || tokens[j].type === "hardbreak") break;
            if (!tokens[j].content) continue;
            nextChar2 = tokens[j].content.charCodeAt(0);
            break;
          }
        }
        const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
        const isNextPunctChar = isMdAsciiPunct(nextChar2) || isPunctChar(String.fromCharCode(nextChar2));
        const isLastWhiteSpace = isWhiteSpace(lastChar);
        const isNextWhiteSpace = isWhiteSpace(nextChar2);
        if (isNextWhiteSpace) {
          canOpen = false;
        } else if (isNextPunctChar) {
          if (!(isLastWhiteSpace || isLastPunctChar)) {
            canOpen = false;
          }
        }
        if (isLastWhiteSpace) {
          canClose = false;
        } else if (isLastPunctChar) {
          if (!(isNextWhiteSpace || isNextPunctChar)) {
            canClose = false;
          }
        }
        if (nextChar2 === 34 && t3[0] === '"') {
          if (lastChar >= 48 && lastChar <= 57) {
            canClose = canOpen = false;
          }
        }
        if (canOpen && canClose) {
          canOpen = isLastPunctChar;
          canClose = isNextPunctChar;
        }
        if (!canOpen && !canClose) {
          if (isSingle) {
            token.content = replaceAt(token.content, t3.index, APOSTROPHE);
          }
          continue;
        }
        if (canClose) {
          for (j = stack.length - 1; j >= 0; j--) {
            let item = stack[j];
            if (stack[j].level < thisLevel) {
              break;
            }
            if (item.single === isSingle && stack[j].level === thisLevel) {
              item = stack[j];
              let openQuote;
              let closeQuote;
              if (isSingle) {
                openQuote = state.md.options.quotes[2];
                closeQuote = state.md.options.quotes[3];
              } else {
                openQuote = state.md.options.quotes[0];
                closeQuote = state.md.options.quotes[1];
              }
              token.content = replaceAt(token.content, t3.index, closeQuote);
              tokens[item.token].content = replaceAt(
                tokens[item.token].content,
                item.pos,
                openQuote
              );
              pos += closeQuote.length - 1;
              if (item.token === i3) {
                pos += openQuote.length - 1;
              }
              text3 = token.content;
              max3 = text3.length;
              stack.length = j;
              continue OUTER;
            }
          }
        }
        if (canOpen) {
          stack.push({
            token: i3,
            pos: t3.index,
            single: isSingle,
            level: thisLevel
          });
        } else if (canClose && isSingle) {
          token.content = replaceAt(token.content, t3.index, APOSTROPHE);
        }
      }
  }
}
function smartquotes(state) {
  if (!state.md.options.typographer) {
    return;
  }
  for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
      continue;
    }
    process_inlines(state.tokens[blkIdx].children, state);
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_core/text_join.mjs
function text_join(state) {
  let curr, last3;
  const blockTokens = state.tokens;
  const l3 = blockTokens.length;
  for (let j = 0; j < l3; j++) {
    if (blockTokens[j].type !== "inline") continue;
    const tokens = blockTokens[j].children;
    const max3 = tokens.length;
    for (curr = 0; curr < max3; curr++) {
      if (tokens[curr].type === "text_special") {
        tokens[curr].type = "text";
      }
    }
    for (curr = last3 = 0; curr < max3; curr++) {
      if (tokens[curr].type === "text" && curr + 1 < max3 && tokens[curr + 1].type === "text") {
        tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
      } else {
        if (curr !== last3) {
          tokens[last3] = tokens[curr];
        }
        last3++;
      }
    }
    if (curr !== last3) {
      tokens.length = last3;
    }
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/parser_core.mjs
var _rules = [
  ["normalize", normalize],
  ["block", block2],
  ["inline", inline2],
  ["linkify", linkify],
  ["replacements", replace3],
  ["smartquotes", smartquotes],
  // `text_join` finds `text_special` tokens (for escape sequences)
  // and joins them with the rest of the text
  ["text_join", text_join]
];
function Core() {
  this.ruler = new ruler_default();
  for (let i3 = 0; i3 < _rules.length; i3++) {
    this.ruler.push(_rules[i3][0], _rules[i3][1]);
  }
}
Core.prototype.process = function(state) {
  const rules = this.ruler.getRules("");
  for (let i3 = 0, l3 = rules.length; i3 < l3; i3++) {
    rules[i3](state);
  }
};
Core.prototype.State = state_core_default;
var parser_core_default = Core;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/state_block.mjs
function StateBlock(src, md2, env, tokens) {
  this.src = src;
  this.md = md2;
  this.env = env;
  this.tokens = tokens;
  this.bMarks = [];
  this.eMarks = [];
  this.tShift = [];
  this.sCount = [];
  this.bsCount = [];
  this.blkIndent = 0;
  this.line = 0;
  this.lineMax = 0;
  this.tight = false;
  this.ddIndent = -1;
  this.listIndent = -1;
  this.parentType = "root";
  this.level = 0;
  const s3 = this.src;
  for (let start = 0, pos = 0, indent = 0, offset = 0, len = s3.length, indent_found = false; pos < len; pos++) {
    const ch = s3.charCodeAt(pos);
    if (!indent_found) {
      if (isSpace(ch)) {
        indent++;
        if (ch === 9) {
          offset += 4 - offset % 4;
        } else {
          offset++;
        }
        continue;
      } else {
        indent_found = true;
      }
    }
    if (ch === 10 || pos === len - 1) {
      if (ch !== 10) {
        pos++;
      }
      this.bMarks.push(start);
      this.eMarks.push(pos);
      this.tShift.push(indent);
      this.sCount.push(offset);
      this.bsCount.push(0);
      indent_found = false;
      indent = 0;
      offset = 0;
      start = pos + 1;
    }
  }
  this.bMarks.push(s3.length);
  this.eMarks.push(s3.length);
  this.tShift.push(0);
  this.sCount.push(0);
  this.bsCount.push(0);
  this.lineMax = this.bMarks.length - 1;
}
StateBlock.prototype.push = function(type, tag, nesting) {
  const token = new token_default(type, tag, nesting);
  token.block = true;
  if (nesting < 0) this.level--;
  token.level = this.level;
  if (nesting > 0) this.level++;
  this.tokens.push(token);
  return token;
};
StateBlock.prototype.isEmpty = function isEmpty3(line) {
  return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];
};
StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from2) {
  for (let max3 = this.lineMax; from2 < max3; from2++) {
    if (this.bMarks[from2] + this.tShift[from2] < this.eMarks[from2]) {
      break;
    }
  }
  return from2;
};
StateBlock.prototype.skipSpaces = function skipSpaces(pos) {
  for (let max3 = this.src.length; pos < max3; pos++) {
    const ch = this.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      break;
    }
  }
  return pos;
};
StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min3) {
  if (pos <= min3) {
    return pos;
  }
  while (pos > min3) {
    if (!isSpace(this.src.charCodeAt(--pos))) {
      return pos + 1;
    }
  }
  return pos;
};
StateBlock.prototype.skipChars = function skipChars(pos, code2) {
  for (let max3 = this.src.length; pos < max3; pos++) {
    if (this.src.charCodeAt(pos) !== code2) {
      break;
    }
  }
  return pos;
};
StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code2, min3) {
  if (pos <= min3) {
    return pos;
  }
  while (pos > min3) {
    if (code2 !== this.src.charCodeAt(--pos)) {
      return pos + 1;
    }
  }
  return pos;
};
StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) {
  if (begin >= end) {
    return "";
  }
  const queue2 = new Array(end - begin);
  for (let i3 = 0, line = begin; line < end; line++, i3++) {
    let lineIndent = 0;
    const lineStart = this.bMarks[line];
    let first2 = lineStart;
    let last3;
    if (line + 1 < end || keepLastLF) {
      last3 = this.eMarks[line] + 1;
    } else {
      last3 = this.eMarks[line];
    }
    while (first2 < last3 && lineIndent < indent) {
      const ch = this.src.charCodeAt(first2);
      if (isSpace(ch)) {
        if (ch === 9) {
          lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4;
        } else {
          lineIndent++;
        }
      } else if (first2 - lineStart < this.tShift[line]) {
        lineIndent++;
      } else {
        break;
      }
      first2++;
    }
    if (lineIndent > indent) {
      queue2[i3] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first2, last3);
    } else {
      queue2[i3] = this.src.slice(first2, last3);
    }
  }
  return queue2.join("");
};
StateBlock.prototype.Token = token_default;
var state_block_default = StateBlock;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/table.mjs
var MAX_AUTOCOMPLETED_CELLS = 65536;
function getLine(state, line) {
  const pos = state.bMarks[line] + state.tShift[line];
  const max3 = state.eMarks[line];
  return state.src.slice(pos, max3);
}
function escapedSplit(str) {
  const result2 = [];
  const max3 = str.length;
  let pos = 0;
  let ch = str.charCodeAt(pos);
  let isEscaped2 = false;
  let lastPos = 0;
  let current = "";
  while (pos < max3) {
    if (ch === 124) {
      if (!isEscaped2) {
        result2.push(current + str.substring(lastPos, pos));
        current = "";
        lastPos = pos + 1;
      } else {
        current += str.substring(lastPos, pos - 1);
        lastPos = pos;
      }
    }
    isEscaped2 = ch === 92;
    pos++;
    ch = str.charCodeAt(pos);
  }
  result2.push(current + str.substring(lastPos));
  return result2;
}
function table(state, startLine, endLine, silent) {
  if (startLine + 2 > endLine) {
    return false;
  }
  let nextLine = startLine + 1;
  if (state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos = state.bMarks[nextLine] + state.tShift[nextLine];
  if (pos >= state.eMarks[nextLine]) {
    return false;
  }
  const firstCh = state.src.charCodeAt(pos++);
  if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
    return false;
  }
  if (pos >= state.eMarks[nextLine]) {
    return false;
  }
  const secondCh = state.src.charCodeAt(pos++);
  if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace(secondCh)) {
    return false;
  }
  if (firstCh === 45 && isSpace(secondCh)) {
    return false;
  }
  while (pos < state.eMarks[nextLine]) {
    const ch = state.src.charCodeAt(pos);
    if (ch !== 124 && ch !== 45 && ch !== 58 && !isSpace(ch)) {
      return false;
    }
    pos++;
  }
  let lineText = getLine(state, startLine + 1);
  let columns2 = lineText.split("|");
  const aligns = [];
  for (let i3 = 0; i3 < columns2.length; i3++) {
    const t3 = columns2[i3].trim();
    if (!t3) {
      if (i3 === 0 || i3 === columns2.length - 1) {
        continue;
      } else {
        return false;
      }
    }
    if (!/^:?-+:?$/.test(t3)) {
      return false;
    }
    if (t3.charCodeAt(t3.length - 1) === 58) {
      aligns.push(t3.charCodeAt(0) === 58 ? "center" : "right");
    } else if (t3.charCodeAt(0) === 58) {
      aligns.push("left");
    } else {
      aligns.push("");
    }
  }
  lineText = getLine(state, startLine).trim();
  if (lineText.indexOf("|") === -1) {
    return false;
  }
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  columns2 = escapedSplit(lineText);
  if (columns2.length && columns2[0] === "") columns2.shift();
  if (columns2.length && columns2[columns2.length - 1] === "") columns2.pop();
  const columnCount = columns2.length;
  if (columnCount === 0 || columnCount !== aligns.length) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldParentType = state.parentType;
  state.parentType = "table";
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const token_to = state.push("table_open", "table", 1);
  const tableLines = [startLine, 0];
  token_to.map = tableLines;
  const token_tho = state.push("thead_open", "thead", 1);
  token_tho.map = [startLine, startLine + 1];
  const token_htro = state.push("tr_open", "tr", 1);
  token_htro.map = [startLine, startLine + 1];
  for (let i3 = 0; i3 < columns2.length; i3++) {
    const token_ho = state.push("th_open", "th", 1);
    if (aligns[i3]) {
      token_ho.attrs = [["style", "text-align:" + aligns[i3]]];
    }
    const token_il = state.push("inline", "", 0);
    token_il.content = columns2[i3].trim();
    token_il.children = [];
    state.push("th_close", "th", -1);
  }
  state.push("tr_close", "tr", -1);
  state.push("thead_close", "thead", -1);
  let tbodyLines;
  let autocompletedCells = 0;
  for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    let terminate = false;
    for (let i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
      if (terminatorRules[i3](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
    lineText = getLine(state, nextLine).trim();
    if (!lineText) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    columns2 = escapedSplit(lineText);
    if (columns2.length && columns2[0] === "") columns2.shift();
    if (columns2.length && columns2[columns2.length - 1] === "") columns2.pop();
    autocompletedCells += columnCount - columns2.length;
    if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) {
      break;
    }
    if (nextLine === startLine + 2) {
      const token_tbo = state.push("tbody_open", "tbody", 1);
      token_tbo.map = tbodyLines = [startLine + 2, 0];
    }
    const token_tro = state.push("tr_open", "tr", 1);
    token_tro.map = [nextLine, nextLine + 1];
    for (let i3 = 0; i3 < columnCount; i3++) {
      const token_tdo = state.push("td_open", "td", 1);
      if (aligns[i3]) {
        token_tdo.attrs = [["style", "text-align:" + aligns[i3]]];
      }
      const token_il = state.push("inline", "", 0);
      token_il.content = columns2[i3] ? columns2[i3].trim() : "";
      token_il.children = [];
      state.push("td_close", "td", -1);
    }
    state.push("tr_close", "tr", -1);
  }
  if (tbodyLines) {
    state.push("tbody_close", "tbody", -1);
    tbodyLines[1] = nextLine;
  }
  state.push("table_close", "table", -1);
  tableLines[1] = nextLine;
  state.parentType = oldParentType;
  state.line = nextLine;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/code.mjs
function code(state, startLine, endLine) {
  if (state.sCount[startLine] - state.blkIndent < 4) {
    return false;
  }
  let nextLine = startLine + 1;
  let last3 = nextLine;
  while (nextLine < endLine) {
    if (state.isEmpty(nextLine)) {
      nextLine++;
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      nextLine++;
      last3 = nextLine;
      continue;
    }
    break;
  }
  state.line = last3;
  const token = state.push("code_block", "code", 0);
  token.content = state.getLines(startLine, last3, 4 + state.blkIndent, false) + "\n";
  token.map = [startLine, state.line];
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/fence.mjs
function fence(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max3 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (pos + 3 > max3) {
    return false;
  }
  const marker = state.src.charCodeAt(pos);
  if (marker !== 126 && marker !== 96) {
    return false;
  }
  let mem = pos;
  pos = state.skipChars(pos, marker);
  let len = pos - mem;
  if (len < 3) {
    return false;
  }
  const markup = state.src.slice(mem, pos);
  const params = state.src.slice(pos, max3);
  if (marker === 96) {
    if (params.indexOf(String.fromCharCode(marker)) >= 0) {
      return false;
    }
  }
  if (silent) {
    return true;
  }
  let nextLine = startLine;
  let haveEndMarker = false;
  for (; ; ) {
    nextLine++;
    if (nextLine >= endLine) {
      break;
    }
    pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
    max3 = state.eMarks[nextLine];
    if (pos < max3 && state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.src.charCodeAt(pos) !== marker) {
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      continue;
    }
    pos = state.skipChars(pos, marker);
    if (pos - mem < len) {
      continue;
    }
    pos = state.skipSpaces(pos);
    if (pos < max3) {
      continue;
    }
    haveEndMarker = true;
    break;
  }
  len = state.sCount[startLine];
  state.line = nextLine + (haveEndMarker ? 1 : 0);
  const token = state.push("fence", "code", 0);
  token.info = params;
  token.content = state.getLines(startLine + 1, nextLine, len, true);
  token.markup = markup;
  token.map = [startLine, state.line];
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/blockquote.mjs
function blockquote(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max3 = state.eMarks[startLine];
  const oldLineMax = state.lineMax;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 62) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldBMarks = [];
  const oldBSCount = [];
  const oldSCount = [];
  const oldTShift = [];
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const oldParentType = state.parentType;
  state.parentType = "blockquote";
  let lastLineEmpty = false;
  let nextLine;
  for (nextLine = startLine; nextLine < endLine; nextLine++) {
    const isOutdented = state.sCount[nextLine] < state.blkIndent;
    pos = state.bMarks[nextLine] + state.tShift[nextLine];
    max3 = state.eMarks[nextLine];
    if (pos >= max3) {
      break;
    }
    if (state.src.charCodeAt(pos++) === 62 && !isOutdented) {
      let initial2 = state.sCount[nextLine] + 1;
      let spaceAfterMarker;
      let adjustTab;
      if (state.src.charCodeAt(pos) === 32) {
        pos++;
        initial2++;
        adjustTab = false;
        spaceAfterMarker = true;
      } else if (state.src.charCodeAt(pos) === 9) {
        spaceAfterMarker = true;
        if ((state.bsCount[nextLine] + initial2) % 4 === 3) {
          pos++;
          initial2++;
          adjustTab = false;
        } else {
          adjustTab = true;
        }
      } else {
        spaceAfterMarker = false;
      }
      let offset = initial2;
      oldBMarks.push(state.bMarks[nextLine]);
      state.bMarks[nextLine] = pos;
      while (pos < max3) {
        const ch = state.src.charCodeAt(pos);
        if (isSpace(ch)) {
          if (ch === 9) {
            offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
          } else {
            offset++;
          }
        } else {
          break;
        }
        pos++;
      }
      lastLineEmpty = pos >= max3;
      oldBSCount.push(state.bsCount[nextLine]);
      state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
      oldSCount.push(state.sCount[nextLine]);
      state.sCount[nextLine] = offset - initial2;
      oldTShift.push(state.tShift[nextLine]);
      state.tShift[nextLine] = pos - state.bMarks[nextLine];
      continue;
    }
    if (lastLineEmpty) {
      break;
    }
    let terminate = false;
    for (let i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
      if (terminatorRules[i3](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      state.lineMax = nextLine;
      if (state.blkIndent !== 0) {
        oldBMarks.push(state.bMarks[nextLine]);
        oldBSCount.push(state.bsCount[nextLine]);
        oldTShift.push(state.tShift[nextLine]);
        oldSCount.push(state.sCount[nextLine]);
        state.sCount[nextLine] -= state.blkIndent;
      }
      break;
    }
    oldBMarks.push(state.bMarks[nextLine]);
    oldBSCount.push(state.bsCount[nextLine]);
    oldTShift.push(state.tShift[nextLine]);
    oldSCount.push(state.sCount[nextLine]);
    state.sCount[nextLine] = -1;
  }
  const oldIndent = state.blkIndent;
  state.blkIndent = 0;
  const token_o = state.push("blockquote_open", "blockquote", 1);
  token_o.markup = ">";
  const lines = [startLine, 0];
  token_o.map = lines;
  state.md.block.tokenize(state, startLine, nextLine);
  const token_c = state.push("blockquote_close", "blockquote", -1);
  token_c.markup = ">";
  state.lineMax = oldLineMax;
  state.parentType = oldParentType;
  lines[1] = state.line;
  for (let i3 = 0; i3 < oldTShift.length; i3++) {
    state.bMarks[i3 + startLine] = oldBMarks[i3];
    state.tShift[i3 + startLine] = oldTShift[i3];
    state.sCount[i3 + startLine] = oldSCount[i3];
    state.bsCount[i3 + startLine] = oldBSCount[i3];
  }
  state.blkIndent = oldIndent;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/hr.mjs
function hr(state, startLine, endLine, silent) {
  const max3 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos++);
  if (marker !== 42 && marker !== 45 && marker !== 95) {
    return false;
  }
  let cnt = 1;
  while (pos < max3) {
    const ch = state.src.charCodeAt(pos++);
    if (ch !== marker && !isSpace(ch)) {
      return false;
    }
    if (ch === marker) {
      cnt++;
    }
  }
  if (cnt < 3) {
    return false;
  }
  if (silent) {
    return true;
  }
  state.line = startLine + 1;
  const token = state.push("hr", "hr", 0);
  token.map = [startLine, state.line];
  token.markup = Array(cnt + 1).join(String.fromCharCode(marker));
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/list.mjs
function skipBulletListMarker(state, startLine) {
  const max3 = state.eMarks[startLine];
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos++);
  if (marker !== 42 && marker !== 45 && marker !== 43) {
    return -1;
  }
  if (pos < max3) {
    const ch = state.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos;
}
function skipOrderedListMarker(state, startLine) {
  const start = state.bMarks[startLine] + state.tShift[startLine];
  const max3 = state.eMarks[startLine];
  let pos = start;
  if (pos + 1 >= max3) {
    return -1;
  }
  let ch = state.src.charCodeAt(pos++);
  if (ch < 48 || ch > 57) {
    return -1;
  }
  for (; ; ) {
    if (pos >= max3) {
      return -1;
    }
    ch = state.src.charCodeAt(pos++);
    if (ch >= 48 && ch <= 57) {
      if (pos - start >= 10) {
        return -1;
      }
      continue;
    }
    if (ch === 41 || ch === 46) {
      break;
    }
    return -1;
  }
  if (pos < max3) {
    ch = state.src.charCodeAt(pos);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos;
}
function markTightParagraphs(state, idx) {
  const level = state.level + 2;
  for (let i3 = idx + 2, l3 = state.tokens.length - 2; i3 < l3; i3++) {
    if (state.tokens[i3].level === level && state.tokens[i3].type === "paragraph_open") {
      state.tokens[i3 + 2].hidden = true;
      state.tokens[i3].hidden = true;
      i3 += 2;
    }
  }
}
function list(state, startLine, endLine, silent) {
  let max3, pos, start, token;
  let nextLine = startLine;
  let tight = true;
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  let isTerminatingParagraph = false;
  if (silent && state.parentType === "paragraph") {
    if (state.sCount[nextLine] >= state.blkIndent) {
      isTerminatingParagraph = true;
    }
  }
  let isOrdered;
  let markerValue;
  let posAfterMarker;
  if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) {
    isOrdered = true;
    start = state.bMarks[nextLine] + state.tShift[nextLine];
    markerValue = Number(state.src.slice(start, posAfterMarker - 1));
    if (isTerminatingParagraph && markerValue !== 1) return false;
  } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) {
    isOrdered = false;
  } else {
    return false;
  }
  if (isTerminatingParagraph) {
    if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false;
  }
  if (silent) {
    return true;
  }
  const markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
  const listTokIdx = state.tokens.length;
  if (isOrdered) {
    token = state.push("ordered_list_open", "ol", 1);
    if (markerValue !== 1) {
      token.attrs = [["start", markerValue]];
    }
  } else {
    token = state.push("bullet_list_open", "ul", 1);
  }
  const listLines = [nextLine, 0];
  token.map = listLines;
  token.markup = String.fromCharCode(markerCharCode);
  let prevEmptyEnd = false;
  const terminatorRules = state.md.block.ruler.getRules("list");
  const oldParentType = state.parentType;
  state.parentType = "list";
  while (nextLine < endLine) {
    pos = posAfterMarker;
    max3 = state.eMarks[nextLine];
    const initial2 = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]);
    let offset = initial2;
    while (pos < max3) {
      const ch = state.src.charCodeAt(pos);
      if (ch === 9) {
        offset += 4 - (offset + state.bsCount[nextLine]) % 4;
      } else if (ch === 32) {
        offset++;
      } else {
        break;
      }
      pos++;
    }
    const contentStart = pos;
    let indentAfterMarker;
    if (contentStart >= max3) {
      indentAfterMarker = 1;
    } else {
      indentAfterMarker = offset - initial2;
    }
    if (indentAfterMarker > 4) {
      indentAfterMarker = 1;
    }
    const indent = initial2 + indentAfterMarker;
    token = state.push("list_item_open", "li", 1);
    token.markup = String.fromCharCode(markerCharCode);
    const itemLines = [nextLine, 0];
    token.map = itemLines;
    if (isOrdered) {
      token.info = state.src.slice(start, posAfterMarker - 1);
    }
    const oldTight = state.tight;
    const oldTShift = state.tShift[nextLine];
    const oldSCount = state.sCount[nextLine];
    const oldListIndent = state.listIndent;
    state.listIndent = state.blkIndent;
    state.blkIndent = indent;
    state.tight = true;
    state.tShift[nextLine] = contentStart - state.bMarks[nextLine];
    state.sCount[nextLine] = offset;
    if (contentStart >= max3 && state.isEmpty(nextLine + 1)) {
      state.line = Math.min(state.line + 2, endLine);
    } else {
      state.md.block.tokenize(state, nextLine, endLine, true);
    }
    if (!state.tight || prevEmptyEnd) {
      tight = false;
    }
    prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1);
    state.blkIndent = state.listIndent;
    state.listIndent = oldListIndent;
    state.tShift[nextLine] = oldTShift;
    state.sCount[nextLine] = oldSCount;
    state.tight = oldTight;
    token = state.push("list_item_close", "li", -1);
    token.markup = String.fromCharCode(markerCharCode);
    nextLine = state.line;
    itemLines[1] = nextLine;
    if (nextLine >= endLine) {
      break;
    }
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    let terminate = false;
    for (let i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
      if (terminatorRules[i3](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
    if (isOrdered) {
      posAfterMarker = skipOrderedListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
      start = state.bMarks[nextLine] + state.tShift[nextLine];
    } else {
      posAfterMarker = skipBulletListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
    }
    if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
      break;
    }
  }
  if (isOrdered) {
    token = state.push("ordered_list_close", "ol", -1);
  } else {
    token = state.push("bullet_list_close", "ul", -1);
  }
  token.markup = String.fromCharCode(markerCharCode);
  listLines[1] = nextLine;
  state.line = nextLine;
  state.parentType = oldParentType;
  if (tight) {
    markTightParagraphs(state, listTokIdx);
  }
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/reference.mjs
function reference(state, startLine, _endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max3 = state.eMarks[startLine];
  let nextLine = startLine + 1;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 91) {
    return false;
  }
  function getNextLine(nextLine2) {
    const endLine = state.lineMax;
    if (nextLine2 >= endLine || state.isEmpty(nextLine2)) {
      return null;
    }
    let isContinuation = false;
    if (state.sCount[nextLine2] - state.blkIndent > 3) {
      isContinuation = true;
    }
    if (state.sCount[nextLine2] < 0) {
      isContinuation = true;
    }
    if (!isContinuation) {
      const terminatorRules = state.md.block.ruler.getRules("reference");
      const oldParentType = state.parentType;
      state.parentType = "reference";
      let terminate = false;
      for (let i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
        if (terminatorRules[i3](state, nextLine2, endLine, true)) {
          terminate = true;
          break;
        }
      }
      state.parentType = oldParentType;
      if (terminate) {
        return null;
      }
    }
    const pos2 = state.bMarks[nextLine2] + state.tShift[nextLine2];
    const max4 = state.eMarks[nextLine2];
    return state.src.slice(pos2, max4 + 1);
  }
  let str = state.src.slice(pos, max3 + 1);
  max3 = str.length;
  let labelEnd = -1;
  for (pos = 1; pos < max3; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 91) {
      return false;
    } else if (ch === 93) {
      labelEnd = pos;
      break;
    } else if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max3 = str.length;
        nextLine++;
      }
    } else if (ch === 92) {
      pos++;
      if (pos < max3 && str.charCodeAt(pos) === 10) {
        const lineContent = getNextLine(nextLine);
        if (lineContent !== null) {
          str += lineContent;
          max3 = str.length;
          nextLine++;
        }
      }
    }
  }
  if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 58) {
    return false;
  }
  for (pos = labelEnd + 2; pos < max3; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max3 = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) {
    } else {
      break;
    }
  }
  const destRes = state.md.helpers.parseLinkDestination(str, pos, max3);
  if (!destRes.ok) {
    return false;
  }
  const href = state.md.normalizeLink(destRes.str);
  if (!state.md.validateLink(href)) {
    return false;
  }
  pos = destRes.pos;
  const destEndPos = pos;
  const destEndLineNo = nextLine;
  const start = pos;
  for (; pos < max3; pos++) {
    const ch = str.charCodeAt(pos);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max3 = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) {
    } else {
      break;
    }
  }
  let titleRes = state.md.helpers.parseLinkTitle(str, pos, max3);
  while (titleRes.can_continue) {
    const lineContent = getNextLine(nextLine);
    if (lineContent === null) break;
    str += lineContent;
    pos = max3;
    max3 = str.length;
    nextLine++;
    titleRes = state.md.helpers.parseLinkTitle(str, pos, max3, titleRes);
  }
  let title;
  if (pos < max3 && start !== pos && titleRes.ok) {
    title = titleRes.str;
    pos = titleRes.pos;
  } else {
    title = "";
    pos = destEndPos;
    nextLine = destEndLineNo;
  }
  while (pos < max3) {
    const ch = str.charCodeAt(pos);
    if (!isSpace(ch)) {
      break;
    }
    pos++;
  }
  if (pos < max3 && str.charCodeAt(pos) !== 10) {
    if (title) {
      title = "";
      pos = destEndPos;
      nextLine = destEndLineNo;
      while (pos < max3) {
        const ch = str.charCodeAt(pos);
        if (!isSpace(ch)) {
          break;
        }
        pos++;
      }
    }
  }
  if (pos < max3 && str.charCodeAt(pos) !== 10) {
    return false;
  }
  const label = normalizeReference(str.slice(1, labelEnd));
  if (!label) {
    return false;
  }
  if (silent) {
    return true;
  }
  if (typeof state.env.references === "undefined") {
    state.env.references = {};
  }
  if (typeof state.env.references[label] === "undefined") {
    state.env.references[label] = { title, href };
  }
  state.line = nextLine;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/common/html_blocks.mjs
var html_blocks_default = [
  "address",
  "article",
  "aside",
  "base",
  "basefont",
  "blockquote",
  "body",
  "caption",
  "center",
  "col",
  "colgroup",
  "dd",
  "details",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hr",
  "html",
  "iframe",
  "legend",
  "li",
  "link",
  "main",
  "menu",
  "menuitem",
  "nav",
  "noframes",
  "ol",
  "optgroup",
  "option",
  "p",
  "param",
  "search",
  "section",
  "summary",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "title",
  "tr",
  "track",
  "ul"
];

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/common/html_re.mjs
var attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
var unquoted = "[^\"'=<>`\\x00-\\x20]+";
var single_quoted = "'[^']*'";
var double_quoted = '"[^"]*"';
var attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")";
var attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)";
var open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>";
var close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
var comment2 = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->";
var processing = "<[?][\\s\\S]*?[?]>";
var declaration = "<![A-Za-z][^>]*>";
var cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
var HTML_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + "|" + comment2 + "|" + processing + "|" + declaration + "|" + cdata + ")");
var HTML_OPEN_CLOSE_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + ")");

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/html_block.mjs
var HTML_SEQUENCES = [
  [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
  [/^<!--/, /-->/, true],
  [/^<\?/, /\?>/, true],
  [/^<![A-Z]/, />/, true],
  [/^<!\[CDATA\[/, /\]\]>/, true],
  [new RegExp("^</?(" + html_blocks_default.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
  [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false]
];
function html_block(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max3 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (!state.md.options.html) {
    return false;
  }
  if (state.src.charCodeAt(pos) !== 60) {
    return false;
  }
  let lineText = state.src.slice(pos, max3);
  let i3 = 0;
  for (; i3 < HTML_SEQUENCES.length; i3++) {
    if (HTML_SEQUENCES[i3][0].test(lineText)) {
      break;
    }
  }
  if (i3 === HTML_SEQUENCES.length) {
    return false;
  }
  if (silent) {
    return HTML_SEQUENCES[i3][2];
  }
  let nextLine = startLine + 1;
  if (!HTML_SEQUENCES[i3][1].test(lineText)) {
    for (; nextLine < endLine; nextLine++) {
      if (state.sCount[nextLine] < state.blkIndent) {
        break;
      }
      pos = state.bMarks[nextLine] + state.tShift[nextLine];
      max3 = state.eMarks[nextLine];
      lineText = state.src.slice(pos, max3);
      if (HTML_SEQUENCES[i3][1].test(lineText)) {
        if (lineText.length !== 0) {
          nextLine++;
        }
        break;
      }
    }
  }
  state.line = nextLine;
  const token = state.push("html_block", "", 0);
  token.map = [startLine, nextLine];
  token.content = state.getLines(startLine, nextLine, state.blkIndent, true);
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/heading.mjs
function heading2(state, startLine, endLine, silent) {
  let pos = state.bMarks[startLine] + state.tShift[startLine];
  let max3 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let ch = state.src.charCodeAt(pos);
  if (ch !== 35 || pos >= max3) {
    return false;
  }
  let level = 1;
  ch = state.src.charCodeAt(++pos);
  while (ch === 35 && pos < max3 && level <= 6) {
    level++;
    ch = state.src.charCodeAt(++pos);
  }
  if (level > 6 || pos < max3 && !isSpace(ch)) {
    return false;
  }
  if (silent) {
    return true;
  }
  max3 = state.skipSpacesBack(max3, pos);
  const tmp = state.skipCharsBack(max3, 35, pos);
  if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) {
    max3 = tmp;
  }
  state.line = startLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = "########".slice(0, level);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = state.src.slice(pos, max3).trim();
  token_i.map = [startLine, state.line];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = "########".slice(0, level);
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/lheading.mjs
function lheading(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  const oldParentType = state.parentType;
  state.parentType = "paragraph";
  let level = 0;
  let marker;
  let nextLine = startLine + 1;
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] >= state.blkIndent) {
      let pos = state.bMarks[nextLine] + state.tShift[nextLine];
      const max3 = state.eMarks[nextLine];
      if (pos < max3) {
        marker = state.src.charCodeAt(pos);
        if (marker === 45 || marker === 61) {
          pos = state.skipChars(pos, marker);
          pos = state.skipSpaces(pos);
          if (pos >= max3) {
            level = marker === 61 ? 1 : 2;
            break;
          }
        }
      }
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate = false;
    for (let i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
      if (terminatorRules[i3](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
  }
  if (!level) {
    return false;
  }
  const content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = String.fromCharCode(marker);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content2;
  token_i.map = [startLine, state.line - 1];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = String.fromCharCode(marker);
  state.parentType = oldParentType;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_block/paragraph.mjs
function paragraph(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  const oldParentType = state.parentType;
  let nextLine = startLine + 1;
  state.parentType = "paragraph";
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate = false;
    for (let i3 = 0, l3 = terminatorRules.length; i3 < l3; i3++) {
      if (terminatorRules[i3](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
  }
  const content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine;
  const token_o = state.push("paragraph_open", "p", 1);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content2;
  token_i.map = [startLine, state.line];
  token_i.children = [];
  state.push("paragraph_close", "p", -1);
  state.parentType = oldParentType;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/parser_block.mjs
var _rules2 = [
  // First 2 params - rule name & source. Secondary array - list of rules,
  // which can be terminated by this one.
  ["table", table, ["paragraph", "reference"]],
  ["code", code],
  ["fence", fence, ["paragraph", "reference", "blockquote", "list"]],
  ["blockquote", blockquote, ["paragraph", "reference", "blockquote", "list"]],
  ["hr", hr, ["paragraph", "reference", "blockquote", "list"]],
  ["list", list, ["paragraph", "reference", "blockquote"]],
  ["reference", reference],
  ["html_block", html_block, ["paragraph", "reference", "blockquote"]],
  ["heading", heading2, ["paragraph", "reference", "blockquote"]],
  ["lheading", lheading],
  ["paragraph", paragraph]
];
function ParserBlock() {
  this.ruler = new ruler_default();
  for (let i3 = 0; i3 < _rules2.length; i3++) {
    this.ruler.push(_rules2[i3][0], _rules2[i3][1], { alt: (_rules2[i3][2] || []).slice() });
  }
}
ParserBlock.prototype.tokenize = function(state, startLine, endLine) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  let line = startLine;
  let hasEmptyLines = false;
  while (line < endLine) {
    state.line = line = state.skipEmptyLines(line);
    if (line >= endLine) {
      break;
    }
    if (state.sCount[line] < state.blkIndent) {
      break;
    }
    if (state.level >= maxNesting) {
      state.line = endLine;
      break;
    }
    const prevLine = state.line;
    let ok = false;
    for (let i3 = 0; i3 < len; i3++) {
      ok = rules[i3](state, line, endLine, false);
      if (ok) {
        if (prevLine >= state.line) {
          throw new Error("block rule didn't increment state.line");
        }
        break;
      }
    }
    if (!ok) throw new Error("none of the block rules matched");
    state.tight = !hasEmptyLines;
    if (state.isEmpty(state.line - 1)) {
      hasEmptyLines = true;
    }
    line = state.line;
    if (line < endLine && state.isEmpty(line)) {
      hasEmptyLines = true;
      line++;
      state.line = line;
    }
  }
};
ParserBlock.prototype.parse = function(src, md2, env, outTokens) {
  if (!src) {
    return;
  }
  const state = new this.State(src, md2, env, outTokens);
  this.tokenize(state, state.line, state.lineMax);
};
ParserBlock.prototype.State = state_block_default;
var parser_block_default = ParserBlock;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/state_inline.mjs
function StateInline(src, md2, env, outTokens) {
  this.src = src;
  this.env = env;
  this.md = md2;
  this.tokens = outTokens;
  this.tokens_meta = Array(outTokens.length);
  this.pos = 0;
  this.posMax = this.src.length;
  this.level = 0;
  this.pending = "";
  this.pendingLevel = 0;
  this.cache = {};
  this.delimiters = [];
  this._prev_delimiters = [];
  this.backticks = {};
  this.backticksScanned = false;
  this.linkLevel = 0;
}
StateInline.prototype.pushPending = function() {
  const token = new token_default("text", "", 0);
  token.content = this.pending;
  token.level = this.pendingLevel;
  this.tokens.push(token);
  this.pending = "";
  return token;
};
StateInline.prototype.push = function(type, tag, nesting) {
  if (this.pending) {
    this.pushPending();
  }
  const token = new token_default(type, tag, nesting);
  let token_meta = null;
  if (nesting < 0) {
    this.level--;
    this.delimiters = this._prev_delimiters.pop();
  }
  token.level = this.level;
  if (nesting > 0) {
    this.level++;
    this._prev_delimiters.push(this.delimiters);
    this.delimiters = [];
    token_meta = { delimiters: this.delimiters };
  }
  this.pendingLevel = this.level;
  this.tokens.push(token);
  this.tokens_meta.push(token_meta);
  return token;
};
StateInline.prototype.scanDelims = function(start, canSplitWord) {
  const max3 = this.posMax;
  const marker = this.src.charCodeAt(start);
  const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 32;
  let pos = start;
  while (pos < max3 && this.src.charCodeAt(pos) === marker) {
    pos++;
  }
  const count = pos - start;
  const nextChar2 = pos < max3 ? this.src.charCodeAt(pos) : 32;
  const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
  const isNextPunctChar = isMdAsciiPunct(nextChar2) || isPunctChar(String.fromCharCode(nextChar2));
  const isLastWhiteSpace = isWhiteSpace(lastChar);
  const isNextWhiteSpace = isWhiteSpace(nextChar2);
  const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);
  const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);
  const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);
  const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);
  return { can_open, can_close, length: count };
};
StateInline.prototype.Token = token_default;
var state_inline_default = StateInline;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/text.mjs
function isTerminatorChar(ch) {
  switch (ch) {
    case 10:
    case 33:
    case 35:
    case 36:
    case 37:
    case 38:
    case 42:
    case 43:
    case 45:
    case 58:
    case 60:
    case 61:
    case 62:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
function text(state, silent) {
  let pos = state.pos;
  while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {
    pos++;
  }
  if (pos === state.pos) {
    return false;
  }
  if (!silent) {
    state.pending += state.src.slice(state.pos, pos);
  }
  state.pos = pos;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/linkify.mjs
var SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
function linkify2(state, silent) {
  if (!state.md.options.linkify) return false;
  if (state.linkLevel > 0) return false;
  const pos = state.pos;
  const max3 = state.posMax;
  if (pos + 3 > max3) return false;
  if (state.src.charCodeAt(pos) !== 58) return false;
  if (state.src.charCodeAt(pos + 1) !== 47) return false;
  if (state.src.charCodeAt(pos + 2) !== 47) return false;
  const match2 = state.pending.match(SCHEME_RE);
  if (!match2) return false;
  const proto = match2[1];
  const link2 = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length));
  if (!link2) return false;
  let url2 = link2.url;
  if (url2.length <= proto.length) return false;
  let urlEnd = url2.length;
  while (urlEnd > 0 && url2.charCodeAt(urlEnd - 1) === 42) {
    urlEnd--;
  }
  if (urlEnd !== url2.length) {
    url2 = url2.slice(0, urlEnd);
  }
  const fullUrl = state.md.normalizeLink(url2);
  if (!state.md.validateLink(fullUrl)) return false;
  if (!silent) {
    state.pending = state.pending.slice(0, -proto.length);
    const token_o = state.push("link_open", "a", 1);
    token_o.attrs = [["href", fullUrl]];
    token_o.markup = "linkify";
    token_o.info = "auto";
    const token_t = state.push("text", "", 0);
    token_t.content = state.md.normalizeLinkText(url2);
    const token_c = state.push("link_close", "a", -1);
    token_c.markup = "linkify";
    token_c.info = "auto";
  }
  state.pos += url2.length - proto.length;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/newline.mjs
function newline(state, silent) {
  let pos = state.pos;
  if (state.src.charCodeAt(pos) !== 10) {
    return false;
  }
  const pmax = state.pending.length - 1;
  const max3 = state.posMax;
  if (!silent) {
    if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
      if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
        let ws = pmax - 1;
        while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 32) ws--;
        state.pending = state.pending.slice(0, ws);
        state.push("hardbreak", "br", 0);
      } else {
        state.pending = state.pending.slice(0, -1);
        state.push("softbreak", "br", 0);
      }
    } else {
      state.push("softbreak", "br", 0);
    }
  }
  pos++;
  while (pos < max3 && isSpace(state.src.charCodeAt(pos))) {
    pos++;
  }
  state.pos = pos;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/escape.mjs
var ESCAPED = [];
for (let i3 = 0; i3 < 256; i3++) {
  ESCAPED.push(0);
}
"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch) {
  ESCAPED[ch.charCodeAt(0)] = 1;
});
function escape3(state, silent) {
  let pos = state.pos;
  const max3 = state.posMax;
  if (state.src.charCodeAt(pos) !== 92) return false;
  pos++;
  if (pos >= max3) return false;
  let ch1 = state.src.charCodeAt(pos);
  if (ch1 === 10) {
    if (!silent) {
      state.push("hardbreak", "br", 0);
    }
    pos++;
    while (pos < max3) {
      ch1 = state.src.charCodeAt(pos);
      if (!isSpace(ch1)) break;
      pos++;
    }
    state.pos = pos;
    return true;
  }
  let escapedStr = state.src[pos];
  if (ch1 >= 55296 && ch1 <= 56319 && pos + 1 < max3) {
    const ch2 = state.src.charCodeAt(pos + 1);
    if (ch2 >= 56320 && ch2 <= 57343) {
      escapedStr += state.src[pos + 1];
      pos++;
    }
  }
  const origStr = "\\" + escapedStr;
  if (!silent) {
    const token = state.push("text_special", "", 0);
    if (ch1 < 256 && ESCAPED[ch1] !== 0) {
      token.content = escapedStr;
    } else {
      token.content = origStr;
    }
    token.markup = origStr;
    token.info = "escape";
  }
  state.pos = pos + 1;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/backticks.mjs
function backtick(state, silent) {
  let pos = state.pos;
  const ch = state.src.charCodeAt(pos);
  if (ch !== 96) {
    return false;
  }
  const start = pos;
  pos++;
  const max3 = state.posMax;
  while (pos < max3 && state.src.charCodeAt(pos) === 96) {
    pos++;
  }
  const marker = state.src.slice(start, pos);
  const openerLength = marker.length;
  if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) {
    if (!silent) state.pending += marker;
    state.pos += openerLength;
    return true;
  }
  let matchEnd = pos;
  let matchStart;
  while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
    matchEnd = matchStart + 1;
    while (matchEnd < max3 && state.src.charCodeAt(matchEnd) === 96) {
      matchEnd++;
    }
    const closerLength = matchEnd - matchStart;
    if (closerLength === openerLength) {
      if (!silent) {
        const token = state.push("code_inline", "code", 0);
        token.markup = marker;
        token.content = state.src.slice(pos, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
      }
      state.pos = matchEnd;
      return true;
    }
    state.backticks[closerLength] = matchStart;
  }
  state.backticksScanned = true;
  if (!silent) state.pending += marker;
  state.pos += openerLength;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/strikethrough.mjs
function strikethrough_tokenize(state, silent) {
  const start = state.pos;
  const marker = state.src.charCodeAt(start);
  if (silent) {
    return false;
  }
  if (marker !== 126) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, true);
  let len = scanned.length;
  const ch = String.fromCharCode(marker);
  if (len < 2) {
    return false;
  }
  let token;
  if (len % 2) {
    token = state.push("text", "", 0);
    token.content = ch;
    len--;
  }
  for (let i3 = 0; i3 < len; i3 += 2) {
    token = state.push("text", "", 0);
    token.content = ch + ch;
    state.delimiters.push({
      marker,
      length: 0,
      // disable "rule of 3" length checks meant for emphasis
      token: state.tokens.length - 1,
      end: -1,
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
function postProcess(state, delimiters) {
  let token;
  const loneMarkers = [];
  const max3 = delimiters.length;
  for (let i3 = 0; i3 < max3; i3++) {
    const startDelim = delimiters[i3];
    if (startDelim.marker !== 126) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    token = state.tokens[startDelim.token];
    token.type = "s_open";
    token.tag = "s";
    token.nesting = 1;
    token.markup = "~~";
    token.content = "";
    token = state.tokens[endDelim.token];
    token.type = "s_close";
    token.tag = "s";
    token.nesting = -1;
    token.markup = "~~";
    token.content = "";
    if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
      loneMarkers.push(endDelim.token - 1);
    }
  }
  while (loneMarkers.length) {
    const i3 = loneMarkers.pop();
    let j = i3 + 1;
    while (j < state.tokens.length && state.tokens[j].type === "s_close") {
      j++;
    }
    j--;
    if (i3 !== j) {
      token = state.tokens[j];
      state.tokens[j] = state.tokens[i3];
      state.tokens[i3] = token;
    }
  }
}
function strikethrough_postProcess(state) {
  const tokens_meta = state.tokens_meta;
  const max3 = state.tokens_meta.length;
  postProcess(state, state.delimiters);
  for (let curr = 0; curr < max3; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess(state, tokens_meta[curr].delimiters);
    }
  }
}
var strikethrough_default = {
  tokenize: strikethrough_tokenize,
  postProcess: strikethrough_postProcess
};

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/emphasis.mjs
function emphasis_tokenize(state, silent) {
  const start = state.pos;
  const marker = state.src.charCodeAt(start);
  if (silent) {
    return false;
  }
  if (marker !== 95 && marker !== 42) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, marker === 42);
  for (let i3 = 0; i3 < scanned.length; i3++) {
    const token = state.push("text", "", 0);
    token.content = String.fromCharCode(marker);
    state.delimiters.push({
      // Char code of the starting marker (number).
      //
      marker,
      // Total length of these series of delimiters.
      //
      length: scanned.length,
      // A position of the token this delimiter corresponds to.
      //
      token: state.tokens.length - 1,
      // If this delimiter is matched as a valid opener, `end` will be
      // equal to its position, otherwise it's `-1`.
      //
      end: -1,
      // Boolean flags that determine if this delimiter could open or close
      // an emphasis.
      //
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
function postProcess2(state, delimiters) {
  const max3 = delimiters.length;
  for (let i3 = max3 - 1; i3 >= 0; i3--) {
    const startDelim = delimiters[i3];
    if (startDelim.marker !== 95 && startDelim.marker !== 42) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    const isStrong = i3 > 0 && delimiters[i3 - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
    delimiters[i3 - 1].marker === startDelim.marker && delimiters[i3 - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
    delimiters[startDelim.end + 1].token === endDelim.token + 1;
    const ch = String.fromCharCode(startDelim.marker);
    const token_o = state.tokens[startDelim.token];
    token_o.type = isStrong ? "strong_open" : "em_open";
    token_o.tag = isStrong ? "strong" : "em";
    token_o.nesting = 1;
    token_o.markup = isStrong ? ch + ch : ch;
    token_o.content = "";
    const token_c = state.tokens[endDelim.token];
    token_c.type = isStrong ? "strong_close" : "em_close";
    token_c.tag = isStrong ? "strong" : "em";
    token_c.nesting = -1;
    token_c.markup = isStrong ? ch + ch : ch;
    token_c.content = "";
    if (isStrong) {
      state.tokens[delimiters[i3 - 1].token].content = "";
      state.tokens[delimiters[startDelim.end + 1].token].content = "";
      i3--;
    }
  }
}
function emphasis_post_process(state) {
  const tokens_meta = state.tokens_meta;
  const max3 = state.tokens_meta.length;
  postProcess2(state, state.delimiters);
  for (let curr = 0; curr < max3; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess2(state, tokens_meta[curr].delimiters);
    }
  }
}
var emphasis_default = {
  tokenize: emphasis_tokenize,
  postProcess: emphasis_post_process
};

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/link.mjs
function link(state, silent) {
  let code2, label, res, ref;
  let href = "";
  let title = "";
  let start = state.pos;
  let parseReference = true;
  if (state.src.charCodeAt(state.pos) !== 91) {
    return false;
  }
  const oldPos = state.pos;
  const max3 = state.posMax;
  const labelStart = state.pos + 1;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
  if (labelEnd < 0) {
    return false;
  }
  let pos = labelEnd + 1;
  if (pos < max3 && state.src.charCodeAt(pos) === 40) {
    parseReference = false;
    pos++;
    for (; pos < max3; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos >= max3) {
      return false;
    }
    start = pos;
    res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos = res.pos;
      } else {
        href = "";
      }
      start = pos;
      for (; pos < max3; pos++) {
        code2 = state.src.charCodeAt(pos);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
      res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
      if (pos < max3 && start !== pos && res.ok) {
        title = res.str;
        pos = res.pos;
        for (; pos < max3; pos++) {
          code2 = state.src.charCodeAt(pos);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
      }
    }
    if (pos >= max3 || state.src.charCodeAt(pos) !== 41) {
      parseReference = true;
    }
    pos++;
  }
  if (parseReference) {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos < max3 && state.src.charCodeAt(pos) === 91) {
      start = pos + 1;
      pos = state.md.helpers.parseLinkLabel(state, pos);
      if (pos >= 0) {
        label = state.src.slice(start, pos++);
      } else {
        pos = labelEnd + 1;
      }
    } else {
      pos = labelEnd + 1;
    }
    if (!label) {
      label = state.src.slice(labelStart, labelEnd);
    }
    ref = state.env.references[normalizeReference(label)];
    if (!ref) {
      state.pos = oldPos;
      return false;
    }
    href = ref.href;
    title = ref.title;
  }
  if (!silent) {
    state.pos = labelStart;
    state.posMax = labelEnd;
    const token_o = state.push("link_open", "a", 1);
    const attrs2 = [["href", href]];
    token_o.attrs = attrs2;
    if (title) {
      attrs2.push(["title", title]);
    }
    state.linkLevel++;
    state.md.inline.tokenize(state);
    state.linkLevel--;
    state.push("link_close", "a", -1);
  }
  state.pos = pos;
  state.posMax = max3;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/image.mjs
function image(state, silent) {
  let code2, content2, label, pos, ref, res, title, start;
  let href = "";
  const oldPos = state.pos;
  const max3 = state.posMax;
  if (state.src.charCodeAt(state.pos) !== 33) {
    return false;
  }
  if (state.src.charCodeAt(state.pos + 1) !== 91) {
    return false;
  }
  const labelStart = state.pos + 2;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
  if (labelEnd < 0) {
    return false;
  }
  pos = labelEnd + 1;
  if (pos < max3 && state.src.charCodeAt(pos) === 40) {
    pos++;
    for (; pos < max3; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos >= max3) {
      return false;
    }
    start = pos;
    res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos = res.pos;
      } else {
        href = "";
      }
    }
    start = pos;
    for (; pos < max3; pos++) {
      code2 = state.src.charCodeAt(pos);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
    if (pos < max3 && start !== pos && res.ok) {
      title = res.str;
      pos = res.pos;
      for (; pos < max3; pos++) {
        code2 = state.src.charCodeAt(pos);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
    } else {
      title = "";
    }
    if (pos >= max3 || state.src.charCodeAt(pos) !== 41) {
      state.pos = oldPos;
      return false;
    }
    pos++;
  } else {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos < max3 && state.src.charCodeAt(pos) === 91) {
      start = pos + 1;
      pos = state.md.helpers.parseLinkLabel(state, pos);
      if (pos >= 0) {
        label = state.src.slice(start, pos++);
      } else {
        pos = labelEnd + 1;
      }
    } else {
      pos = labelEnd + 1;
    }
    if (!label) {
      label = state.src.slice(labelStart, labelEnd);
    }
    ref = state.env.references[normalizeReference(label)];
    if (!ref) {
      state.pos = oldPos;
      return false;
    }
    href = ref.href;
    title = ref.title;
  }
  if (!silent) {
    content2 = state.src.slice(labelStart, labelEnd);
    const tokens = [];
    state.md.inline.parse(
      content2,
      state.md,
      state.env,
      tokens
    );
    const token = state.push("image", "img", 0);
    const attrs2 = [["src", href], ["alt", ""]];
    token.attrs = attrs2;
    token.children = tokens;
    token.content = content2;
    if (title) {
      attrs2.push(["title", title]);
    }
  }
  state.pos = pos;
  state.posMax = max3;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/autolink.mjs
var EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;
var AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;
function autolink(state, silent) {
  let pos = state.pos;
  if (state.src.charCodeAt(pos) !== 60) {
    return false;
  }
  const start = state.pos;
  const max3 = state.posMax;
  for (; ; ) {
    if (++pos >= max3) return false;
    const ch = state.src.charCodeAt(pos);
    if (ch === 60) return false;
    if (ch === 62) break;
  }
  const url2 = state.src.slice(start + 1, pos);
  if (AUTOLINK_RE.test(url2)) {
    const fullUrl = state.md.normalizeLink(url2);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url2);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url2.length + 2;
    return true;
  }
  if (EMAIL_RE.test(url2)) {
    const fullUrl = state.md.normalizeLink("mailto:" + url2);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url2);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url2.length + 2;
    return true;
  }
  return false;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/html_inline.mjs
function isLinkOpen2(str) {
  return /^<a[>\s]/i.test(str);
}
function isLinkClose2(str) {
  return /^<\/a\s*>/i.test(str);
}
function isLetter(ch) {
  const lc = ch | 32;
  return lc >= 97 && lc <= 122;
}
function html_inline(state, silent) {
  if (!state.md.options.html) {
    return false;
  }
  const max3 = state.posMax;
  const pos = state.pos;
  if (state.src.charCodeAt(pos) !== 60 || pos + 2 >= max3) {
    return false;
  }
  const ch = state.src.charCodeAt(pos + 1);
  if (ch !== 33 && ch !== 63 && ch !== 47 && !isLetter(ch)) {
    return false;
  }
  const match2 = state.src.slice(pos).match(HTML_TAG_RE);
  if (!match2) {
    return false;
  }
  if (!silent) {
    const token = state.push("html_inline", "", 0);
    token.content = match2[0];
    if (isLinkOpen2(token.content)) state.linkLevel++;
    if (isLinkClose2(token.content)) state.linkLevel--;
  }
  state.pos += match2[0].length;
  return true;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/entity.mjs
var DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
var NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
function entity(state, silent) {
  const pos = state.pos;
  const max3 = state.posMax;
  if (state.src.charCodeAt(pos) !== 38) return false;
  if (pos + 1 >= max3) return false;
  const ch = state.src.charCodeAt(pos + 1);
  if (ch === 35) {
    const match2 = state.src.slice(pos).match(DIGITAL_RE);
    if (match2) {
      if (!silent) {
        const code2 = match2[1][0].toLowerCase() === "x" ? parseInt(match2[1].slice(1), 16) : parseInt(match2[1], 10);
        const token = state.push("text_special", "", 0);
        token.content = isValidEntityCode(code2) ? fromCodePoint3(code2) : fromCodePoint3(65533);
        token.markup = match2[0];
        token.info = "entity";
      }
      state.pos += match2[0].length;
      return true;
    }
  } else {
    const match2 = state.src.slice(pos).match(NAMED_RE);
    if (match2) {
      const decoded = decodeHTML(match2[0]);
      if (decoded !== match2[0]) {
        if (!silent) {
          const token = state.push("text_special", "", 0);
          token.content = decoded;
          token.markup = match2[0];
          token.info = "entity";
        }
        state.pos += match2[0].length;
        return true;
      }
    }
  }
  return false;
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/balance_pairs.mjs
function processDelimiters(delimiters) {
  const openersBottom = {};
  const max3 = delimiters.length;
  if (!max3) return;
  let headerIdx = 0;
  let lastTokenIdx = -2;
  const jumps = [];
  for (let closerIdx = 0; closerIdx < max3; closerIdx++) {
    const closer = delimiters[closerIdx];
    jumps.push(0);
    if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
      headerIdx = closerIdx;
    }
    lastTokenIdx = closer.token;
    closer.length = closer.length || 0;
    if (!closer.close) continue;
    if (!openersBottom.hasOwnProperty(closer.marker)) {
      openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
    }
    const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
    let openerIdx = headerIdx - jumps[headerIdx] - 1;
    let newMinOpenerIdx = openerIdx;
    for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
      const opener = delimiters[openerIdx];
      if (opener.marker !== closer.marker) continue;
      if (opener.open && opener.end < 0) {
        let isOddMatch = false;
        if (opener.close || closer.open) {
          if ((opener.length + closer.length) % 3 === 0) {
            if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
              isOddMatch = true;
            }
          }
        }
        if (!isOddMatch) {
          const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
          jumps[closerIdx] = closerIdx - openerIdx + lastJump;
          jumps[openerIdx] = lastJump;
          closer.open = false;
          opener.end = closerIdx;
          opener.close = false;
          newMinOpenerIdx = -1;
          lastTokenIdx = -2;
          break;
        }
      }
    }
    if (newMinOpenerIdx !== -1) {
      openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
    }
  }
}
function link_pairs(state) {
  const tokens_meta = state.tokens_meta;
  const max3 = state.tokens_meta.length;
  processDelimiters(state.delimiters);
  for (let curr = 0; curr < max3; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      processDelimiters(tokens_meta[curr].delimiters);
    }
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/rules_inline/fragments_join.mjs
function fragments_join(state) {
  let curr, last3;
  let level = 0;
  const tokens = state.tokens;
  const max3 = state.tokens.length;
  for (curr = last3 = 0; curr < max3; curr++) {
    if (tokens[curr].nesting < 0) level--;
    tokens[curr].level = level;
    if (tokens[curr].nesting > 0) level++;
    if (tokens[curr].type === "text" && curr + 1 < max3 && tokens[curr + 1].type === "text") {
      tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
    } else {
      if (curr !== last3) {
        tokens[last3] = tokens[curr];
      }
      last3++;
    }
  }
  if (curr !== last3) {
    tokens.length = last3;
  }
}

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/parser_inline.mjs
var _rules3 = [
  ["text", text],
  ["linkify", linkify2],
  ["newline", newline],
  ["escape", escape3],
  ["backticks", backtick],
  ["strikethrough", strikethrough_default.tokenize],
  ["emphasis", emphasis_default.tokenize],
  ["link", link],
  ["image", image],
  ["autolink", autolink],
  ["html_inline", html_inline],
  ["entity", entity]
];
var _rules22 = [
  ["balance_pairs", link_pairs],
  ["strikethrough", strikethrough_default.postProcess],
  ["emphasis", emphasis_default.postProcess],
  // rules for pairs separate '**' into its own text tokens, which may be left unused,
  // rule below merges unused segments back with the rest of the text
  ["fragments_join", fragments_join]
];
function ParserInline() {
  this.ruler = new ruler_default();
  for (let i3 = 0; i3 < _rules3.length; i3++) {
    this.ruler.push(_rules3[i3][0], _rules3[i3][1]);
  }
  this.ruler2 = new ruler_default();
  for (let i3 = 0; i3 < _rules22.length; i3++) {
    this.ruler2.push(_rules22[i3][0], _rules22[i3][1]);
  }
}
ParserInline.prototype.skipToken = function(state) {
  const pos = state.pos;
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  const cache5 = state.cache;
  if (typeof cache5[pos] !== "undefined") {
    state.pos = cache5[pos];
    return;
  }
  let ok = false;
  if (state.level < maxNesting) {
    for (let i3 = 0; i3 < len; i3++) {
      state.level++;
      ok = rules[i3](state, true);
      state.level--;
      if (ok) {
        if (pos >= state.pos) {
          throw new Error("inline rule didn't increment state.pos");
        }
        break;
      }
    }
  } else {
    state.pos = state.posMax;
  }
  if (!ok) {
    state.pos++;
  }
  cache5[pos] = state.pos;
};
ParserInline.prototype.tokenize = function(state) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const end = state.posMax;
  const maxNesting = state.md.options.maxNesting;
  while (state.pos < end) {
    const prevPos = state.pos;
    let ok = false;
    if (state.level < maxNesting) {
      for (let i3 = 0; i3 < len; i3++) {
        ok = rules[i3](state, false);
        if (ok) {
          if (prevPos >= state.pos) {
            throw new Error("inline rule didn't increment state.pos");
          }
          break;
        }
      }
    }
    if (ok) {
      if (state.pos >= end) {
        break;
      }
      continue;
    }
    state.pending += state.src[state.pos++];
  }
  if (state.pending) {
    state.pushPending();
  }
};
ParserInline.prototype.parse = function(str, md2, env, outTokens) {
  const state = new this.State(str, md2, env, outTokens);
  this.tokenize(state);
  const rules = this.ruler2.getRules("");
  const len = rules.length;
  for (let i3 = 0; i3 < len; i3++) {
    rules[i3](state);
  }
};
ParserInline.prototype.State = state_inline_default;
var parser_inline_default = ParserInline;

// node_modules/codemirror-json-schema/node_modules/linkify-it/lib/re.mjs
function re_default(opts) {
  const re2 = {};
  opts = opts || {};
  re2.src_Any = regex_default.source;
  re2.src_Cc = regex_default2.source;
  re2.src_Z = regex_default6.source;
  re2.src_P = regex_default4.source;
  re2.src_ZPCc = [re2.src_Z, re2.src_P, re2.src_Cc].join("|");
  re2.src_ZCc = [re2.src_Z, re2.src_Cc].join("|");
  const text_separators = "[><\uFF5C]";
  re2.src_pseudo_letter = "(?:(?!" + text_separators + "|" + re2.src_ZPCc + ")" + re2.src_Any + ")";
  re2.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
  re2.src_auth = "(?:(?:(?!" + re2.src_ZCc + "|[@/\\[\\]()]).)+@)?";
  re2.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
  re2.src_host_terminator = "(?=$|" + text_separators + "|" + re2.src_ZPCc + ")(?!" + (opts["---"] ? "-(?!--)|" : "-|") + "_|:\\d|\\.-|\\.(?!$|" + re2.src_ZPCc + "))";
  re2.src_path = "(?:[/?#](?:(?!" + re2.src_ZCc + "|" + text_separators + `|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!` + re2.src_ZCc + "|\\]).)*\\]|\\((?:(?!" + re2.src_ZCc + "|[)]).)*\\)|\\{(?:(?!" + re2.src_ZCc + '|[}]).)*\\}|\\"(?:(?!' + re2.src_ZCc + `|["]).)+\\"|\\'(?:(?!` + re2.src_ZCc + "|[']).)+\\'|\\'(?=" + re2.src_pseudo_letter + "|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!" + re2.src_ZCc + "|[.]|$)|" + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + // allow `,,,` in paths
  ",(?!" + re2.src_ZCc + "|$)|;(?!" + re2.src_ZCc + "|$)|\\!+(?!" + re2.src_ZCc + "|[!]|$)|\\?(?!" + re2.src_ZCc + "|[?]|$))+|\\/)?";
  re2.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*';
  re2.src_xn = "xn--[a-z0-9\\-]{1,59}";
  re2.src_domain_root = // Allow letters & digits (http://test1)
  "(?:" + re2.src_xn + "|" + re2.src_pseudo_letter + "{1,63})";
  re2.src_domain = "(?:" + re2.src_xn + "|(?:" + re2.src_pseudo_letter + ")|(?:" + re2.src_pseudo_letter + "(?:-|" + re2.src_pseudo_letter + "){0,61}" + re2.src_pseudo_letter + "))";
  re2.src_host = "(?:(?:(?:(?:" + re2.src_domain + ")\\.)*" + re2.src_domain + "))";
  re2.tpl_host_fuzzy = "(?:" + re2.src_ip4 + "|(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%)))";
  re2.tpl_host_no_ip_fuzzy = "(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%))";
  re2.src_host_strict = re2.src_host + re2.src_host_terminator;
  re2.tpl_host_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_host_terminator;
  re2.src_host_port_strict = re2.src_host + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_no_ip_fuzzy_strict = re2.tpl_host_no_ip_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_fuzzy_test = "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + re2.src_ZPCc + "|>|$))";
  re2.tpl_email_fuzzy = "(^|" + text_separators + '|"|\\(|' + re2.src_ZCc + ")(" + re2.src_email_name + "@" + re2.tpl_host_fuzzy_strict + ")";
  re2.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uFF5C]|" + re2.src_ZPCc + "))((?![$+<=>^`|\uFF5C])" + re2.tpl_host_port_fuzzy_strict + re2.src_path + ")";
  re2.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uFF5C]|" + re2.src_ZPCc + "))((?![$+<=>^`|\uFF5C])" + re2.tpl_host_port_no_ip_fuzzy_strict + re2.src_path + ")";
  return re2;
}

// node_modules/codemirror-json-schema/node_modules/linkify-it/index.mjs
function assign5(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source) {
    if (!source) {
      return;
    }
    Object.keys(source).forEach(function(key2) {
      obj[key2] = source[key2];
    });
  });
  return obj;
}
function _class2(obj) {
  return Object.prototype.toString.call(obj);
}
function isString4(obj) {
  return _class2(obj) === "[object String]";
}
function isObject6(obj) {
  return _class2(obj) === "[object Object]";
}
function isRegExp(obj) {
  return _class2(obj) === "[object RegExp]";
}
function isFunction3(obj) {
  return _class2(obj) === "[object Function]";
}
function escapeRE2(str) {
  return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
}
var defaultOptions3 = {
  fuzzyLink: true,
  fuzzyEmail: true,
  fuzzyIP: false
};
function isOptionsObj(obj) {
  return Object.keys(obj || {}).reduce(function(acc, k2) {
    return acc || defaultOptions3.hasOwnProperty(k2);
  }, false);
}
var defaultSchemas = {
  "http:": {
    validate: function(text3, pos, self2) {
      const tail = text3.slice(pos);
      if (!self2.re.http) {
        self2.re.http = new RegExp(
          "^\\/\\/" + self2.re.src_auth + self2.re.src_host_port_strict + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.http.test(tail)) {
        return tail.match(self2.re.http)[0].length;
      }
      return 0;
    }
  },
  "https:": "http:",
  "ftp:": "http:",
  "//": {
    validate: function(text3, pos, self2) {
      const tail = text3.slice(pos);
      if (!self2.re.no_http) {
        self2.re.no_http = new RegExp(
          "^" + self2.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
          // with code comments
          "(?:localhost|(?:(?:" + self2.re.src_domain + ")\\.)+" + self2.re.src_domain_root + ")" + self2.re.src_port + self2.re.src_host_terminator + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.no_http.test(tail)) {
        if (pos >= 3 && text3[pos - 3] === ":") {
          return 0;
        }
        if (pos >= 3 && text3[pos - 3] === "/") {
          return 0;
        }
        return tail.match(self2.re.no_http)[0].length;
      }
      return 0;
    }
  },
  "mailto:": {
    validate: function(text3, pos, self2) {
      const tail = text3.slice(pos);
      if (!self2.re.mailto) {
        self2.re.mailto = new RegExp(
          "^" + self2.re.src_email_name + "@" + self2.re.src_host_strict,
          "i"
        );
      }
      if (self2.re.mailto.test(tail)) {
        return tail.match(self2.re.mailto)[0].length;
      }
      return 0;
    }
  }
};
var tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
var tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|\u0440\u0444".split("|");
function resetScanCache(self2) {
  self2.__index__ = -1;
  self2.__text_cache__ = "";
}
function createValidator(re2) {
  return function(text3, pos) {
    const tail = text3.slice(pos);
    if (re2.test(tail)) {
      return tail.match(re2)[0].length;
    }
    return 0;
  };
}
function createNormalizer() {
  return function(match2, self2) {
    self2.normalize(match2);
  };
}
function compile(self2) {
  const re2 = self2.re = re_default(self2.__opts__);
  const tlds2 = self2.__tlds__.slice();
  self2.onCompile();
  if (!self2.__tlds_replaced__) {
    tlds2.push(tlds_2ch_src_re);
  }
  tlds2.push(re2.src_xn);
  re2.src_tlds = tlds2.join("|");
  function untpl(tpl) {
    return tpl.replace("%TLDS%", re2.src_tlds);
  }
  re2.email_fuzzy = RegExp(untpl(re2.tpl_email_fuzzy), "i");
  re2.link_fuzzy = RegExp(untpl(re2.tpl_link_fuzzy), "i");
  re2.link_no_ip_fuzzy = RegExp(untpl(re2.tpl_link_no_ip_fuzzy), "i");
  re2.host_fuzzy_test = RegExp(untpl(re2.tpl_host_fuzzy_test), "i");
  const aliases = [];
  self2.__compiled__ = {};
  function schemaError(name2, val) {
    throw new Error('(LinkifyIt) Invalid schema "' + name2 + '": ' + val);
  }
  Object.keys(self2.__schemas__).forEach(function(name2) {
    const val = self2.__schemas__[name2];
    if (val === null) {
      return;
    }
    const compiled = { validate: null, link: null };
    self2.__compiled__[name2] = compiled;
    if (isObject6(val)) {
      if (isRegExp(val.validate)) {
        compiled.validate = createValidator(val.validate);
      } else if (isFunction3(val.validate)) {
        compiled.validate = val.validate;
      } else {
        schemaError(name2, val);
      }
      if (isFunction3(val.normalize)) {
        compiled.normalize = val.normalize;
      } else if (!val.normalize) {
        compiled.normalize = createNormalizer();
      } else {
        schemaError(name2, val);
      }
      return;
    }
    if (isString4(val)) {
      aliases.push(name2);
      return;
    }
    schemaError(name2, val);
  });
  aliases.forEach(function(alias) {
    if (!self2.__compiled__[self2.__schemas__[alias]]) {
      return;
    }
    self2.__compiled__[alias].validate = self2.__compiled__[self2.__schemas__[alias]].validate;
    self2.__compiled__[alias].normalize = self2.__compiled__[self2.__schemas__[alias]].normalize;
  });
  self2.__compiled__[""] = { validate: null, normalize: createNormalizer() };
  const slist = Object.keys(self2.__compiled__).filter(function(name2) {
    return name2.length > 0 && self2.__compiled__[name2];
  }).map(escapeRE2).join("|");
  self2.re.schema_test = RegExp("(^|(?!_)(?:[><\uFF5C]|" + re2.src_ZPCc + "))(" + slist + ")", "i");
  self2.re.schema_search = RegExp("(^|(?!_)(?:[><\uFF5C]|" + re2.src_ZPCc + "))(" + slist + ")", "ig");
  self2.re.schema_at_start = RegExp("^" + self2.re.schema_search.source, "i");
  self2.re.pretest = RegExp(
    "(" + self2.re.schema_test.source + ")|(" + self2.re.host_fuzzy_test.source + ")|@",
    "i"
  );
  resetScanCache(self2);
}
function Match2(self2, shift2) {
  const start = self2.__index__;
  const end = self2.__last_index__;
  const text3 = self2.__text_cache__.slice(start, end);
  this.schema = self2.__schema__.toLowerCase();
  this.index = start + shift2;
  this.lastIndex = end + shift2;
  this.raw = text3;
  this.text = text3;
  this.url = text3;
}
function createMatch(self2, shift2) {
  const match2 = new Match2(self2, shift2);
  self2.__compiled__[match2.schema].normalize(match2, self2);
  return match2;
}
function LinkifyIt(schemas2, options2) {
  if (!(this instanceof LinkifyIt)) {
    return new LinkifyIt(schemas2, options2);
  }
  if (!options2) {
    if (isOptionsObj(schemas2)) {
      options2 = schemas2;
      schemas2 = {};
    }
  }
  this.__opts__ = assign5({}, defaultOptions3, options2);
  this.__index__ = -1;
  this.__last_index__ = -1;
  this.__schema__ = "";
  this.__text_cache__ = "";
  this.__schemas__ = assign5({}, defaultSchemas, schemas2);
  this.__compiled__ = {};
  this.__tlds__ = tlds_default;
  this.__tlds_replaced__ = false;
  this.re = {};
  compile(this);
}
LinkifyIt.prototype.add = function add2(schema7, definition) {
  this.__schemas__[schema7] = definition;
  compile(this);
  return this;
};
LinkifyIt.prototype.set = function set2(options2) {
  this.__opts__ = assign5(this.__opts__, options2);
  return this;
};
LinkifyIt.prototype.test = function test(text3) {
  this.__text_cache__ = text3;
  this.__index__ = -1;
  if (!text3.length) {
    return false;
  }
  let m3, ml, me, len, shift2, next2, re2, tld_pos, at_pos;
  if (this.re.schema_test.test(text3)) {
    re2 = this.re.schema_search;
    re2.lastIndex = 0;
    while ((m3 = re2.exec(text3)) !== null) {
      len = this.testSchemaAt(text3, m3[2], re2.lastIndex);
      if (len) {
        this.__schema__ = m3[2];
        this.__index__ = m3.index + m3[1].length;
        this.__last_index__ = m3.index + m3[0].length + len;
        break;
      }
    }
  }
  if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
    tld_pos = text3.search(this.re.host_fuzzy_test);
    if (tld_pos >= 0) {
      if (this.__index__ < 0 || tld_pos < this.__index__) {
        if ((ml = text3.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
          shift2 = ml.index + ml[1].length;
          if (this.__index__ < 0 || shift2 < this.__index__) {
            this.__schema__ = "";
            this.__index__ = shift2;
            this.__last_index__ = ml.index + ml[0].length;
          }
        }
      }
    }
  }
  if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
    at_pos = text3.indexOf("@");
    if (at_pos >= 0) {
      if ((me = text3.match(this.re.email_fuzzy)) !== null) {
        shift2 = me.index + me[1].length;
        next2 = me.index + me[0].length;
        if (this.__index__ < 0 || shift2 < this.__index__ || shift2 === this.__index__ && next2 > this.__last_index__) {
          this.__schema__ = "mailto:";
          this.__index__ = shift2;
          this.__last_index__ = next2;
        }
      }
    }
  }
  return this.__index__ >= 0;
};
LinkifyIt.prototype.pretest = function pretest(text3) {
  return this.re.pretest.test(text3);
};
LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text3, schema7, pos) {
  if (!this.__compiled__[schema7.toLowerCase()]) {
    return 0;
  }
  return this.__compiled__[schema7.toLowerCase()].validate(text3, pos, this);
};
LinkifyIt.prototype.match = function match(text3) {
  const result2 = [];
  let shift2 = 0;
  if (this.__index__ >= 0 && this.__text_cache__ === text3) {
    result2.push(createMatch(this, shift2));
    shift2 = this.__last_index__;
  }
  let tail = shift2 ? text3.slice(shift2) : text3;
  while (this.test(tail)) {
    result2.push(createMatch(this, shift2));
    tail = tail.slice(this.__last_index__);
    shift2 += this.__last_index__;
  }
  if (result2.length) {
    return result2;
  }
  return null;
};
LinkifyIt.prototype.matchAtStart = function matchAtStart(text3) {
  this.__text_cache__ = text3;
  this.__index__ = -1;
  if (!text3.length) return null;
  const m3 = this.re.schema_at_start.exec(text3);
  if (!m3) return null;
  const len = this.testSchemaAt(text3, m3[2], m3[0].length);
  if (!len) return null;
  this.__schema__ = m3[2];
  this.__index__ = m3.index + m3[1].length;
  this.__last_index__ = m3.index + m3[0].length + len;
  return createMatch(this, 0);
};
LinkifyIt.prototype.tlds = function tlds(list2, keepOld) {
  list2 = Array.isArray(list2) ? list2 : [list2];
  if (!keepOld) {
    this.__tlds__ = list2.slice();
    this.__tlds_replaced__ = true;
    compile(this);
    return this;
  }
  this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el2, idx, arr) {
    return el2 !== arr[idx - 1];
  }).reverse();
  compile(this);
  return this;
};
LinkifyIt.prototype.normalize = function normalize2(match2) {
  if (!match2.schema) {
    match2.url = "http://" + match2.url;
  }
  if (match2.schema === "mailto:" && !/^mailto:/i.test(match2.url)) {
    match2.url = "mailto:" + match2.url;
  }
};
LinkifyIt.prototype.onCompile = function onCompile() {
};
var linkify_it_default = LinkifyIt;

// node_modules/punycode.js/punycode.es6.js
var maxInt = 2147483647;
var base2 = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128;
var delimiter = "-";
var regexPunycode = /^xn--/;
var regexNonASCII = /[^\0-\x7F]/;
var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
var errors2 = {
  "overflow": "Overflow: input needs wider integers to process",
  "not-basic": "Illegal input >= 0x80 (not a basic code point)",
  "invalid-input": "Invalid input"
};
var baseMinusTMin = base2 - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;
function error(type) {
  throw new RangeError(errors2[type]);
}
function map2(array, callback) {
  const result2 = [];
  let length = array.length;
  while (length--) {
    result2[length] = callback(array[length]);
  }
  return result2;
}
function mapDomain(domain2, callback) {
  const parts = domain2.split("@");
  let result2 = "";
  if (parts.length > 1) {
    result2 = parts[0] + "@";
    domain2 = parts[1];
  }
  domain2 = domain2.replace(regexSeparators, ".");
  const labels = domain2.split(".");
  const encoded = map2(labels, callback).join(".");
  return result2 + encoded;
}
function ucs2decode2(string3) {
  const output = [];
  let counter3 = 0;
  const length = string3.length;
  while (counter3 < length) {
    const value2 = string3.charCodeAt(counter3++);
    if (value2 >= 55296 && value2 <= 56319 && counter3 < length) {
      const extra = string3.charCodeAt(counter3++);
      if ((extra & 64512) == 56320) {
        output.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output.push(value2);
        counter3--;
      }
    } else {
      output.push(value2);
    }
  }
  return output;
}
var ucs2encode = (codePoints) => String.fromCodePoint(...codePoints);
var basicToDigit = function(codePoint) {
  if (codePoint >= 48 && codePoint < 58) {
    return 26 + (codePoint - 48);
  }
  if (codePoint >= 65 && codePoint < 91) {
    return codePoint - 65;
  }
  if (codePoint >= 97 && codePoint < 123) {
    return codePoint - 97;
  }
  return base2;
};
var digitToBasic = function(digit, flag) {
  return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
var adapt = function(delta, numPoints, firstTime) {
  let k2 = 0;
  delta = firstTime ? floor(delta / damp) : delta >> 1;
  delta += floor(delta / numPoints);
  for (; delta > baseMinusTMin * tMax >> 1; k2 += base2) {
    delta = floor(delta / baseMinusTMin);
  }
  return floor(k2 + (baseMinusTMin + 1) * delta / (delta + skew));
};
var decode2 = function(input) {
  const output = [];
  const inputLength = input.length;
  let i3 = 0;
  let n4 = initialN;
  let bias = initialBias;
  let basic = input.lastIndexOf(delimiter);
  if (basic < 0) {
    basic = 0;
  }
  for (let j = 0; j < basic; ++j) {
    if (input.charCodeAt(j) >= 128) {
      error("not-basic");
    }
    output.push(input.charCodeAt(j));
  }
  for (let index2 = basic > 0 ? basic + 1 : 0; index2 < inputLength; ) {
    const oldi = i3;
    for (let w3 = 1, k2 = base2; ; k2 += base2) {
      if (index2 >= inputLength) {
        error("invalid-input");
      }
      const digit = basicToDigit(input.charCodeAt(index2++));
      if (digit >= base2) {
        error("invalid-input");
      }
      if (digit > floor((maxInt - i3) / w3)) {
        error("overflow");
      }
      i3 += digit * w3;
      const t3 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
      if (digit < t3) {
        break;
      }
      const baseMinusT = base2 - t3;
      if (w3 > floor(maxInt / baseMinusT)) {
        error("overflow");
      }
      w3 *= baseMinusT;
    }
    const out = output.length + 1;
    bias = adapt(i3 - oldi, out, oldi == 0);
    if (floor(i3 / out) > maxInt - n4) {
      error("overflow");
    }
    n4 += floor(i3 / out);
    i3 %= out;
    output.splice(i3++, 0, n4);
  }
  return String.fromCodePoint(...output);
};
var encode2 = function(input) {
  const output = [];
  input = ucs2decode2(input);
  const inputLength = input.length;
  let n4 = initialN;
  let delta = 0;
  let bias = initialBias;
  for (const currentValue of input) {
    if (currentValue < 128) {
      output.push(stringFromCharCode(currentValue));
    }
  }
  const basicLength = output.length;
  let handledCPCount = basicLength;
  if (basicLength) {
    output.push(delimiter);
  }
  while (handledCPCount < inputLength) {
    let m3 = maxInt;
    for (const currentValue of input) {
      if (currentValue >= n4 && currentValue < m3) {
        m3 = currentValue;
      }
    }
    const handledCPCountPlusOne = handledCPCount + 1;
    if (m3 - n4 > floor((maxInt - delta) / handledCPCountPlusOne)) {
      error("overflow");
    }
    delta += (m3 - n4) * handledCPCountPlusOne;
    n4 = m3;
    for (const currentValue of input) {
      if (currentValue < n4 && ++delta > maxInt) {
        error("overflow");
      }
      if (currentValue === n4) {
        let q = delta;
        for (let k2 = base2; ; k2 += base2) {
          const t3 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
          if (q < t3) {
            break;
          }
          const qMinusT = q - t3;
          const baseMinusT = base2 - t3;
          output.push(
            stringFromCharCode(digitToBasic(t3 + qMinusT % baseMinusT, 0))
          );
          q = floor(qMinusT / baseMinusT);
        }
        output.push(stringFromCharCode(digitToBasic(q, 0)));
        bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
        delta = 0;
        ++handledCPCount;
      }
    }
    ++delta;
    ++n4;
  }
  return output.join("");
};
var toUnicode = function(input) {
  return mapDomain(input, function(string3) {
    return regexPunycode.test(string3) ? decode2(string3.slice(4).toLowerCase()) : string3;
  });
};
var toASCII = function(input) {
  return mapDomain(input, function(string3) {
    return regexNonASCII.test(string3) ? "xn--" + encode2(string3) : string3;
  });
};
var punycode = {
  /**
   * A string representing the current Punycode.js version number.
   * @memberOf punycode
   * @type String
   */
  "version": "2.3.1",
  /**
   * An object of methods to convert from JavaScript's internal character
   * representation (UCS-2) to Unicode code points, and back.
   * @see <https://mathiasbynens.be/notes/javascript-encoding>
   * @memberOf punycode
   * @type Object
   */
  "ucs2": {
    "decode": ucs2decode2,
    "encode": ucs2encode
  },
  "decode": decode2,
  "encode": encode2,
  "toASCII": toASCII,
  "toUnicode": toUnicode
};
var punycode_es6_default = punycode;

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/presets/default.mjs
var default_default = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "\u201C\u201D\u2018\u2019",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 100
  },
  components: {
    core: {},
    block: {},
    inline: {}
  }
};

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/presets/zero.mjs
var zero_default = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "\u201C\u201D\u2018\u2019",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "text"
      ],
      rules2: [
        "balance_pairs",
        "fragments_join"
      ]
    }
  }
};

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/presets/commonmark.mjs
var commonmark_default = {
  options: {
    // Enable HTML tags in source
    html: true,
    // Use '/' to close single tags (<br />)
    xhtmlOut: true,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "\u201C\u201D\u2018\u2019",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "blockquote",
        "code",
        "fence",
        "heading",
        "hr",
        "html_block",
        "lheading",
        "list",
        "reference",
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "autolink",
        "backticks",
        "emphasis",
        "entity",
        "escape",
        "html_inline",
        "image",
        "link",
        "newline",
        "text"
      ],
      rules2: [
        "balance_pairs",
        "emphasis",
        "fragments_join"
      ]
    }
  }
};

// node_modules/codemirror-json-schema/node_modules/markdown-it/lib/index.mjs
var config2 = {
  default: default_default,
  zero: zero_default,
  commonmark: commonmark_default
};
var BAD_PROTO_RE = /^(vbscript|javascript|file|data):/;
var GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/;
function validateLink(url2) {
  const str = url2.trim().toLowerCase();
  return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true;
}
var RECODE_HOSTNAME_FOR = ["http:", "https:", "mailto:"];
function normalizeLink(url2) {
  const parsed = parse_default(url2, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode_es6_default.toASCII(parsed.hostname);
      } catch (er) {
      }
    }
  }
  return encode_default(format(parsed));
}
function normalizeLinkText(url2) {
  const parsed = parse_default(url2, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode_es6_default.toUnicode(parsed.hostname);
      } catch (er) {
      }
    }
  }
  return decode_default(format(parsed), decode_default.defaultChars + "%");
}
function MarkdownIt(presetName, options2) {
  if (!(this instanceof MarkdownIt)) {
    return new MarkdownIt(presetName, options2);
  }
  if (!options2) {
    if (!isString3(presetName)) {
      options2 = presetName || {};
      presetName = "default";
    }
  }
  this.inline = new parser_inline_default();
  this.block = new parser_block_default();
  this.core = new parser_core_default();
  this.renderer = new renderer_default();
  this.linkify = new linkify_it_default();
  this.validateLink = validateLink;
  this.normalizeLink = normalizeLink;
  this.normalizeLinkText = normalizeLinkText;
  this.utils = utils_exports;
  this.helpers = assign4({}, helpers_exports);
  this.options = {};
  this.configure(presetName);
  if (options2) {
    this.set(options2);
  }
}
MarkdownIt.prototype.set = function(options2) {
  assign4(this.options, options2);
  return this;
};
MarkdownIt.prototype.configure = function(presets) {
  const self2 = this;
  if (isString3(presets)) {
    const presetName = presets;
    presets = config2[presetName];
    if (!presets) {
      throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
    }
  }
  if (!presets) {
    throw new Error("Wrong `markdown-it` preset, can't be empty");
  }
  if (presets.options) {
    self2.set(presets.options);
  }
  if (presets.components) {
    Object.keys(presets.components).forEach(function(name2) {
      if (presets.components[name2].rules) {
        self2[name2].ruler.enableOnly(presets.components[name2].rules);
      }
      if (presets.components[name2].rules2) {
        self2[name2].ruler2.enableOnly(presets.components[name2].rules2);
      }
    });
  }
  return this;
};
MarkdownIt.prototype.enable = function(list2, ignoreInvalid) {
  let result2 = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain3) {
    result2 = result2.concat(this[chain3].ruler.enable(list2, true));
  }, this);
  result2 = result2.concat(this.inline.ruler2.enable(list2, true));
  const missed = list2.filter(function(name2) {
    return result2.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.disable = function(list2, ignoreInvalid) {
  let result2 = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain3) {
    result2 = result2.concat(this[chain3].ruler.disable(list2, true));
  }, this);
  result2 = result2.concat(this.inline.ruler2.disable(list2, true));
  const missed = list2.filter(function(name2) {
    return result2.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.use = function(plugin) {
  const args = [this].concat(Array.prototype.slice.call(arguments, 1));
  plugin.apply(plugin, args);
  return this;
};
MarkdownIt.prototype.parse = function(src, env) {
  if (typeof src !== "string") {
    throw new Error("Input data should be a String");
  }
  const state = new this.core.State(src, this, env);
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.render = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parse(src, env), this.options, env);
};
MarkdownIt.prototype.parseInline = function(src, env) {
  const state = new this.core.State(src, this, env);
  state.inlineMode = true;
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.renderInline = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parseInline(src, env), this.options, env);
};
var lib_default = MarkdownIt;

// node_modules/@shikijs/markdown-it/dist/core.mjs
function setupMarkdownIt(markdownit3, highlighter, options2) {
  const {
    parseMetaString,
    trimEndingNewline = true,
    defaultLanguage = "text",
    fallbackLanguage
  } = options2;
  const langs = highlighter.getLoadedLanguages();
  markdownit3.options.highlight = (code2, lang2 = "text", attrs2) => {
    if (lang2 === "") {
      lang2 = defaultLanguage;
    }
    if (fallbackLanguage && !langs.includes(lang2)) {
      lang2 = fallbackLanguage;
    }
    const meta2 = parseMetaString?.(attrs2, code2, lang2) || {};
    const codeOptions = {
      ...options2,
      lang: lang2,
      meta: {
        ...options2.meta,
        ...meta2,
        __raw: attrs2
      }
    };
    const builtInTransformer = [];
    builtInTransformer.push({
      name: "@shikijs/markdown-it:block-class",
      code(node) {
        node.properties.class = `language-${lang2}`;
      }
    });
    if (trimEndingNewline) {
      if (code2.endsWith("\n"))
        code2 = code2.slice(0, -1);
    }
    return highlighter.codeToHtml(
      code2,
      {
        ...codeOptions,
        transformers: [
          ...builtInTransformer,
          ...codeOptions.transformers || []
        ]
      }
    );
  };
}
function fromHighlighter(highlighter, options2) {
  return function(markdownit3) {
    setupMarkdownIt(markdownit3, highlighter, options2);
  };
}

// node_modules/@shikijs/types/dist/index.mjs
var ShikiError = class extends Error {
  constructor(message) {
    super(message);
    this.name = "ShikiError";
  }
};

// node_modules/@shikijs/engine-oniguruma/dist/index.mjs
var ShikiError2 = class extends Error {
  constructor(message) {
    super(message);
    this.name = "ShikiError";
  }
};
function getHeapMax() {
  return 2147483648;
}
function _emscripten_get_now() {
  return typeof performance !== "undefined" ? performance.now() : Date.now();
}
var alignUp = (x3, multiple) => x3 + (multiple - x3 % multiple) % multiple;
async function main(init) {
  let wasmMemory;
  let buffer;
  const binding = {};
  function updateGlobalBufferAndViews(buf) {
    buffer = buf;
    binding.HEAPU8 = new Uint8Array(buf);
    binding.HEAPU32 = new Uint32Array(buf);
  }
  function _emscripten_memcpy_big(dest, src, num) {
    binding.HEAPU8.copyWithin(dest, src, src + num);
  }
  function emscripten_realloc_buffer(size4) {
    try {
      wasmMemory.grow(size4 - buffer.byteLength + 65535 >>> 16);
      updateGlobalBufferAndViews(wasmMemory.buffer);
      return 1;
    } catch {
    }
  }
  function _emscripten_resize_heap(requestedSize) {
    const oldSize = binding.HEAPU8.length;
    requestedSize = requestedSize >>> 0;
    const maxHeapSize = getHeapMax();
    if (requestedSize > maxHeapSize)
      return false;
    for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {
      let overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
      overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
      const newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
      const replacement = emscripten_realloc_buffer(newSize);
      if (replacement)
        return true;
    }
    return false;
  }
  const UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;
  function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead = 1024) {
    const endIdx = idx + maxBytesToRead;
    let endPtr = idx;
    while (heapOrArray[endPtr] && !(endPtr >= endIdx))
      ++endPtr;
    if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
      return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
    }
    let str = "";
    while (idx < endPtr) {
      let u0 = heapOrArray[idx++];
      if (!(u0 & 128)) {
        str += String.fromCharCode(u0);
        continue;
      }
      const u1 = heapOrArray[idx++] & 63;
      if ((u0 & 224) === 192) {
        str += String.fromCharCode((u0 & 31) << 6 | u1);
        continue;
      }
      const u22 = heapOrArray[idx++] & 63;
      if ((u0 & 240) === 224) {
        u0 = (u0 & 15) << 12 | u1 << 6 | u22;
      } else {
        u0 = (u0 & 7) << 18 | u1 << 12 | u22 << 6 | heapOrArray[idx++] & 63;
      }
      if (u0 < 65536) {
        str += String.fromCharCode(u0);
      } else {
        const ch = u0 - 65536;
        str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
      }
    }
    return str;
  }
  function UTF8ToString(ptr, maxBytesToRead) {
    return ptr ? UTF8ArrayToString(binding.HEAPU8, ptr, maxBytesToRead) : "";
  }
  const asmLibraryArg = {
    emscripten_get_now: _emscripten_get_now,
    emscripten_memcpy_big: _emscripten_memcpy_big,
    emscripten_resize_heap: _emscripten_resize_heap,
    fd_write: () => 0
  };
  async function createWasm() {
    const info = {
      env: asmLibraryArg,
      wasi_snapshot_preview1: asmLibraryArg
    };
    const exports = await init(info);
    wasmMemory = exports.memory;
    updateGlobalBufferAndViews(wasmMemory.buffer);
    Object.assign(binding, exports);
    binding.UTF8ToString = UTF8ToString;
  }
  await createWasm();
  return binding;
}
var __defProp2 = Object.defineProperty;
var __defNormalProp = (obj, key2, value2) => key2 in obj ? __defProp2(obj, key2, { enumerable: true, configurable: true, writable: true, value: value2 }) : obj[key2] = value2;
var __publicField = (obj, key2, value2) => {
  __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value2);
  return value2;
};
var onigBinding = null;
function throwLastOnigError(onigBinding2) {
  throw new ShikiError2(onigBinding2.UTF8ToString(onigBinding2.getLastOnigError()));
}
var UtfString = class _UtfString {
  constructor(str) {
    __publicField(this, "utf16Length");
    __publicField(this, "utf8Length");
    __publicField(this, "utf16Value");
    __publicField(this, "utf8Value");
    __publicField(this, "utf16OffsetToUtf8");
    __publicField(this, "utf8OffsetToUtf16");
    const utf16Length = str.length;
    const utf8Length = _UtfString._utf8ByteLength(str);
    const computeIndicesMapping = utf8Length !== utf16Length;
    const utf16OffsetToUtf8 = computeIndicesMapping ? new Uint32Array(utf16Length + 1) : null;
    if (computeIndicesMapping)
      utf16OffsetToUtf8[utf16Length] = utf8Length;
    const utf8OffsetToUtf16 = computeIndicesMapping ? new Uint32Array(utf8Length + 1) : null;
    if (computeIndicesMapping)
      utf8OffsetToUtf16[utf8Length] = utf16Length;
    const utf8Value = new Uint8Array(utf8Length);
    let i8 = 0;
    for (let i16 = 0; i16 < utf16Length; i16++) {
      const charCode = str.charCodeAt(i16);
      let codePoint = charCode;
      let wasSurrogatePair = false;
      if (charCode >= 55296 && charCode <= 56319) {
        if (i16 + 1 < utf16Length) {
          const nextCharCode = str.charCodeAt(i16 + 1);
          if (nextCharCode >= 56320 && nextCharCode <= 57343) {
            codePoint = (charCode - 55296 << 10) + 65536 | nextCharCode - 56320;
            wasSurrogatePair = true;
          }
        }
      }
      if (computeIndicesMapping) {
        utf16OffsetToUtf8[i16] = i8;
        if (wasSurrogatePair)
          utf16OffsetToUtf8[i16 + 1] = i8;
        if (codePoint <= 127) {
          utf8OffsetToUtf16[i8 + 0] = i16;
        } else if (codePoint <= 2047) {
          utf8OffsetToUtf16[i8 + 0] = i16;
          utf8OffsetToUtf16[i8 + 1] = i16;
        } else if (codePoint <= 65535) {
          utf8OffsetToUtf16[i8 + 0] = i16;
          utf8OffsetToUtf16[i8 + 1] = i16;
          utf8OffsetToUtf16[i8 + 2] = i16;
        } else {
          utf8OffsetToUtf16[i8 + 0] = i16;
          utf8OffsetToUtf16[i8 + 1] = i16;
          utf8OffsetToUtf16[i8 + 2] = i16;
          utf8OffsetToUtf16[i8 + 3] = i16;
        }
      }
      if (codePoint <= 127) {
        utf8Value[i8++] = codePoint;
      } else if (codePoint <= 2047) {
        utf8Value[i8++] = 192 | (codePoint & 1984) >>> 6;
        utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
      } else if (codePoint <= 65535) {
        utf8Value[i8++] = 224 | (codePoint & 61440) >>> 12;
        utf8Value[i8++] = 128 | (codePoint & 4032) >>> 6;
        utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
      } else {
        utf8Value[i8++] = 240 | (codePoint & 1835008) >>> 18;
        utf8Value[i8++] = 128 | (codePoint & 258048) >>> 12;
        utf8Value[i8++] = 128 | (codePoint & 4032) >>> 6;
        utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
      }
      if (wasSurrogatePair)
        i16++;
    }
    this.utf16Length = utf16Length;
    this.utf8Length = utf8Length;
    this.utf16Value = str;
    this.utf8Value = utf8Value;
    this.utf16OffsetToUtf8 = utf16OffsetToUtf8;
    this.utf8OffsetToUtf16 = utf8OffsetToUtf16;
  }
  static _utf8ByteLength(str) {
    let result2 = 0;
    for (let i3 = 0, len = str.length; i3 < len; i3++) {
      const charCode = str.charCodeAt(i3);
      let codepoint = charCode;
      let wasSurrogatePair = false;
      if (charCode >= 55296 && charCode <= 56319) {
        if (i3 + 1 < len) {
          const nextCharCode = str.charCodeAt(i3 + 1);
          if (nextCharCode >= 56320 && nextCharCode <= 57343) {
            codepoint = (charCode - 55296 << 10) + 65536 | nextCharCode - 56320;
            wasSurrogatePair = true;
          }
        }
      }
      if (codepoint <= 127)
        result2 += 1;
      else if (codepoint <= 2047)
        result2 += 2;
      else if (codepoint <= 65535)
        result2 += 3;
      else
        result2 += 4;
      if (wasSurrogatePair)
        i3++;
    }
    return result2;
  }
  createString(onigBinding2) {
    const result2 = onigBinding2.omalloc(this.utf8Length);
    onigBinding2.HEAPU8.set(this.utf8Value, result2);
    return result2;
  }
};
var _OnigString = class {
  constructor(str) {
    __publicField(this, "id", ++_OnigString.LAST_ID);
    __publicField(this, "_onigBinding");
    __publicField(this, "content");
    __publicField(this, "utf16Length");
    __publicField(this, "utf8Length");
    __publicField(this, "utf16OffsetToUtf8");
    __publicField(this, "utf8OffsetToUtf16");
    __publicField(this, "ptr");
    if (!onigBinding)
      throw new ShikiError2("Must invoke loadWasm first.");
    this._onigBinding = onigBinding;
    this.content = str;
    const utfString = new UtfString(str);
    this.utf16Length = utfString.utf16Length;
    this.utf8Length = utfString.utf8Length;
    this.utf16OffsetToUtf8 = utfString.utf16OffsetToUtf8;
    this.utf8OffsetToUtf16 = utfString.utf8OffsetToUtf16;
    if (this.utf8Length < 1e4 && !_OnigString._sharedPtrInUse) {
      if (!_OnigString._sharedPtr)
        _OnigString._sharedPtr = onigBinding.omalloc(1e4);
      _OnigString._sharedPtrInUse = true;
      onigBinding.HEAPU8.set(utfString.utf8Value, _OnigString._sharedPtr);
      this.ptr = _OnigString._sharedPtr;
    } else {
      this.ptr = utfString.createString(onigBinding);
    }
  }
  convertUtf8OffsetToUtf16(utf8Offset) {
    if (this.utf8OffsetToUtf16) {
      if (utf8Offset < 0)
        return 0;
      if (utf8Offset > this.utf8Length)
        return this.utf16Length;
      return this.utf8OffsetToUtf16[utf8Offset];
    }
    return utf8Offset;
  }
  convertUtf16OffsetToUtf8(utf16Offset) {
    if (this.utf16OffsetToUtf8) {
      if (utf16Offset < 0)
        return 0;
      if (utf16Offset > this.utf16Length)
        return this.utf8Length;
      return this.utf16OffsetToUtf8[utf16Offset];
    }
    return utf16Offset;
  }
  dispose() {
    if (this.ptr === _OnigString._sharedPtr)
      _OnigString._sharedPtrInUse = false;
    else
      this._onigBinding.ofree(this.ptr);
  }
};
var OnigString = _OnigString;
__publicField(OnigString, "LAST_ID", 0);
__publicField(OnigString, "_sharedPtr", 0);
__publicField(OnigString, "_sharedPtrInUse", false);
var OnigScanner = class {
  constructor(patterns) {
    __publicField(this, "_onigBinding");
    __publicField(this, "_ptr");
    if (!onigBinding)
      throw new ShikiError2("Must invoke loadWasm first.");
    const strPtrsArr = [];
    const strLenArr = [];
    for (let i3 = 0, len = patterns.length; i3 < len; i3++) {
      const utfString = new UtfString(patterns[i3]);
      strPtrsArr[i3] = utfString.createString(onigBinding);
      strLenArr[i3] = utfString.utf8Length;
    }
    const strPtrsPtr = onigBinding.omalloc(4 * patterns.length);
    onigBinding.HEAPU32.set(strPtrsArr, strPtrsPtr / 4);
    const strLenPtr = onigBinding.omalloc(4 * patterns.length);
    onigBinding.HEAPU32.set(strLenArr, strLenPtr / 4);
    const scannerPtr = onigBinding.createOnigScanner(strPtrsPtr, strLenPtr, patterns.length);
    for (let i3 = 0, len = patterns.length; i3 < len; i3++)
      onigBinding.ofree(strPtrsArr[i3]);
    onigBinding.ofree(strLenPtr);
    onigBinding.ofree(strPtrsPtr);
    if (scannerPtr === 0)
      throwLastOnigError(onigBinding);
    this._onigBinding = onigBinding;
    this._ptr = scannerPtr;
  }
  dispose() {
    this._onigBinding.freeOnigScanner(this._ptr);
  }
  findNextMatchSync(string3, startPosition, arg) {
    let options2 = 0;
    if (typeof arg === "number") {
      options2 = arg;
    }
    if (typeof string3 === "string") {
      string3 = new OnigString(string3);
      const result2 = this._findNextMatchSync(string3, startPosition, false, options2);
      string3.dispose();
      return result2;
    }
    return this._findNextMatchSync(string3, startPosition, false, options2);
  }
  _findNextMatchSync(string3, startPosition, debugCall, options2) {
    const onigBinding2 = this._onigBinding;
    const resultPtr = onigBinding2.findNextOnigScannerMatch(this._ptr, string3.id, string3.ptr, string3.utf8Length, string3.convertUtf16OffsetToUtf8(startPosition), options2);
    if (resultPtr === 0) {
      return null;
    }
    const HEAPU32 = onigBinding2.HEAPU32;
    let offset = resultPtr / 4;
    const index2 = HEAPU32[offset++];
    const count = HEAPU32[offset++];
    const captureIndices = [];
    for (let i3 = 0; i3 < count; i3++) {
      const beg = string3.convertUtf8OffsetToUtf16(HEAPU32[offset++]);
      const end = string3.convertUtf8OffsetToUtf16(HEAPU32[offset++]);
      captureIndices[i3] = {
        start: beg,
        end,
        length: end - beg
      };
    }
    return {
      index: index2,
      captureIndices
    };
  }
};
function isInstantiatorOptionsObject(dataOrOptions) {
  return typeof dataOrOptions.instantiator === "function";
}
function isInstantiatorModule(dataOrOptions) {
  return typeof dataOrOptions.default === "function";
}
function isDataOptionsObject(dataOrOptions) {
  return typeof dataOrOptions.data !== "undefined";
}
function isResponse(dataOrOptions) {
  return typeof Response !== "undefined" && dataOrOptions instanceof Response;
}
function isArrayBuffer(data2) {
  return typeof ArrayBuffer !== "undefined" && (data2 instanceof ArrayBuffer || ArrayBuffer.isView(data2)) || typeof Buffer !== "undefined" && Buffer.isBuffer?.(data2) || typeof SharedArrayBuffer !== "undefined" && data2 instanceof SharedArrayBuffer || typeof Uint32Array !== "undefined" && data2 instanceof Uint32Array;
}
var initPromise;
function loadWasm(options2) {
  if (initPromise)
    return initPromise;
  async function _load() {
    onigBinding = await main(async (info) => {
      let instance = options2;
      instance = await instance;
      if (typeof instance === "function")
        instance = await instance(info);
      if (typeof instance === "function")
        instance = await instance(info);
      if (isInstantiatorOptionsObject(instance)) {
        instance = await instance.instantiator(info);
      } else if (isInstantiatorModule(instance)) {
        instance = await instance.default(info);
      } else {
        if (isDataOptionsObject(instance))
          instance = instance.data;
        if (isResponse(instance)) {
          if (typeof WebAssembly.instantiateStreaming === "function")
            instance = await _makeResponseStreamingLoader(instance)(info);
          else
            instance = await _makeResponseNonStreamingLoader(instance)(info);
        } else if (isArrayBuffer(instance)) {
          instance = await _makeArrayBufferLoader(instance)(info);
        } else if (instance instanceof WebAssembly.Module) {
          instance = await _makeArrayBufferLoader(instance)(info);
        } else if ("default" in instance && instance.default instanceof WebAssembly.Module) {
          instance = await _makeArrayBufferLoader(instance.default)(info);
        }
      }
      if ("instance" in instance)
        instance = instance.instance;
      if ("exports" in instance)
        instance = instance.exports;
      return instance;
    });
  }
  initPromise = _load();
  return initPromise;
}
function _makeArrayBufferLoader(data2) {
  return (importObject) => WebAssembly.instantiate(data2, importObject);
}
function _makeResponseStreamingLoader(data2) {
  return (importObject) => WebAssembly.instantiateStreaming(data2, importObject);
}
function _makeResponseNonStreamingLoader(data2) {
  return async (importObject) => {
    const arrayBuffer = await data2.arrayBuffer();
    return WebAssembly.instantiate(arrayBuffer, importObject);
  };
}
var _defaultWasmLoader;
function getDefaultWasmLoader() {
  return _defaultWasmLoader;
}
async function createOnigurumaEngine(options2) {
  if (options2)
    await loadWasm(options2);
  return {
    createScanner(patterns) {
      return new OnigScanner(patterns.map((p4) => typeof p4 === "string" ? p4 : p4.source));
    },
    createString(s3) {
      return new OnigString(s3);
    }
  };
}

// node_modules/@shikijs/core/dist/shared/core.Bn_XU0Iv.mjs
var _emitDeprecation = false;
var _emitError = false;
function warnDeprecated(message, version = 3) {
  if (!_emitDeprecation)
    return;
  if (typeof _emitDeprecation === "number" && version > _emitDeprecation)
    return;
  if (_emitError) {
    throw new Error(`[SHIKI DEPRECATE]: ${message}`);
  } else {
    console.trace(`[SHIKI DEPRECATE]: ${message}`);
  }
}

// node_modules/@shikijs/vscode-textmate/dist/index.js
function clone2(something) {
  return doClone(something);
}
function doClone(something) {
  if (Array.isArray(something)) {
    return cloneArray(something);
  }
  if (something instanceof RegExp) {
    return something;
  }
  if (typeof something === "object") {
    return cloneObj(something);
  }
  return something;
}
function cloneArray(arr) {
  let r3 = [];
  for (let i3 = 0, len = arr.length; i3 < len; i3++) {
    r3[i3] = doClone(arr[i3]);
  }
  return r3;
}
function cloneObj(obj) {
  let r3 = {};
  for (let key2 in obj) {
    r3[key2] = doClone(obj[key2]);
  }
  return r3;
}
function mergeObjects(target, ...sources) {
  sources.forEach((source) => {
    for (let key2 in source) {
      target[key2] = source[key2];
    }
  });
  return target;
}
function basename(path) {
  const idx = ~path.lastIndexOf("/") || ~path.lastIndexOf("\\");
  if (idx === 0) {
    return path;
  } else if (~idx === path.length - 1) {
    return basename(path.substring(0, path.length - 1));
  } else {
    return path.substr(~idx + 1);
  }
}
var CAPTURING_REGEX_SOURCE = /\$(\d+)|\${(\d+):\/(downcase|upcase)}/g;
var RegexSource = class {
  static hasCaptures(regexSource) {
    if (regexSource === null) {
      return false;
    }
    CAPTURING_REGEX_SOURCE.lastIndex = 0;
    return CAPTURING_REGEX_SOURCE.test(regexSource);
  }
  static replaceCaptures(regexSource, captureSource, captureIndices) {
    return regexSource.replace(CAPTURING_REGEX_SOURCE, (match2, index2, commandIndex, command2) => {
      let capture = captureIndices[parseInt(index2 || commandIndex, 10)];
      if (capture) {
        let result2 = captureSource.substring(capture.start, capture.end);
        while (result2[0] === ".") {
          result2 = result2.substring(1);
        }
        switch (command2) {
          case "downcase":
            return result2.toLowerCase();
          case "upcase":
            return result2.toUpperCase();
          default:
            return result2;
        }
      } else {
        return match2;
      }
    });
  }
};
function strcmp(a3, b3) {
  if (a3 < b3) {
    return -1;
  }
  if (a3 > b3) {
    return 1;
  }
  return 0;
}
function strArrCmp(a3, b3) {
  if (a3 === null && b3 === null) {
    return 0;
  }
  if (!a3) {
    return -1;
  }
  if (!b3) {
    return 1;
  }
  let len1 = a3.length;
  let len2 = b3.length;
  if (len1 === len2) {
    for (let i3 = 0; i3 < len1; i3++) {
      let res = strcmp(a3[i3], b3[i3]);
      if (res !== 0) {
        return res;
      }
    }
    return 0;
  }
  return len1 - len2;
}
function isValidHexColor(hex) {
  if (/^#[0-9a-f]{6}$/i.test(hex)) {
    return true;
  }
  if (/^#[0-9a-f]{8}$/i.test(hex)) {
    return true;
  }
  if (/^#[0-9a-f]{3}$/i.test(hex)) {
    return true;
  }
  if (/^#[0-9a-f]{4}$/i.test(hex)) {
    return true;
  }
  return false;
}
function escapeRegExpCharacters(value2) {
  return value2.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&");
}
var CachedFn = class {
  constructor(fn) {
    this.fn = fn;
  }
  cache = /* @__PURE__ */ new Map();
  get(key2) {
    if (this.cache.has(key2)) {
      return this.cache.get(key2);
    }
    const value2 = this.fn(key2);
    this.cache.set(key2, value2);
    return value2;
  }
};
var Theme = class {
  constructor(_colorMap, _defaults, _root) {
    this._colorMap = _colorMap;
    this._defaults = _defaults;
    this._root = _root;
  }
  static createFromRawTheme(source, colorMap) {
    return this.createFromParsedTheme(parseTheme(source), colorMap);
  }
  static createFromParsedTheme(source, colorMap) {
    return resolveParsedThemeRules(source, colorMap);
  }
  _cachedMatchRoot = new CachedFn(
    (scopeName) => this._root.match(scopeName)
  );
  getColorMap() {
    return this._colorMap.getColorMap();
  }
  getDefaults() {
    return this._defaults;
  }
  match(scopePath) {
    if (scopePath === null) {
      return this._defaults;
    }
    const scopeName = scopePath.scopeName;
    const matchingTrieElements = this._cachedMatchRoot.get(scopeName);
    const effectiveRule = matchingTrieElements.find(
      (v3) => _scopePathMatchesParentScopes(scopePath.parent, v3.parentScopes)
    );
    if (!effectiveRule) {
      return null;
    }
    return new StyleAttributes(
      effectiveRule.fontStyle,
      effectiveRule.foreground,
      effectiveRule.background
    );
  }
};
var ScopeStack = class _ScopeStack {
  constructor(parent, scopeName) {
    this.parent = parent;
    this.scopeName = scopeName;
  }
  static push(path, scopeNames) {
    for (const name2 of scopeNames) {
      path = new _ScopeStack(path, name2);
    }
    return path;
  }
  static from(...segments) {
    let result2 = null;
    for (let i3 = 0; i3 < segments.length; i3++) {
      result2 = new _ScopeStack(result2, segments[i3]);
    }
    return result2;
  }
  push(scopeName) {
    return new _ScopeStack(this, scopeName);
  }
  getSegments() {
    let item = this;
    const result2 = [];
    while (item) {
      result2.push(item.scopeName);
      item = item.parent;
    }
    result2.reverse();
    return result2;
  }
  toString() {
    return this.getSegments().join(" ");
  }
  extends(other) {
    if (this === other) {
      return true;
    }
    if (this.parent === null) {
      return false;
    }
    return this.parent.extends(other);
  }
  getExtensionIfDefined(base3) {
    const result2 = [];
    let item = this;
    while (item && item !== base3) {
      result2.push(item.scopeName);
      item = item.parent;
    }
    return item === base3 ? result2.reverse() : void 0;
  }
};
function _scopePathMatchesParentScopes(scopePath, parentScopes) {
  if (parentScopes.length === 0) {
    return true;
  }
  for (let index2 = 0; index2 < parentScopes.length; index2++) {
    let scopePattern = parentScopes[index2];
    let scopeMustMatch = false;
    if (scopePattern === ">") {
      if (index2 === parentScopes.length - 1) {
        return false;
      }
      scopePattern = parentScopes[++index2];
      scopeMustMatch = true;
    }
    while (scopePath) {
      if (_matchesScope(scopePath.scopeName, scopePattern)) {
        break;
      }
      if (scopeMustMatch) {
        return false;
      }
      scopePath = scopePath.parent;
    }
    if (!scopePath) {
      return false;
    }
    scopePath = scopePath.parent;
  }
  return true;
}
function _matchesScope(scopeName, scopePattern) {
  return scopePattern === scopeName || scopeName.startsWith(scopePattern) && scopeName[scopePattern.length] === ".";
}
var StyleAttributes = class {
  constructor(fontStyle, foregroundId, backgroundId) {
    this.fontStyle = fontStyle;
    this.foregroundId = foregroundId;
    this.backgroundId = backgroundId;
  }
};
function parseTheme(source) {
  if (!source) {
    return [];
  }
  if (!source.settings || !Array.isArray(source.settings)) {
    return [];
  }
  let settings = source.settings;
  let result2 = [], resultLen = 0;
  for (let i3 = 0, len = settings.length; i3 < len; i3++) {
    let entry = settings[i3];
    if (!entry.settings) {
      continue;
    }
    let scopes;
    if (typeof entry.scope === "string") {
      let _scope = entry.scope;
      _scope = _scope.replace(/^[,]+/, "");
      _scope = _scope.replace(/[,]+$/, "");
      scopes = _scope.split(",");
    } else if (Array.isArray(entry.scope)) {
      scopes = entry.scope;
    } else {
      scopes = [""];
    }
    let fontStyle = -1;
    if (typeof entry.settings.fontStyle === "string") {
      fontStyle = 0;
      let segments = entry.settings.fontStyle.split(" ");
      for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
        let segment = segments[j];
        switch (segment) {
          case "italic":
            fontStyle = fontStyle | 1;
            break;
          case "bold":
            fontStyle = fontStyle | 2;
            break;
          case "underline":
            fontStyle = fontStyle | 4;
            break;
          case "strikethrough":
            fontStyle = fontStyle | 8;
            break;
        }
      }
    }
    let foreground = null;
    if (typeof entry.settings.foreground === "string" && isValidHexColor(entry.settings.foreground)) {
      foreground = entry.settings.foreground;
    }
    let background = null;
    if (typeof entry.settings.background === "string" && isValidHexColor(entry.settings.background)) {
      background = entry.settings.background;
    }
    for (let j = 0, lenJ = scopes.length; j < lenJ; j++) {
      let _scope = scopes[j].trim();
      let segments = _scope.split(" ");
      let scope = segments[segments.length - 1];
      let parentScopes = null;
      if (segments.length > 1) {
        parentScopes = segments.slice(0, segments.length - 1);
        parentScopes.reverse();
      }
      result2[resultLen++] = new ParsedThemeRule(
        scope,
        parentScopes,
        i3,
        fontStyle,
        foreground,
        background
      );
    }
  }
  return result2;
}
var ParsedThemeRule = class {
  constructor(scope, parentScopes, index2, fontStyle, foreground, background) {
    this.scope = scope;
    this.parentScopes = parentScopes;
    this.index = index2;
    this.fontStyle = fontStyle;
    this.foreground = foreground;
    this.background = background;
  }
};
var FontStyle = /* @__PURE__ */ ((FontStyle2) => {
  FontStyle2[FontStyle2["NotSet"] = -1] = "NotSet";
  FontStyle2[FontStyle2["None"] = 0] = "None";
  FontStyle2[FontStyle2["Italic"] = 1] = "Italic";
  FontStyle2[FontStyle2["Bold"] = 2] = "Bold";
  FontStyle2[FontStyle2["Underline"] = 4] = "Underline";
  FontStyle2[FontStyle2["Strikethrough"] = 8] = "Strikethrough";
  return FontStyle2;
})(FontStyle || {});
function resolveParsedThemeRules(parsedThemeRules, _colorMap) {
  parsedThemeRules.sort((a3, b3) => {
    let r3 = strcmp(a3.scope, b3.scope);
    if (r3 !== 0) {
      return r3;
    }
    r3 = strArrCmp(a3.parentScopes, b3.parentScopes);
    if (r3 !== 0) {
      return r3;
    }
    return a3.index - b3.index;
  });
  let defaultFontStyle = 0;
  let defaultForeground = "#000000";
  let defaultBackground = "#ffffff";
  while (parsedThemeRules.length >= 1 && parsedThemeRules[0].scope === "") {
    let incomingDefaults = parsedThemeRules.shift();
    if (incomingDefaults.fontStyle !== -1) {
      defaultFontStyle = incomingDefaults.fontStyle;
    }
    if (incomingDefaults.foreground !== null) {
      defaultForeground = incomingDefaults.foreground;
    }
    if (incomingDefaults.background !== null) {
      defaultBackground = incomingDefaults.background;
    }
  }
  let colorMap = new ColorMap(_colorMap);
  let defaults5 = new StyleAttributes(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));
  let root3 = new ThemeTrieElement(new ThemeTrieElementRule(0, null, -1, 0, 0), []);
  for (let i3 = 0, len = parsedThemeRules.length; i3 < len; i3++) {
    let rule = parsedThemeRules[i3];
    root3.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
  }
  return new Theme(colorMap, defaults5, root3);
}
var ColorMap = class {
  _isFrozen;
  _lastColorId;
  _id2color;
  _color2id;
  constructor(_colorMap) {
    this._lastColorId = 0;
    this._id2color = [];
    this._color2id = /* @__PURE__ */ Object.create(null);
    if (Array.isArray(_colorMap)) {
      this._isFrozen = true;
      for (let i3 = 0, len = _colorMap.length; i3 < len; i3++) {
        this._color2id[_colorMap[i3]] = i3;
        this._id2color[i3] = _colorMap[i3];
      }
    } else {
      this._isFrozen = false;
    }
  }
  getId(color) {
    if (color === null) {
      return 0;
    }
    color = color.toUpperCase();
    let value2 = this._color2id[color];
    if (value2) {
      return value2;
    }
    if (this._isFrozen) {
      throw new Error(`Missing color in color map - ${color}`);
    }
    value2 = ++this._lastColorId;
    this._color2id[color] = value2;
    this._id2color[value2] = color;
    return value2;
  }
  getColorMap() {
    return this._id2color.slice(0);
  }
};
var emptyParentScopes = Object.freeze([]);
var ThemeTrieElementRule = class _ThemeTrieElementRule {
  scopeDepth;
  parentScopes;
  fontStyle;
  foreground;
  background;
  constructor(scopeDepth, parentScopes, fontStyle, foreground, background) {
    this.scopeDepth = scopeDepth;
    this.parentScopes = parentScopes || emptyParentScopes;
    this.fontStyle = fontStyle;
    this.foreground = foreground;
    this.background = background;
  }
  clone() {
    return new _ThemeTrieElementRule(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);
  }
  static cloneArr(arr) {
    let r3 = [];
    for (let i3 = 0, len = arr.length; i3 < len; i3++) {
      r3[i3] = arr[i3].clone();
    }
    return r3;
  }
  acceptOverwrite(scopeDepth, fontStyle, foreground, background) {
    if (this.scopeDepth > scopeDepth) {
      console.log("how did this happen?");
    } else {
      this.scopeDepth = scopeDepth;
    }
    if (fontStyle !== -1) {
      this.fontStyle = fontStyle;
    }
    if (foreground !== 0) {
      this.foreground = foreground;
    }
    if (background !== 0) {
      this.background = background;
    }
  }
};
var ThemeTrieElement = class _ThemeTrieElement {
  constructor(_mainRule, rulesWithParentScopes = [], _children = {}) {
    this._mainRule = _mainRule;
    this._children = _children;
    this._rulesWithParentScopes = rulesWithParentScopes;
  }
  _rulesWithParentScopes;
  static _cmpBySpecificity(a3, b3) {
    if (a3.scopeDepth !== b3.scopeDepth) {
      return b3.scopeDepth - a3.scopeDepth;
    }
    let aParentIndex = 0;
    let bParentIndex = 0;
    while (true) {
      if (a3.parentScopes[aParentIndex] === ">") {
        aParentIndex++;
      }
      if (b3.parentScopes[bParentIndex] === ">") {
        bParentIndex++;
      }
      if (aParentIndex >= a3.parentScopes.length || bParentIndex >= b3.parentScopes.length) {
        break;
      }
      const parentScopeLengthDiff = b3.parentScopes[bParentIndex].length - a3.parentScopes[aParentIndex].length;
      if (parentScopeLengthDiff !== 0) {
        return parentScopeLengthDiff;
      }
      aParentIndex++;
      bParentIndex++;
    }
    return b3.parentScopes.length - a3.parentScopes.length;
  }
  match(scope) {
    if (scope !== "") {
      let dotIndex = scope.indexOf(".");
      let head2;
      let tail;
      if (dotIndex === -1) {
        head2 = scope;
        tail = "";
      } else {
        head2 = scope.substring(0, dotIndex);
        tail = scope.substring(dotIndex + 1);
      }
      if (this._children.hasOwnProperty(head2)) {
        return this._children[head2].match(tail);
      }
    }
    const rules = this._rulesWithParentScopes.concat(this._mainRule);
    rules.sort(_ThemeTrieElement._cmpBySpecificity);
    return rules;
  }
  insert(scopeDepth, scope, parentScopes, fontStyle, foreground, background) {
    if (scope === "") {
      this._doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background);
      return;
    }
    let dotIndex = scope.indexOf(".");
    let head2;
    let tail;
    if (dotIndex === -1) {
      head2 = scope;
      tail = "";
    } else {
      head2 = scope.substring(0, dotIndex);
      tail = scope.substring(dotIndex + 1);
    }
    let child;
    if (this._children.hasOwnProperty(head2)) {
      child = this._children[head2];
    } else {
      child = new _ThemeTrieElement(this._mainRule.clone(), ThemeTrieElementRule.cloneArr(this._rulesWithParentScopes));
      this._children[head2] = child;
    }
    child.insert(scopeDepth + 1, tail, parentScopes, fontStyle, foreground, background);
  }
  _doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background) {
    if (parentScopes === null) {
      this._mainRule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);
      return;
    }
    for (let i3 = 0, len = this._rulesWithParentScopes.length; i3 < len; i3++) {
      let rule = this._rulesWithParentScopes[i3];
      if (strArrCmp(rule.parentScopes, parentScopes) === 0) {
        rule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);
        return;
      }
    }
    if (fontStyle === -1) {
      fontStyle = this._mainRule.fontStyle;
    }
    if (foreground === 0) {
      foreground = this._mainRule.foreground;
    }
    if (background === 0) {
      background = this._mainRule.background;
    }
    this._rulesWithParentScopes.push(new ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background));
  }
};
var EncodedTokenMetadata = class _EncodedTokenMetadata {
  static toBinaryStr(encodedTokenAttributes) {
    return encodedTokenAttributes.toString(2).padStart(32, "0");
  }
  static print(encodedTokenAttributes) {
    const languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);
    const tokenType2 = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);
    const fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);
    const foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);
    const background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);
    console.log({
      languageId,
      tokenType: tokenType2,
      fontStyle,
      foreground,
      background
    });
  }
  static getLanguageId(encodedTokenAttributes) {
    return (encodedTokenAttributes & 255) >>> 0;
  }
  static getTokenType(encodedTokenAttributes) {
    return (encodedTokenAttributes & 768) >>> 8;
  }
  static containsBalancedBrackets(encodedTokenAttributes) {
    return (encodedTokenAttributes & 1024) !== 0;
  }
  static getFontStyle(encodedTokenAttributes) {
    return (encodedTokenAttributes & 30720) >>> 11;
  }
  static getForeground(encodedTokenAttributes) {
    return (encodedTokenAttributes & 16744448) >>> 15;
  }
  static getBackground(encodedTokenAttributes) {
    return (encodedTokenAttributes & 4278190080) >>> 24;
  }
  /**
   * Updates the fields in `metadata`.
   * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.
   */
  static set(encodedTokenAttributes, languageId, tokenType2, containsBalancedBrackets, fontStyle, foreground, background) {
    let _languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);
    let _tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);
    let _containsBalancedBracketsBit = _EncodedTokenMetadata.containsBalancedBrackets(encodedTokenAttributes) ? 1 : 0;
    let _fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);
    let _foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);
    let _background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);
    if (languageId !== 0) {
      _languageId = languageId;
    }
    if (tokenType2 !== 8) {
      _tokenType = fromOptionalTokenType(tokenType2);
    }
    if (containsBalancedBrackets !== null) {
      _containsBalancedBracketsBit = containsBalancedBrackets ? 1 : 0;
    }
    if (fontStyle !== -1) {
      _fontStyle = fontStyle;
    }
    if (foreground !== 0) {
      _foreground = foreground;
    }
    if (background !== 0) {
      _background = background;
    }
    return (_languageId << 0 | _tokenType << 8 | _containsBalancedBracketsBit << 10 | _fontStyle << 11 | _foreground << 15 | _background << 24) >>> 0;
  }
};
function toOptionalTokenType(standardType) {
  return standardType;
}
function fromOptionalTokenType(standardType) {
  return standardType;
}
function createMatchers(selector, matchesName) {
  const results2 = [];
  const tokenizer = newTokenizer(selector);
  let token = tokenizer.next();
  while (token !== null) {
    let priority = 0;
    if (token.length === 2 && token.charAt(1) === ":") {
      switch (token.charAt(0)) {
        case "R":
          priority = 1;
          break;
        case "L":
          priority = -1;
          break;
        default:
          console.log(`Unknown priority ${token} in scope selector`);
      }
      token = tokenizer.next();
    }
    let matcher2 = parseConjunction();
    results2.push({ matcher: matcher2, priority });
    if (token !== ",") {
      break;
    }
    token = tokenizer.next();
  }
  return results2;
  function parseOperand() {
    if (token === "-") {
      token = tokenizer.next();
      const expressionToNegate = parseOperand();
      return (matcherInput) => !!expressionToNegate && !expressionToNegate(matcherInput);
    }
    if (token === "(") {
      token = tokenizer.next();
      const expressionInParents = parseInnerExpression();
      if (token === ")") {
        token = tokenizer.next();
      }
      return expressionInParents;
    }
    if (isIdentifier(token)) {
      const identifiers = [];
      do {
        identifiers.push(token);
        token = tokenizer.next();
      } while (isIdentifier(token));
      return (matcherInput) => matchesName(identifiers, matcherInput);
    }
    return null;
  }
  function parseConjunction() {
    const matchers = [];
    let matcher2 = parseOperand();
    while (matcher2) {
      matchers.push(matcher2);
      matcher2 = parseOperand();
    }
    return (matcherInput) => matchers.every((matcher22) => matcher22(matcherInput));
  }
  function parseInnerExpression() {
    const matchers = [];
    let matcher2 = parseConjunction();
    while (matcher2) {
      matchers.push(matcher2);
      if (token === "|" || token === ",") {
        do {
          token = tokenizer.next();
        } while (token === "|" || token === ",");
      } else {
        break;
      }
      matcher2 = parseConjunction();
    }
    return (matcherInput) => matchers.some((matcher22) => matcher22(matcherInput));
  }
}
function isIdentifier(token) {
  return !!token && !!token.match(/[\w\.:]+/);
}
function newTokenizer(input) {
  let regex = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g;
  let match2 = regex.exec(input);
  return {
    next: () => {
      if (!match2) {
        return null;
      }
      const res = match2[0];
      match2 = regex.exec(input);
      return res;
    }
  };
}
function disposeOnigString(str) {
  if (typeof str.dispose === "function") {
    str.dispose();
  }
}
var TopLevelRuleReference = class {
  constructor(scopeName) {
    this.scopeName = scopeName;
  }
  toKey() {
    return this.scopeName;
  }
};
var TopLevelRepositoryRuleReference = class {
  constructor(scopeName, ruleName) {
    this.scopeName = scopeName;
    this.ruleName = ruleName;
  }
  toKey() {
    return `${this.scopeName}#${this.ruleName}`;
  }
};
var ExternalReferenceCollector = class {
  _references = [];
  _seenReferenceKeys = /* @__PURE__ */ new Set();
  get references() {
    return this._references;
  }
  visitedRule = /* @__PURE__ */ new Set();
  add(reference2) {
    const key2 = reference2.toKey();
    if (this._seenReferenceKeys.has(key2)) {
      return;
    }
    this._seenReferenceKeys.add(key2);
    this._references.push(reference2);
  }
};
var ScopeDependencyProcessor = class {
  constructor(repo, initialScopeName) {
    this.repo = repo;
    this.initialScopeName = initialScopeName;
    this.seenFullScopeRequests.add(this.initialScopeName);
    this.Q = [new TopLevelRuleReference(this.initialScopeName)];
  }
  seenFullScopeRequests = /* @__PURE__ */ new Set();
  seenPartialScopeRequests = /* @__PURE__ */ new Set();
  Q;
  processQueue() {
    const q = this.Q;
    this.Q = [];
    const deps = new ExternalReferenceCollector();
    for (const dep of q) {
      collectReferencesOfReference(dep, this.initialScopeName, this.repo, deps);
    }
    for (const dep of deps.references) {
      if (dep instanceof TopLevelRuleReference) {
        if (this.seenFullScopeRequests.has(dep.scopeName)) {
          continue;
        }
        this.seenFullScopeRequests.add(dep.scopeName);
        this.Q.push(dep);
      } else {
        if (this.seenFullScopeRequests.has(dep.scopeName)) {
          continue;
        }
        if (this.seenPartialScopeRequests.has(dep.toKey())) {
          continue;
        }
        this.seenPartialScopeRequests.add(dep.toKey());
        this.Q.push(dep);
      }
    }
  }
};
function collectReferencesOfReference(reference2, baseGrammarScopeName, repo, result2) {
  const selfGrammar = repo.lookup(reference2.scopeName);
  if (!selfGrammar) {
    if (reference2.scopeName === baseGrammarScopeName) {
      throw new Error(`No grammar provided for <${baseGrammarScopeName}>`);
    }
    return;
  }
  const baseGrammar = repo.lookup(baseGrammarScopeName);
  if (reference2 instanceof TopLevelRuleReference) {
    collectExternalReferencesInTopLevelRule({ baseGrammar, selfGrammar }, result2);
  } else {
    collectExternalReferencesInTopLevelRepositoryRule(
      reference2.ruleName,
      { baseGrammar, selfGrammar, repository: selfGrammar.repository },
      result2
    );
  }
  const injections = repo.injections(reference2.scopeName);
  if (injections) {
    for (const injection of injections) {
      result2.add(new TopLevelRuleReference(injection));
    }
  }
}
function collectExternalReferencesInTopLevelRepositoryRule(ruleName, context, result2) {
  if (context.repository && context.repository[ruleName]) {
    const rule = context.repository[ruleName];
    collectExternalReferencesInRules([rule], context, result2);
  }
}
function collectExternalReferencesInTopLevelRule(context, result2) {
  if (context.selfGrammar.patterns && Array.isArray(context.selfGrammar.patterns)) {
    collectExternalReferencesInRules(
      context.selfGrammar.patterns,
      { ...context, repository: context.selfGrammar.repository },
      result2
    );
  }
  if (context.selfGrammar.injections) {
    collectExternalReferencesInRules(
      Object.values(context.selfGrammar.injections),
      { ...context, repository: context.selfGrammar.repository },
      result2
    );
  }
}
function collectExternalReferencesInRules(rules, context, result2) {
  for (const rule of rules) {
    if (result2.visitedRule.has(rule)) {
      continue;
    }
    result2.visitedRule.add(rule);
    const patternRepository = rule.repository ? mergeObjects({}, context.repository, rule.repository) : context.repository;
    if (Array.isArray(rule.patterns)) {
      collectExternalReferencesInRules(rule.patterns, { ...context, repository: patternRepository }, result2);
    }
    const include = rule.include;
    if (!include) {
      continue;
    }
    const reference2 = parseInclude(include);
    switch (reference2.kind) {
      case 0:
        collectExternalReferencesInTopLevelRule({ ...context, selfGrammar: context.baseGrammar }, result2);
        break;
      case 1:
        collectExternalReferencesInTopLevelRule(context, result2);
        break;
      case 2:
        collectExternalReferencesInTopLevelRepositoryRule(reference2.ruleName, { ...context, repository: patternRepository }, result2);
        break;
      case 3:
      case 4:
        const selfGrammar = reference2.scopeName === context.selfGrammar.scopeName ? context.selfGrammar : reference2.scopeName === context.baseGrammar.scopeName ? context.baseGrammar : void 0;
        if (selfGrammar) {
          const newContext = { baseGrammar: context.baseGrammar, selfGrammar, repository: patternRepository };
          if (reference2.kind === 4) {
            collectExternalReferencesInTopLevelRepositoryRule(reference2.ruleName, newContext, result2);
          } else {
            collectExternalReferencesInTopLevelRule(newContext, result2);
          }
        } else {
          if (reference2.kind === 4) {
            result2.add(new TopLevelRepositoryRuleReference(reference2.scopeName, reference2.ruleName));
          } else {
            result2.add(new TopLevelRuleReference(reference2.scopeName));
          }
        }
        break;
    }
  }
}
var BaseReference = class {
  kind = 0;
};
var SelfReference = class {
  kind = 1;
};
var RelativeReference = class {
  constructor(ruleName) {
    this.ruleName = ruleName;
  }
  kind = 2;
};
var TopLevelReference = class {
  constructor(scopeName) {
    this.scopeName = scopeName;
  }
  kind = 3;
};
var TopLevelRepositoryReference = class {
  constructor(scopeName, ruleName) {
    this.scopeName = scopeName;
    this.ruleName = ruleName;
  }
  kind = 4;
};
function parseInclude(include) {
  if (include === "$base") {
    return new BaseReference();
  } else if (include === "$self") {
    return new SelfReference();
  }
  const indexOfSharp = include.indexOf("#");
  if (indexOfSharp === -1) {
    return new TopLevelReference(include);
  } else if (indexOfSharp === 0) {
    return new RelativeReference(include.substring(1));
  } else {
    const scopeName = include.substring(0, indexOfSharp);
    const ruleName = include.substring(indexOfSharp + 1);
    return new TopLevelRepositoryReference(scopeName, ruleName);
  }
}
var HAS_BACK_REFERENCES = /\\(\d+)/;
var BACK_REFERENCING_END = /\\(\d+)/g;
var ruleIdSymbol = Symbol("RuleId");
var endRuleId = -1;
var whileRuleId = -2;
function ruleIdFromNumber(id) {
  return id;
}
function ruleIdToNumber(id) {
  return id;
}
var Rule2 = class {
  $location;
  id;
  _nameIsCapturing;
  _name;
  _contentNameIsCapturing;
  _contentName;
  constructor($location, id, name2, contentName) {
    this.$location = $location;
    this.id = id;
    this._name = name2 || null;
    this._nameIsCapturing = RegexSource.hasCaptures(this._name);
    this._contentName = contentName || null;
    this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName);
  }
  get debugName() {
    const location2 = this.$location ? `${basename(this.$location.filename)}:${this.$location.line}` : "unknown";
    return `${this.constructor.name}#${this.id} @ ${location2}`;
  }
  getName(lineText, captureIndices) {
    if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) {
      return this._name;
    }
    return RegexSource.replaceCaptures(this._name, lineText, captureIndices);
  }
  getContentName(lineText, captureIndices) {
    if (!this._contentNameIsCapturing || this._contentName === null) {
      return this._contentName;
    }
    return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices);
  }
};
var CaptureRule = class extends Rule2 {
  retokenizeCapturedWithRuleId;
  constructor($location, id, name2, contentName, retokenizeCapturedWithRuleId) {
    super($location, id, name2, contentName);
    this.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId;
  }
  dispose() {
  }
  collectPatterns(grammar, out) {
    throw new Error("Not supported!");
  }
  compile(grammar, endRegexSource) {
    throw new Error("Not supported!");
  }
  compileAG(grammar, endRegexSource, allowA, allowG) {
    throw new Error("Not supported!");
  }
};
var MatchRule = class extends Rule2 {
  _match;
  captures;
  _cachedCompiledPatterns;
  constructor($location, id, name2, match2, captures) {
    super($location, id, name2, null);
    this._match = new RegExpSource(match2, this.id);
    this.captures = captures;
    this._cachedCompiledPatterns = null;
  }
  dispose() {
    if (this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns.dispose();
      this._cachedCompiledPatterns = null;
    }
  }
  get debugMatchRegExp() {
    return `${this._match.source}`;
  }
  collectPatterns(grammar, out) {
    out.push(this._match);
  }
  compile(grammar, endRegexSource) {
    return this._getCachedCompiledPatterns(grammar).compile(grammar);
  }
  compileAG(grammar, endRegexSource, allowA, allowG) {
    return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
  }
  _getCachedCompiledPatterns(grammar) {
    if (!this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns = new RegExpSourceList();
      this.collectPatterns(grammar, this._cachedCompiledPatterns);
    }
    return this._cachedCompiledPatterns;
  }
};
var IncludeOnlyRule = class extends Rule2 {
  hasMissingPatterns;
  patterns;
  _cachedCompiledPatterns;
  constructor($location, id, name2, contentName, patterns) {
    super($location, id, name2, contentName);
    this.patterns = patterns.patterns;
    this.hasMissingPatterns = patterns.hasMissingPatterns;
    this._cachedCompiledPatterns = null;
  }
  dispose() {
    if (this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns.dispose();
      this._cachedCompiledPatterns = null;
    }
  }
  collectPatterns(grammar, out) {
    for (const pattern2 of this.patterns) {
      const rule = grammar.getRule(pattern2);
      rule.collectPatterns(grammar, out);
    }
  }
  compile(grammar, endRegexSource) {
    return this._getCachedCompiledPatterns(grammar).compile(grammar);
  }
  compileAG(grammar, endRegexSource, allowA, allowG) {
    return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
  }
  _getCachedCompiledPatterns(grammar) {
    if (!this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns = new RegExpSourceList();
      this.collectPatterns(grammar, this._cachedCompiledPatterns);
    }
    return this._cachedCompiledPatterns;
  }
};
var BeginEndRule = class extends Rule2 {
  _begin;
  beginCaptures;
  _end;
  endHasBackReferences;
  endCaptures;
  applyEndPatternLast;
  hasMissingPatterns;
  patterns;
  _cachedCompiledPatterns;
  constructor($location, id, name2, contentName, begin, beginCaptures, end, endCaptures, applyEndPatternLast, patterns) {
    super($location, id, name2, contentName);
    this._begin = new RegExpSource(begin, this.id);
    this.beginCaptures = beginCaptures;
    this._end = new RegExpSource(end ? end : "\uFFFF", -1);
    this.endHasBackReferences = this._end.hasBackReferences;
    this.endCaptures = endCaptures;
    this.applyEndPatternLast = applyEndPatternLast || false;
    this.patterns = patterns.patterns;
    this.hasMissingPatterns = patterns.hasMissingPatterns;
    this._cachedCompiledPatterns = null;
  }
  dispose() {
    if (this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns.dispose();
      this._cachedCompiledPatterns = null;
    }
  }
  get debugBeginRegExp() {
    return `${this._begin.source}`;
  }
  get debugEndRegExp() {
    return `${this._end.source}`;
  }
  getEndWithResolvedBackReferences(lineText, captureIndices) {
    return this._end.resolveBackReferences(lineText, captureIndices);
  }
  collectPatterns(grammar, out) {
    out.push(this._begin);
  }
  compile(grammar, endRegexSource) {
    return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar);
  }
  compileAG(grammar, endRegexSource, allowA, allowG) {
    return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);
  }
  _getCachedCompiledPatterns(grammar, endRegexSource) {
    if (!this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns = new RegExpSourceList();
      for (const pattern2 of this.patterns) {
        const rule = grammar.getRule(pattern2);
        rule.collectPatterns(grammar, this._cachedCompiledPatterns);
      }
      if (this.applyEndPatternLast) {
        this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end);
      } else {
        this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);
      }
    }
    if (this._end.hasBackReferences) {
      if (this.applyEndPatternLast) {
        this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource);
      } else {
        this._cachedCompiledPatterns.setSource(0, endRegexSource);
      }
    }
    return this._cachedCompiledPatterns;
  }
};
var BeginWhileRule = class extends Rule2 {
  _begin;
  beginCaptures;
  whileCaptures;
  _while;
  whileHasBackReferences;
  hasMissingPatterns;
  patterns;
  _cachedCompiledPatterns;
  _cachedCompiledWhilePatterns;
  constructor($location, id, name2, contentName, begin, beginCaptures, _while, whileCaptures, patterns) {
    super($location, id, name2, contentName);
    this._begin = new RegExpSource(begin, this.id);
    this.beginCaptures = beginCaptures;
    this.whileCaptures = whileCaptures;
    this._while = new RegExpSource(_while, whileRuleId);
    this.whileHasBackReferences = this._while.hasBackReferences;
    this.patterns = patterns.patterns;
    this.hasMissingPatterns = patterns.hasMissingPatterns;
    this._cachedCompiledPatterns = null;
    this._cachedCompiledWhilePatterns = null;
  }
  dispose() {
    if (this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns.dispose();
      this._cachedCompiledPatterns = null;
    }
    if (this._cachedCompiledWhilePatterns) {
      this._cachedCompiledWhilePatterns.dispose();
      this._cachedCompiledWhilePatterns = null;
    }
  }
  get debugBeginRegExp() {
    return `${this._begin.source}`;
  }
  get debugWhileRegExp() {
    return `${this._while.source}`;
  }
  getWhileWithResolvedBackReferences(lineText, captureIndices) {
    return this._while.resolveBackReferences(lineText, captureIndices);
  }
  collectPatterns(grammar, out) {
    out.push(this._begin);
  }
  compile(grammar, endRegexSource) {
    return this._getCachedCompiledPatterns(grammar).compile(grammar);
  }
  compileAG(grammar, endRegexSource, allowA, allowG) {
    return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
  }
  _getCachedCompiledPatterns(grammar) {
    if (!this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns = new RegExpSourceList();
      for (const pattern2 of this.patterns) {
        const rule = grammar.getRule(pattern2);
        rule.collectPatterns(grammar, this._cachedCompiledPatterns);
      }
    }
    return this._cachedCompiledPatterns;
  }
  compileWhile(grammar, endRegexSource) {
    return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar);
  }
  compileWhileAG(grammar, endRegexSource, allowA, allowG) {
    return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);
  }
  _getCachedCompiledWhilePatterns(grammar, endRegexSource) {
    if (!this._cachedCompiledWhilePatterns) {
      this._cachedCompiledWhilePatterns = new RegExpSourceList();
      this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while);
    }
    if (this._while.hasBackReferences) {
      this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : "\uFFFF");
    }
    return this._cachedCompiledWhilePatterns;
  }
};
var RuleFactory = class _RuleFactory {
  static createCaptureRule(helper, $location, name2, contentName, retokenizeCapturedWithRuleId) {
    return helper.registerRule((id) => {
      return new CaptureRule($location, id, name2, contentName, retokenizeCapturedWithRuleId);
    });
  }
  static getCompiledRuleId(desc, helper, repository) {
    if (!desc.id) {
      helper.registerRule((id) => {
        desc.id = id;
        if (desc.match) {
          return new MatchRule(
            desc.$vscodeTextmateLocation,
            desc.id,
            desc.name,
            desc.match,
            _RuleFactory._compileCaptures(desc.captures, helper, repository)
          );
        }
        if (typeof desc.begin === "undefined") {
          if (desc.repository) {
            repository = mergeObjects({}, repository, desc.repository);
          }
          let patterns = desc.patterns;
          if (typeof patterns === "undefined" && desc.include) {
            patterns = [{ include: desc.include }];
          }
          return new IncludeOnlyRule(
            desc.$vscodeTextmateLocation,
            desc.id,
            desc.name,
            desc.contentName,
            _RuleFactory._compilePatterns(patterns, helper, repository)
          );
        }
        if (desc.while) {
          return new BeginWhileRule(
            desc.$vscodeTextmateLocation,
            desc.id,
            desc.name,
            desc.contentName,
            desc.begin,
            _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),
            desc.while,
            _RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository),
            _RuleFactory._compilePatterns(desc.patterns, helper, repository)
          );
        }
        return new BeginEndRule(
          desc.$vscodeTextmateLocation,
          desc.id,
          desc.name,
          desc.contentName,
          desc.begin,
          _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),
          desc.end,
          _RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository),
          desc.applyEndPatternLast,
          _RuleFactory._compilePatterns(desc.patterns, helper, repository)
        );
      });
    }
    return desc.id;
  }
  static _compileCaptures(captures, helper, repository) {
    let r3 = [];
    if (captures) {
      let maximumCaptureId = 0;
      for (const captureId in captures) {
        if (captureId === "$vscodeTextmateLocation") {
          continue;
        }
        const numericCaptureId = parseInt(captureId, 10);
        if (numericCaptureId > maximumCaptureId) {
          maximumCaptureId = numericCaptureId;
        }
      }
      for (let i3 = 0; i3 <= maximumCaptureId; i3++) {
        r3[i3] = null;
      }
      for (const captureId in captures) {
        if (captureId === "$vscodeTextmateLocation") {
          continue;
        }
        const numericCaptureId = parseInt(captureId, 10);
        let retokenizeCapturedWithRuleId = 0;
        if (captures[captureId].patterns) {
          retokenizeCapturedWithRuleId = _RuleFactory.getCompiledRuleId(captures[captureId], helper, repository);
        }
        r3[numericCaptureId] = _RuleFactory.createCaptureRule(helper, captures[captureId].$vscodeTextmateLocation, captures[captureId].name, captures[captureId].contentName, retokenizeCapturedWithRuleId);
      }
    }
    return r3;
  }
  static _compilePatterns(patterns, helper, repository) {
    let r3 = [];
    if (patterns) {
      for (let i3 = 0, len = patterns.length; i3 < len; i3++) {
        const pattern2 = patterns[i3];
        let ruleId = -1;
        if (pattern2.include) {
          const reference2 = parseInclude(pattern2.include);
          switch (reference2.kind) {
            case 0:
            case 1:
              ruleId = _RuleFactory.getCompiledRuleId(repository[pattern2.include], helper, repository);
              break;
            case 2:
              let localIncludedRule = repository[reference2.ruleName];
              if (localIncludedRule) {
                ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);
              } else {
              }
              break;
            case 3:
            case 4:
              const externalGrammarName = reference2.scopeName;
              const externalGrammarInclude = reference2.kind === 4 ? reference2.ruleName : null;
              const externalGrammar = helper.getExternalGrammar(externalGrammarName, repository);
              if (externalGrammar) {
                if (externalGrammarInclude) {
                  let externalIncludedRule = externalGrammar.repository[externalGrammarInclude];
                  if (externalIncludedRule) {
                    ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);
                  } else {
                  }
                } else {
                  ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);
                }
              } else {
              }
              break;
          }
        } else {
          ruleId = _RuleFactory.getCompiledRuleId(pattern2, helper, repository);
        }
        if (ruleId !== -1) {
          const rule = helper.getRule(ruleId);
          let skipRule = false;
          if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) {
            if (rule.hasMissingPatterns && rule.patterns.length === 0) {
              skipRule = true;
            }
          }
          if (skipRule) {
            continue;
          }
          r3.push(ruleId);
        }
      }
    }
    return {
      patterns: r3,
      hasMissingPatterns: (patterns ? patterns.length : 0) !== r3.length
    };
  }
};
var RegExpSource = class _RegExpSource {
  source;
  ruleId;
  hasAnchor;
  hasBackReferences;
  _anchorCache;
  constructor(regExpSource, ruleId) {
    if (regExpSource && typeof regExpSource === "string") {
      const len = regExpSource.length;
      let lastPushedPos = 0;
      let output = [];
      let hasAnchor2 = false;
      for (let pos = 0; pos < len; pos++) {
        const ch = regExpSource.charAt(pos);
        if (ch === "\\") {
          if (pos + 1 < len) {
            const nextCh = regExpSource.charAt(pos + 1);
            if (nextCh === "z") {
              output.push(regExpSource.substring(lastPushedPos, pos));
              output.push("$(?!\\n)(?<!\\n)");
              lastPushedPos = pos + 2;
            } else if (nextCh === "A" || nextCh === "G") {
              hasAnchor2 = true;
            }
            pos++;
          }
        }
      }
      this.hasAnchor = hasAnchor2;
      if (lastPushedPos === 0) {
        this.source = regExpSource;
      } else {
        output.push(regExpSource.substring(lastPushedPos, len));
        this.source = output.join("");
      }
    } else {
      this.hasAnchor = false;
      this.source = regExpSource;
    }
    if (this.hasAnchor) {
      this._anchorCache = this._buildAnchorCache();
    } else {
      this._anchorCache = null;
    }
    this.ruleId = ruleId;
    if (typeof this.source === "string") {
      this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source);
    } else {
      this.hasBackReferences = false;
    }
  }
  clone() {
    return new _RegExpSource(this.source, this.ruleId);
  }
  setSource(newSource) {
    if (this.source === newSource) {
      return;
    }
    this.source = newSource;
    if (this.hasAnchor) {
      this._anchorCache = this._buildAnchorCache();
    }
  }
  resolveBackReferences(lineText, captureIndices) {
    if (typeof this.source !== "string") {
      throw new Error("This method should only be called if the source is a string");
    }
    let capturedValues = captureIndices.map((capture) => {
      return lineText.substring(capture.start, capture.end);
    });
    BACK_REFERENCING_END.lastIndex = 0;
    return this.source.replace(BACK_REFERENCING_END, (match2, g1) => {
      return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || "");
    });
  }
  _buildAnchorCache() {
    if (typeof this.source !== "string") {
      throw new Error("This method should only be called if the source is a string");
    }
    let A0_G0_result = [];
    let A0_G1_result = [];
    let A1_G0_result = [];
    let A1_G1_result = [];
    let pos, len, ch, nextCh;
    for (pos = 0, len = this.source.length; pos < len; pos++) {
      ch = this.source.charAt(pos);
      A0_G0_result[pos] = ch;
      A0_G1_result[pos] = ch;
      A1_G0_result[pos] = ch;
      A1_G1_result[pos] = ch;
      if (ch === "\\") {
        if (pos + 1 < len) {
          nextCh = this.source.charAt(pos + 1);
          if (nextCh === "A") {
            A0_G0_result[pos + 1] = "\uFFFF";
            A0_G1_result[pos + 1] = "\uFFFF";
            A1_G0_result[pos + 1] = "A";
            A1_G1_result[pos + 1] = "A";
          } else if (nextCh === "G") {
            A0_G0_result[pos + 1] = "\uFFFF";
            A0_G1_result[pos + 1] = "G";
            A1_G0_result[pos + 1] = "\uFFFF";
            A1_G1_result[pos + 1] = "G";
          } else {
            A0_G0_result[pos + 1] = nextCh;
            A0_G1_result[pos + 1] = nextCh;
            A1_G0_result[pos + 1] = nextCh;
            A1_G1_result[pos + 1] = nextCh;
          }
          pos++;
        }
      }
    }
    return {
      A0_G0: A0_G0_result.join(""),
      A0_G1: A0_G1_result.join(""),
      A1_G0: A1_G0_result.join(""),
      A1_G1: A1_G1_result.join("")
    };
  }
  resolveAnchors(allowA, allowG) {
    if (!this.hasAnchor || !this._anchorCache || typeof this.source !== "string") {
      return this.source;
    }
    if (allowA) {
      if (allowG) {
        return this._anchorCache.A1_G1;
      } else {
        return this._anchorCache.A1_G0;
      }
    } else {
      if (allowG) {
        return this._anchorCache.A0_G1;
      } else {
        return this._anchorCache.A0_G0;
      }
    }
  }
};
var RegExpSourceList = class {
  _items;
  _hasAnchors;
  _cached;
  _anchorCache;
  constructor() {
    this._items = [];
    this._hasAnchors = false;
    this._cached = null;
    this._anchorCache = {
      A0_G0: null,
      A0_G1: null,
      A1_G0: null,
      A1_G1: null
    };
  }
  dispose() {
    this._disposeCaches();
  }
  _disposeCaches() {
    if (this._cached) {
      this._cached.dispose();
      this._cached = null;
    }
    if (this._anchorCache.A0_G0) {
      this._anchorCache.A0_G0.dispose();
      this._anchorCache.A0_G0 = null;
    }
    if (this._anchorCache.A0_G1) {
      this._anchorCache.A0_G1.dispose();
      this._anchorCache.A0_G1 = null;
    }
    if (this._anchorCache.A1_G0) {
      this._anchorCache.A1_G0.dispose();
      this._anchorCache.A1_G0 = null;
    }
    if (this._anchorCache.A1_G1) {
      this._anchorCache.A1_G1.dispose();
      this._anchorCache.A1_G1 = null;
    }
  }
  push(item) {
    this._items.push(item);
    this._hasAnchors = this._hasAnchors || item.hasAnchor;
  }
  unshift(item) {
    this._items.unshift(item);
    this._hasAnchors = this._hasAnchors || item.hasAnchor;
  }
  length() {
    return this._items.length;
  }
  setSource(index2, newSource) {
    if (this._items[index2].source !== newSource) {
      this._disposeCaches();
      this._items[index2].setSource(newSource);
    }
  }
  compile(onigLib) {
    if (!this._cached) {
      let regExps = this._items.map((e3) => e3.source);
      this._cached = new CompiledRule(onigLib, regExps, this._items.map((e3) => e3.ruleId));
    }
    return this._cached;
  }
  compileAG(onigLib, allowA, allowG) {
    if (!this._hasAnchors) {
      return this.compile(onigLib);
    } else {
      if (allowA) {
        if (allowG) {
          if (!this._anchorCache.A1_G1) {
            this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG);
          }
          return this._anchorCache.A1_G1;
        } else {
          if (!this._anchorCache.A1_G0) {
            this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG);
          }
          return this._anchorCache.A1_G0;
        }
      } else {
        if (allowG) {
          if (!this._anchorCache.A0_G1) {
            this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG);
          }
          return this._anchorCache.A0_G1;
        } else {
          if (!this._anchorCache.A0_G0) {
            this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG);
          }
          return this._anchorCache.A0_G0;
        }
      }
    }
  }
  _resolveAnchors(onigLib, allowA, allowG) {
    let regExps = this._items.map((e3) => e3.resolveAnchors(allowA, allowG));
    return new CompiledRule(onigLib, regExps, this._items.map((e3) => e3.ruleId));
  }
};
var CompiledRule = class {
  constructor(onigLib, regExps, rules) {
    this.regExps = regExps;
    this.rules = rules;
    this.scanner = onigLib.createOnigScanner(regExps);
  }
  scanner;
  dispose() {
    if (typeof this.scanner.dispose === "function") {
      this.scanner.dispose();
    }
  }
  toString() {
    const r3 = [];
    for (let i3 = 0, len = this.rules.length; i3 < len; i3++) {
      r3.push("   - " + this.rules[i3] + ": " + this.regExps[i3]);
    }
    return r3.join("\n");
  }
  findNextMatchSync(string3, startPosition, options2) {
    const result2 = this.scanner.findNextMatchSync(string3, startPosition, options2);
    if (!result2) {
      return null;
    }
    return {
      ruleId: this.rules[result2.index],
      captureIndices: result2.captureIndices
    };
  }
};
var BasicScopeAttributes = class {
  constructor(languageId, tokenType2) {
    this.languageId = languageId;
    this.tokenType = tokenType2;
  }
};
var BasicScopeAttributesProvider = class _BasicScopeAttributesProvider {
  _defaultAttributes;
  _embeddedLanguagesMatcher;
  constructor(initialLanguageId, embeddedLanguages) {
    this._defaultAttributes = new BasicScopeAttributes(
      initialLanguageId,
      8
      /* NotSet */
    );
    this._embeddedLanguagesMatcher = new ScopeMatcher(Object.entries(embeddedLanguages || {}));
  }
  getDefaultAttributes() {
    return this._defaultAttributes;
  }
  getBasicScopeAttributes(scopeName) {
    if (scopeName === null) {
      return _BasicScopeAttributesProvider._NULL_SCOPE_METADATA;
    }
    return this._getBasicScopeAttributes.get(scopeName);
  }
  static _NULL_SCOPE_METADATA = new BasicScopeAttributes(0, 0);
  _getBasicScopeAttributes = new CachedFn((scopeName) => {
    const languageId = this._scopeToLanguage(scopeName);
    const standardTokenType = this._toStandardTokenType(scopeName);
    return new BasicScopeAttributes(languageId, standardTokenType);
  });
  /**
   * Given a produced TM scope, return the language that token describes or null if unknown.
   * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null
   */
  _scopeToLanguage(scope) {
    return this._embeddedLanguagesMatcher.match(scope) || 0;
  }
  _toStandardTokenType(scopeName) {
    const m3 = scopeName.match(_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP);
    if (!m3) {
      return 8;
    }
    switch (m3[1]) {
      case "comment":
        return 1;
      case "string":
        return 2;
      case "regex":
        return 3;
      case "meta.embedded":
        return 0;
    }
    throw new Error("Unexpected match for standard token type!");
  }
  static STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|meta\.embedded)\b/;
};
var ScopeMatcher = class {
  values;
  scopesRegExp;
  constructor(values2) {
    if (values2.length === 0) {
      this.values = null;
      this.scopesRegExp = null;
    } else {
      this.values = new Map(values2);
      const escapedScopes = values2.map(
        ([scopeName, value2]) => escapeRegExpCharacters(scopeName)
      );
      escapedScopes.sort();
      escapedScopes.reverse();
      this.scopesRegExp = new RegExp(
        `^((${escapedScopes.join(")|(")}))($|\\.)`,
        ""
      );
    }
  }
  match(scope) {
    if (!this.scopesRegExp) {
      return void 0;
    }
    const m3 = scope.match(this.scopesRegExp);
    if (!m3) {
      return void 0;
    }
    return this.values.get(m3[1]);
  }
};
var DebugFlags = {
  InDebugMode: typeof process !== "undefined" && !!process.env["VSCODE_TEXTMATE_DEBUG"]
};
var UseOnigurumaFindOptions = false;
var TokenizeStringResult = class {
  constructor(stack, stoppedEarly) {
    this.stack = stack;
    this.stoppedEarly = stoppedEarly;
  }
};
function _tokenizeString(grammar, lineText, isFirstLine, linePos, stack, lineTokens, checkWhileConditions, timeLimit) {
  const lineLength = lineText.content.length;
  let STOP = false;
  let anchorPosition = -1;
  if (checkWhileConditions) {
    const whileCheckResult = _checkWhileConditions(
      grammar,
      lineText,
      isFirstLine,
      linePos,
      stack,
      lineTokens
    );
    stack = whileCheckResult.stack;
    linePos = whileCheckResult.linePos;
    isFirstLine = whileCheckResult.isFirstLine;
    anchorPosition = whileCheckResult.anchorPosition;
  }
  const startTime = Date.now();
  while (!STOP) {
    if (timeLimit !== 0) {
      const elapsedTime = Date.now() - startTime;
      if (elapsedTime > timeLimit) {
        return new TokenizeStringResult(stack, true);
      }
    }
    scanNext();
  }
  return new TokenizeStringResult(stack, false);
  function scanNext() {
    if (false) {
      console.log("");
      console.log(
        `@@scanNext ${linePos}: |${lineText.content.substr(linePos).replace(/\n$/, "\\n")}|`
      );
    }
    const r3 = matchRuleOrInjections(
      grammar,
      lineText,
      isFirstLine,
      linePos,
      stack,
      anchorPosition
    );
    if (!r3) {
      lineTokens.produce(stack, lineLength);
      STOP = true;
      return;
    }
    const captureIndices = r3.captureIndices;
    const matchedRuleId = r3.matchedRuleId;
    const hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false;
    if (matchedRuleId === endRuleId) {
      const poppedRule = stack.getRule(grammar);
      if (false) {
        console.log(
          "  popping " + poppedRule.debugName + " - " + poppedRule.debugEndRegExp
        );
      }
      lineTokens.produce(stack, captureIndices[0].start);
      stack = stack.withContentNameScopesList(stack.nameScopesList);
      handleCaptures(
        grammar,
        lineText,
        isFirstLine,
        stack,
        lineTokens,
        poppedRule.endCaptures,
        captureIndices
      );
      lineTokens.produce(stack, captureIndices[0].end);
      const popped = stack;
      stack = stack.parent;
      anchorPosition = popped.getAnchorPos();
      if (!hasAdvanced && popped.getEnterPos() === linePos) {
        if (false) {
          console.error(
            "[1] - Grammar is in an endless loop - Grammar pushed & popped a rule without advancing"
          );
        }
        stack = popped;
        lineTokens.produce(stack, lineLength);
        STOP = true;
        return;
      }
    } else {
      const _rule = grammar.getRule(matchedRuleId);
      lineTokens.produce(stack, captureIndices[0].start);
      const beforePush = stack;
      const scopeName = _rule.getName(lineText.content, captureIndices);
      const nameScopesList = stack.contentNameScopesList.pushAttributed(
        scopeName,
        grammar
      );
      stack = stack.push(
        matchedRuleId,
        linePos,
        anchorPosition,
        captureIndices[0].end === lineLength,
        null,
        nameScopesList,
        nameScopesList
      );
      if (_rule instanceof BeginEndRule) {
        const pushedRule = _rule;
        if (false) {
          console.log(
            "  pushing " + pushedRule.debugName + " - " + pushedRule.debugBeginRegExp
          );
        }
        handleCaptures(
          grammar,
          lineText,
          isFirstLine,
          stack,
          lineTokens,
          pushedRule.beginCaptures,
          captureIndices
        );
        lineTokens.produce(stack, captureIndices[0].end);
        anchorPosition = captureIndices[0].end;
        const contentName = pushedRule.getContentName(
          lineText.content,
          captureIndices
        );
        const contentNameScopesList = nameScopesList.pushAttributed(
          contentName,
          grammar
        );
        stack = stack.withContentNameScopesList(contentNameScopesList);
        if (pushedRule.endHasBackReferences) {
          stack = stack.withEndRule(
            pushedRule.getEndWithResolvedBackReferences(
              lineText.content,
              captureIndices
            )
          );
        }
        if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
          if (false) {
            console.error(
              "[2] - Grammar is in an endless loop - Grammar pushed the same rule without advancing"
            );
          }
          stack = stack.pop();
          lineTokens.produce(stack, lineLength);
          STOP = true;
          return;
        }
      } else if (_rule instanceof BeginWhileRule) {
        const pushedRule = _rule;
        if (false) {
          console.log("  pushing " + pushedRule.debugName);
        }
        handleCaptures(
          grammar,
          lineText,
          isFirstLine,
          stack,
          lineTokens,
          pushedRule.beginCaptures,
          captureIndices
        );
        lineTokens.produce(stack, captureIndices[0].end);
        anchorPosition = captureIndices[0].end;
        const contentName = pushedRule.getContentName(
          lineText.content,
          captureIndices
        );
        const contentNameScopesList = nameScopesList.pushAttributed(
          contentName,
          grammar
        );
        stack = stack.withContentNameScopesList(contentNameScopesList);
        if (pushedRule.whileHasBackReferences) {
          stack = stack.withEndRule(
            pushedRule.getWhileWithResolvedBackReferences(
              lineText.content,
              captureIndices
            )
          );
        }
        if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
          if (false) {
            console.error(
              "[3] - Grammar is in an endless loop - Grammar pushed the same rule without advancing"
            );
          }
          stack = stack.pop();
          lineTokens.produce(stack, lineLength);
          STOP = true;
          return;
        }
      } else {
        const matchingRule = _rule;
        if (false) {
          console.log(
            "  matched " + matchingRule.debugName + " - " + matchingRule.debugMatchRegExp
          );
        }
        handleCaptures(
          grammar,
          lineText,
          isFirstLine,
          stack,
          lineTokens,
          matchingRule.captures,
          captureIndices
        );
        lineTokens.produce(stack, captureIndices[0].end);
        stack = stack.pop();
        if (!hasAdvanced) {
          if (false) {
            console.error(
              "[4] - Grammar is in an endless loop - Grammar is not advancing, nor is it pushing/popping"
            );
          }
          stack = stack.safePop();
          lineTokens.produce(stack, lineLength);
          STOP = true;
          return;
        }
      }
    }
    if (captureIndices[0].end > linePos) {
      linePos = captureIndices[0].end;
      isFirstLine = false;
    }
  }
}
function _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens) {
  let anchorPosition = stack.beginRuleCapturedEOL ? 0 : -1;
  const whileRules = [];
  for (let node = stack; node; node = node.pop()) {
    const nodeRule = node.getRule(grammar);
    if (nodeRule instanceof BeginWhileRule) {
      whileRules.push({
        rule: nodeRule,
        stack: node
      });
    }
  }
  for (let whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) {
    const { ruleScanner, findOptions } = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition);
    const r3 = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
    if (false) {
      console.log("  scanning for while rule");
      console.log(ruleScanner.toString());
    }
    if (r3) {
      const matchedRuleId = r3.ruleId;
      if (matchedRuleId !== whileRuleId) {
        stack = whileRule.stack.pop();
        break;
      }
      if (r3.captureIndices && r3.captureIndices.length) {
        lineTokens.produce(whileRule.stack, r3.captureIndices[0].start);
        handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r3.captureIndices);
        lineTokens.produce(whileRule.stack, r3.captureIndices[0].end);
        anchorPosition = r3.captureIndices[0].end;
        if (r3.captureIndices[0].end > linePos) {
          linePos = r3.captureIndices[0].end;
          isFirstLine = false;
        }
      }
    } else {
      if (false) {
        console.log("  popping " + whileRule.rule.debugName + " - " + whileRule.rule.debugWhileRegExp);
      }
      stack = whileRule.stack.pop();
      break;
    }
  }
  return { stack, linePos, anchorPosition, isFirstLine };
}
function matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
  const matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
  const injections = grammar.getInjections();
  if (injections.length === 0) {
    return matchResult;
  }
  const injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
  if (!injectionResult) {
    return matchResult;
  }
  if (!matchResult) {
    return injectionResult;
  }
  const matchResultScore = matchResult.captureIndices[0].start;
  const injectionResultScore = injectionResult.captureIndices[0].start;
  if (injectionResultScore < matchResultScore || injectionResult.priorityMatch && injectionResultScore === matchResultScore) {
    return injectionResult;
  }
  return matchResult;
}
function matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
  const rule = stack.getRule(grammar);
  const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition);
  const r3 = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
  if (r3) {
    return {
      captureIndices: r3.captureIndices,
      matchedRuleId: r3.ruleId
    };
  }
  return null;
}
function matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
  let bestMatchRating = Number.MAX_VALUE;
  let bestMatchCaptureIndices = null;
  let bestMatchRuleId;
  let bestMatchResultPriority = 0;
  const scopes = stack.contentNameScopesList.getScopeNames();
  for (let i3 = 0, len = injections.length; i3 < len; i3++) {
    const injection = injections[i3];
    if (!injection.matcher(scopes)) {
      continue;
    }
    const rule = grammar.getRule(injection.ruleId);
    const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition);
    const matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
    if (!matchResult) {
      continue;
    }
    if (false) {
      console.log(`  matched injection: ${injection.debugSelector}`);
      console.log(ruleScanner.toString());
    }
    const matchRating = matchResult.captureIndices[0].start;
    if (matchRating >= bestMatchRating) {
      continue;
    }
    bestMatchRating = matchRating;
    bestMatchCaptureIndices = matchResult.captureIndices;
    bestMatchRuleId = matchResult.ruleId;
    bestMatchResultPriority = injection.priority;
    if (bestMatchRating === linePos) {
      break;
    }
  }
  if (bestMatchCaptureIndices) {
    return {
      priorityMatch: bestMatchResultPriority === -1,
      captureIndices: bestMatchCaptureIndices,
      matchedRuleId: bestMatchRuleId
    };
  }
  return null;
}
function prepareRuleSearch(rule, grammar, endRegexSource, allowA, allowG) {
  if (UseOnigurumaFindOptions) {
    const ruleScanner2 = rule.compile(grammar, endRegexSource);
    const findOptions = getFindOptions(allowA, allowG);
    return { ruleScanner: ruleScanner2, findOptions };
  }
  const ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG);
  return {
    ruleScanner,
    findOptions: 0
    /* None */
  };
}
function prepareRuleWhileSearch(rule, grammar, endRegexSource, allowA, allowG) {
  if (UseOnigurumaFindOptions) {
    const ruleScanner2 = rule.compileWhile(grammar, endRegexSource);
    const findOptions = getFindOptions(allowA, allowG);
    return { ruleScanner: ruleScanner2, findOptions };
  }
  const ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG);
  return {
    ruleScanner,
    findOptions: 0
    /* None */
  };
}
function getFindOptions(allowA, allowG) {
  let options2 = 0;
  if (!allowA) {
    options2 |= 1;
  }
  if (!allowG) {
    options2 |= 4;
  }
  return options2;
}
function handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, captures, captureIndices) {
  if (captures.length === 0) {
    return;
  }
  const lineTextContent = lineText.content;
  const len = Math.min(captures.length, captureIndices.length);
  const localStack = [];
  const maxEnd = captureIndices[0].end;
  for (let i3 = 0; i3 < len; i3++) {
    const captureRule = captures[i3];
    if (captureRule === null) {
      continue;
    }
    const captureIndex = captureIndices[i3];
    if (captureIndex.length === 0) {
      continue;
    }
    if (captureIndex.start > maxEnd) {
      break;
    }
    while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) {
      lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);
      localStack.pop();
    }
    if (localStack.length > 0) {
      lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start);
    } else {
      lineTokens.produce(stack, captureIndex.start);
    }
    if (captureRule.retokenizeCapturedWithRuleId) {
      const scopeName = captureRule.getName(lineTextContent, captureIndices);
      const nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);
      const contentName = captureRule.getContentName(lineTextContent, captureIndices);
      const contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);
      const stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList);
      const onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end));
      _tokenizeString(
        grammar,
        onigSubStr,
        isFirstLine && captureIndex.start === 0,
        captureIndex.start,
        stackClone,
        lineTokens,
        false,
        /* no time limit */
        0
      );
      disposeOnigString(onigSubStr);
      continue;
    }
    const captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices);
    if (captureRuleScopeName !== null) {
      const base3 = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList;
      const captureRuleScopesList = base3.pushAttributed(captureRuleScopeName, grammar);
      localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end));
    }
  }
  while (localStack.length > 0) {
    lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);
    localStack.pop();
  }
}
var LocalStackElement = class {
  scopes;
  endPos;
  constructor(scopes, endPos) {
    this.scopes = scopes;
    this.endPos = endPos;
  }
};
function createGrammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib) {
  return new Grammar(
    scopeName,
    grammar,
    initialLanguage,
    embeddedLanguages,
    tokenTypes,
    balancedBracketSelectors,
    grammarRepository,
    onigLib
  );
}
function collectInjections(result2, selector, rule, ruleFactoryHelper, grammar) {
  const matchers = createMatchers(selector, nameMatcher);
  const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);
  for (const matcher2 of matchers) {
    result2.push({
      debugSelector: selector,
      matcher: matcher2.matcher,
      ruleId,
      grammar,
      priority: matcher2.priority
    });
  }
}
function nameMatcher(identifers, scopes) {
  if (scopes.length < identifers.length) {
    return false;
  }
  let lastIndex = 0;
  return identifers.every((identifier) => {
    for (let i3 = lastIndex; i3 < scopes.length; i3++) {
      if (scopesAreMatching(scopes[i3], identifier)) {
        lastIndex = i3 + 1;
        return true;
      }
    }
    return false;
  });
}
function scopesAreMatching(thisScopeName, scopeName) {
  if (!thisScopeName) {
    return false;
  }
  if (thisScopeName === scopeName) {
    return true;
  }
  const len = scopeName.length;
  return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === ".";
}
var Grammar = class {
  constructor(_rootScopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, _onigLib) {
    this._rootScopeName = _rootScopeName;
    this.balancedBracketSelectors = balancedBracketSelectors;
    this._onigLib = _onigLib;
    this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(
      initialLanguage,
      embeddedLanguages
    );
    this._rootId = -1;
    this._lastRuleId = 0;
    this._ruleId2desc = [null];
    this._includedGrammars = {};
    this._grammarRepository = grammarRepository;
    this._grammar = initGrammar(grammar, null);
    this._injections = null;
    this._tokenTypeMatchers = [];
    if (tokenTypes) {
      for (const selector of Object.keys(tokenTypes)) {
        const matchers = createMatchers(selector, nameMatcher);
        for (const matcher2 of matchers) {
          this._tokenTypeMatchers.push({
            matcher: matcher2.matcher,
            type: tokenTypes[selector]
          });
        }
      }
    }
  }
  _rootId;
  _lastRuleId;
  _ruleId2desc;
  _includedGrammars;
  _grammarRepository;
  _grammar;
  _injections;
  _basicScopeAttributesProvider;
  _tokenTypeMatchers;
  get themeProvider() {
    return this._grammarRepository;
  }
  dispose() {
    for (const rule of this._ruleId2desc) {
      if (rule) {
        rule.dispose();
      }
    }
  }
  createOnigScanner(sources) {
    return this._onigLib.createOnigScanner(sources);
  }
  createOnigString(sources) {
    return this._onigLib.createOnigString(sources);
  }
  getMetadataForScope(scope) {
    return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);
  }
  _collectInjections() {
    const grammarRepository = {
      lookup: (scopeName2) => {
        if (scopeName2 === this._rootScopeName) {
          return this._grammar;
        }
        return this.getExternalGrammar(scopeName2);
      },
      injections: (scopeName2) => {
        return this._grammarRepository.injections(scopeName2);
      }
    };
    const result2 = [];
    const scopeName = this._rootScopeName;
    const grammar = grammarRepository.lookup(scopeName);
    if (grammar) {
      const rawInjections = grammar.injections;
      if (rawInjections) {
        for (let expression in rawInjections) {
          collectInjections(
            result2,
            expression,
            rawInjections[expression],
            this,
            grammar
          );
        }
      }
      const injectionScopeNames = this._grammarRepository.injections(scopeName);
      if (injectionScopeNames) {
        injectionScopeNames.forEach((injectionScopeName) => {
          const injectionGrammar = this.getExternalGrammar(injectionScopeName);
          if (injectionGrammar) {
            const selector = injectionGrammar.injectionSelector;
            if (selector) {
              collectInjections(
                result2,
                selector,
                injectionGrammar,
                this,
                injectionGrammar
              );
            }
          }
        });
      }
    }
    result2.sort((i1, i22) => i1.priority - i22.priority);
    return result2;
  }
  getInjections() {
    if (this._injections === null) {
      this._injections = this._collectInjections();
    }
    return this._injections;
  }
  registerRule(factory) {
    const id = ++this._lastRuleId;
    const result2 = factory(ruleIdFromNumber(id));
    this._ruleId2desc[id] = result2;
    return result2;
  }
  getRule(ruleId) {
    return this._ruleId2desc[ruleIdToNumber(ruleId)];
  }
  getExternalGrammar(scopeName, repository) {
    if (this._includedGrammars[scopeName]) {
      return this._includedGrammars[scopeName];
    } else if (this._grammarRepository) {
      const rawIncludedGrammar = this._grammarRepository.lookup(scopeName);
      if (rawIncludedGrammar) {
        this._includedGrammars[scopeName] = initGrammar(
          rawIncludedGrammar,
          repository && repository.$base
        );
        return this._includedGrammars[scopeName];
      }
    }
    return void 0;
  }
  tokenizeLine(lineText, prevState, timeLimit = 0) {
    const r3 = this._tokenize(lineText, prevState, false, timeLimit);
    return {
      tokens: r3.lineTokens.getResult(r3.ruleStack, r3.lineLength),
      ruleStack: r3.ruleStack,
      stoppedEarly: r3.stoppedEarly
    };
  }
  tokenizeLine2(lineText, prevState, timeLimit = 0) {
    const r3 = this._tokenize(lineText, prevState, true, timeLimit);
    return {
      tokens: r3.lineTokens.getBinaryResult(r3.ruleStack, r3.lineLength),
      ruleStack: r3.ruleStack,
      stoppedEarly: r3.stoppedEarly
    };
  }
  _tokenize(lineText, prevState, emitBinaryTokens, timeLimit) {
    if (this._rootId === -1) {
      this._rootId = RuleFactory.getCompiledRuleId(
        this._grammar.repository.$self,
        this,
        this._grammar.repository
      );
      this.getInjections();
    }
    let isFirstLine;
    if (!prevState || prevState === StateStackImpl.NULL) {
      isFirstLine = true;
      const rawDefaultMetadata = this._basicScopeAttributesProvider.getDefaultAttributes();
      const defaultStyle = this.themeProvider.getDefaults();
      const defaultMetadata = EncodedTokenMetadata.set(
        0,
        rawDefaultMetadata.languageId,
        rawDefaultMetadata.tokenType,
        null,
        defaultStyle.fontStyle,
        defaultStyle.foregroundId,
        defaultStyle.backgroundId
      );
      const rootScopeName = this.getRule(this._rootId).getName(
        null,
        null
      );
      let scopeList;
      if (rootScopeName) {
        scopeList = AttributedScopeStack.createRootAndLookUpScopeName(
          rootScopeName,
          defaultMetadata,
          this
        );
      } else {
        scopeList = AttributedScopeStack.createRoot(
          "unknown",
          defaultMetadata
        );
      }
      prevState = new StateStackImpl(
        null,
        this._rootId,
        -1,
        -1,
        false,
        null,
        scopeList,
        scopeList
      );
    } else {
      isFirstLine = false;
      prevState.reset();
    }
    lineText = lineText + "\n";
    const onigLineText = this.createOnigString(lineText);
    const lineLength = onigLineText.content.length;
    const lineTokens = new LineTokens(
      emitBinaryTokens,
      lineText,
      this._tokenTypeMatchers,
      this.balancedBracketSelectors
    );
    const r3 = _tokenizeString(
      this,
      onigLineText,
      isFirstLine,
      0,
      prevState,
      lineTokens,
      true,
      timeLimit
    );
    disposeOnigString(onigLineText);
    return {
      lineLength,
      lineTokens,
      ruleStack: r3.stack,
      stoppedEarly: r3.stoppedEarly
    };
  }
};
function initGrammar(grammar, base3) {
  grammar = clone2(grammar);
  grammar.repository = grammar.repository || {};
  grammar.repository.$self = {
    $vscodeTextmateLocation: grammar.$vscodeTextmateLocation,
    patterns: grammar.patterns,
    name: grammar.scopeName
  };
  grammar.repository.$base = base3 || grammar.repository.$self;
  return grammar;
}
var AttributedScopeStack = class _AttributedScopeStack {
  /**
   * Invariant:
   * ```
   * if (parent && !scopePath.extends(parent.scopePath)) {
   * 	throw new Error();
   * }
   * ```
   */
  constructor(parent, scopePath, tokenAttributes) {
    this.parent = parent;
    this.scopePath = scopePath;
    this.tokenAttributes = tokenAttributes;
  }
  static fromExtension(namesScopeList, contentNameScopesList) {
    let current = namesScopeList;
    let scopeNames = namesScopeList?.scopePath ?? null;
    for (const frame of contentNameScopesList) {
      scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);
      current = new _AttributedScopeStack(current, scopeNames, frame.encodedTokenAttributes);
    }
    return current;
  }
  static createRoot(scopeName, tokenAttributes) {
    return new _AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);
  }
  static createRootAndLookUpScopeName(scopeName, tokenAttributes, grammar) {
    const rawRootMetadata = grammar.getMetadataForScope(scopeName);
    const scopePath = new ScopeStack(null, scopeName);
    const rootStyle = grammar.themeProvider.themeMatch(scopePath);
    const resolvedTokenAttributes = _AttributedScopeStack.mergeAttributes(
      tokenAttributes,
      rawRootMetadata,
      rootStyle
    );
    return new _AttributedScopeStack(null, scopePath, resolvedTokenAttributes);
  }
  get scopeName() {
    return this.scopePath.scopeName;
  }
  toString() {
    return this.getScopeNames().join(" ");
  }
  equals(other) {
    return _AttributedScopeStack.equals(this, other);
  }
  static equals(a3, b3) {
    do {
      if (a3 === b3) {
        return true;
      }
      if (!a3 && !b3) {
        return true;
      }
      if (!a3 || !b3) {
        return false;
      }
      if (a3.scopeName !== b3.scopeName || a3.tokenAttributes !== b3.tokenAttributes) {
        return false;
      }
      a3 = a3.parent;
      b3 = b3.parent;
    } while (true);
  }
  static mergeAttributes(existingTokenAttributes, basicScopeAttributes, styleAttributes) {
    let fontStyle = -1;
    let foreground = 0;
    let background = 0;
    if (styleAttributes !== null) {
      fontStyle = styleAttributes.fontStyle;
      foreground = styleAttributes.foregroundId;
      background = styleAttributes.backgroundId;
    }
    return EncodedTokenMetadata.set(
      existingTokenAttributes,
      basicScopeAttributes.languageId,
      basicScopeAttributes.tokenType,
      null,
      fontStyle,
      foreground,
      background
    );
  }
  pushAttributed(scopePath, grammar) {
    if (scopePath === null) {
      return this;
    }
    if (scopePath.indexOf(" ") === -1) {
      return _AttributedScopeStack._pushAttributed(this, scopePath, grammar);
    }
    const scopes = scopePath.split(/ /g);
    let result2 = this;
    for (const scope of scopes) {
      result2 = _AttributedScopeStack._pushAttributed(result2, scope, grammar);
    }
    return result2;
  }
  static _pushAttributed(target, scopeName, grammar) {
    const rawMetadata = grammar.getMetadataForScope(scopeName);
    const newPath = target.scopePath.push(scopeName);
    const scopeThemeMatchResult = grammar.themeProvider.themeMatch(newPath);
    const metadata = _AttributedScopeStack.mergeAttributes(
      target.tokenAttributes,
      rawMetadata,
      scopeThemeMatchResult
    );
    return new _AttributedScopeStack(target, newPath, metadata);
  }
  getScopeNames() {
    return this.scopePath.getSegments();
  }
  getExtensionIfDefined(base3) {
    const result2 = [];
    let self2 = this;
    while (self2 && self2 !== base3) {
      result2.push({
        encodedTokenAttributes: self2.tokenAttributes,
        scopeNames: self2.scopePath.getExtensionIfDefined(self2.parent?.scopePath ?? null)
      });
      self2 = self2.parent;
    }
    return self2 === base3 ? result2.reverse() : void 0;
  }
};
var StateStackImpl = class _StateStackImpl {
  /**
   * Invariant:
   * ```
   * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {
   * 	throw new Error();
   * }
   * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {
   * 	throw new Error();
   * }
   * ```
   */
  constructor(parent, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {
    this.parent = parent;
    this.ruleId = ruleId;
    this.beginRuleCapturedEOL = beginRuleCapturedEOL;
    this.endRule = endRule;
    this.nameScopesList = nameScopesList;
    this.contentNameScopesList = contentNameScopesList;
    this.depth = this.parent ? this.parent.depth + 1 : 1;
    this._enterPos = enterPos;
    this._anchorPos = anchorPos;
  }
  _stackElementBrand = void 0;
  // TODO remove me
  static NULL = new _StateStackImpl(
    null,
    0,
    0,
    0,
    false,
    null,
    null,
    null
  );
  /**
   * The position on the current line where this state was pushed.
   * This is relevant only while tokenizing a line, to detect endless loops.
   * Its value is meaningless across lines.
   */
  _enterPos;
  /**
   * The captured anchor position when this stack element was pushed.
   * This is relevant only while tokenizing a line, to restore the anchor position when popping.
   * Its value is meaningless across lines.
   */
  _anchorPos;
  /**
   * The depth of the stack.
   */
  depth;
  equals(other) {
    if (other === null) {
      return false;
    }
    return _StateStackImpl._equals(this, other);
  }
  static _equals(a3, b3) {
    if (a3 === b3) {
      return true;
    }
    if (!this._structuralEquals(a3, b3)) {
      return false;
    }
    return AttributedScopeStack.equals(a3.contentNameScopesList, b3.contentNameScopesList);
  }
  /**
   * A structural equals check. Does not take into account `scopes`.
   */
  static _structuralEquals(a3, b3) {
    do {
      if (a3 === b3) {
        return true;
      }
      if (!a3 && !b3) {
        return true;
      }
      if (!a3 || !b3) {
        return false;
      }
      if (a3.depth !== b3.depth || a3.ruleId !== b3.ruleId || a3.endRule !== b3.endRule) {
        return false;
      }
      a3 = a3.parent;
      b3 = b3.parent;
    } while (true);
  }
  clone() {
    return this;
  }
  static _reset(el2) {
    while (el2) {
      el2._enterPos = -1;
      el2._anchorPos = -1;
      el2 = el2.parent;
    }
  }
  reset() {
    _StateStackImpl._reset(this);
  }
  pop() {
    return this.parent;
  }
  safePop() {
    if (this.parent) {
      return this.parent;
    }
    return this;
  }
  push(ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {
    return new _StateStackImpl(
      this,
      ruleId,
      enterPos,
      anchorPos,
      beginRuleCapturedEOL,
      endRule,
      nameScopesList,
      contentNameScopesList
    );
  }
  getEnterPos() {
    return this._enterPos;
  }
  getAnchorPos() {
    return this._anchorPos;
  }
  getRule(grammar) {
    return grammar.getRule(this.ruleId);
  }
  toString() {
    const r3 = [];
    this._writeString(r3, 0);
    return "[" + r3.join(",") + "]";
  }
  _writeString(res, outIndex) {
    if (this.parent) {
      outIndex = this.parent._writeString(res, outIndex);
    }
    res[outIndex++] = `(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`;
    return outIndex;
  }
  withContentNameScopesList(contentNameScopeStack) {
    if (this.contentNameScopesList === contentNameScopeStack) {
      return this;
    }
    return this.parent.push(
      this.ruleId,
      this._enterPos,
      this._anchorPos,
      this.beginRuleCapturedEOL,
      this.endRule,
      this.nameScopesList,
      contentNameScopeStack
    );
  }
  withEndRule(endRule) {
    if (this.endRule === endRule) {
      return this;
    }
    return new _StateStackImpl(
      this.parent,
      this.ruleId,
      this._enterPos,
      this._anchorPos,
      this.beginRuleCapturedEOL,
      endRule,
      this.nameScopesList,
      this.contentNameScopesList
    );
  }
  // Used to warn of endless loops
  hasSameRuleAs(other) {
    let el2 = this;
    while (el2 && el2._enterPos === other._enterPos) {
      if (el2.ruleId === other.ruleId) {
        return true;
      }
      el2 = el2.parent;
    }
    return false;
  }
  toStateStackFrame() {
    return {
      ruleId: ruleIdToNumber(this.ruleId),
      beginRuleCapturedEOL: this.beginRuleCapturedEOL,
      endRule: this.endRule,
      nameScopesList: this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList ?? null) ?? [],
      contentNameScopesList: this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList) ?? []
    };
  }
  static pushFrame(self2, frame) {
    const namesScopeList = AttributedScopeStack.fromExtension(self2?.nameScopesList ?? null, frame.nameScopesList);
    return new _StateStackImpl(
      self2,
      ruleIdFromNumber(frame.ruleId),
      frame.enterPos ?? -1,
      frame.anchorPos ?? -1,
      frame.beginRuleCapturedEOL,
      frame.endRule,
      namesScopeList,
      AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList)
    );
  }
};
var BalancedBracketSelectors = class {
  balancedBracketScopes;
  unbalancedBracketScopes;
  allowAny = false;
  constructor(balancedBracketScopes, unbalancedBracketScopes) {
    this.balancedBracketScopes = balancedBracketScopes.flatMap(
      (selector) => {
        if (selector === "*") {
          this.allowAny = true;
          return [];
        }
        return createMatchers(selector, nameMatcher).map((m3) => m3.matcher);
      }
    );
    this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap(
      (selector) => createMatchers(selector, nameMatcher).map((m3) => m3.matcher)
    );
  }
  get matchesAlways() {
    return this.allowAny && this.unbalancedBracketScopes.length === 0;
  }
  get matchesNever() {
    return this.balancedBracketScopes.length === 0 && !this.allowAny;
  }
  match(scopes) {
    for (const excluder of this.unbalancedBracketScopes) {
      if (excluder(scopes)) {
        return false;
      }
    }
    for (const includer of this.balancedBracketScopes) {
      if (includer(scopes)) {
        return true;
      }
    }
    return this.allowAny;
  }
};
var LineTokens = class {
  constructor(emitBinaryTokens, lineText, tokenTypeOverrides, balancedBracketSelectors) {
    this.balancedBracketSelectors = balancedBracketSelectors;
    this._emitBinaryTokens = emitBinaryTokens;
    this._tokenTypeOverrides = tokenTypeOverrides;
    if (false) {
      this._lineText = lineText;
    } else {
      this._lineText = null;
    }
    this._tokens = [];
    this._binaryTokens = [];
    this._lastTokenEndIndex = 0;
  }
  _emitBinaryTokens;
  /**
   * defined only if `false`.
   */
  _lineText;
  /**
   * used only if `_emitBinaryTokens` is false.
   */
  _tokens;
  /**
   * used only if `_emitBinaryTokens` is true.
   */
  _binaryTokens;
  _lastTokenEndIndex;
  _tokenTypeOverrides;
  produce(stack, endIndex) {
    this.produceFromScopes(stack.contentNameScopesList, endIndex);
  }
  produceFromScopes(scopesList, endIndex) {
    if (this._lastTokenEndIndex >= endIndex) {
      return;
    }
    if (this._emitBinaryTokens) {
      let metadata = scopesList?.tokenAttributes ?? 0;
      let containsBalancedBrackets = false;
      if (this.balancedBracketSelectors?.matchesAlways) {
        containsBalancedBrackets = true;
      }
      if (this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {
        const scopes2 = scopesList?.getScopeNames() ?? [];
        for (const tokenType2 of this._tokenTypeOverrides) {
          if (tokenType2.matcher(scopes2)) {
            metadata = EncodedTokenMetadata.set(
              metadata,
              0,
              toOptionalTokenType(tokenType2.type),
              null,
              -1,
              0,
              0
            );
          }
        }
        if (this.balancedBracketSelectors) {
          containsBalancedBrackets = this.balancedBracketSelectors.match(scopes2);
        }
      }
      if (containsBalancedBrackets) {
        metadata = EncodedTokenMetadata.set(
          metadata,
          0,
          8,
          containsBalancedBrackets,
          -1,
          0,
          0
        );
      }
      if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {
        this._lastTokenEndIndex = endIndex;
        return;
      }
      this._binaryTokens.push(this._lastTokenEndIndex);
      this._binaryTokens.push(metadata);
      this._lastTokenEndIndex = endIndex;
      return;
    }
    const scopes = scopesList?.getScopeNames() ?? [];
    this._tokens.push({
      startIndex: this._lastTokenEndIndex,
      endIndex,
      // value: lineText.substring(lastTokenEndIndex, endIndex),
      scopes
    });
    this._lastTokenEndIndex = endIndex;
  }
  getResult(stack, lineLength) {
    if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {
      this._tokens.pop();
    }
    if (this._tokens.length === 0) {
      this._lastTokenEndIndex = -1;
      this.produce(stack, lineLength);
      this._tokens[this._tokens.length - 1].startIndex = 0;
    }
    return this._tokens;
  }
  getBinaryResult(stack, lineLength) {
    if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {
      this._binaryTokens.pop();
      this._binaryTokens.pop();
    }
    if (this._binaryTokens.length === 0) {
      this._lastTokenEndIndex = -1;
      this.produce(stack, lineLength);
      this._binaryTokens[this._binaryTokens.length - 2] = 0;
    }
    const result2 = new Uint32Array(this._binaryTokens.length);
    for (let i3 = 0, len = this._binaryTokens.length; i3 < len; i3++) {
      result2[i3] = this._binaryTokens[i3];
    }
    return result2;
  }
};
var SyncRegistry = class {
  constructor(theme2, _onigLib) {
    this._onigLib = _onigLib;
    this._theme = theme2;
  }
  _grammars = /* @__PURE__ */ new Map();
  _rawGrammars = /* @__PURE__ */ new Map();
  _injectionGrammars = /* @__PURE__ */ new Map();
  _theme;
  dispose() {
    for (const grammar of this._grammars.values()) {
      grammar.dispose();
    }
  }
  setTheme(theme2) {
    this._theme = theme2;
  }
  getColorMap() {
    return this._theme.getColorMap();
  }
  /**
   * Add `grammar` to registry and return a list of referenced scope names
   */
  addGrammar(grammar, injectionScopeNames) {
    this._rawGrammars.set(grammar.scopeName, grammar);
    if (injectionScopeNames) {
      this._injectionGrammars.set(grammar.scopeName, injectionScopeNames);
    }
  }
  /**
   * Lookup a raw grammar.
   */
  lookup(scopeName) {
    return this._rawGrammars.get(scopeName);
  }
  /**
   * Returns the injections for the given grammar
   */
  injections(targetScope) {
    return this._injectionGrammars.get(targetScope);
  }
  /**
   * Get the default theme settings
   */
  getDefaults() {
    return this._theme.getDefaults();
  }
  /**
   * Match a scope in the theme.
   */
  themeMatch(scopePath) {
    return this._theme.match(scopePath);
  }
  /**
   * Lookup a grammar.
   */
  grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {
    if (!this._grammars.has(scopeName)) {
      let rawGrammar = this._rawGrammars.get(scopeName);
      if (!rawGrammar) {
        return null;
      }
      this._grammars.set(scopeName, createGrammar(
        scopeName,
        rawGrammar,
        initialLanguage,
        embeddedLanguages,
        tokenTypes,
        balancedBracketSelectors,
        this,
        this._onigLib
      ));
    }
    return this._grammars.get(scopeName);
  }
};
var Registry2 = class {
  _options;
  _syncRegistry;
  _ensureGrammarCache;
  constructor(options2) {
    this._options = options2;
    this._syncRegistry = new SyncRegistry(
      Theme.createFromRawTheme(options2.theme, options2.colorMap),
      options2.onigLib
    );
    this._ensureGrammarCache = /* @__PURE__ */ new Map();
  }
  dispose() {
    this._syncRegistry.dispose();
  }
  /**
   * Change the theme. Once called, no previous `ruleStack` should be used anymore.
   */
  setTheme(theme2, colorMap) {
    this._syncRegistry.setTheme(Theme.createFromRawTheme(theme2, colorMap));
  }
  /**
   * Returns a lookup array for color ids.
   */
  getColorMap() {
    return this._syncRegistry.getColorMap();
  }
  /**
   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
   * Please do not use language id 0.
   */
  loadGrammarWithEmbeddedLanguages(initialScopeName, initialLanguage, embeddedLanguages) {
    return this.loadGrammarWithConfiguration(initialScopeName, initialLanguage, { embeddedLanguages });
  }
  /**
   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
   * Please do not use language id 0.
   */
  loadGrammarWithConfiguration(initialScopeName, initialLanguage, configuration) {
    return this._loadGrammar(
      initialScopeName,
      initialLanguage,
      configuration.embeddedLanguages,
      configuration.tokenTypes,
      new BalancedBracketSelectors(
        configuration.balancedBracketSelectors || [],
        configuration.unbalancedBracketSelectors || []
      )
    );
  }
  /**
   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
   */
  loadGrammar(initialScopeName) {
    return this._loadGrammar(initialScopeName, 0, null, null, null);
  }
  _loadGrammar(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {
    const dependencyProcessor = new ScopeDependencyProcessor(this._syncRegistry, initialScopeName);
    while (dependencyProcessor.Q.length > 0) {
      dependencyProcessor.Q.map((request2) => this._loadSingleGrammar(request2.scopeName));
      dependencyProcessor.processQueue();
    }
    return this._grammarForScopeName(
      initialScopeName,
      initialLanguage,
      embeddedLanguages,
      tokenTypes,
      balancedBracketSelectors
    );
  }
  _loadSingleGrammar(scopeName) {
    if (!this._ensureGrammarCache.has(scopeName)) {
      this._doLoadSingleGrammar(scopeName);
      this._ensureGrammarCache.set(scopeName, true);
    }
  }
  _doLoadSingleGrammar(scopeName) {
    const grammar = this._options.loadGrammar(scopeName);
    if (grammar) {
      const injections = typeof this._options.getInjections === "function" ? this._options.getInjections(scopeName) : void 0;
      this._syncRegistry.addGrammar(grammar, injections);
    }
  }
  /**
   * Adds a rawGrammar.
   */
  addGrammar(rawGrammar, injections = [], initialLanguage = 0, embeddedLanguages = null) {
    this._syncRegistry.addGrammar(rawGrammar, injections);
    return this._grammarForScopeName(rawGrammar.scopeName, initialLanguage, embeddedLanguages);
  }
  /**
   * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.
   */
  _grammarForScopeName(scopeName, initialLanguage = 0, embeddedLanguages = null, tokenTypes = null, balancedBracketSelectors = null) {
    return this._syncRegistry.grammarForScopeName(
      scopeName,
      initialLanguage,
      embeddedLanguages,
      tokenTypes,
      balancedBracketSelectors
    );
  }
};
var INITIAL = StateStackImpl.NULL;

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

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

// node_modules/property-information/lib/util/merge.js
function merge2(definitions, space) {
  const property2 = {};
  const normal = {};
  for (const definition of definitions) {
    Object.assign(property2, definition.property);
    Object.assign(normal, definition.normal);
  }
  return new Schema2(property2, normal, space);
}

// node_modules/property-information/lib/normalize.js
function normalize3(value2) {
  return value2.toLowerCase();
}

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

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

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

// node_modules/property-information/lib/util/create.js
function create5(definition) {
  const properties = {};
  const normals = {};
  for (const [property2, value2] of Object.entries(definition.properties)) {
    const info = new DefinedInfo(
      property2,
      definition.transform(definition.attributes || {}, property2),
      value2,
      definition.space
    );
    if (definition.mustUseProperty && definition.mustUseProperty.includes(property2)) {
      info.mustUseProperty = true;
    }
    properties[property2] = info;
    normals[normalize3(property2)] = property2;
    normals[normalize3(info.attribute)] = property2;
  }
  return new Schema2(properties, normals, definition.space);
}

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

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

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

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

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

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

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

// node_modules/property-information/lib/xml.js
var xml = create5({
  properties: { xmlBase: null, xmlLang: null, xmlSpace: null },
  space: "xml",
  transform(_5, property2) {
    return "xml:" + property2.slice(3).toLowerCase();
  }
});

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

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

// node_modules/zwitch/index.js
var own = {}.hasOwnProperty;
function zwitch(key2, options2) {
  const settings = options2 || {};
  function one2(value2, ...parameters) {
    let fn = one2.invalid;
    const handlers3 = one2.handlers;
    if (value2 && own.call(value2, key2)) {
      const id = String(value2[key2]);
      fn = own.call(handlers3, id) ? handlers3[id] : one2.unknown;
    }
    if (fn) {
      return fn.call(this, value2, ...parameters);
    }
  }
  one2.handlers = settings.handlers || {};
  one2.invalid = settings.invalid;
  one2.unknown = settings.unknown;
  return one2;
}

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

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

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

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

// node_modules/character-entities-html4/index.js
var characterEntitiesHtml4 = {
  nbsp: "\xA0",
  iexcl: "\xA1",
  cent: "\xA2",
  pound: "\xA3",
  curren: "\xA4",
  yen: "\xA5",
  brvbar: "\xA6",
  sect: "\xA7",
  uml: "\xA8",
  copy: "\xA9",
  ordf: "\xAA",
  laquo: "\xAB",
  not: "\xAC",
  shy: "\xAD",
  reg: "\xAE",
  macr: "\xAF",
  deg: "\xB0",
  plusmn: "\xB1",
  sup2: "\xB2",
  sup3: "\xB3",
  acute: "\xB4",
  micro: "\xB5",
  para: "\xB6",
  middot: "\xB7",
  cedil: "\xB8",
  sup1: "\xB9",
  ordm: "\xBA",
  raquo: "\xBB",
  frac14: "\xBC",
  frac12: "\xBD",
  frac34: "\xBE",
  iquest: "\xBF",
  Agrave: "\xC0",
  Aacute: "\xC1",
  Acirc: "\xC2",
  Atilde: "\xC3",
  Auml: "\xC4",
  Aring: "\xC5",
  AElig: "\xC6",
  Ccedil: "\xC7",
  Egrave: "\xC8",
  Eacute: "\xC9",
  Ecirc: "\xCA",
  Euml: "\xCB",
  Igrave: "\xCC",
  Iacute: "\xCD",
  Icirc: "\xCE",
  Iuml: "\xCF",
  ETH: "\xD0",
  Ntilde: "\xD1",
  Ograve: "\xD2",
  Oacute: "\xD3",
  Ocirc: "\xD4",
  Otilde: "\xD5",
  Ouml: "\xD6",
  times: "\xD7",
  Oslash: "\xD8",
  Ugrave: "\xD9",
  Uacute: "\xDA",
  Ucirc: "\xDB",
  Uuml: "\xDC",
  Yacute: "\xDD",
  THORN: "\xDE",
  szlig: "\xDF",
  agrave: "\xE0",
  aacute: "\xE1",
  acirc: "\xE2",
  atilde: "\xE3",
  auml: "\xE4",
  aring: "\xE5",
  aelig: "\xE6",
  ccedil: "\xE7",
  egrave: "\xE8",
  eacute: "\xE9",
  ecirc: "\xEA",
  euml: "\xEB",
  igrave: "\xEC",
  iacute: "\xED",
  icirc: "\xEE",
  iuml: "\xEF",
  eth: "\xF0",
  ntilde: "\xF1",
  ograve: "\xF2",
  oacute: "\xF3",
  ocirc: "\xF4",
  otilde: "\xF5",
  ouml: "\xF6",
  divide: "\xF7",
  oslash: "\xF8",
  ugrave: "\xF9",
  uacute: "\xFA",
  ucirc: "\xFB",
  uuml: "\xFC",
  yacute: "\xFD",
  thorn: "\xFE",
  yuml: "\xFF",
  fnof: "\u0192",
  Alpha: "\u0391",
  Beta: "\u0392",
  Gamma: "\u0393",
  Delta: "\u0394",
  Epsilon: "\u0395",
  Zeta: "\u0396",
  Eta: "\u0397",
  Theta: "\u0398",
  Iota: "\u0399",
  Kappa: "\u039A",
  Lambda: "\u039B",
  Mu: "\u039C",
  Nu: "\u039D",
  Xi: "\u039E",
  Omicron: "\u039F",
  Pi: "\u03A0",
  Rho: "\u03A1",
  Sigma: "\u03A3",
  Tau: "\u03A4",
  Upsilon: "\u03A5",
  Phi: "\u03A6",
  Chi: "\u03A7",
  Psi: "\u03A8",
  Omega: "\u03A9",
  alpha: "\u03B1",
  beta: "\u03B2",
  gamma: "\u03B3",
  delta: "\u03B4",
  epsilon: "\u03B5",
  zeta: "\u03B6",
  eta: "\u03B7",
  theta: "\u03B8",
  iota: "\u03B9",
  kappa: "\u03BA",
  lambda: "\u03BB",
  mu: "\u03BC",
  nu: "\u03BD",
  xi: "\u03BE",
  omicron: "\u03BF",
  pi: "\u03C0",
  rho: "\u03C1",
  sigmaf: "\u03C2",
  sigma: "\u03C3",
  tau: "\u03C4",
  upsilon: "\u03C5",
  phi: "\u03C6",
  chi: "\u03C7",
  psi: "\u03C8",
  omega: "\u03C9",
  thetasym: "\u03D1",
  upsih: "\u03D2",
  piv: "\u03D6",
  bull: "\u2022",
  hellip: "\u2026",
  prime: "\u2032",
  Prime: "\u2033",
  oline: "\u203E",
  frasl: "\u2044",
  weierp: "\u2118",
  image: "\u2111",
  real: "\u211C",
  trade: "\u2122",
  alefsym: "\u2135",
  larr: "\u2190",
  uarr: "\u2191",
  rarr: "\u2192",
  darr: "\u2193",
  harr: "\u2194",
  crarr: "\u21B5",
  lArr: "\u21D0",
  uArr: "\u21D1",
  rArr: "\u21D2",
  dArr: "\u21D3",
  hArr: "\u21D4",
  forall: "\u2200",
  part: "\u2202",
  exist: "\u2203",
  empty: "\u2205",
  nabla: "\u2207",
  isin: "\u2208",
  notin: "\u2209",
  ni: "\u220B",
  prod: "\u220F",
  sum: "\u2211",
  minus: "\u2212",
  lowast: "\u2217",
  radic: "\u221A",
  prop: "\u221D",
  infin: "\u221E",
  ang: "\u2220",
  and: "\u2227",
  or: "\u2228",
  cap: "\u2229",
  cup: "\u222A",
  int: "\u222B",
  there4: "\u2234",
  sim: "\u223C",
  cong: "\u2245",
  asymp: "\u2248",
  ne: "\u2260",
  equiv: "\u2261",
  le: "\u2264",
  ge: "\u2265",
  sub: "\u2282",
  sup: "\u2283",
  nsub: "\u2284",
  sube: "\u2286",
  supe: "\u2287",
  oplus: "\u2295",
  otimes: "\u2297",
  perp: "\u22A5",
  sdot: "\u22C5",
  lceil: "\u2308",
  rceil: "\u2309",
  lfloor: "\u230A",
  rfloor: "\u230B",
  lang: "\u2329",
  rang: "\u232A",
  loz: "\u25CA",
  spades: "\u2660",
  clubs: "\u2663",
  hearts: "\u2665",
  diams: "\u2666",
  quot: '"',
  amp: "&",
  lt: "<",
  gt: ">",
  OElig: "\u0152",
  oelig: "\u0153",
  Scaron: "\u0160",
  scaron: "\u0161",
  Yuml: "\u0178",
  circ: "\u02C6",
  tilde: "\u02DC",
  ensp: "\u2002",
  emsp: "\u2003",
  thinsp: "\u2009",
  zwnj: "\u200C",
  zwj: "\u200D",
  lrm: "\u200E",
  rlm: "\u200F",
  ndash: "\u2013",
  mdash: "\u2014",
  lsquo: "\u2018",
  rsquo: "\u2019",
  sbquo: "\u201A",
  ldquo: "\u201C",
  rdquo: "\u201D",
  bdquo: "\u201E",
  dagger: "\u2020",
  Dagger: "\u2021",
  permil: "\u2030",
  lsaquo: "\u2039",
  rsaquo: "\u203A",
  euro: "\u20AC"
};

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

// node_modules/stringify-entities/lib/util/to-named.js
var own2 = {}.hasOwnProperty;
var characters = {};
var key;
for (key in characterEntitiesHtml4) {
  if (own2.call(characterEntitiesHtml4, key)) {
    characters[characterEntitiesHtml4[key]] = key;
  }
}
var notAlphanumericRegex = /[^\dA-Za-z]/;
function toNamed(code2, next2, omit2, attribute2) {
  const character = String.fromCharCode(code2);
  if (own2.call(characters, character)) {
    const name2 = characters[character];
    const value2 = "&" + name2;
    if (omit2 && characterEntitiesLegacy.includes(name2) && !dangerous.includes(name2) && (!attribute2 || next2 && next2 !== 61 && notAlphanumericRegex.test(String.fromCharCode(next2)))) {
      return value2;
    }
    return value2 + ";";
  }
  return "";
}

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

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

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

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

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

// node_modules/comma-separated-tokens/index.js
function stringify(values2, options2) {
  const settings = options2 || {};
  const input = values2[values2.length - 1] === "" ? [...values2, ""] : values2;
  return input.join(
    (settings.padRight ? " " : "") + "," + (settings.padLeft === false ? "" : " ")
  ).trim();
}

// node_modules/space-separated-tokens/index.js
function stringify2(values2) {
  return values2.join(" ").trim();
}

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

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

// node_modules/hast-util-to-html/lib/omission/omission.js
var own3 = {}.hasOwnProperty;
function omission(handlers3) {
  return omit2;
  function omit2(node, index2, parent) {
    return own3.call(handlers3, node.tagName) && handlers3[node.tagName](node, index2, parent);
  }
}

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

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

// node_modules/hast-util-to-html/lib/handle/element.js
var constants = {
  // See: <https://html.spec.whatwg.org/#attribute-name-state>.
  name: [
    ["	\n\f\r &/=>".split(""), "	\n\f\r \"&'/=>`".split("")],
    [`\0	
\f\r "&'/<=>`.split(""), "\0	\n\f\r \"&'/<=>`".split("")]
  ],
  // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.
  unquoted: [
    ["	\n\f\r &>".split(""), "\0	\n\f\r \"&'<=>`".split("")],
    ["\0	\n\f\r \"&'<=>`".split(""), "\0	\n\f\r \"&'<=>`".split("")]
  ],
  // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.
  single: [
    ["&'".split(""), "\"&'`".split("")],
    ["\0&'".split(""), "\0\"&'`".split("")]
  ],
  // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.
  double: [
    ['"&'.split(""), "\"&'`".split("")],
    ['\0"&'.split(""), "\0\"&'`".split("")]
  ]
};
function element(node, index2, parent, state) {
  const schema7 = state.schema;
  const omit2 = schema7.space === "svg" ? false : state.settings.omitOptionalTags;
  let selfClosing = schema7.space === "svg" ? state.settings.closeEmptyElements : state.settings.voids.includes(node.tagName.toLowerCase());
  const parts = [];
  let last3;
  if (schema7.space === "html" && node.tagName === "svg") {
    state.schema = svg3;
  }
  const attributes = serializeAttributes(state, node.properties);
  const content2 = state.all(
    schema7.space === "html" && node.tagName === "template" ? node.content : node
  );
  state.schema = schema7;
  if (content2) selfClosing = false;
  if (attributes || !omit2 || !opening(node, index2, parent)) {
    parts.push("<", node.tagName, attributes ? " " + attributes : "");
    if (selfClosing && (schema7.space === "svg" || state.settings.closeSelfClosing)) {
      last3 = attributes.charAt(attributes.length - 1);
      if (!state.settings.tightSelfClosing || last3 === "/" || last3 && last3 !== '"' && last3 !== "'") {
        parts.push(" ");
      }
      parts.push("/");
    }
    parts.push(">");
  }
  parts.push(content2);
  if (!selfClosing && (!omit2 || !closing2(node, index2, parent))) {
    parts.push("</" + node.tagName + ">");
  }
  return parts.join("");
}
function serializeAttributes(state, properties) {
  const values2 = [];
  let index2 = -1;
  let key2;
  if (properties) {
    for (key2 in properties) {
      if (properties[key2] !== null && properties[key2] !== void 0) {
        const value2 = serializeAttribute(state, key2, properties[key2]);
        if (value2) values2.push(value2);
      }
    }
  }
  while (++index2 < values2.length) {
    const last3 = state.settings.tightAttributes ? values2[index2].charAt(values2[index2].length - 1) : void 0;
    if (index2 !== values2.length - 1 && last3 !== '"' && last3 !== "'") {
      values2[index2] += " ";
    }
  }
  return values2.join("");
}
function serializeAttribute(state, key2, value2) {
  const info = find3(state.schema, key2);
  const x3 = state.settings.allowParseErrors && state.schema.space === "html" ? 0 : 1;
  const y3 = state.settings.allowDangerousCharacters ? 0 : 1;
  let quote = state.quote;
  let result2;
  if (info.overloadedBoolean && (value2 === info.attribute || value2 === "")) {
    value2 = true;
  } else if ((info.boolean || info.overloadedBoolean) && (typeof value2 !== "string" || value2 === info.attribute || value2 === "")) {
    value2 = Boolean(value2);
  }
  if (value2 === null || value2 === void 0 || value2 === false || typeof value2 === "number" && Number.isNaN(value2)) {
    return "";
  }
  const name2 = stringifyEntities(
    info.attribute,
    Object.assign({}, state.settings.characterReferences, {
      // Always encode without parse errors in non-HTML.
      subset: constants.name[x3][y3]
    })
  );
  if (value2 === true) return name2;
  value2 = Array.isArray(value2) ? (info.commaSeparated ? stringify : stringify2)(value2, {
    padLeft: !state.settings.tightCommaSeparatedLists
  }) : String(value2);
  if (state.settings.collapseEmptyAttributes && !value2) return name2;
  if (state.settings.preferUnquoted) {
    result2 = stringifyEntities(
      value2,
      Object.assign({}, state.settings.characterReferences, {
        attribute: true,
        subset: constants.unquoted[x3][y3]
      })
    );
  }
  if (result2 !== value2) {
    if (state.settings.quoteSmart && ccount(value2, quote) > ccount(value2, state.alternative)) {
      quote = state.alternative;
    }
    result2 = quote + stringifyEntities(
      value2,
      Object.assign({}, state.settings.characterReferences, {
        // Always encode without parse errors in non-HTML.
        subset: (quote === "'" ? constants.single : constants.double)[x3][y3],
        attribute: true
      })
    ) + quote;
  }
  return name2 + (result2 ? "=" + result2 : result2);
}

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

// node_modules/hast-util-to-html/lib/handle/raw.js
function raw(node, index2, parent, state) {
  return state.settings.allowDangerousHtml ? node.value : text2(node, index2, parent, state);
}

// node_modules/hast-util-to-html/lib/handle/root.js
function root2(node, _1, _22, state) {
  return state.all(node);
}

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

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

// node_modules/@shikijs/core/dist/index.mjs
function toArray2(x3) {
  return Array.isArray(x3) ? x3 : [x3];
}
function splitLines(code2, preserveEnding = false) {
  const parts = code2.split(/(\r?\n)/g);
  let index2 = 0;
  const lines = [];
  for (let i3 = 0; i3 < parts.length; i3 += 2) {
    const line = preserveEnding ? parts[i3] + (parts[i3 + 1] || "") : parts[i3];
    lines.push([line, index2]);
    index2 += parts[i3].length;
    index2 += parts[i3 + 1]?.length || 0;
  }
  return lines;
}
function isPlainLang(lang2) {
  return !lang2 || ["plaintext", "txt", "text", "plain"].includes(lang2);
}
function isSpecialLang(lang2) {
  return lang2 === "ansi" || isPlainLang(lang2);
}
function isNoneTheme(theme2) {
  return theme2 === "none";
}
function isSpecialTheme(theme2) {
  return isNoneTheme(theme2);
}
function addClassToHast(node, className2) {
  if (!className2)
    return node;
  node.properties ||= {};
  node.properties.class ||= [];
  if (typeof node.properties.class === "string")
    node.properties.class = node.properties.class.split(/\s+/g);
  if (!Array.isArray(node.properties.class))
    node.properties.class = [];
  const targets = Array.isArray(className2) ? className2 : className2.split(/\s+/g);
  for (const c3 of targets) {
    if (c3 && !node.properties.class.includes(c3))
      node.properties.class.push(c3);
  }
  return node;
}
function splitToken(token, offsets) {
  let lastOffset = 0;
  const tokens = [];
  for (const offset of offsets) {
    if (offset > lastOffset) {
      tokens.push({
        ...token,
        content: token.content.slice(lastOffset, offset),
        offset: token.offset + lastOffset
      });
    }
    lastOffset = offset;
  }
  if (lastOffset < token.content.length) {
    tokens.push({
      ...token,
      content: token.content.slice(lastOffset),
      offset: token.offset + lastOffset
    });
  }
  return tokens;
}
function splitTokens(tokens, breakpoints2) {
  const sorted = Array.from(breakpoints2 instanceof Set ? breakpoints2 : new Set(breakpoints2)).sort((a3, b3) => a3 - b3);
  if (!sorted.length)
    return tokens;
  return tokens.map((line) => {
    return line.flatMap((token) => {
      const breakpointsInToken = sorted.filter((i3) => token.offset < i3 && i3 < token.offset + token.content.length).map((i3) => i3 - token.offset).sort((a3, b3) => a3 - b3);
      if (!breakpointsInToken.length)
        return token;
      return splitToken(token, breakpointsInToken);
    });
  });
}
async function normalizeGetter(p4) {
  return Promise.resolve(typeof p4 === "function" ? p4() : p4).then((r3) => r3.default || r3);
}
function resolveColorReplacements(theme2, options2) {
  const replacements = typeof theme2 === "string" ? {} : { ...theme2.colorReplacements };
  const themeName2 = typeof theme2 === "string" ? theme2 : theme2.name;
  for (const [key2, value2] of Object.entries(options2?.colorReplacements || {})) {
    if (typeof value2 === "string")
      replacements[key2] = value2;
    else if (key2 === themeName2)
      Object.assign(replacements, value2);
  }
  return replacements;
}
function applyColorReplacements(color, replacements) {
  if (!color)
    return color;
  return replacements?.[color?.toLowerCase()] || color;
}
function getTokenStyleObject(token) {
  const styles = {};
  if (token.color)
    styles.color = token.color;
  if (token.bgColor)
    styles["background-color"] = token.bgColor;
  if (token.fontStyle) {
    if (token.fontStyle & FontStyle.Italic)
      styles["font-style"] = "italic";
    if (token.fontStyle & FontStyle.Bold)
      styles["font-weight"] = "bold";
    if (token.fontStyle & FontStyle.Underline)
      styles["text-decoration"] = "underline";
  }
  return styles;
}
function stringifyTokenStyle(token) {
  if (typeof token === "string")
    return token;
  return Object.entries(token).map(([key2, value2]) => `${key2}:${value2}`).join(";");
}
function createPositionConverter(code2) {
  const lines = splitLines(code2, true).map(([line]) => line);
  function indexToPos(index2) {
    if (index2 === code2.length) {
      return {
        line: lines.length - 1,
        character: lines[lines.length - 1].length
      };
    }
    let character = index2;
    let line = 0;
    for (const lineText of lines) {
      if (character < lineText.length)
        break;
      character -= lineText.length;
      line++;
    }
    return { line, character };
  }
  function posToIndex(line, character) {
    let index2 = 0;
    for (let i3 = 0; i3 < line; i3++)
      index2 += lines[i3].length;
    index2 += character;
    return index2;
  }
  return {
    lines,
    indexToPos,
    posToIndex
  };
}
var ShikiError3 = class extends Error {
  constructor(message) {
    super(message);
    this.name = "ShikiError";
  }
};
var _grammarStateMap = /* @__PURE__ */ new WeakMap();
function setLastGrammarStateToMap(keys5, state) {
  _grammarStateMap.set(keys5, state);
}
function getLastGrammarStateFromMap(keys5) {
  return _grammarStateMap.get(keys5);
}
var GrammarState = class _GrammarState {
  /**
   * Theme to Stack mapping
   */
  _stacks = {};
  lang;
  get themes() {
    return Object.keys(this._stacks);
  }
  get theme() {
    return this.themes[0];
  }
  get _stack() {
    return this._stacks[this.theme];
  }
  /**
   * Static method to create a initial grammar state.
   */
  static initial(lang2, themes) {
    return new _GrammarState(
      Object.fromEntries(toArray2(themes).map((theme2) => [theme2, INITIAL])),
      lang2
    );
  }
  constructor(...args) {
    if (args.length === 2) {
      const [stacksMap, lang2] = args;
      this.lang = lang2;
      this._stacks = stacksMap;
    } else {
      const [stack, lang2, theme2] = args;
      this.lang = lang2;
      this._stacks = { [theme2]: stack };
    }
  }
  /**
   * Get the internal stack object.
   * @internal
   */
  getInternalStack(theme2 = this.theme) {
    return this._stacks[theme2];
  }
  /**
   * @deprecated use `getScopes` instead
   */
  get scopes() {
    warnDeprecated("GrammarState.scopes is deprecated, use GrammarState.getScopes() instead");
    return getScopes(this._stacks[this.theme]);
  }
  getScopes(theme2 = this.theme) {
    return getScopes(this._stacks[theme2]);
  }
  toJSON() {
    return {
      lang: this.lang,
      theme: this.theme,
      themes: this.themes,
      scopes: this.scopes
    };
  }
};
function getScopes(stack) {
  const scopes = [];
  const visited = /* @__PURE__ */ new Set();
  function pushScope(stack2) {
    if (visited.has(stack2))
      return;
    visited.add(stack2);
    const name2 = stack2?.nameScopesList?.scopeName;
    if (name2)
      scopes.push(name2);
    if (stack2.parent)
      pushScope(stack2.parent);
  }
  pushScope(stack);
  return scopes;
}
function getGrammarStack(state, theme2) {
  if (!(state instanceof GrammarState))
    throw new ShikiError3("Invalid grammar state");
  return state.getInternalStack(theme2);
}
function transformerDecorations() {
  const map5 = /* @__PURE__ */ new WeakMap();
  function getContext(shiki) {
    if (!map5.has(shiki.meta)) {
      let normalizePosition = function(p4) {
        if (typeof p4 === "number") {
          if (p4 < 0 || p4 > shiki.source.length)
            throw new ShikiError3(`Invalid decoration offset: ${p4}. Code length: ${shiki.source.length}`);
          return {
            ...converter.indexToPos(p4),
            offset: p4
          };
        } else {
          const line = converter.lines[p4.line];
          if (line === void 0)
            throw new ShikiError3(`Invalid decoration position ${JSON.stringify(p4)}. Lines length: ${converter.lines.length}`);
          if (p4.character < 0 || p4.character > line.length)
            throw new ShikiError3(`Invalid decoration position ${JSON.stringify(p4)}. Line ${p4.line} length: ${line.length}`);
          return {
            ...p4,
            offset: converter.posToIndex(p4.line, p4.character)
          };
        }
      };
      const converter = createPositionConverter(shiki.source);
      const decorations3 = (shiki.options.decorations || []).map((d3) => ({
        ...d3,
        start: normalizePosition(d3.start),
        end: normalizePosition(d3.end)
      }));
      verifyIntersections(decorations3);
      map5.set(shiki.meta, {
        decorations: decorations3,
        converter,
        source: shiki.source
      });
    }
    return map5.get(shiki.meta);
  }
  return {
    name: "shiki:decorations",
    tokens(tokens) {
      if (!this.options.decorations?.length)
        return;
      const ctx = getContext(this);
      const breakpoints2 = ctx.decorations.flatMap((d3) => [d3.start.offset, d3.end.offset]);
      const splitted = splitTokens(tokens, breakpoints2);
      return splitted;
    },
    code(codeEl) {
      if (!this.options.decorations?.length)
        return;
      const ctx = getContext(this);
      const lines = Array.from(codeEl.children).filter((i3) => i3.type === "element" && i3.tagName === "span");
      if (lines.length !== ctx.converter.lines.length)
        throw new ShikiError3(`Number of lines in code element (${lines.length}) does not match the number of lines in the source (${ctx.converter.lines.length}). Failed to apply decorations.`);
      function applyLineSection(line, start, end, decoration) {
        const lineEl = lines[line];
        let text3 = "";
        let startIndex = -1;
        let endIndex = -1;
        if (start === 0)
          startIndex = 0;
        if (end === 0)
          endIndex = 0;
        if (end === Number.POSITIVE_INFINITY)
          endIndex = lineEl.children.length;
        if (startIndex === -1 || endIndex === -1) {
          for (let i3 = 0; i3 < lineEl.children.length; i3++) {
            text3 += stringify3(lineEl.children[i3]);
            if (startIndex === -1 && text3.length === start)
              startIndex = i3 + 1;
            if (endIndex === -1 && text3.length === end)
              endIndex = i3 + 1;
          }
        }
        if (startIndex === -1)
          throw new ShikiError3(`Failed to find start index for decoration ${JSON.stringify(decoration.start)}`);
        if (endIndex === -1)
          throw new ShikiError3(`Failed to find end index for decoration ${JSON.stringify(decoration.end)}`);
        const children2 = lineEl.children.slice(startIndex, endIndex);
        if (!decoration.alwaysWrap && children2.length === lineEl.children.length) {
          applyDecoration(lineEl, decoration, "line");
        } else if (!decoration.alwaysWrap && children2.length === 1 && children2[0].type === "element") {
          applyDecoration(children2[0], decoration, "token");
        } else {
          const wrapper = {
            type: "element",
            tagName: "span",
            properties: {},
            children: children2
          };
          applyDecoration(wrapper, decoration, "wrapper");
          lineEl.children.splice(startIndex, children2.length, wrapper);
        }
      }
      function applyLine(line, decoration) {
        lines[line] = applyDecoration(lines[line], decoration, "line");
      }
      function applyDecoration(el2, decoration, type) {
        const properties = decoration.properties || {};
        const transform = decoration.transform || ((i3) => i3);
        el2.tagName = decoration.tagName || "span";
        el2.properties = {
          ...el2.properties,
          ...properties,
          class: el2.properties.class
        };
        if (decoration.properties?.class)
          addClassToHast(el2, decoration.properties.class);
        el2 = transform(el2, type) || el2;
        return el2;
      }
      const lineApplies = [];
      const sorted = ctx.decorations.sort((a3, b3) => b3.start.offset - a3.start.offset);
      for (const decoration of sorted) {
        const { start, end } = decoration;
        if (start.line === end.line) {
          applyLineSection(start.line, start.character, end.character, decoration);
        } else if (start.line < end.line) {
          applyLineSection(start.line, start.character, Number.POSITIVE_INFINITY, decoration);
          for (let i3 = start.line + 1; i3 < end.line; i3++)
            lineApplies.unshift(() => applyLine(i3, decoration));
          applyLineSection(end.line, 0, end.character, decoration);
        }
      }
      lineApplies.forEach((i3) => i3());
    }
  };
}
function verifyIntersections(items) {
  for (let i3 = 0; i3 < items.length; i3++) {
    const foo = items[i3];
    if (foo.start.offset > foo.end.offset)
      throw new ShikiError3(`Invalid decoration range: ${JSON.stringify(foo.start)} - ${JSON.stringify(foo.end)}`);
    for (let j = i3 + 1; j < items.length; j++) {
      const bar = items[j];
      const isFooHasBarStart = foo.start.offset < bar.start.offset && bar.start.offset < foo.end.offset;
      const isFooHasBarEnd = foo.start.offset < bar.end.offset && bar.end.offset < foo.end.offset;
      const isBarHasFooStart = bar.start.offset < foo.start.offset && foo.start.offset < bar.end.offset;
      const isBarHasFooEnd = bar.start.offset < foo.end.offset && foo.end.offset < bar.end.offset;
      if (isFooHasBarStart || isFooHasBarEnd || isBarHasFooStart || isBarHasFooEnd) {
        if (isFooHasBarEnd && isFooHasBarEnd)
          continue;
        if (isBarHasFooStart && isBarHasFooEnd)
          continue;
        throw new ShikiError3(`Decorations ${JSON.stringify(foo.start)} and ${JSON.stringify(bar.start)} intersect.`);
      }
    }
  }
}
function stringify3(el2) {
  if (el2.type === "text")
    return el2.value;
  if (el2.type === "element")
    return el2.children.map(stringify3).join("");
  return "";
}
var builtInTransformers = [
  /* @__PURE__ */ transformerDecorations()
];
function getTransformers(options2) {
  return [
    ...options2.transformers || [],
    ...builtInTransformers
  ];
}
var namedColors = [
  "black",
  "red",
  "green",
  "yellow",
  "blue",
  "magenta",
  "cyan",
  "white",
  "brightBlack",
  "brightRed",
  "brightGreen",
  "brightYellow",
  "brightBlue",
  "brightMagenta",
  "brightCyan",
  "brightWhite"
];
var decorations2 = {
  1: "bold",
  2: "dim",
  3: "italic",
  4: "underline",
  7: "reverse",
  9: "strikethrough"
};
function findSequence(value2, position) {
  const nextEscape = value2.indexOf("\x1B[", position);
  if (nextEscape !== -1) {
    const nextClose = value2.indexOf("m", nextEscape);
    return {
      sequence: value2.substring(nextEscape + 2, nextClose).split(";"),
      startPosition: nextEscape,
      position: nextClose + 1
    };
  }
  return {
    position: value2.length
  };
}
function parseColor(sequence, index2) {
  let offset = 1;
  const colorMode = sequence[index2 + offset++];
  let color;
  if (colorMode === "2") {
    const rgb = [
      sequence[index2 + offset++],
      sequence[index2 + offset++],
      sequence[index2 + offset]
    ].map((x3) => Number.parseInt(x3));
    if (rgb.length === 3 && !rgb.some((x3) => Number.isNaN(x3))) {
      color = {
        type: "rgb",
        rgb
      };
    }
  } else if (colorMode === "5") {
    const colorIndex = Number.parseInt(sequence[index2 + offset]);
    if (!Number.isNaN(colorIndex)) {
      color = { type: "table", index: Number(colorIndex) };
    }
  }
  return [offset, color];
}
function parseSequence(sequence) {
  const commands = [];
  for (let i3 = 0; i3 < sequence.length; i3++) {
    const code2 = sequence[i3];
    const codeInt = Number.parseInt(code2);
    if (Number.isNaN(codeInt))
      continue;
    if (codeInt === 0) {
      commands.push({ type: "resetAll" });
    } else if (codeInt <= 9) {
      const decoration = decorations2[codeInt];
      if (decoration) {
        commands.push({
          type: "setDecoration",
          value: decorations2[codeInt]
        });
      }
    } else if (codeInt <= 29) {
      const decoration = decorations2[codeInt - 20];
      if (decoration) {
        commands.push({
          type: "resetDecoration",
          value: decoration
        });
      }
    } else if (codeInt <= 37) {
      commands.push({
        type: "setForegroundColor",
        value: { type: "named", name: namedColors[codeInt - 30] }
      });
    } else if (codeInt === 38) {
      const [offset, color] = parseColor(sequence, i3);
      if (color) {
        commands.push({
          type: "setForegroundColor",
          value: color
        });
      }
      i3 += offset;
    } else if (codeInt === 39) {
      commands.push({
        type: "resetForegroundColor"
      });
    } else if (codeInt <= 47) {
      commands.push({
        type: "setBackgroundColor",
        value: { type: "named", name: namedColors[codeInt - 40] }
      });
    } else if (codeInt === 48) {
      const [offset, color] = parseColor(sequence, i3);
      if (color) {
        commands.push({
          type: "setBackgroundColor",
          value: color
        });
      }
      i3 += offset;
    } else if (codeInt === 49) {
      commands.push({
        type: "resetBackgroundColor"
      });
    } else if (codeInt >= 90 && codeInt <= 97) {
      commands.push({
        type: "setForegroundColor",
        value: { type: "named", name: namedColors[codeInt - 90 + 8] }
      });
    } else if (codeInt >= 100 && codeInt <= 107) {
      commands.push({
        type: "setBackgroundColor",
        value: { type: "named", name: namedColors[codeInt - 100 + 8] }
      });
    }
  }
  return commands;
}
function createAnsiSequenceParser() {
  let foreground = null;
  let background = null;
  let decorations22 = /* @__PURE__ */ new Set();
  return {
    parse(value2) {
      const tokens = [];
      let position = 0;
      do {
        const findResult = findSequence(value2, position);
        const text3 = findResult.sequence ? value2.substring(position, findResult.startPosition) : value2.substring(position);
        if (text3.length > 0) {
          tokens.push({
            value: text3,
            foreground,
            background,
            decorations: new Set(decorations22)
          });
        }
        if (findResult.sequence) {
          const commands = parseSequence(findResult.sequence);
          for (const styleToken of commands) {
            if (styleToken.type === "resetAll") {
              foreground = null;
              background = null;
              decorations22.clear();
            } else if (styleToken.type === "resetForegroundColor") {
              foreground = null;
            } else if (styleToken.type === "resetBackgroundColor") {
              background = null;
            } else if (styleToken.type === "resetDecoration") {
              decorations22.delete(styleToken.value);
            }
          }
          for (const styleToken of commands) {
            if (styleToken.type === "setForegroundColor") {
              foreground = styleToken.value;
            } else if (styleToken.type === "setBackgroundColor") {
              background = styleToken.value;
            } else if (styleToken.type === "setDecoration") {
              decorations22.add(styleToken.value);
            }
          }
        }
        position = findResult.position;
      } while (position < value2.length);
      return tokens;
    }
  };
}
var defaultNamedColorsMap = {
  black: "#000000",
  red: "#bb0000",
  green: "#00bb00",
  yellow: "#bbbb00",
  blue: "#0000bb",
  magenta: "#ff00ff",
  cyan: "#00bbbb",
  white: "#eeeeee",
  brightBlack: "#555555",
  brightRed: "#ff5555",
  brightGreen: "#00ff00",
  brightYellow: "#ffff55",
  brightBlue: "#5555ff",
  brightMagenta: "#ff55ff",
  brightCyan: "#55ffff",
  brightWhite: "#ffffff"
};
function createColorPalette(namedColorsMap = defaultNamedColorsMap) {
  function namedColor(name2) {
    return namedColorsMap[name2];
  }
  function rgbColor(rgb) {
    return `#${rgb.map((x3) => Math.max(0, Math.min(x3, 255)).toString(16).padStart(2, "0")).join("")}`;
  }
  let colorTable;
  function getColorTable() {
    if (colorTable) {
      return colorTable;
    }
    colorTable = [];
    for (let i3 = 0; i3 < namedColors.length; i3++) {
      colorTable.push(namedColor(namedColors[i3]));
    }
    let levels = [0, 95, 135, 175, 215, 255];
    for (let r3 = 0; r3 < 6; r3++) {
      for (let g3 = 0; g3 < 6; g3++) {
        for (let b3 = 0; b3 < 6; b3++) {
          colorTable.push(rgbColor([levels[r3], levels[g3], levels[b3]]));
        }
      }
    }
    let level = 8;
    for (let i3 = 0; i3 < 24; i3++, level += 10) {
      colorTable.push(rgbColor([level, level, level]));
    }
    return colorTable;
  }
  function tableColor(index2) {
    return getColorTable()[index2];
  }
  function value2(color) {
    switch (color.type) {
      case "named":
        return namedColor(color.name);
      case "rgb":
        return rgbColor(color.rgb);
      case "table":
        return tableColor(color.index);
    }
  }
  return {
    value: value2
  };
}
function tokenizeAnsiWithTheme(theme2, fileContents, options2) {
  const colorReplacements = resolveColorReplacements(theme2, options2);
  const lines = splitLines(fileContents);
  const colorPalette2 = createColorPalette(
    Object.fromEntries(
      namedColors.map((name2) => [
        name2,
        theme2.colors?.[`terminal.ansi${name2[0].toUpperCase()}${name2.substring(1)}`]
      ])
    )
  );
  const parser4 = createAnsiSequenceParser();
  return lines.map(
    (line) => parser4.parse(line[0]).map((token) => {
      let color;
      let bgColor;
      if (token.decorations.has("reverse")) {
        color = token.background ? colorPalette2.value(token.background) : theme2.bg;
        bgColor = token.foreground ? colorPalette2.value(token.foreground) : theme2.fg;
      } else {
        color = token.foreground ? colorPalette2.value(token.foreground) : theme2.fg;
        bgColor = token.background ? colorPalette2.value(token.background) : void 0;
      }
      color = applyColorReplacements(color, colorReplacements);
      bgColor = applyColorReplacements(bgColor, colorReplacements);
      if (token.decorations.has("dim"))
        color = dimColor(color);
      let fontStyle = FontStyle.None;
      if (token.decorations.has("bold"))
        fontStyle |= FontStyle.Bold;
      if (token.decorations.has("italic"))
        fontStyle |= FontStyle.Italic;
      if (token.decorations.has("underline"))
        fontStyle |= FontStyle.Underline;
      return {
        content: token.value,
        offset: line[1],
        // TODO: more accurate offset? might need to fork ansi-sequence-parser
        color,
        bgColor,
        fontStyle
      };
    })
  );
}
function dimColor(color) {
  const hexMatch = color.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/);
  if (hexMatch) {
    if (hexMatch[3]) {
      const alpha = Math.round(Number.parseInt(hexMatch[3], 16) / 2).toString(16).padStart(2, "0");
      return `#${hexMatch[1]}${hexMatch[2]}${alpha}`;
    } else if (hexMatch[2]) {
      return `#${hexMatch[1]}${hexMatch[2]}80`;
    } else {
      return `#${Array.from(hexMatch[1]).map((x3) => `${x3}${x3}`).join("")}80`;
    }
  }
  const cssVarMatch = color.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);
  if (cssVarMatch)
    return `var(${cssVarMatch[1]}-dim)`;
  return color;
}
function codeToTokensBase(internal, code2, options2 = {}) {
  const {
    lang: lang2 = "text",
    theme: themeName2 = internal.getLoadedThemes()[0]
  } = options2;
  if (isPlainLang(lang2) || isNoneTheme(themeName2))
    return splitLines(code2).map((line) => [{ content: line[0], offset: line[1] }]);
  const { theme: theme2, colorMap } = internal.setTheme(themeName2);
  if (lang2 === "ansi")
    return tokenizeAnsiWithTheme(theme2, code2, options2);
  const _grammar = internal.getLanguage(lang2);
  if (options2.grammarState) {
    if (options2.grammarState.lang !== _grammar.name) {
      throw new ShikiError(`Grammar state language "${options2.grammarState.lang}" does not match highlight language "${_grammar.name}"`);
    }
    if (!options2.grammarState.themes.includes(theme2.name)) {
      throw new ShikiError(`Grammar state themes "${options2.grammarState.themes}" do not contain highlight theme "${theme2.name}"`);
    }
  }
  return tokenizeWithTheme(code2, _grammar, theme2, colorMap, options2);
}
function getLastGrammarState(...args) {
  if (args.length === 2) {
    return getLastGrammarStateFromMap(args[1]);
  }
  const [internal, code2, options2 = {}] = args;
  const {
    lang: lang2 = "text",
    theme: themeName2 = internal.getLoadedThemes()[0]
  } = options2;
  if (isPlainLang(lang2) || isNoneTheme(themeName2))
    throw new ShikiError("Plain language does not have grammar state");
  if (lang2 === "ansi")
    throw new ShikiError("ANSI language does not have grammar state");
  const { theme: theme2, colorMap } = internal.setTheme(themeName2);
  const _grammar = internal.getLanguage(lang2);
  return new GrammarState(
    _tokenizeWithTheme(code2, _grammar, theme2, colorMap, options2).stateStack,
    _grammar.name,
    theme2.name
  );
}
function tokenizeWithTheme(code2, grammar, theme2, colorMap, options2) {
  const result2 = _tokenizeWithTheme(code2, grammar, theme2, colorMap, options2);
  const grammarState = new GrammarState(
    _tokenizeWithTheme(code2, grammar, theme2, colorMap, options2).stateStack,
    grammar.name,
    theme2.name
  );
  setLastGrammarStateToMap(result2.tokens, grammarState);
  return result2.tokens;
}
function _tokenizeWithTheme(code2, grammar, theme2, colorMap, options2) {
  const colorReplacements = resolveColorReplacements(theme2, options2);
  const {
    tokenizeMaxLineLength = 0,
    tokenizeTimeLimit = 500
  } = options2;
  const lines = splitLines(code2);
  let stateStack = options2.grammarState ? getGrammarStack(options2.grammarState, theme2.name) ?? INITIAL : options2.grammarContextCode != null ? _tokenizeWithTheme(
    options2.grammarContextCode,
    grammar,
    theme2,
    colorMap,
    {
      ...options2,
      grammarState: void 0,
      grammarContextCode: void 0
    }
  ).stateStack : INITIAL;
  let actual = [];
  const final = [];
  for (let i3 = 0, len = lines.length; i3 < len; i3++) {
    const [line, lineOffset] = lines[i3];
    if (line === "") {
      actual = [];
      final.push([]);
      continue;
    }
    if (tokenizeMaxLineLength > 0 && line.length >= tokenizeMaxLineLength) {
      actual = [];
      final.push([{
        content: line,
        offset: lineOffset,
        color: "",
        fontStyle: 0
      }]);
      continue;
    }
    let resultWithScopes;
    let tokensWithScopes;
    let tokensWithScopesIndex;
    if (options2.includeExplanation) {
      resultWithScopes = grammar.tokenizeLine(line, stateStack);
      tokensWithScopes = resultWithScopes.tokens;
      tokensWithScopesIndex = 0;
    }
    const result2 = grammar.tokenizeLine2(line, stateStack, tokenizeTimeLimit);
    const tokensLength = result2.tokens.length / 2;
    for (let j = 0; j < tokensLength; j++) {
      const startIndex = result2.tokens[2 * j];
      const nextStartIndex = j + 1 < tokensLength ? result2.tokens[2 * j + 2] : line.length;
      if (startIndex === nextStartIndex)
        continue;
      const metadata = result2.tokens[2 * j + 1];
      const color = applyColorReplacements(
        colorMap[EncodedTokenMetadata.getForeground(metadata)],
        colorReplacements
      );
      const fontStyle = EncodedTokenMetadata.getFontStyle(metadata);
      const token = {
        content: line.substring(startIndex, nextStartIndex),
        offset: lineOffset + startIndex,
        color,
        fontStyle
      };
      if (options2.includeExplanation) {
        const themeSettingsSelectors = [];
        if (options2.includeExplanation !== "scopeName") {
          for (const setting of theme2.settings) {
            let selectors;
            switch (typeof setting.scope) {
              case "string":
                selectors = setting.scope.split(/,/).map((scope) => scope.trim());
                break;
              case "object":
                selectors = setting.scope;
                break;
              default:
                continue;
            }
            themeSettingsSelectors.push({
              settings: setting,
              selectors: selectors.map((selector) => selector.split(/ /))
            });
          }
        }
        token.explanation = [];
        let offset = 0;
        while (startIndex + offset < nextStartIndex) {
          const tokenWithScopes = tokensWithScopes[tokensWithScopesIndex];
          const tokenWithScopesText = line.substring(
            tokenWithScopes.startIndex,
            tokenWithScopes.endIndex
          );
          offset += tokenWithScopesText.length;
          token.explanation.push({
            content: tokenWithScopesText,
            scopes: options2.includeExplanation === "scopeName" ? explainThemeScopesNameOnly(
              tokenWithScopes.scopes
            ) : explainThemeScopesFull(
              themeSettingsSelectors,
              tokenWithScopes.scopes
            )
          });
          tokensWithScopesIndex += 1;
        }
      }
      actual.push(token);
    }
    final.push(actual);
    actual = [];
    stateStack = result2.ruleStack;
  }
  return {
    tokens: final,
    stateStack
  };
}
function explainThemeScopesNameOnly(scopes) {
  return scopes.map((scope) => ({ scopeName: scope }));
}
function explainThemeScopesFull(themeSelectors, scopes) {
  const result2 = [];
  for (let i3 = 0, len = scopes.length; i3 < len; i3++) {
    const scope = scopes[i3];
    result2[i3] = {
      scopeName: scope,
      themeMatches: explainThemeScope(themeSelectors, scope, scopes.slice(0, i3))
    };
  }
  return result2;
}
function matchesOne(selector, scope) {
  return selector === scope || scope.substring(0, selector.length) === selector && scope[selector.length] === ".";
}
function matches2(selectors, scope, parentScopes) {
  if (!matchesOne(selectors[selectors.length - 1], scope))
    return false;
  let selectorParentIndex = selectors.length - 2;
  let parentIndex = parentScopes.length - 1;
  while (selectorParentIndex >= 0 && parentIndex >= 0) {
    if (matchesOne(selectors[selectorParentIndex], parentScopes[parentIndex]))
      selectorParentIndex -= 1;
    parentIndex -= 1;
  }
  if (selectorParentIndex === -1)
    return true;
  return false;
}
function explainThemeScope(themeSettingsSelectors, scope, parentScopes) {
  const result2 = [];
  for (const { selectors, settings } of themeSettingsSelectors) {
    for (const selectorPieces of selectors) {
      if (matches2(selectorPieces, scope, parentScopes)) {
        result2.push(settings);
        break;
      }
    }
  }
  return result2;
}
function codeToTokensWithThemes(internal, code2, options2) {
  const themes = Object.entries(options2.themes).filter((i3) => i3[1]).map((i3) => ({ color: i3[0], theme: i3[1] }));
  const themedTokens = themes.map((t3) => {
    const tokens2 = codeToTokensBase(internal, code2, {
      ...options2,
      theme: t3.theme
    });
    const state = getLastGrammarStateFromMap(tokens2);
    const theme2 = typeof t3.theme === "string" ? t3.theme : t3.theme.name;
    return {
      tokens: tokens2,
      state,
      theme: theme2
    };
  });
  const tokens = syncThemesTokenization(
    ...themedTokens.map((i3) => i3.tokens)
  );
  const mergedTokens = tokens[0].map(
    (line, lineIdx) => line.map((_token, tokenIdx) => {
      const mergedToken = {
        content: _token.content,
        variants: {},
        offset: _token.offset
      };
      if ("includeExplanation" in options2 && options2.includeExplanation) {
        mergedToken.explanation = _token.explanation;
      }
      tokens.forEach((t3, themeIdx) => {
        const {
          content: _5,
          explanation: __2,
          offset: ___,
          ...styles
        } = t3[lineIdx][tokenIdx];
        mergedToken.variants[themes[themeIdx].color] = styles;
      });
      return mergedToken;
    })
  );
  const mergedGrammarState = themedTokens[0].state ? new GrammarState(
    Object.fromEntries(themedTokens.map((s3) => [s3.theme, s3.state?.getInternalStack(s3.theme)])),
    themedTokens[0].state.lang
  ) : void 0;
  if (mergedGrammarState)
    setLastGrammarStateToMap(mergedTokens, mergedGrammarState);
  return mergedTokens;
}
function syncThemesTokenization(...themes) {
  const outThemes = themes.map(() => []);
  const count = themes.length;
  for (let i3 = 0; i3 < themes[0].length; i3++) {
    const lines = themes.map((t3) => t3[i3]);
    const outLines = outThemes.map(() => []);
    outThemes.forEach((t3, i22) => t3.push(outLines[i22]));
    const indexes = lines.map(() => 0);
    const current = lines.map((l3) => l3[0]);
    while (current.every((t3) => t3)) {
      const minLength = Math.min(...current.map((t3) => t3.content.length));
      for (let n4 = 0; n4 < count; n4++) {
        const token = current[n4];
        if (token.content.length === minLength) {
          outLines[n4].push(token);
          indexes[n4] += 1;
          current[n4] = lines[n4][indexes[n4]];
        } else {
          outLines[n4].push({
            ...token,
            content: token.content.slice(0, minLength)
          });
          current[n4] = {
            ...token,
            content: token.content.slice(minLength),
            offset: token.offset + minLength
          };
        }
      }
    }
  }
  return outThemes;
}
function codeToTokens(internal, code2, options2) {
  let bg;
  let fg;
  let tokens;
  let themeName2;
  let rootStyle;
  let grammarState;
  if ("themes" in options2) {
    const {
      defaultColor = "light",
      cssVariablePrefix = "--shiki-"
    } = options2;
    const themes = Object.entries(options2.themes).filter((i3) => i3[1]).map((i3) => ({ color: i3[0], theme: i3[1] })).sort((a3, b3) => a3.color === defaultColor ? -1 : b3.color === defaultColor ? 1 : 0);
    if (themes.length === 0)
      throw new ShikiError("`themes` option must not be empty");
    const themeTokens = codeToTokensWithThemes(
      internal,
      code2,
      options2
    );
    grammarState = getLastGrammarStateFromMap(themeTokens);
    if (defaultColor && !themes.find((t3) => t3.color === defaultColor))
      throw new ShikiError(`\`themes\` option must contain the defaultColor key \`${defaultColor}\``);
    const themeRegs = themes.map((t3) => internal.getTheme(t3.theme));
    const themesOrder = themes.map((t3) => t3.color);
    tokens = themeTokens.map((line) => line.map((token) => mergeToken(token, themesOrder, cssVariablePrefix, defaultColor)));
    if (grammarState)
      setLastGrammarStateToMap(tokens, grammarState);
    const themeColorReplacements = themes.map((t3) => resolveColorReplacements(t3.theme, options2));
    fg = themes.map((t3, idx) => (idx === 0 && defaultColor ? "" : `${cssVariablePrefix + t3.color}:`) + (applyColorReplacements(themeRegs[idx].fg, themeColorReplacements[idx]) || "inherit")).join(";");
    bg = themes.map((t3, idx) => (idx === 0 && defaultColor ? "" : `${cssVariablePrefix + t3.color}-bg:`) + (applyColorReplacements(themeRegs[idx].bg, themeColorReplacements[idx]) || "inherit")).join(";");
    themeName2 = `shiki-themes ${themeRegs.map((t3) => t3.name).join(" ")}`;
    rootStyle = defaultColor ? void 0 : [fg, bg].join(";");
  } else if ("theme" in options2) {
    const colorReplacements = resolveColorReplacements(options2.theme, options2);
    tokens = codeToTokensBase(
      internal,
      code2,
      options2
    );
    const _theme = internal.getTheme(options2.theme);
    bg = applyColorReplacements(_theme.bg, colorReplacements);
    fg = applyColorReplacements(_theme.fg, colorReplacements);
    themeName2 = _theme.name;
    grammarState = getLastGrammarStateFromMap(tokens);
  } else {
    throw new ShikiError("Invalid options, either `theme` or `themes` must be provided");
  }
  return {
    tokens,
    fg,
    bg,
    themeName: themeName2,
    rootStyle,
    grammarState
  };
}
function mergeToken(merged, variantsOrder, cssVariablePrefix, defaultColor) {
  const token = {
    content: merged.content,
    explanation: merged.explanation,
    offset: merged.offset
  };
  const styles = variantsOrder.map((t3) => getTokenStyleObject(merged.variants[t3]));
  const styleKeys = new Set(styles.flatMap((t3) => Object.keys(t3)));
  const mergedStyles = {};
  styles.forEach((cur2, idx) => {
    for (const key2 of styleKeys) {
      const value2 = cur2[key2] || "inherit";
      if (idx === 0 && defaultColor) {
        mergedStyles[key2] = value2;
      } else {
        const keyName2 = key2 === "color" ? "" : key2 === "background-color" ? "-bg" : `-${key2}`;
        const varKey = cssVariablePrefix + variantsOrder[idx] + (key2 === "color" ? "" : keyName2);
        mergedStyles[varKey] = value2;
      }
    }
  });
  token.htmlStyle = mergedStyles;
  return token;
}
function codeToHast(internal, code2, options2, transformerContext = {
  meta: {},
  options: options2,
  codeToHast: (_code, _options) => codeToHast(internal, _code, _options),
  codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)
}) {
  let input = code2;
  for (const transformer of getTransformers(options2))
    input = transformer.preprocess?.call(transformerContext, input, options2) || input;
  let {
    tokens,
    fg,
    bg,
    themeName: themeName2,
    rootStyle,
    grammarState
  } = codeToTokens(internal, input, options2);
  const {
    mergeWhitespaces = true
  } = options2;
  if (mergeWhitespaces === true)
    tokens = mergeWhitespaceTokens(tokens);
  else if (mergeWhitespaces === "never")
    tokens = splitWhitespaceTokens(tokens);
  const contextSource = {
    ...transformerContext,
    get source() {
      return input;
    }
  };
  for (const transformer of getTransformers(options2))
    tokens = transformer.tokens?.call(contextSource, tokens) || tokens;
  return tokensToHast(
    tokens,
    {
      ...options2,
      fg,
      bg,
      themeName: themeName2,
      rootStyle
    },
    contextSource,
    grammarState
  );
}
function tokensToHast(tokens, options2, transformerContext, grammarState = getLastGrammarStateFromMap(tokens)) {
  const transformers = getTransformers(options2);
  const lines = [];
  const root3 = {
    type: "root",
    children: []
  };
  const {
    structure = "classic",
    tabindex = "0"
  } = options2;
  let preNode = {
    type: "element",
    tagName: "pre",
    properties: {
      class: `shiki ${options2.themeName || ""}`,
      style: options2.rootStyle || `background-color:${options2.bg};color:${options2.fg}`,
      ...tabindex !== false && tabindex != null ? {
        tabindex: tabindex.toString()
      } : {},
      ...Object.fromEntries(
        Array.from(
          Object.entries(options2.meta || {})
        ).filter(([key2]) => !key2.startsWith("_"))
      )
    },
    children: []
  };
  let codeNode = {
    type: "element",
    tagName: "code",
    properties: {},
    children: lines
  };
  const lineNodes = [];
  const context = {
    ...transformerContext,
    structure,
    addClassToHast,
    get source() {
      return transformerContext.source;
    },
    get tokens() {
      return tokens;
    },
    get options() {
      return options2;
    },
    get root() {
      return root3;
    },
    get pre() {
      return preNode;
    },
    get code() {
      return codeNode;
    },
    get lines() {
      return lineNodes;
    }
  };
  tokens.forEach((line, idx) => {
    if (idx) {
      if (structure === "inline")
        root3.children.push({ type: "element", tagName: "br", properties: {}, children: [] });
      else if (structure === "classic")
        lines.push({ type: "text", value: "\n" });
    }
    let lineNode = {
      type: "element",
      tagName: "span",
      properties: { class: "line" },
      children: []
    };
    let col = 0;
    for (const token of line) {
      let tokenNode = {
        type: "element",
        tagName: "span",
        properties: {
          ...token.htmlAttrs
        },
        children: [{ type: "text", value: token.content }]
      };
      if (typeof token.htmlStyle === "string")
        warnDeprecated("`htmlStyle` as a string is deprecated. Use an object instead.");
      const style3 = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));
      if (style3)
        tokenNode.properties.style = style3;
      for (const transformer of transformers)
        tokenNode = transformer?.span?.call(context, tokenNode, idx + 1, col, lineNode, token) || tokenNode;
      if (structure === "inline")
        root3.children.push(tokenNode);
      else if (structure === "classic")
        lineNode.children.push(tokenNode);
      col += token.content.length;
    }
    if (structure === "classic") {
      for (const transformer of transformers)
        lineNode = transformer?.line?.call(context, lineNode, idx + 1) || lineNode;
      lineNodes.push(lineNode);
      lines.push(lineNode);
    }
  });
  if (structure === "classic") {
    for (const transformer of transformers)
      codeNode = transformer?.code?.call(context, codeNode) || codeNode;
    preNode.children.push(codeNode);
    for (const transformer of transformers)
      preNode = transformer?.pre?.call(context, preNode) || preNode;
    root3.children.push(preNode);
  }
  let result2 = root3;
  for (const transformer of transformers)
    result2 = transformer?.root?.call(context, result2) || result2;
  if (grammarState)
    setLastGrammarStateToMap(result2, grammarState);
  return result2;
}
function mergeWhitespaceTokens(tokens) {
  return tokens.map((line) => {
    const newLine = [];
    let carryOnContent = "";
    let firstOffset = 0;
    line.forEach((token, idx) => {
      const isUnderline = token.fontStyle && token.fontStyle & FontStyle.Underline;
      const couldMerge = !isUnderline;
      if (couldMerge && token.content.match(/^\s+$/) && line[idx + 1]) {
        if (!firstOffset)
          firstOffset = token.offset;
        carryOnContent += token.content;
      } else {
        if (carryOnContent) {
          if (couldMerge) {
            newLine.push({
              ...token,
              offset: firstOffset,
              content: carryOnContent + token.content
            });
          } else {
            newLine.push(
              {
                content: carryOnContent,
                offset: firstOffset
              },
              token
            );
          }
          firstOffset = 0;
          carryOnContent = "";
        } else {
          newLine.push(token);
        }
      }
    });
    return newLine;
  });
}
function splitWhitespaceTokens(tokens) {
  return tokens.map((line) => {
    return line.flatMap((token) => {
      if (token.content.match(/^\s+$/))
        return token;
      const match2 = token.content.match(/^(\s*)(.*?)(\s*)$/);
      if (!match2)
        return token;
      const [, leading, content2, trailing] = match2;
      if (!leading && !trailing)
        return token;
      const expanded = [{
        ...token,
        offset: token.offset + leading.length,
        content: content2
      }];
      if (leading) {
        expanded.unshift({
          content: leading,
          offset: token.offset
        });
      }
      if (trailing) {
        expanded.push({
          content: trailing,
          offset: token.offset + leading.length + content2.length
        });
      }
      return expanded;
    });
  });
}
function codeToHtml(internal, code2, options2) {
  const context = {
    meta: {},
    options: options2,
    codeToHast: (_code, _options) => codeToHast(internal, _code, _options),
    codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)
  };
  let result2 = toHtml(codeToHast(internal, code2, options2, context));
  for (const transformer of getTransformers(options2))
    result2 = transformer.postprocess?.call(context, result2, options2) || result2;
  return result2;
}
var VSCODE_FALLBACK_EDITOR_FG = { light: "#333333", dark: "#bbbbbb" };
var VSCODE_FALLBACK_EDITOR_BG = { light: "#fffffe", dark: "#1e1e1e" };
var RESOLVED_KEY = "__shiki_resolved";
function normalizeTheme(rawTheme) {
  if (rawTheme?.[RESOLVED_KEY])
    return rawTheme;
  const theme2 = {
    ...rawTheme
  };
  if (theme2.tokenColors && !theme2.settings) {
    theme2.settings = theme2.tokenColors;
    delete theme2.tokenColors;
  }
  theme2.type ||= "dark";
  theme2.colorReplacements = { ...theme2.colorReplacements };
  theme2.settings ||= [];
  let { bg, fg } = theme2;
  if (!bg || !fg) {
    const globalSetting = theme2.settings ? theme2.settings.find((s3) => !s3.name && !s3.scope) : void 0;
    if (globalSetting?.settings?.foreground)
      fg = globalSetting.settings.foreground;
    if (globalSetting?.settings?.background)
      bg = globalSetting.settings.background;
    if (!fg && theme2?.colors?.["editor.foreground"])
      fg = theme2.colors["editor.foreground"];
    if (!bg && theme2?.colors?.["editor.background"])
      bg = theme2.colors["editor.background"];
    if (!fg)
      fg = theme2.type === "light" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark;
    if (!bg)
      bg = theme2.type === "light" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark;
    theme2.fg = fg;
    theme2.bg = bg;
  }
  if (!(theme2.settings[0] && theme2.settings[0].settings && !theme2.settings[0].scope)) {
    theme2.settings.unshift({
      settings: {
        foreground: theme2.fg,
        background: theme2.bg
      }
    });
  }
  let replacementCount = 0;
  const replacementMap = /* @__PURE__ */ new Map();
  function getReplacementColor(value2) {
    if (replacementMap.has(value2))
      return replacementMap.get(value2);
    replacementCount += 1;
    const hex = `#${replacementCount.toString(16).padStart(8, "0").toLowerCase()}`;
    if (theme2.colorReplacements?.[`#${hex}`])
      return getReplacementColor(value2);
    replacementMap.set(value2, hex);
    return hex;
  }
  theme2.settings = theme2.settings.map((setting) => {
    const replaceFg = setting.settings?.foreground && !setting.settings.foreground.startsWith("#");
    const replaceBg = setting.settings?.background && !setting.settings.background.startsWith("#");
    if (!replaceFg && !replaceBg)
      return setting;
    const clone3 = {
      ...setting,
      settings: {
        ...setting.settings
      }
    };
    if (replaceFg) {
      const replacement = getReplacementColor(setting.settings.foreground);
      theme2.colorReplacements[replacement] = setting.settings.foreground;
      clone3.settings.foreground = replacement;
    }
    if (replaceBg) {
      const replacement = getReplacementColor(setting.settings.background);
      theme2.colorReplacements[replacement] = setting.settings.background;
      clone3.settings.background = replacement;
    }
    return clone3;
  });
  for (const key2 of Object.keys(theme2.colors || {})) {
    if (key2 === "editor.foreground" || key2 === "editor.background" || key2.startsWith("terminal.ansi")) {
      if (!theme2.colors[key2]?.startsWith("#")) {
        const replacement = getReplacementColor(theme2.colors[key2]);
        theme2.colorReplacements[replacement] = theme2.colors[key2];
        theme2.colors[key2] = replacement;
      }
    }
  }
  Object.defineProperty(theme2, RESOLVED_KEY, {
    enumerable: false,
    writable: false,
    value: true
  });
  return theme2;
}
async function resolveLangs(langs) {
  return Array.from(new Set((await Promise.all(
    langs.filter((l3) => !isSpecialLang(l3)).map(async (lang2) => await normalizeGetter(lang2).then((r3) => Array.isArray(r3) ? r3 : [r3]))
  )).flat()));
}
async function resolveThemes(themes) {
  const resolved = await Promise.all(
    themes.map(
      async (theme2) => isSpecialTheme(theme2) ? null : normalizeTheme(await normalizeGetter(theme2))
    )
  );
  return resolved.filter((i3) => !!i3);
}
var Registry3 = class extends Registry2 {
  constructor(_resolver, _themes, _langs, _alias = {}) {
    super(_resolver);
    this._resolver = _resolver;
    this._themes = _themes;
    this._langs = _langs;
    this._alias = _alias;
    this._themes.map((t3) => this.loadTheme(t3));
    this.loadLanguages(this._langs);
  }
  _resolvedThemes = /* @__PURE__ */ new Map();
  _resolvedGrammars = /* @__PURE__ */ new Map();
  _langMap = /* @__PURE__ */ new Map();
  _langGraph = /* @__PURE__ */ new Map();
  _textmateThemeCache = /* @__PURE__ */ new WeakMap();
  _loadedThemesCache = null;
  _loadedLanguagesCache = null;
  getTheme(theme2) {
    if (typeof theme2 === "string")
      return this._resolvedThemes.get(theme2);
    else
      return this.loadTheme(theme2);
  }
  loadTheme(theme2) {
    const _theme = normalizeTheme(theme2);
    if (_theme.name) {
      this._resolvedThemes.set(_theme.name, _theme);
      this._loadedThemesCache = null;
    }
    return _theme;
  }
  getLoadedThemes() {
    if (!this._loadedThemesCache)
      this._loadedThemesCache = [...this._resolvedThemes.keys()];
    return this._loadedThemesCache;
  }
  // Override and re-implement this method to cache the textmate themes as `TextMateTheme.createFromRawTheme`
  // is expensive. Themes can switch often especially for dual-theme support.
  //
  // The parent class also accepts `colorMap` as the second parameter, but since we don't use that,
  // we omit here so it's easier to cache the themes.
  setTheme(theme2) {
    let textmateTheme = this._textmateThemeCache.get(theme2);
    if (!textmateTheme) {
      textmateTheme = Theme.createFromRawTheme(theme2);
      this._textmateThemeCache.set(theme2, textmateTheme);
    }
    this._syncRegistry.setTheme(textmateTheme);
  }
  getGrammar(name2) {
    if (this._alias[name2]) {
      const resolved = /* @__PURE__ */ new Set([name2]);
      while (this._alias[name2]) {
        name2 = this._alias[name2];
        if (resolved.has(name2))
          throw new ShikiError3(`Circular alias \`${Array.from(resolved).join(" -> ")} -> ${name2}\``);
        resolved.add(name2);
      }
    }
    return this._resolvedGrammars.get(name2);
  }
  loadLanguage(lang2) {
    if (this.getGrammar(lang2.name))
      return;
    const embeddedLazilyBy = new Set(
      [...this._langMap.values()].filter((i3) => i3.embeddedLangsLazy?.includes(lang2.name))
    );
    this._resolver.addLanguage(lang2);
    const grammarConfig = {
      balancedBracketSelectors: lang2.balancedBracketSelectors || ["*"],
      unbalancedBracketSelectors: lang2.unbalancedBracketSelectors || []
    };
    this._syncRegistry._rawGrammars.set(lang2.scopeName, lang2);
    const g3 = this.loadGrammarWithConfiguration(lang2.scopeName, 1, grammarConfig);
    g3.name = lang2.name;
    this._resolvedGrammars.set(lang2.name, g3);
    if (lang2.aliases) {
      lang2.aliases.forEach((alias) => {
        this._alias[alias] = lang2.name;
      });
    }
    this._loadedLanguagesCache = null;
    if (embeddedLazilyBy.size) {
      for (const e3 of embeddedLazilyBy) {
        this._resolvedGrammars.delete(e3.name);
        this._loadedLanguagesCache = null;
        this._syncRegistry?._injectionGrammars?.delete(e3.scopeName);
        this._syncRegistry?._grammars?.delete(e3.scopeName);
        this.loadLanguage(this._langMap.get(e3.name));
      }
    }
  }
  dispose() {
    super.dispose();
    this._resolvedThemes.clear();
    this._resolvedGrammars.clear();
    this._langMap.clear();
    this._langGraph.clear();
    this._loadedThemesCache = null;
  }
  loadLanguages(langs) {
    for (const lang2 of langs)
      this.resolveEmbeddedLanguages(lang2);
    const langsGraphArray = Array.from(this._langGraph.entries());
    const missingLangs = langsGraphArray.filter(([_5, lang2]) => !lang2);
    if (missingLangs.length) {
      const dependents = langsGraphArray.filter(([_5, lang2]) => lang2 && lang2.embeddedLangs?.some((l3) => missingLangs.map(([name2]) => name2).includes(l3))).filter((lang2) => !missingLangs.includes(lang2));
      throw new ShikiError3(`Missing languages ${missingLangs.map(([name2]) => `\`${name2}\``).join(", ")}, required by ${dependents.map(([name2]) => `\`${name2}\``).join(", ")}`);
    }
    for (const [_5, lang2] of langsGraphArray)
      this._resolver.addLanguage(lang2);
    for (const [_5, lang2] of langsGraphArray)
      this.loadLanguage(lang2);
  }
  getLoadedLanguages() {
    if (!this._loadedLanguagesCache) {
      this._loadedLanguagesCache = [
        .../* @__PURE__ */ new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])
      ];
    }
    return this._loadedLanguagesCache;
  }
  resolveEmbeddedLanguages(lang2) {
    this._langMap.set(lang2.name, lang2);
    this._langGraph.set(lang2.name, lang2);
    if (lang2.embeddedLangs) {
      for (const embeddedLang of lang2.embeddedLangs)
        this._langGraph.set(embeddedLang, this._langMap.get(embeddedLang));
    }
  }
};
var Resolver = class {
  _langs = /* @__PURE__ */ new Map();
  _scopeToLang = /* @__PURE__ */ new Map();
  _injections = /* @__PURE__ */ new Map();
  _onigLib;
  constructor(engine, langs) {
    this._onigLib = {
      createOnigScanner: (patterns) => engine.createScanner(patterns),
      createOnigString: (s3) => engine.createString(s3)
    };
    langs.forEach((i3) => this.addLanguage(i3));
  }
  get onigLib() {
    return this._onigLib;
  }
  getLangRegistration(langIdOrAlias) {
    return this._langs.get(langIdOrAlias);
  }
  loadGrammar(scopeName) {
    return this._scopeToLang.get(scopeName);
  }
  addLanguage(l3) {
    this._langs.set(l3.name, l3);
    if (l3.aliases) {
      l3.aliases.forEach((a3) => {
        this._langs.set(a3, l3);
      });
    }
    this._scopeToLang.set(l3.scopeName, l3);
    if (l3.injectTo) {
      l3.injectTo.forEach((i3) => {
        if (!this._injections.get(i3))
          this._injections.set(i3, []);
        this._injections.get(i3).push(l3.scopeName);
      });
    }
  }
  getInjections(scopeName) {
    const scopeParts = scopeName.split(".");
    let injections = [];
    for (let i3 = 1; i3 <= scopeParts.length; i3++) {
      const subScopeName = scopeParts.slice(0, i3).join(".");
      injections = [...injections, ...this._injections.get(subScopeName) || []];
    }
    return injections;
  }
};
var instancesCount = 0;
function createShikiInternalSync(options2) {
  instancesCount += 1;
  if (options2.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)
    console.warn(`[Shiki] ${instancesCount} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);
  let isDisposed = false;
  if (!options2.engine)
    throw new ShikiError3("`engine` option is required for synchronous mode");
  const langs = (options2.langs || []).flat(1);
  const themes = (options2.themes || []).flat(1).map(normalizeTheme);
  const resolver = new Resolver(options2.engine, langs);
  const _registry = new Registry3(resolver, themes, langs, options2.langAlias);
  let _lastTheme;
  function getLanguage(name2) {
    ensureNotDisposed();
    const _lang = _registry.getGrammar(typeof name2 === "string" ? name2 : name2.name);
    if (!_lang)
      throw new ShikiError3(`Language \`${name2}\` not found, you may need to load it first`);
    return _lang;
  }
  function getTheme(name2) {
    if (name2 === "none")
      return { bg: "", fg: "", name: "none", settings: [], type: "dark" };
    ensureNotDisposed();
    const _theme = _registry.getTheme(name2);
    if (!_theme)
      throw new ShikiError3(`Theme \`${name2}\` not found, you may need to load it first`);
    return _theme;
  }
  function setTheme(name2) {
    ensureNotDisposed();
    const theme2 = getTheme(name2);
    if (_lastTheme !== name2) {
      _registry.setTheme(theme2);
      _lastTheme = name2;
    }
    const colorMap = _registry.getColorMap();
    return {
      theme: theme2,
      colorMap
    };
  }
  function getLoadedThemes() {
    ensureNotDisposed();
    return _registry.getLoadedThemes();
  }
  function getLoadedLanguages() {
    ensureNotDisposed();
    return _registry.getLoadedLanguages();
  }
  function loadLanguageSync(...langs2) {
    ensureNotDisposed();
    _registry.loadLanguages(langs2.flat(1));
  }
  async function loadLanguage(...langs2) {
    return loadLanguageSync(await resolveLangs(langs2));
  }
  function loadThemeSync(...themes2) {
    ensureNotDisposed();
    for (const theme2 of themes2.flat(1)) {
      _registry.loadTheme(theme2);
    }
  }
  async function loadTheme(...themes2) {
    ensureNotDisposed();
    return loadThemeSync(await resolveThemes(themes2));
  }
  function ensureNotDisposed() {
    if (isDisposed)
      throw new ShikiError3("Shiki instance has been disposed");
  }
  function dispose2() {
    if (isDisposed)
      return;
    isDisposed = true;
    _registry.dispose();
    instancesCount -= 1;
  }
  return {
    setTheme,
    getTheme,
    getLanguage,
    getLoadedThemes,
    getLoadedLanguages,
    loadLanguage,
    loadLanguageSync,
    loadTheme,
    loadThemeSync,
    dispose: dispose2,
    [Symbol.dispose]: dispose2
  };
}
async function createShikiInternal(options2 = {}) {
  if (options2.loadWasm) {
    warnDeprecated("`loadWasm` option is deprecated. Use `engine: createOnigurumaEngine(loadWasm)` instead.");
  }
  const [
    themes,
    langs,
    engine
  ] = await Promise.all([
    resolveThemes(options2.themes || []),
    resolveLangs(options2.langs || []),
    options2.engine || createOnigurumaEngine(options2.loadWasm || getDefaultWasmLoader())
  ]);
  return createShikiInternalSync({
    ...options2,
    loadWasm: void 0,
    themes,
    langs,
    engine
  });
}
async function createHighlighterCore(options2 = {}) {
  const internal = await createShikiInternal(options2);
  return {
    getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),
    codeToTokensBase: (code2, options22) => codeToTokensBase(internal, code2, options22),
    codeToTokensWithThemes: (code2, options22) => codeToTokensWithThemes(internal, code2, options22),
    codeToTokens: (code2, options22) => codeToTokens(internal, code2, options22),
    codeToHast: (code2, options22) => codeToHast(internal, code2, options22),
    codeToHtml: (code2, options22) => codeToHtml(internal, code2, options22),
    ...internal,
    getInternalContext: () => internal
  };
}

// node_modules/codemirror-json-schema/dist/utils/markdown.js
var renderer = lib_default({
  linkify: true,
  typographer: true
});
(async () => {
  const highlighter = await createHighlighterCore({
    themes: [
      Promise.resolve().then(() => (init_vitesse_light2(), vitesse_light_exports)),
      Promise.resolve().then(() => (init_vitesse_dark2(), vitesse_dark_exports))
    ],
    langs: [Promise.resolve().then(() => (init_javascript2(), javascript_exports))]
  });
  renderer.use(fromHighlighter(highlighter, {
    themes: {
      light: "vitesse-light",
      dark: "vitesse-dark"
    }
  }));
})();
function renderMarkdown(markdown, inline3 = true) {
  if (!inline3)
    return renderer.render(markdown);
  return renderer.renderInline(markdown);
}

// node_modules/codemirror-json-schema/dist/parsers/json-parser.js
var import_best_effort_json_parser = __toESM(require_parse(), 1);
function parseJSONDocumentState(state) {
  let data2 = null;
  try {
    data2 = JSON.parse(state.doc.toString());
  } catch (_a4) {
    try {
      data2 = (0, import_best_effort_json_parser.parse)(state.doc.toString());
    } catch (_b) {
    }
  }
  const pointers = getJsonPointers(state, MODES.JSON);
  return { data: data2, pointers };
}

// node_modules/codemirror-json-schema/dist/parsers/json5-parser.js
var import_json5 = __toESM(require_dist(), 1);
var import_best_effort_json_parser2 = __toESM(require_parse(), 1);
function parseJSON5DocumentState(state) {
  const stateDoc = state.doc.toString();
  let data2 = null;
  try {
    data2 = import_json5.default.parse(stateDoc);
  } catch (_a4) {
    try {
      data2 = (0, import_best_effort_json_parser2.parse)(stateDoc);
    } catch (_b) {
    }
  }
  const pointers = getJsonPointers(state, MODES.JSON5);
  return { data: data2, pointers };
}

// node_modules/yaml/browser/dist/index.js
var dist_exports = {};
__export(dist_exports, {
  Alias: () => Alias,
  CST: () => cst_exports,
  Composer: () => Composer,
  Document: () => Document,
  Lexer: () => Lexer2,
  LineCounter: () => LineCounter,
  Pair: () => Pair,
  Parser: () => Parser3,
  Scalar: () => Scalar,
  Schema: () => Schema3,
  YAMLError: () => YAMLError,
  YAMLMap: () => YAMLMap,
  YAMLParseError: () => YAMLParseError,
  YAMLSeq: () => YAMLSeq,
  YAMLWarning: () => YAMLWarning,
  isAlias: () => isAlias,
  isCollection: () => isCollection,
  isDocument: () => isDocument,
  isMap: () => isMap,
  isNode: () => isNode,
  isPair: () => isPair,
  isScalar: () => isScalar,
  isSeq: () => isSeq,
  parse: () => parse3,
  parseAllDocuments: () => parseAllDocuments,
  parseDocument: () => parseDocument,
  stringify: () => stringify6,
  visit: () => visit,
  visitAsync: () => visitAsync
});

// node_modules/yaml/browser/dist/nodes/identity.js
var ALIAS = Symbol.for("yaml.alias");
var DOC = Symbol.for("yaml.document");
var MAP = Symbol.for("yaml.map");
var PAIR = Symbol.for("yaml.pair");
var SCALAR = Symbol.for("yaml.scalar");
var SEQ = Symbol.for("yaml.seq");
var NODE_TYPE = Symbol.for("yaml.node.type");
var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
function isCollection(node) {
  if (node && typeof node === "object")
    switch (node[NODE_TYPE]) {
      case MAP:
      case SEQ:
        return true;
    }
  return false;
}
function isNode(node) {
  if (node && typeof node === "object")
    switch (node[NODE_TYPE]) {
      case ALIAS:
      case MAP:
      case SCALAR:
      case SEQ:
        return true;
    }
  return false;
}
var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;

// node_modules/yaml/browser/dist/visit.js
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove node");
function visit(node, visitor) {
  const visitor_ = initVisitor(visitor);
  if (isDocument(node)) {
    const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
    if (cd === REMOVE)
      node.contents = null;
  } else
    visit_(null, node, visitor_, Object.freeze([]));
}
visit.BREAK = BREAK;
visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
function visit_(key2, node, visitor, path) {
  const ctrl = callVisitor(key2, node, visitor, path);
  if (isNode(ctrl) || isPair(ctrl)) {
    replaceNode(key2, path, ctrl);
    return visit_(key2, ctrl, visitor, path);
  }
  if (typeof ctrl !== "symbol") {
    if (isCollection(node)) {
      path = Object.freeze(path.concat(node));
      for (let i3 = 0; i3 < node.items.length; ++i3) {
        const ci = visit_(i3, node.items[i3], visitor, path);
        if (typeof ci === "number")
          i3 = ci - 1;
        else if (ci === BREAK)
          return BREAK;
        else if (ci === REMOVE) {
          node.items.splice(i3, 1);
          i3 -= 1;
        }
      }
    } else if (isPair(node)) {
      path = Object.freeze(path.concat(node));
      const ck = visit_("key", node.key, visitor, path);
      if (ck === BREAK)
        return BREAK;
      else if (ck === REMOVE)
        node.key = null;
      const cv = visit_("value", node.value, visitor, path);
      if (cv === BREAK)
        return BREAK;
      else if (cv === REMOVE)
        node.value = null;
    }
  }
  return ctrl;
}
async function visitAsync(node, visitor) {
  const visitor_ = initVisitor(visitor);
  if (isDocument(node)) {
    const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
    if (cd === REMOVE)
      node.contents = null;
  } else
    await visitAsync_(null, node, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK;
visitAsync.SKIP = SKIP;
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key2, node, visitor, path) {
  const ctrl = await callVisitor(key2, node, visitor, path);
  if (isNode(ctrl) || isPair(ctrl)) {
    replaceNode(key2, path, ctrl);
    return visitAsync_(key2, ctrl, visitor, path);
  }
  if (typeof ctrl !== "symbol") {
    if (isCollection(node)) {
      path = Object.freeze(path.concat(node));
      for (let i3 = 0; i3 < node.items.length; ++i3) {
        const ci = await visitAsync_(i3, node.items[i3], visitor, path);
        if (typeof ci === "number")
          i3 = ci - 1;
        else if (ci === BREAK)
          return BREAK;
        else if (ci === REMOVE) {
          node.items.splice(i3, 1);
          i3 -= 1;
        }
      }
    } else if (isPair(node)) {
      path = Object.freeze(path.concat(node));
      const ck = await visitAsync_("key", node.key, visitor, path);
      if (ck === BREAK)
        return BREAK;
      else if (ck === REMOVE)
        node.key = null;
      const cv = await visitAsync_("value", node.value, visitor, path);
      if (cv === BREAK)
        return BREAK;
      else if (cv === REMOVE)
        node.value = null;
    }
  }
  return ctrl;
}
function initVisitor(visitor) {
  if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
    return Object.assign({
      Alias: visitor.Node,
      Map: visitor.Node,
      Scalar: visitor.Node,
      Seq: visitor.Node
    }, visitor.Value && {
      Map: visitor.Value,
      Scalar: visitor.Value,
      Seq: visitor.Value
    }, visitor.Collection && {
      Map: visitor.Collection,
      Seq: visitor.Collection
    }, visitor);
  }
  return visitor;
}
function callVisitor(key2, node, visitor, path) {
  if (typeof visitor === "function")
    return visitor(key2, node, path);
  if (isMap(node))
    return visitor.Map?.(key2, node, path);
  if (isSeq(node))
    return visitor.Seq?.(key2, node, path);
  if (isPair(node))
    return visitor.Pair?.(key2, node, path);
  if (isScalar(node))
    return visitor.Scalar?.(key2, node, path);
  if (isAlias(node))
    return visitor.Alias?.(key2, node, path);
  return void 0;
}
function replaceNode(key2, path, node) {
  const parent = path[path.length - 1];
  if (isCollection(parent)) {
    parent.items[key2] = node;
  } else if (isPair(parent)) {
    if (key2 === "key")
      parent.key = node;
    else
      parent.value = node;
  } else if (isDocument(parent)) {
    parent.contents = node;
  } else {
    const pt2 = isAlias(parent) ? "alias" : "scalar";
    throw new Error(`Cannot replace node with ${pt2} parent`);
  }
}

// node_modules/yaml/browser/dist/doc/directives.js
var escapeChars = {
  "!": "%21",
  ",": "%2C",
  "[": "%5B",
  "]": "%5D",
  "{": "%7B",
  "}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
var Directives = class _Directives {
  constructor(yaml, tags2) {
    this.docStart = null;
    this.docEnd = false;
    this.yaml = Object.assign({}, _Directives.defaultYaml, yaml);
    this.tags = Object.assign({}, _Directives.defaultTags, tags2);
  }
  clone() {
    const copy2 = new _Directives(this.yaml, this.tags);
    copy2.docStart = this.docStart;
    return copy2;
  }
  /**
   * During parsing, get a Directives instance for the current document and
   * update the stream state according to the current version's spec.
   */
  atDocument() {
    const res = new _Directives(this.yaml, this.tags);
    switch (this.yaml.version) {
      case "1.1":
        this.atNextDocument = true;
        break;
      case "1.2":
        this.atNextDocument = false;
        this.yaml = {
          explicit: _Directives.defaultYaml.explicit,
          version: "1.2"
        };
        this.tags = Object.assign({}, _Directives.defaultTags);
        break;
    }
    return res;
  }
  /**
   * @param onError - May be called even if the action was successful
   * @returns `true` on success
   */
  add(line, onError) {
    if (this.atNextDocument) {
      this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
      this.tags = Object.assign({}, _Directives.defaultTags);
      this.atNextDocument = false;
    }
    const parts = line.trim().split(/[ \t]+/);
    const name2 = parts.shift();
    switch (name2) {
      case "%TAG": {
        if (parts.length !== 2) {
          onError(0, "%TAG directive should contain exactly two parts");
          if (parts.length < 2)
            return false;
        }
        const [handle2, prefix5] = parts;
        this.tags[handle2] = prefix5;
        return true;
      }
      case "%YAML": {
        this.yaml.explicit = true;
        if (parts.length !== 1) {
          onError(0, "%YAML directive should contain exactly one part");
          return false;
        }
        const [version] = parts;
        if (version === "1.1" || version === "1.2") {
          this.yaml.version = version;
          return true;
        } else {
          const isValid2 = /^\d+\.\d+$/.test(version);
          onError(6, `Unsupported YAML version ${version}`, isValid2);
          return false;
        }
      }
      default:
        onError(0, `Unknown directive ${name2}`, true);
        return false;
    }
  }
  /**
   * Resolves a tag, matching handles to those defined in %TAG directives.
   *
   * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
   *   `'!local'` tag, or `null` if unresolvable.
   */
  tagName(source, onError) {
    if (source === "!")
      return "!";
    if (source[0] !== "!") {
      onError(`Not a valid tag: ${source}`);
      return null;
    }
    if (source[1] === "<") {
      const verbatim = source.slice(2, -1);
      if (verbatim === "!" || verbatim === "!!") {
        onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
        return null;
      }
      if (source[source.length - 1] !== ">")
        onError("Verbatim tags must end with a >");
      return verbatim;
    }
    const [, handle2, suffix] = source.match(/^(.*!)([^!]*)$/s);
    if (!suffix)
      onError(`The ${source} tag has no suffix`);
    const prefix5 = this.tags[handle2];
    if (prefix5) {
      try {
        return prefix5 + decodeURIComponent(suffix);
      } catch (error2) {
        onError(String(error2));
        return null;
      }
    }
    if (handle2 === "!")
      return source;
    onError(`Could not resolve tag: ${source}`);
    return null;
  }
  /**
   * Given a fully resolved tag, returns its printable string form,
   * taking into account current tag prefixes and defaults.
   */
  tagString(tag) {
    for (const [handle2, prefix5] of Object.entries(this.tags)) {
      if (tag.startsWith(prefix5))
        return handle2 + escapeTagName(tag.substring(prefix5.length));
    }
    return tag[0] === "!" ? tag : `!<${tag}>`;
  }
  toString(doc4) {
    const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
    const tagEntries = Object.entries(this.tags);
    let tagNames;
    if (doc4 && tagEntries.length > 0 && isNode(doc4.contents)) {
      const tags2 = {};
      visit(doc4.contents, (_key, node) => {
        if (isNode(node) && node.tag)
          tags2[node.tag] = true;
      });
      tagNames = Object.keys(tags2);
    } else
      tagNames = [];
    for (const [handle2, prefix5] of tagEntries) {
      if (handle2 === "!!" && prefix5 === "tag:yaml.org,2002:")
        continue;
      if (!doc4 || tagNames.some((tn) => tn.startsWith(prefix5)))
        lines.push(`%TAG ${handle2} ${prefix5}`);
    }
    return lines.join("\n");
  }
};
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };

// node_modules/yaml/browser/dist/doc/anchors.js
function anchorIsValid(anchor) {
  if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
    const sa = JSON.stringify(anchor);
    const msg2 = `Anchor must not contain whitespace or control characters: ${sa}`;
    throw new Error(msg2);
  }
  return true;
}
function anchorNames(root3) {
  const anchors = /* @__PURE__ */ new Set();
  visit(root3, {
    Value(_key, node) {
      if (node.anchor)
        anchors.add(node.anchor);
    }
  });
  return anchors;
}
function findNewAnchor(prefix5, exclude) {
  for (let i3 = 1; true; ++i3) {
    const name2 = `${prefix5}${i3}`;
    if (!exclude.has(name2))
      return name2;
  }
}
function createNodeAnchors(doc4, prefix5) {
  const aliasObjects = [];
  const sourceObjects = /* @__PURE__ */ new Map();
  let prevAnchors = null;
  return {
    onAnchor: (source) => {
      aliasObjects.push(source);
      prevAnchors ?? (prevAnchors = anchorNames(doc4));
      const anchor = findNewAnchor(prefix5, prevAnchors);
      prevAnchors.add(anchor);
      return anchor;
    },
    /**
     * With circular references, the source node is only resolved after all
     * of its child nodes are. This is why anchors are set only after all of
     * the nodes have been created.
     */
    setAnchors: () => {
      for (const source of aliasObjects) {
        const ref = sourceObjects.get(source);
        if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) {
          ref.node.anchor = ref.anchor;
        } else {
          const error2 = new Error("Failed to resolve repeated object (this should not happen)");
          error2.source = source;
          throw error2;
        }
      }
    },
    sourceObjects
  };
}

// node_modules/yaml/browser/dist/doc/applyReviver.js
function applyReviver(reviver, obj, key2, val) {
  if (val && typeof val === "object") {
    if (Array.isArray(val)) {
      for (let i3 = 0, len = val.length; i3 < len; ++i3) {
        const v0 = val[i3];
        const v1 = applyReviver(reviver, val, String(i3), v0);
        if (v1 === void 0)
          delete val[i3];
        else if (v1 !== v0)
          val[i3] = v1;
      }
    } else if (val instanceof Map) {
      for (const k2 of Array.from(val.keys())) {
        const v0 = val.get(k2);
        const v1 = applyReviver(reviver, val, k2, v0);
        if (v1 === void 0)
          val.delete(k2);
        else if (v1 !== v0)
          val.set(k2, v1);
      }
    } else if (val instanceof Set) {
      for (const v0 of Array.from(val)) {
        const v1 = applyReviver(reviver, val, v0, v0);
        if (v1 === void 0)
          val.delete(v0);
        else if (v1 !== v0) {
          val.delete(v0);
          val.add(v1);
        }
      }
    } else {
      for (const [k2, v0] of Object.entries(val)) {
        const v1 = applyReviver(reviver, val, k2, v0);
        if (v1 === void 0)
          delete val[k2];
        else if (v1 !== v0)
          val[k2] = v1;
      }
    }
  }
  return reviver.call(obj, key2, val);
}

// node_modules/yaml/browser/dist/nodes/toJS.js
function toJS(value2, arg, ctx) {
  if (Array.isArray(value2))
    return value2.map((v3, i3) => toJS(v3, String(i3), ctx));
  if (value2 && typeof value2.toJSON === "function") {
    if (!ctx || !hasAnchor(value2))
      return value2.toJSON(arg, ctx);
    const data2 = { aliasCount: 0, count: 1, res: void 0 };
    ctx.anchors.set(value2, data2);
    ctx.onCreate = (res2) => {
      data2.res = res2;
      delete ctx.onCreate;
    };
    const res = value2.toJSON(arg, ctx);
    if (ctx.onCreate)
      ctx.onCreate(res);
    return res;
  }
  if (typeof value2 === "bigint" && !ctx?.keep)
    return Number(value2);
  return value2;
}

// node_modules/yaml/browser/dist/nodes/Node.js
var NodeBase = class {
  constructor(type) {
    Object.defineProperty(this, NODE_TYPE, { value: type });
  }
  /** Create a copy of this node.  */
  clone() {
    const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
    if (this.range)
      copy2.range = this.range.slice();
    return copy2;
  }
  /** A plain JavaScript representation of this node. */
  toJS(doc4, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
    if (!isDocument(doc4))
      throw new TypeError("A document argument is required");
    const ctx = {
      anchors: /* @__PURE__ */ new Map(),
      doc: doc4,
      keep: true,
      mapAsMap: mapAsMap === true,
      mapKeyWarned: false,
      maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
    };
    const res = toJS(this, "", ctx);
    if (typeof onAnchor === "function")
      for (const { count, res: res2 } of ctx.anchors.values())
        onAnchor(res2, count);
    return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
  }
};

// node_modules/yaml/browser/dist/nodes/Alias.js
var Alias = class extends NodeBase {
  constructor(source) {
    super(ALIAS);
    this.source = source;
    Object.defineProperty(this, "tag", {
      set() {
        throw new Error("Alias nodes cannot have tags");
      }
    });
  }
  /**
   * Resolve the value of this alias within `doc`, finding the last
   * instance of the `source` anchor before this node.
   */
  resolve(doc4, ctx) {
    let nodes2;
    if (ctx?.aliasResolveCache) {
      nodes2 = ctx.aliasResolveCache;
    } else {
      nodes2 = [];
      visit(doc4, {
        Node: (_key, node) => {
          if (isAlias(node) || hasAnchor(node))
            nodes2.push(node);
        }
      });
      if (ctx)
        ctx.aliasResolveCache = nodes2;
    }
    let found2 = void 0;
    for (const node of nodes2) {
      if (node === this)
        break;
      if (node.anchor === this.source)
        found2 = node;
    }
    return found2;
  }
  toJSON(_arg, ctx) {
    if (!ctx)
      return { source: this.source };
    const { anchors, doc: doc4, maxAliasCount } = ctx;
    const source = this.resolve(doc4, ctx);
    if (!source) {
      const msg2 = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
      throw new ReferenceError(msg2);
    }
    let data2 = anchors.get(source);
    if (!data2) {
      toJS(source, null, ctx);
      data2 = anchors.get(source);
    }
    if (data2?.res === void 0) {
      const msg2 = "This should not happen: Alias anchor was not resolved?";
      throw new ReferenceError(msg2);
    }
    if (maxAliasCount >= 0) {
      data2.count += 1;
      if (data2.aliasCount === 0)
        data2.aliasCount = getAliasCount(doc4, source, anchors);
      if (data2.count * data2.aliasCount > maxAliasCount) {
        const msg2 = "Excessive alias count indicates a resource exhaustion attack";
        throw new ReferenceError(msg2);
      }
    }
    return data2.res;
  }
  toString(ctx, _onComment, _onChompKeep) {
    const src = `*${this.source}`;
    if (ctx) {
      anchorIsValid(this.source);
      if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
        const msg2 = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
        throw new Error(msg2);
      }
      if (ctx.implicitKey)
        return `${src} `;
    }
    return src;
  }
};
function getAliasCount(doc4, node, anchors) {
  if (isAlias(node)) {
    const source = node.resolve(doc4);
    const anchor = anchors && source && anchors.get(source);
    return anchor ? anchor.count * anchor.aliasCount : 0;
  } else if (isCollection(node)) {
    let count = 0;
    for (const item of node.items) {
      const c3 = getAliasCount(doc4, item, anchors);
      if (c3 > count)
        count = c3;
    }
    return count;
  } else if (isPair(node)) {
    const kc = getAliasCount(doc4, node.key, anchors);
    const vc = getAliasCount(doc4, node.value, anchors);
    return Math.max(kc, vc);
  }
  return 1;
}

// node_modules/yaml/browser/dist/nodes/Scalar.js
var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object";
var Scalar = class extends NodeBase {
  constructor(value2) {
    super(SCALAR);
    this.value = value2;
  }
  toJSON(arg, ctx) {
    return ctx?.keep ? this.value : toJS(this.value, arg, ctx);
  }
  toString() {
    return String(this.value);
  }
};
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";

// node_modules/yaml/browser/dist/doc/createNode.js
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value2, tagName, tags2) {
  if (tagName) {
    const match2 = tags2.filter((t3) => t3.tag === tagName);
    const tagObj = match2.find((t3) => !t3.format) ?? match2[0];
    if (!tagObj)
      throw new Error(`Tag ${tagName} not found`);
    return tagObj;
  }
  return tags2.find((t3) => t3.identify?.(value2) && !t3.format);
}
function createNode(value2, tagName, ctx) {
  if (isDocument(value2))
    value2 = value2.contents;
  if (isNode(value2))
    return value2;
  if (isPair(value2)) {
    const map5 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
    map5.items.push(value2);
    return map5;
  }
  if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) {
    value2 = value2.valueOf();
  }
  const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema7, sourceObjects } = ctx;
  let ref = void 0;
  if (aliasDuplicateObjects && value2 && typeof value2 === "object") {
    ref = sourceObjects.get(value2);
    if (ref) {
      ref.anchor ?? (ref.anchor = onAnchor(value2));
      return new Alias(ref.anchor);
    } else {
      ref = { anchor: null, node: null };
      sourceObjects.set(value2, ref);
    }
  }
  if (tagName?.startsWith("!!"))
    tagName = defaultTagPrefix + tagName.slice(2);
  let tagObj = findTagObject(value2, tagName, schema7.tags);
  if (!tagObj) {
    if (value2 && typeof value2.toJSON === "function") {
      value2 = value2.toJSON();
    }
    if (!value2 || typeof value2 !== "object") {
      const node2 = new Scalar(value2);
      if (ref)
        ref.node = node2;
      return node2;
    }
    tagObj = value2 instanceof Map ? schema7[MAP] : Symbol.iterator in Object(value2) ? schema7[SEQ] : schema7[MAP];
  }
  if (onTagObj) {
    onTagObj(tagObj);
    delete ctx.onTagObj;
  }
  const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2);
  if (tagName)
    node.tag = tagName;
  else if (!tagObj.default)
    node.tag = tagObj.tag;
  if (ref)
    ref.node = node;
  return node;
}

// node_modules/yaml/browser/dist/nodes/Collection.js
function collectionFromPath(schema7, path, value2) {
  let v3 = value2;
  for (let i3 = path.length - 1; i3 >= 0; --i3) {
    const k2 = path[i3];
    if (typeof k2 === "number" && Number.isInteger(k2) && k2 >= 0) {
      const a3 = [];
      a3[k2] = v3;
      v3 = a3;
    } else {
      v3 = /* @__PURE__ */ new Map([[k2, v3]]);
    }
  }
  return createNode(v3, void 0, {
    aliasDuplicateObjects: false,
    keepUndefined: false,
    onAnchor: () => {
      throw new Error("This should not happen, please report a bug.");
    },
    schema: schema7,
    sourceObjects: /* @__PURE__ */ new Map()
  });
}
var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
var Collection = class extends NodeBase {
  constructor(type, schema7) {
    super(type);
    Object.defineProperty(this, "schema", {
      value: schema7,
      configurable: true,
      enumerable: false,
      writable: true
    });
  }
  /**
   * Create a copy of this collection.
   *
   * @param schema - If defined, overwrites the original's schema
   */
  clone(schema7) {
    const copy2 = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
    if (schema7)
      copy2.schema = schema7;
    copy2.items = copy2.items.map((it2) => isNode(it2) || isPair(it2) ? it2.clone(schema7) : it2);
    if (this.range)
      copy2.range = this.range.slice();
    return copy2;
  }
  /**
   * Adds a value to the collection. For `!!map` and `!!omap` the value must
   * be a Pair instance or a `{ key, value }` object, which may not have a key
   * that already exists in the map.
   */
  addIn(path, value2) {
    if (isEmptyPath(path))
      this.add(value2);
    else {
      const [key2, ...rest2] = path;
      const node = this.get(key2, true);
      if (isCollection(node))
        node.addIn(rest2, value2);
      else if (node === void 0 && this.schema)
        this.set(key2, collectionFromPath(this.schema, rest2, value2));
      else
        throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest2}`);
    }
  }
  /**
   * Removes a value from the collection.
   * @returns `true` if the item was found and removed.
   */
  deleteIn(path) {
    const [key2, ...rest2] = path;
    if (rest2.length === 0)
      return this.delete(key2);
    const node = this.get(key2, true);
    if (isCollection(node))
      return node.deleteIn(rest2);
    else
      throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest2}`);
  }
  /**
   * Returns item at `key`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  getIn(path, keepScalar) {
    const [key2, ...rest2] = path;
    const node = this.get(key2, true);
    if (rest2.length === 0)
      return !keepScalar && isScalar(node) ? node.value : node;
    else
      return isCollection(node) ? node.getIn(rest2, keepScalar) : void 0;
  }
  hasAllNullValues(allowScalar) {
    return this.items.every((node) => {
      if (!isPair(node))
        return false;
      const n4 = node.value;
      return n4 == null || allowScalar && isScalar(n4) && n4.value == null && !n4.commentBefore && !n4.comment && !n4.tag;
    });
  }
  /**
   * Checks if the collection includes a value with the key `key`.
   */
  hasIn(path) {
    const [key2, ...rest2] = path;
    if (rest2.length === 0)
      return this.has(key2);
    const node = this.get(key2, true);
    return isCollection(node) ? node.hasIn(rest2) : false;
  }
  /**
   * Sets a value in this collection. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  setIn(path, value2) {
    const [key2, ...rest2] = path;
    if (rest2.length === 0) {
      this.set(key2, value2);
    } else {
      const node = this.get(key2, true);
      if (isCollection(node))
        node.setIn(rest2, value2);
      else if (node === void 0 && this.schema)
        this.set(key2, collectionFromPath(this.schema, rest2, value2));
      else
        throw new Error(`Expected YAML collection at ${key2}. Remaining path: ${rest2}`);
    }
  }
};

// node_modules/yaml/browser/dist/stringify/stringifyComment.js
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment4, indent) {
  if (/^\n+$/.test(comment4))
    return comment4.substring(1);
  return indent ? comment4.replace(/^(?! *$)/gm, indent) : comment4;
}
var lineComment = (str, indent, comment4) => str.endsWith("\n") ? indentComment(comment4, indent) : comment4.includes("\n") ? "\n" + indentComment(comment4, indent) : (str.endsWith(" ") ? "" : " ") + comment4;

// node_modules/yaml/browser/dist/stringify/foldFlowLines.js
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text3, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
  if (!lineWidth || lineWidth < 0)
    return text3;
  if (lineWidth < minContentWidth)
    minContentWidth = 0;
  const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  if (text3.length <= endStep)
    return text3;
  const folds = [];
  const escapedFolds = {};
  let end = lineWidth - indent.length;
  if (typeof indentAtStart === "number") {
    if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
      folds.push(0);
    else
      end = lineWidth - indentAtStart;
  }
  let split3 = void 0;
  let prev = void 0;
  let overflow = false;
  let i3 = -1;
  let escStart = -1;
  let escEnd = -1;
  if (mode === FOLD_BLOCK) {
    i3 = consumeMoreIndentedLines(text3, i3, indent.length);
    if (i3 !== -1)
      end = i3 + endStep;
  }
  for (let ch; ch = text3[i3 += 1]; ) {
    if (mode === FOLD_QUOTED && ch === "\\") {
      escStart = i3;
      switch (text3[i3 + 1]) {
        case "x":
          i3 += 3;
          break;
        case "u":
          i3 += 5;
          break;
        case "U":
          i3 += 9;
          break;
        default:
          i3 += 1;
      }
      escEnd = i3;
    }
    if (ch === "\n") {
      if (mode === FOLD_BLOCK)
        i3 = consumeMoreIndentedLines(text3, i3, indent.length);
      end = i3 + indent.length + endStep;
      split3 = void 0;
    } else {
      if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== "	") {
        const next2 = text3[i3 + 1];
        if (next2 && next2 !== " " && next2 !== "\n" && next2 !== "	")
          split3 = i3;
      }
      if (i3 >= end) {
        if (split3) {
          folds.push(split3);
          end = split3 + endStep;
          split3 = void 0;
        } else if (mode === FOLD_QUOTED) {
          while (prev === " " || prev === "	") {
            prev = ch;
            ch = text3[i3 += 1];
            overflow = true;
          }
          const j = i3 > escEnd + 1 ? i3 - 2 : escStart - 1;
          if (escapedFolds[j])
            return text3;
          folds.push(j);
          escapedFolds[j] = true;
          end = j + endStep;
          split3 = void 0;
        } else {
          overflow = true;
        }
      }
    }
    prev = ch;
  }
  if (overflow && onOverflow)
    onOverflow();
  if (folds.length === 0)
    return text3;
  if (onFold)
    onFold();
  let res = text3.slice(0, folds[0]);
  for (let i4 = 0; i4 < folds.length; ++i4) {
    const fold = folds[i4];
    const end2 = folds[i4 + 1] || text3.length;
    if (fold === 0)
      res = `
${indent}${text3.slice(0, end2)}`;
    else {
      if (mode === FOLD_QUOTED && escapedFolds[fold])
        res += `${text3[fold]}\\`;
      res += `
${indent}${text3.slice(fold + 1, end2)}`;
    }
  }
  return res;
}
function consumeMoreIndentedLines(text3, i3, indent) {
  let end = i3;
  let start = i3 + 1;
  let ch = text3[start];
  while (ch === " " || ch === "	") {
    if (i3 < start + indent) {
      ch = text3[++i3];
    } else {
      do {
        ch = text3[++i3];
      } while (ch && ch !== "\n");
      end = i3;
      start = i3 + 1;
      ch = text3[start];
    }
  }
  return end;
}

// node_modules/yaml/browser/dist/stringify/stringifyString.js
var getFoldOptions = (ctx, isBlock2) => ({
  indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart,
  lineWidth: ctx.options.lineWidth,
  minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
  if (!lineWidth || lineWidth < 0)
    return false;
  const limit = lineWidth - indentLength;
  const strLen = str.length;
  if (strLen <= limit)
    return false;
  for (let i3 = 0, start = 0; i3 < strLen; ++i3) {
    if (str[i3] === "\n") {
      if (i3 - start > limit)
        return true;
      start = i3 + 1;
      if (strLen - start <= limit)
        return false;
    }
  }
  return true;
}
function doubleQuotedString(value2, ctx) {
  const json2 = JSON.stringify(value2);
  if (ctx.options.doubleQuotedAsJSON)
    return json2;
  const { implicitKey } = ctx;
  const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
  const indent = ctx.indent || (containsDocumentMarker(value2) ? "  " : "");
  let str = "";
  let start = 0;
  for (let i3 = 0, ch = json2[i3]; ch; ch = json2[++i3]) {
    if (ch === " " && json2[i3 + 1] === "\\" && json2[i3 + 2] === "n") {
      str += json2.slice(start, i3) + "\\ ";
      i3 += 1;
      start = i3;
      ch = "\\";
    }
    if (ch === "\\")
      switch (json2[i3 + 1]) {
        case "u":
          {
            str += json2.slice(start, i3);
            const code2 = json2.substr(i3 + 2, 4);
            switch (code2) {
              case "0000":
                str += "\\0";
                break;
              case "0007":
                str += "\\a";
                break;
              case "000b":
                str += "\\v";
                break;
              case "001b":
                str += "\\e";
                break;
              case "0085":
                str += "\\N";
                break;
              case "00a0":
                str += "\\_";
                break;
              case "2028":
                str += "\\L";
                break;
              case "2029":
                str += "\\P";
                break;
              default:
                if (code2.substr(0, 2) === "00")
                  str += "\\x" + code2.substr(2);
                else
                  str += json2.substr(i3, 6);
            }
            i3 += 5;
            start = i3 + 1;
          }
          break;
        case "n":
          if (implicitKey || json2[i3 + 2] === '"' || json2.length < minMultiLineLength) {
            i3 += 1;
          } else {
            str += json2.slice(start, i3) + "\n\n";
            while (json2[i3 + 2] === "\\" && json2[i3 + 3] === "n" && json2[i3 + 4] !== '"') {
              str += "\n";
              i3 += 2;
            }
            str += indent;
            if (json2[i3 + 2] === " ")
              str += "\\";
            i3 += 1;
            start = i3 + 1;
          }
          break;
        default:
          i3 += 1;
      }
  }
  str = start ? str + json2.slice(start) : json2;
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value2, ctx) {
  if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2))
    return doubleQuotedString(value2, ctx);
  const indent = ctx.indent || (containsDocumentMarker(value2) ? "  " : "");
  const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
  return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value2, ctx) {
  const { singleQuote } = ctx.options;
  let qs;
  if (singleQuote === false)
    qs = doubleQuotedString;
  else {
    const hasDouble = value2.includes('"');
    const hasSingle = value2.includes("'");
    if (hasDouble && !hasSingle)
      qs = singleQuotedString;
    else if (hasSingle && !hasDouble)
      qs = doubleQuotedString;
    else
      qs = singleQuote ? singleQuotedString : doubleQuotedString;
  }
  return qs(value2, ctx);
}
var blockEndNewlines;
try {
  blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
} catch {
  blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment: comment4, type, value: value2 }, ctx, onComment, onChompKeep) {
  const { blockQuote, commentString, lineWidth } = ctx.options;
  if (!blockQuote || /\n[\t ]+$/.test(value2)) {
    return quotedString(value2, ctx);
  }
  const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value2) ? "  " : "");
  const literal2 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value2, lineWidth, indent.length);
  if (!value2)
    return literal2 ? "|\n" : ">\n";
  let chomp;
  let endStart;
  for (endStart = value2.length; endStart > 0; --endStart) {
    const ch = value2[endStart - 1];
    if (ch !== "\n" && ch !== "	" && ch !== " ")
      break;
  }
  let end = value2.substring(endStart);
  const endNlPos = end.indexOf("\n");
  if (endNlPos === -1) {
    chomp = "-";
  } else if (value2 === end || endNlPos !== end.length - 1) {
    chomp = "+";
    if (onChompKeep)
      onChompKeep();
  } else {
    chomp = "";
  }
  if (end) {
    value2 = value2.slice(0, -end.length);
    if (end[end.length - 1] === "\n")
      end = end.slice(0, -1);
    end = end.replace(blockEndNewlines, `$&${indent}`);
  }
  let startWithSpace = false;
  let startEnd;
  let startNlPos = -1;
  for (startEnd = 0; startEnd < value2.length; ++startEnd) {
    const ch = value2[startEnd];
    if (ch === " ")
      startWithSpace = true;
    else if (ch === "\n")
      startNlPos = startEnd;
    else
      break;
  }
  let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
  if (start) {
    value2 = value2.substring(start.length);
    start = start.replace(/\n+/g, `$&${indent}`);
  }
  const indentSize = indent ? "2" : "1";
  let header = (startWithSpace ? indentSize : "") + chomp;
  if (comment4) {
    header += " " + commentString(comment4.replace(/ ?[\r\n]+/g, " "));
    if (onComment)
      onComment();
  }
  if (!literal2) {
    const foldedValue = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
    let literalFallback = false;
    const foldOptions = getFoldOptions(ctx, true);
    if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) {
      foldOptions.onOverflow = () => {
        literalFallback = true;
      };
    }
    const body3 = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);
    if (!literalFallback)
      return `>${header}
${indent}${body3}`;
  }
  value2 = value2.replace(/\n+/g, `$&${indent}`);
  return `|${header}
${indent}${start}${value2}${end}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
  const { type, value: value2 } = item;
  const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
  if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) {
    return quotedString(value2, ctx);
  }
  if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) {
    return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep);
  }
  if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) {
    return blockString(item, ctx, onComment, onChompKeep);
  }
  if (containsDocumentMarker(value2)) {
    if (indent === "") {
      ctx.forceBlockIndent = true;
      return blockString(item, ctx, onComment, onChompKeep);
    } else if (implicitKey && indent === indentStep) {
      return quotedString(value2, ctx);
    }
  }
  const str = value2.replace(/\n+/g, `$&
${indent}`);
  if (actualString) {
    const test2 = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
    const { compat, tags: tags2 } = ctx.doc.schema;
    if (tags2.some(test2) || compat?.some(test2))
      return quotedString(value2, ctx);
  }
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
  const { implicitKey, inFlow } = ctx;
  const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
  let { type } = item;
  if (type !== Scalar.QUOTE_DOUBLE) {
    if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
      type = Scalar.QUOTE_DOUBLE;
  }
  const _stringify = (_type) => {
    switch (_type) {
      case Scalar.BLOCK_FOLDED:
      case Scalar.BLOCK_LITERAL:
        return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
      case Scalar.QUOTE_DOUBLE:
        return doubleQuotedString(ss.value, ctx);
      case Scalar.QUOTE_SINGLE:
        return singleQuotedString(ss.value, ctx);
      case Scalar.PLAIN:
        return plainString(ss, ctx, onComment, onChompKeep);
      default:
        return null;
    }
  };
  let res = _stringify(type);
  if (res === null) {
    const { defaultKeyType, defaultStringType } = ctx.options;
    const t3 = implicitKey && defaultKeyType || defaultStringType;
    res = _stringify(t3);
    if (res === null)
      throw new Error(`Unsupported default string type ${t3}`);
  }
  return res;
}

// node_modules/yaml/browser/dist/stringify/stringify.js
function createStringifyContext(doc4, options2) {
  const opt = Object.assign({
    blockQuote: true,
    commentString: stringifyComment,
    defaultKeyType: null,
    defaultStringType: "PLAIN",
    directives: null,
    doubleQuotedAsJSON: false,
    doubleQuotedMinMultiLineLength: 40,
    falseStr: "false",
    flowCollectionPadding: true,
    indentSeq: true,
    lineWidth: 80,
    minContentWidth: 20,
    nullStr: "null",
    simpleKeys: false,
    singleQuote: null,
    trueStr: "true",
    verifyAliasOrder: true
  }, doc4.schema.toStringOptions, options2);
  let inFlow;
  switch (opt.collectionStyle) {
    case "block":
      inFlow = false;
      break;
    case "flow":
      inFlow = true;
      break;
    default:
      inFlow = null;
  }
  return {
    anchors: /* @__PURE__ */ new Set(),
    doc: doc4,
    flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
    indent: "",
    indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
    inFlow,
    options: opt
  };
}
function getTagObject(tags2, item) {
  if (item.tag) {
    const match2 = tags2.filter((t3) => t3.tag === item.tag);
    if (match2.length > 0)
      return match2.find((t3) => t3.format === item.format) ?? match2[0];
  }
  let tagObj = void 0;
  let obj;
  if (isScalar(item)) {
    obj = item.value;
    let match2 = tags2.filter((t3) => t3.identify?.(obj));
    if (match2.length > 1) {
      const testMatch = match2.filter((t3) => t3.test);
      if (testMatch.length > 0)
        match2 = testMatch;
    }
    tagObj = match2.find((t3) => t3.format === item.format) ?? match2.find((t3) => !t3.format);
  } else {
    obj = item;
    tagObj = tags2.find((t3) => t3.nodeClass && obj instanceof t3.nodeClass);
  }
  if (!tagObj) {
    const name2 = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
    throw new Error(`Tag not resolved for ${name2} value`);
  }
  return tagObj;
}
function stringifyProps(node, tagObj, { anchors, doc: doc4 }) {
  if (!doc4.directives)
    return "";
  const props2 = [];
  const anchor = (isScalar(node) || isCollection(node)) && node.anchor;
  if (anchor && anchorIsValid(anchor)) {
    anchors.add(anchor);
    props2.push(`&${anchor}`);
  }
  const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
  if (tag)
    props2.push(doc4.directives.tagString(tag));
  return props2.join(" ");
}
function stringify4(item, ctx, onComment, onChompKeep) {
  if (isPair(item))
    return item.toString(ctx, onComment, onChompKeep);
  if (isAlias(item)) {
    if (ctx.doc.directives)
      return item.toString(ctx);
    if (ctx.resolvedAliases?.has(item)) {
      throw new TypeError(`Cannot stringify circular structure without alias nodes`);
    } else {
      if (ctx.resolvedAliases)
        ctx.resolvedAliases.add(item);
      else
        ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
      item = item.resolve(ctx.doc);
    }
  }
  let tagObj = void 0;
  const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o3) => tagObj = o3 });
  tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
  const props2 = stringifyProps(node, tagObj, ctx);
  if (props2.length > 0)
    ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props2.length + 1;
  const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
  if (!props2)
    return str;
  return isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props2} ${str}` : `${props2}
${ctx.indent}${str}`;
}

// node_modules/yaml/browser/dist/stringify/stringifyPair.js
function stringifyPair({ key: key2, value: value2 }, ctx, onComment, onChompKeep) {
  const { allNullValues, doc: doc4, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
  let keyComment = isNode(key2) && key2.comment || null;
  if (simpleKeys) {
    if (keyComment) {
      throw new Error("With simple keys, key nodes cannot have comments");
    }
    if (isCollection(key2) || !isNode(key2) && typeof key2 === "object") {
      const msg2 = "With simple keys, collection cannot be used as a key value";
      throw new Error(msg2);
    }
  }
  let explicitKey = !simpleKeys && (!key2 || keyComment && value2 == null && !ctx.inFlow || isCollection(key2) || (isScalar(key2) ? key2.type === Scalar.BLOCK_FOLDED || key2.type === Scalar.BLOCK_LITERAL : typeof key2 === "object"));
  ctx = Object.assign({}, ctx, {
    allNullValues: false,
    implicitKey: !explicitKey && (simpleKeys || !allNullValues),
    indent: indent + indentStep
  });
  let keyCommentDone = false;
  let chompKeep = false;
  let str = stringify4(key2, ctx, () => keyCommentDone = true, () => chompKeep = true);
  if (!explicitKey && !ctx.inFlow && str.length > 1024) {
    if (simpleKeys)
      throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
    explicitKey = true;
  }
  if (ctx.inFlow) {
    if (allNullValues || value2 == null) {
      if (keyCommentDone && onComment)
        onComment();
      return str === "" ? "?" : explicitKey ? `? ${str}` : str;
    }
  } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) {
    str = `? ${str}`;
    if (keyComment && !keyCommentDone) {
      str += lineComment(str, ctx.indent, commentString(keyComment));
    } else if (chompKeep && onChompKeep)
      onChompKeep();
    return str;
  }
  if (keyCommentDone)
    keyComment = null;
  if (explicitKey) {
    if (keyComment)
      str += lineComment(str, ctx.indent, commentString(keyComment));
    str = `? ${str}
${indent}:`;
  } else {
    str = `${str}:`;
    if (keyComment)
      str += lineComment(str, ctx.indent, commentString(keyComment));
  }
  let vsb, vcb, valueComment;
  if (isNode(value2)) {
    vsb = !!value2.spaceBefore;
    vcb = value2.commentBefore;
    valueComment = value2.comment;
  } else {
    vsb = false;
    vcb = null;
    valueComment = null;
    if (value2 && typeof value2 === "object")
      value2 = doc4.createNode(value2);
  }
  ctx.implicitKey = false;
  if (!explicitKey && !keyComment && isScalar(value2))
    ctx.indentAtStart = str.length + 1;
  chompKeep = false;
  if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) {
    ctx.indent = ctx.indent.substring(2);
  }
  let valueCommentDone = false;
  const valueStr = stringify4(value2, ctx, () => valueCommentDone = true, () => chompKeep = true);
  let ws = " ";
  if (keyComment || vsb || vcb) {
    ws = vsb ? "\n" : "";
    if (vcb) {
      const cs = commentString(vcb);
      ws += `
${indentComment(cs, ctx.indent)}`;
    }
    if (valueStr === "" && !ctx.inFlow) {
      if (ws === "\n" && valueComment)
        ws = "\n\n";
    } else {
      ws += `
${ctx.indent}`;
    }
  } else if (!explicitKey && isCollection(value2)) {
    const vs0 = valueStr[0];
    const nl0 = valueStr.indexOf("\n");
    const hasNewline = nl0 !== -1;
    const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0;
    if (hasNewline || !flow) {
      let hasPropsLine = false;
      if (hasNewline && (vs0 === "&" || vs0 === "!")) {
        let sp0 = valueStr.indexOf(" ");
        if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
          sp0 = valueStr.indexOf(" ", sp0 + 1);
        }
        if (sp0 === -1 || nl0 < sp0)
          hasPropsLine = true;
      }
      if (!hasPropsLine)
        ws = `
${ctx.indent}`;
    }
  } else if (valueStr === "" || valueStr[0] === "\n") {
    ws = "";
  }
  str += ws + valueStr;
  if (ctx.inFlow) {
    if (valueCommentDone && onComment)
      onComment();
  } else if (valueComment && !valueCommentDone) {
    str += lineComment(str, ctx.indent, commentString(valueComment));
  } else if (chompKeep && onChompKeep) {
    onChompKeep();
  }
  return str;
}

// node_modules/yaml/browser/dist/log.js
function warn(logLevel, warning2) {
  if (logLevel === "debug" || logLevel === "warn") {
    console.warn(warning2);
  }
}

// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js
var MERGE_KEY = "<<";
var merge3 = {
  identify: (value2) => value2 === MERGE_KEY || typeof value2 === "symbol" && value2.description === MERGE_KEY,
  default: "key",
  tag: "tag:yaml.org,2002:merge",
  test: /^<<$/,
  resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {
    addToJSMap: addMergeToJSMap
  }),
  stringify: () => MERGE_KEY
};
var isMergeKey = (ctx, key2) => (merge3.identify(key2) || isScalar(key2) && (!key2.type || key2.type === Scalar.PLAIN) && merge3.identify(key2.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default);
function addMergeToJSMap(ctx, map5, value2) {
  value2 = ctx && isAlias(value2) ? value2.resolve(ctx.doc) : value2;
  if (isSeq(value2))
    for (const it2 of value2.items)
      mergeValue(ctx, map5, it2);
  else if (Array.isArray(value2))
    for (const it2 of value2)
      mergeValue(ctx, map5, it2);
  else
    mergeValue(ctx, map5, value2);
}
function mergeValue(ctx, map5, value2) {
  const source = ctx && isAlias(value2) ? value2.resolve(ctx.doc) : value2;
  if (!isMap(source))
    throw new Error("Merge sources must be maps or map aliases");
  const srcMap = source.toJSON(null, ctx, Map);
  for (const [key2, value3] of srcMap) {
    if (map5 instanceof Map) {
      if (!map5.has(key2))
        map5.set(key2, value3);
    } else if (map5 instanceof Set) {
      map5.add(key2);
    } else if (!Object.prototype.hasOwnProperty.call(map5, key2)) {
      Object.defineProperty(map5, key2, {
        value: value3,
        writable: true,
        enumerable: true,
        configurable: true
      });
    }
  }
  return map5;
}

// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js
function addPairToJSMap(ctx, map5, { key: key2, value: value2 }) {
  if (isNode(key2) && key2.addToJSMap)
    key2.addToJSMap(ctx, map5, value2);
  else if (isMergeKey(ctx, key2))
    addMergeToJSMap(ctx, map5, value2);
  else {
    const jsKey = toJS(key2, "", ctx);
    if (map5 instanceof Map) {
      map5.set(jsKey, toJS(value2, jsKey, ctx));
    } else if (map5 instanceof Set) {
      map5.add(jsKey);
    } else {
      const stringKey = stringifyKey(key2, jsKey, ctx);
      const jsValue = toJS(value2, stringKey, ctx);
      if (stringKey in map5)
        Object.defineProperty(map5, stringKey, {
          value: jsValue,
          writable: true,
          enumerable: true,
          configurable: true
        });
      else
        map5[stringKey] = jsValue;
    }
  }
  return map5;
}
function stringifyKey(key2, jsKey, ctx) {
  if (jsKey === null)
    return "";
  if (typeof jsKey !== "object")
    return String(jsKey);
  if (isNode(key2) && ctx?.doc) {
    const strCtx = createStringifyContext(ctx.doc, {});
    strCtx.anchors = /* @__PURE__ */ new Set();
    for (const node of ctx.anchors.keys())
      strCtx.anchors.add(node.anchor);
    strCtx.inFlow = true;
    strCtx.inStringifyKey = true;
    const strKey = key2.toString(strCtx);
    if (!ctx.mapKeyWarned) {
      let jsonStr = JSON.stringify(strKey);
      if (jsonStr.length > 40)
        jsonStr = jsonStr.substring(0, 36) + '..."';
      warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
      ctx.mapKeyWarned = true;
    }
    return strKey;
  }
  return JSON.stringify(jsKey);
}

// node_modules/yaml/browser/dist/nodes/Pair.js
function createPair(key2, value2, ctx) {
  const k2 = createNode(key2, void 0, ctx);
  const v3 = createNode(value2, void 0, ctx);
  return new Pair(k2, v3);
}
var Pair = class _Pair {
  constructor(key2, value2 = null) {
    Object.defineProperty(this, NODE_TYPE, { value: PAIR });
    this.key = key2;
    this.value = value2;
  }
  clone(schema7) {
    let { key: key2, value: value2 } = this;
    if (isNode(key2))
      key2 = key2.clone(schema7);
    if (isNode(value2))
      value2 = value2.clone(schema7);
    return new _Pair(key2, value2);
  }
  toJSON(_5, ctx) {
    const pair2 = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
    return addPairToJSMap(ctx, pair2, this);
  }
  toString(ctx, onComment, onChompKeep) {
    return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
  }
};

// node_modules/yaml/browser/dist/stringify/stringifyCollection.js
function stringifyCollection(collection, ctx, options2) {
  const flow = ctx.inFlow ?? collection.flow;
  const stringify7 = flow ? stringifyFlowCollection : stringifyBlockCollection;
  return stringify7(collection, ctx, options2);
}
function stringifyBlockCollection({ comment: comment4, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
  const { indent, options: { commentString } } = ctx;
  const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
  let chompKeep = false;
  const lines = [];
  for (let i3 = 0; i3 < items.length; ++i3) {
    const item = items[i3];
    let comment5 = null;
    if (isNode(item)) {
      if (!chompKeep && item.spaceBefore)
        lines.push("");
      addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
      if (item.comment)
        comment5 = item.comment;
    } else if (isPair(item)) {
      const ik = isNode(item.key) ? item.key : null;
      if (ik) {
        if (!chompKeep && ik.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
      }
    }
    chompKeep = false;
    let str2 = stringify4(item, itemCtx, () => comment5 = null, () => chompKeep = true);
    if (comment5)
      str2 += lineComment(str2, itemIndent, commentString(comment5));
    if (chompKeep && comment5)
      chompKeep = false;
    lines.push(blockItemPrefix + str2);
  }
  let str;
  if (lines.length === 0) {
    str = flowChars.start + flowChars.end;
  } else {
    str = lines[0];
    for (let i3 = 1; i3 < lines.length; ++i3) {
      const line = lines[i3];
      str += line ? `
${indent}${line}` : "\n";
    }
  }
  if (comment4) {
    str += "\n" + indentComment(commentString(comment4), indent);
    if (onComment)
      onComment();
  } else if (chompKeep && onChompKeep)
    onChompKeep();
  return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
  const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
  itemIndent += indentStep;
  const itemCtx = Object.assign({}, ctx, {
    indent: itemIndent,
    inFlow: true,
    type: null
  });
  let reqNewline = false;
  let linesAtValue = 0;
  const lines = [];
  for (let i3 = 0; i3 < items.length; ++i3) {
    const item = items[i3];
    let comment4 = null;
    if (isNode(item)) {
      if (item.spaceBefore)
        lines.push("");
      addCommentBefore(ctx, lines, item.commentBefore, false);
      if (item.comment)
        comment4 = item.comment;
    } else if (isPair(item)) {
      const ik = isNode(item.key) ? item.key : null;
      if (ik) {
        if (ik.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, ik.commentBefore, false);
        if (ik.comment)
          reqNewline = true;
      }
      const iv = isNode(item.value) ? item.value : null;
      if (iv) {
        if (iv.comment)
          comment4 = iv.comment;
        if (iv.commentBefore)
          reqNewline = true;
      } else if (item.value == null && ik?.comment) {
        comment4 = ik.comment;
      }
    }
    if (comment4)
      reqNewline = true;
    let str = stringify4(item, itemCtx, () => comment4 = null);
    if (i3 < items.length - 1)
      str += ",";
    if (comment4)
      str += lineComment(str, itemIndent, commentString(comment4));
    if (!reqNewline && (lines.length > linesAtValue || str.includes("\n")))
      reqNewline = true;
    lines.push(str);
    linesAtValue = lines.length;
  }
  const { start, end } = flowChars;
  if (lines.length === 0) {
    return start + end;
  } else {
    if (!reqNewline) {
      const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
      reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
    }
    if (reqNewline) {
      let str = start;
      for (const line of lines)
        str += line ? `
${indentStep}${indent}${line}` : "\n";
      return `${str}
${indent}${end}`;
    } else {
      return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
    }
  }
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment4, chompKeep) {
  if (comment4 && chompKeep)
    comment4 = comment4.replace(/^\n+/, "");
  if (comment4) {
    const ic = indentComment(commentString(comment4), indent);
    lines.push(ic.trimStart());
  }
}

// node_modules/yaml/browser/dist/nodes/YAMLMap.js
function findPair(items, key2) {
  const k2 = isScalar(key2) ? key2.value : key2;
  for (const it2 of items) {
    if (isPair(it2)) {
      if (it2.key === key2 || it2.key === k2)
        return it2;
      if (isScalar(it2.key) && it2.key.value === k2)
        return it2;
    }
  }
  return void 0;
}
var YAMLMap = class extends Collection {
  static get tagName() {
    return "tag:yaml.org,2002:map";
  }
  constructor(schema7) {
    super(MAP, schema7);
    this.items = [];
  }
  /**
   * A generic collection parsing method that can be extended
   * to other node classes that inherit from YAMLMap
   */
  static from(schema7, obj, ctx) {
    const { keepUndefined, replacer } = ctx;
    const map5 = new this(schema7);
    const add4 = (key2, value2) => {
      if (typeof replacer === "function")
        value2 = replacer.call(obj, key2, value2);
      else if (Array.isArray(replacer) && !replacer.includes(key2))
        return;
      if (value2 !== void 0 || keepUndefined)
        map5.items.push(createPair(key2, value2, ctx));
    };
    if (obj instanceof Map) {
      for (const [key2, value2] of obj)
        add4(key2, value2);
    } else if (obj && typeof obj === "object") {
      for (const key2 of Object.keys(obj))
        add4(key2, obj[key2]);
    }
    if (typeof schema7.sortMapEntries === "function") {
      map5.items.sort(schema7.sortMapEntries);
    }
    return map5;
  }
  /**
   * Adds a value to the collection.
   *
   * @param overwrite - If not set `true`, using a key that is already in the
   *   collection will throw. Otherwise, overwrites the previous value.
   */
  add(pair2, overwrite) {
    let _pair;
    if (isPair(pair2))
      _pair = pair2;
    else if (!pair2 || typeof pair2 !== "object" || !("key" in pair2)) {
      _pair = new Pair(pair2, pair2?.value);
    } else
      _pair = new Pair(pair2.key, pair2.value);
    const prev = findPair(this.items, _pair.key);
    const sortEntries = this.schema?.sortMapEntries;
    if (prev) {
      if (!overwrite)
        throw new Error(`Key ${_pair.key} already set`);
      if (isScalar(prev.value) && isScalarValue(_pair.value))
        prev.value.value = _pair.value;
      else
        prev.value = _pair.value;
    } else if (sortEntries) {
      const i3 = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
      if (i3 === -1)
        this.items.push(_pair);
      else
        this.items.splice(i3, 0, _pair);
    } else {
      this.items.push(_pair);
    }
  }
  delete(key2) {
    const it2 = findPair(this.items, key2);
    if (!it2)
      return false;
    const del2 = this.items.splice(this.items.indexOf(it2), 1);
    return del2.length > 0;
  }
  get(key2, keepScalar) {
    const it2 = findPair(this.items, key2);
    const node = it2?.value;
    return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0;
  }
  has(key2) {
    return !!findPair(this.items, key2);
  }
  set(key2, value2) {
    this.add(new Pair(key2, value2), true);
  }
  /**
   * @param ctx - Conversion context, originally set in Document#toJS()
   * @param {Class} Type - If set, forces the returned collection type
   * @returns Instance of Type, Map, or Object
   */
  toJSON(_5, ctx, Type) {
    const map5 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
    if (ctx?.onCreate)
      ctx.onCreate(map5);
    for (const item of this.items)
      addPairToJSMap(ctx, map5, item);
    return map5;
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    for (const item of this.items) {
      if (!isPair(item))
        throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
    }
    if (!ctx.allNullValues && this.hasAllNullValues(false))
      ctx = Object.assign({}, ctx, { allNullValues: true });
    return stringifyCollection(this, ctx, {
      blockItemPrefix: "",
      flowChars: { start: "{", end: "}" },
      itemIndent: ctx.indent || "",
      onChompKeep,
      onComment
    });
  }
};

// node_modules/yaml/browser/dist/schema/common/map.js
var map3 = {
  collection: "map",
  default: true,
  nodeClass: YAMLMap,
  tag: "tag:yaml.org,2002:map",
  resolve(map5, onError) {
    if (!isMap(map5))
      onError("Expected a mapping for this tag");
    return map5;
  },
  createNode: (schema7, obj, ctx) => YAMLMap.from(schema7, obj, ctx)
};

// node_modules/yaml/browser/dist/nodes/YAMLSeq.js
var YAMLSeq = class extends Collection {
  static get tagName() {
    return "tag:yaml.org,2002:seq";
  }
  constructor(schema7) {
    super(SEQ, schema7);
    this.items = [];
  }
  add(value2) {
    this.items.push(value2);
  }
  /**
   * Removes a value from the collection.
   *
   * `key` must contain a representation of an integer for this to succeed.
   * It may be wrapped in a `Scalar`.
   *
   * @returns `true` if the item was found and removed.
   */
  delete(key2) {
    const idx = asItemIndex(key2);
    if (typeof idx !== "number")
      return false;
    const del2 = this.items.splice(idx, 1);
    return del2.length > 0;
  }
  get(key2, keepScalar) {
    const idx = asItemIndex(key2);
    if (typeof idx !== "number")
      return void 0;
    const it2 = this.items[idx];
    return !keepScalar && isScalar(it2) ? it2.value : it2;
  }
  /**
   * Checks if the collection includes a value with the key `key`.
   *
   * `key` must contain a representation of an integer for this to succeed.
   * It may be wrapped in a `Scalar`.
   */
  has(key2) {
    const idx = asItemIndex(key2);
    return typeof idx === "number" && idx < this.items.length;
  }
  /**
   * Sets a value in this collection. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   *
   * If `key` does not contain a representation of an integer, this will throw.
   * It may be wrapped in a `Scalar`.
   */
  set(key2, value2) {
    const idx = asItemIndex(key2);
    if (typeof idx !== "number")
      throw new Error(`Expected a valid index, not ${key2}.`);
    const prev = this.items[idx];
    if (isScalar(prev) && isScalarValue(value2))
      prev.value = value2;
    else
      this.items[idx] = value2;
  }
  toJSON(_5, ctx) {
    const seq2 = [];
    if (ctx?.onCreate)
      ctx.onCreate(seq2);
    let i3 = 0;
    for (const item of this.items)
      seq2.push(toJS(item, String(i3++), ctx));
    return seq2;
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    return stringifyCollection(this, ctx, {
      blockItemPrefix: "- ",
      flowChars: { start: "[", end: "]" },
      itemIndent: (ctx.indent || "") + "  ",
      onChompKeep,
      onComment
    });
  }
  static from(schema7, obj, ctx) {
    const { replacer } = ctx;
    const seq2 = new this(schema7);
    if (obj && Symbol.iterator in Object(obj)) {
      let i3 = 0;
      for (let it2 of obj) {
        if (typeof replacer === "function") {
          const key2 = obj instanceof Set ? it2 : String(i3++);
          it2 = replacer.call(obj, key2, it2);
        }
        seq2.items.push(createNode(it2, void 0, ctx));
      }
    }
    return seq2;
  }
};
function asItemIndex(key2) {
  let idx = isScalar(key2) ? key2.value : key2;
  if (idx && typeof idx === "string")
    idx = Number(idx);
  return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}

// node_modules/yaml/browser/dist/schema/common/seq.js
var seq = {
  collection: "seq",
  default: true,
  nodeClass: YAMLSeq,
  tag: "tag:yaml.org,2002:seq",
  resolve(seq2, onError) {
    if (!isSeq(seq2))
      onError("Expected a sequence for this tag");
    return seq2;
  },
  createNode: (schema7, obj, ctx) => YAMLSeq.from(schema7, obj, ctx)
};

// node_modules/yaml/browser/dist/schema/common/string.js
var string2 = {
  identify: (value2) => typeof value2 === "string",
  default: true,
  tag: "tag:yaml.org,2002:str",
  resolve: (str) => str,
  stringify(item, ctx, onComment, onChompKeep) {
    ctx = Object.assign({ actualString: true }, ctx);
    return stringifyString(item, ctx, onComment, onChompKeep);
  }
};

// node_modules/yaml/browser/dist/schema/common/null.js
var nullTag = {
  identify: (value2) => value2 == null,
  createNode: () => new Scalar(null),
  default: true,
  tag: "tag:yaml.org,2002:null",
  test: /^(?:~|[Nn]ull|NULL)?$/,
  resolve: () => new Scalar(null),
  stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
};

// node_modules/yaml/browser/dist/schema/core/bool.js
var boolTag = {
  identify: (value2) => typeof value2 === "boolean",
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"),
  stringify({ source, value: value2 }, ctx) {
    if (source && boolTag.test.test(source)) {
      const sv = source[0] === "t" || source[0] === "T";
      if (value2 === sv)
        return source;
    }
    return value2 ? ctx.options.trueStr : ctx.options.falseStr;
  }
};

// node_modules/yaml/browser/dist/stringify/stringifyNumber.js
function stringifyNumber({ format: format2, minFractionDigits, tag, value: value2 }) {
  if (typeof value2 === "bigint")
    return String(value2);
  const num = typeof value2 === "number" ? value2 : Number(value2);
  if (!isFinite(num))
    return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
  let n4 = Object.is(value2, -0) ? "-0" : JSON.stringify(value2);
  if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n4)) {
    let i3 = n4.indexOf(".");
    if (i3 < 0) {
      i3 = n4.length;
      n4 += ".";
    }
    let d3 = minFractionDigits - (n4.length - i3 - 1);
    while (d3-- > 0)
      n4 += "0";
  }
  return n4;
}

// node_modules/yaml/browser/dist/schema/core/float.js
var floatNaN = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  stringify: stringifyNumber
};
var floatExp = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "EXP",
  test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  resolve: (str) => parseFloat(str),
  stringify(node) {
    const num = Number(node.value);
    return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  }
};
var float = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
  resolve(str) {
    const node = new Scalar(parseFloat(str));
    const dot = str.indexOf(".");
    if (dot !== -1 && str[str.length - 1] === "0")
      node.minFractionDigits = str.length - dot - 1;
    return node;
  },
  stringify: stringifyNumber
};

// node_modules/yaml/browser/dist/schema/core/int.js
var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
function intStringify(node, radix, prefix5) {
  const { value: value2 } = node;
  if (intIdentify(value2) && value2 >= 0)
    return prefix5 + value2.toString(radix);
  return stringifyNumber(node);
}
var intOct = {
  identify: (value2) => intIdentify(value2) && value2 >= 0,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "OCT",
  test: /^0o[0-7]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
  stringify: (node) => intStringify(node, 8, "0o")
};
var int = {
  identify: intIdentify,
  default: true,
  tag: "tag:yaml.org,2002:int",
  test: /^[-+]?[0-9]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  stringify: stringifyNumber
};
var intHex = {
  identify: (value2) => intIdentify(value2) && value2 >= 0,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "HEX",
  test: /^0x[0-9a-fA-F]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  stringify: (node) => intStringify(node, 16, "0x")
};

// node_modules/yaml/browser/dist/schema/core/schema.js
var schema = [
  map3,
  seq,
  string2,
  nullTag,
  boolTag,
  intOct,
  int,
  intHex,
  floatNaN,
  floatExp,
  float
];

// node_modules/yaml/browser/dist/schema/json/schema.js
function intIdentify2(value2) {
  return typeof value2 === "bigint" || Number.isInteger(value2);
}
var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2);
var jsonScalars = [
  {
    identify: (value2) => typeof value2 === "string",
    default: true,
    tag: "tag:yaml.org,2002:str",
    resolve: (str) => str,
    stringify: stringifyJSON
  },
  {
    identify: (value2) => value2 == null,
    createNode: () => new Scalar(null),
    default: true,
    tag: "tag:yaml.org,2002:null",
    test: /^null$/,
    resolve: () => null,
    stringify: stringifyJSON
  },
  {
    identify: (value2) => typeof value2 === "boolean",
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^true$|^false$/,
    resolve: (str) => str === "true",
    stringify: stringifyJSON
  },
  {
    identify: intIdentify2,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^-?(?:0|[1-9][0-9]*)$/,
    resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
    stringify: ({ value: value2 }) => intIdentify2(value2) ? value2.toString() : JSON.stringify(value2)
  },
  {
    identify: (value2) => typeof value2 === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
    resolve: (str) => parseFloat(str),
    stringify: stringifyJSON
  }
];
var jsonError = {
  default: true,
  tag: "",
  test: /^/,
  resolve(str, onError) {
    onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
    return str;
  }
};
var schema2 = [map3, seq].concat(jsonScalars, jsonError);

// node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js
var binary = {
  identify: (value2) => value2 instanceof Uint8Array,
  // Buffer inherits from Uint8Array
  default: false,
  tag: "tag:yaml.org,2002:binary",
  /**
   * Returns a Buffer in node and an Uint8Array in browsers
   *
   * To use the resulting buffer as an image, you'll want to do something like:
   *
   *   const blob = new Blob([buffer], { type: 'image/jpeg' })
   *   document.querySelector('#photo').src = URL.createObjectURL(blob)
   */
  resolve(src, onError) {
    if (typeof atob === "function") {
      const str = atob(src.replace(/[\n\r]/g, ""));
      const buffer = new Uint8Array(str.length);
      for (let i3 = 0; i3 < str.length; ++i3)
        buffer[i3] = str.charCodeAt(i3);
      return buffer;
    } else {
      onError("This environment does not support reading binary tags; either Buffer or atob is required");
      return src;
    }
  },
  stringify({ comment: comment4, type, value: value2 }, ctx, onComment, onChompKeep) {
    if (!value2)
      return "";
    const buf = value2;
    let str;
    if (typeof btoa === "function") {
      let s3 = "";
      for (let i3 = 0; i3 < buf.length; ++i3)
        s3 += String.fromCharCode(buf[i3]);
      str = btoa(s3);
    } else {
      throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
    }
    type ?? (type = Scalar.BLOCK_LITERAL);
    if (type !== Scalar.QUOTE_DOUBLE) {
      const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
      const n4 = Math.ceil(str.length / lineWidth);
      const lines = new Array(n4);
      for (let i3 = 0, o3 = 0; i3 < n4; ++i3, o3 += lineWidth) {
        lines[i3] = str.substr(o3, lineWidth);
      }
      str = lines.join(type === Scalar.BLOCK_LITERAL ? "\n" : " ");
    }
    return stringifyString({ comment: comment4, type, value: str }, ctx, onComment, onChompKeep);
  }
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js
function resolvePairs(seq2, onError) {
  if (isSeq(seq2)) {
    for (let i3 = 0; i3 < seq2.items.length; ++i3) {
      let item = seq2.items[i3];
      if (isPair(item))
        continue;
      else if (isMap(item)) {
        if (item.items.length > 1)
          onError("Each pair must have its own sequence indicator");
        const pair2 = item.items[0] || new Pair(new Scalar(null));
        if (item.commentBefore)
          pair2.key.commentBefore = pair2.key.commentBefore ? `${item.commentBefore}
${pair2.key.commentBefore}` : item.commentBefore;
        if (item.comment) {
          const cn = pair2.value ?? pair2.key;
          cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
        }
        item = pair2;
      }
      seq2.items[i3] = isPair(item) ? item : new Pair(item);
    }
  } else
    onError("Expected a sequence for this tag");
  return seq2;
}
function createPairs(schema7, iterable, ctx) {
  const { replacer } = ctx;
  const pairs3 = new YAMLSeq(schema7);
  pairs3.tag = "tag:yaml.org,2002:pairs";
  let i3 = 0;
  if (iterable && Symbol.iterator in Object(iterable))
    for (let it2 of iterable) {
      if (typeof replacer === "function")
        it2 = replacer.call(iterable, String(i3++), it2);
      let key2, value2;
      if (Array.isArray(it2)) {
        if (it2.length === 2) {
          key2 = it2[0];
          value2 = it2[1];
        } else
          throw new TypeError(`Expected [key, value] tuple: ${it2}`);
      } else if (it2 && it2 instanceof Object) {
        const keys5 = Object.keys(it2);
        if (keys5.length === 1) {
          key2 = keys5[0];
          value2 = it2[key2];
        } else {
          throw new TypeError(`Expected tuple with one key, not ${keys5.length} keys`);
        }
      } else {
        key2 = it2;
      }
      pairs3.items.push(createPair(key2, value2, ctx));
    }
  return pairs3;
}
var pairs2 = {
  collection: "seq",
  default: false,
  tag: "tag:yaml.org,2002:pairs",
  resolve: resolvePairs,
  createNode: createPairs
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js
var YAMLOMap = class _YAMLOMap extends YAMLSeq {
  constructor() {
    super();
    this.add = YAMLMap.prototype.add.bind(this);
    this.delete = YAMLMap.prototype.delete.bind(this);
    this.get = YAMLMap.prototype.get.bind(this);
    this.has = YAMLMap.prototype.has.bind(this);
    this.set = YAMLMap.prototype.set.bind(this);
    this.tag = _YAMLOMap.tag;
  }
  /**
   * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
   * but TypeScript won't allow widening the signature of a child method.
   */
  toJSON(_5, ctx) {
    if (!ctx)
      return super.toJSON(_5);
    const map5 = /* @__PURE__ */ new Map();
    if (ctx?.onCreate)
      ctx.onCreate(map5);
    for (const pair2 of this.items) {
      let key2, value2;
      if (isPair(pair2)) {
        key2 = toJS(pair2.key, "", ctx);
        value2 = toJS(pair2.value, key2, ctx);
      } else {
        key2 = toJS(pair2, "", ctx);
      }
      if (map5.has(key2))
        throw new Error("Ordered maps must not include duplicate keys");
      map5.set(key2, value2);
    }
    return map5;
  }
  static from(schema7, iterable, ctx) {
    const pairs3 = createPairs(schema7, iterable, ctx);
    const omap2 = new this();
    omap2.items = pairs3.items;
    return omap2;
  }
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
  collection: "seq",
  identify: (value2) => value2 instanceof Map,
  nodeClass: YAMLOMap,
  default: false,
  tag: "tag:yaml.org,2002:omap",
  resolve(seq2, onError) {
    const pairs3 = resolvePairs(seq2, onError);
    const seenKeys = [];
    for (const { key: key2 } of pairs3.items) {
      if (isScalar(key2)) {
        if (seenKeys.includes(key2.value)) {
          onError(`Ordered maps must not include duplicate keys: ${key2.value}`);
        } else {
          seenKeys.push(key2.value);
        }
      }
    }
    return Object.assign(new YAMLOMap(), pairs3);
  },
  createNode: (schema7, iterable, ctx) => YAMLOMap.from(schema7, iterable, ctx)
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js
function boolStringify({ value: value2, source }, ctx) {
  const boolObj = value2 ? trueTag : falseTag;
  if (source && boolObj.test.test(source))
    return source;
  return value2 ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
  identify: (value2) => value2 === true,
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  resolve: () => new Scalar(true),
  stringify: boolStringify
};
var falseTag = {
  identify: (value2) => value2 === false,
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
  resolve: () => new Scalar(false),
  stringify: boolStringify
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/float.js
var floatNaN2 = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  stringify: stringifyNumber
};
var floatExp2 = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "EXP",
  test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  resolve: (str) => parseFloat(str.replace(/_/g, "")),
  stringify(node) {
    const num = Number(node.value);
    return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  }
};
var float2 = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
  resolve(str) {
    const node = new Scalar(parseFloat(str.replace(/_/g, "")));
    const dot = str.indexOf(".");
    if (dot !== -1) {
      const f3 = str.substring(dot + 1).replace(/_/g, "");
      if (f3[f3.length - 1] === "0")
        node.minFractionDigits = f3.length;
    }
    return node;
  },
  stringify: stringifyNumber
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/int.js
var intIdentify3 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
function intResolve2(str, offset, radix, { intAsBigInt }) {
  const sign = str[0];
  if (sign === "-" || sign === "+")
    offset += 1;
  str = str.substring(offset).replace(/_/g, "");
  if (intAsBigInt) {
    switch (radix) {
      case 2:
        str = `0b${str}`;
        break;
      case 8:
        str = `0o${str}`;
        break;
      case 16:
        str = `0x${str}`;
        break;
    }
    const n5 = BigInt(str);
    return sign === "-" ? BigInt(-1) * n5 : n5;
  }
  const n4 = parseInt(str, radix);
  return sign === "-" ? -1 * n4 : n4;
}
function intStringify2(node, radix, prefix5) {
  const { value: value2 } = node;
  if (intIdentify3(value2)) {
    const str = value2.toString(radix);
    return value2 < 0 ? "-" + prefix5 + str.substr(1) : prefix5 + str;
  }
  return stringifyNumber(node);
}
var intBin = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "BIN",
  test: /^[-+]?0b[0-1_]+$/,
  resolve: (str, _onError, opt) => intResolve2(str, 2, 2, opt),
  stringify: (node) => intStringify2(node, 2, "0b")
};
var intOct2 = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "OCT",
  test: /^[-+]?0[0-7_]+$/,
  resolve: (str, _onError, opt) => intResolve2(str, 1, 8, opt),
  stringify: (node) => intStringify2(node, 8, "0")
};
var int2 = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  test: /^[-+]?[0-9][0-9_]*$/,
  resolve: (str, _onError, opt) => intResolve2(str, 0, 10, opt),
  stringify: stringifyNumber
};
var intHex2 = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "HEX",
  test: /^[-+]?0x[0-9a-fA-F_]+$/,
  resolve: (str, _onError, opt) => intResolve2(str, 2, 16, opt),
  stringify: (node) => intStringify2(node, 16, "0x")
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js
var YAMLSet = class _YAMLSet extends YAMLMap {
  constructor(schema7) {
    super(schema7);
    this.tag = _YAMLSet.tag;
  }
  add(key2) {
    let pair2;
    if (isPair(key2))
      pair2 = key2;
    else if (key2 && typeof key2 === "object" && "key" in key2 && "value" in key2 && key2.value === null)
      pair2 = new Pair(key2.key, null);
    else
      pair2 = new Pair(key2, null);
    const prev = findPair(this.items, pair2.key);
    if (!prev)
      this.items.push(pair2);
  }
  /**
   * If `keepPair` is `true`, returns the Pair matching `key`.
   * Otherwise, returns the value of that Pair's key.
   */
  get(key2, keepPair) {
    const pair2 = findPair(this.items, key2);
    return !keepPair && isPair(pair2) ? isScalar(pair2.key) ? pair2.key.value : pair2.key : pair2;
  }
  set(key2, value2) {
    if (typeof value2 !== "boolean")
      throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`);
    const prev = findPair(this.items, key2);
    if (prev && !value2) {
      this.items.splice(this.items.indexOf(prev), 1);
    } else if (!prev && value2) {
      this.items.push(new Pair(key2));
    }
  }
  toJSON(_5, ctx) {
    return super.toJSON(_5, ctx, Set);
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    if (this.hasAllNullValues(true))
      return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
    else
      throw new Error("Set items must all have null values");
  }
  static from(schema7, iterable, ctx) {
    const { replacer } = ctx;
    const set4 = new this(schema7);
    if (iterable && Symbol.iterator in Object(iterable))
      for (let value2 of iterable) {
        if (typeof replacer === "function")
          value2 = replacer.call(iterable, value2, value2);
        set4.items.push(createPair(value2, null, ctx));
      }
    return set4;
  }
};
YAMLSet.tag = "tag:yaml.org,2002:set";
var set3 = {
  collection: "map",
  identify: (value2) => value2 instanceof Set,
  nodeClass: YAMLSet,
  default: false,
  tag: "tag:yaml.org,2002:set",
  createNode: (schema7, iterable, ctx) => YAMLSet.from(schema7, iterable, ctx),
  resolve(map5, onError) {
    if (isMap(map5)) {
      if (map5.hasAllNullValues(true))
        return Object.assign(new YAMLSet(), map5);
      else
        onError("Set items must all have null values");
    } else
      onError("Expected a mapping for this tag");
    return map5;
  }
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js
function parseSexagesimal(str, asBigInt) {
  const sign = str[0];
  const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
  const num = (n4) => asBigInt ? BigInt(n4) : Number(n4);
  const res = parts.replace(/_/g, "").split(":").reduce((res2, p4) => res2 * num(60) + num(p4), num(0));
  return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node) {
  let { value: value2 } = node;
  let num = (n4) => n4;
  if (typeof value2 === "bigint")
    num = (n4) => BigInt(n4);
  else if (isNaN(value2) || !isFinite(value2))
    return stringifyNumber(node);
  let sign = "";
  if (value2 < 0) {
    sign = "-";
    value2 *= num(-1);
  }
  const _60 = num(60);
  const parts = [value2 % _60];
  if (value2 < 60) {
    parts.unshift(0);
  } else {
    value2 = (value2 - parts[0]) / _60;
    parts.unshift(value2 % _60);
    if (value2 >= 60) {
      value2 = (value2 - parts[0]) / _60;
      parts.unshift(value2);
    }
  }
  return sign + parts.map((n4) => String(n4).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
  identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2),
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "TIME",
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
  resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
  stringify: stringifySexagesimal
};
var floatTime = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "TIME",
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
  resolve: (str) => parseSexagesimal(str, false),
  stringify: stringifySexagesimal
};
var timestamp = {
  identify: (value2) => value2 instanceof Date,
  default: true,
  tag: "tag:yaml.org,2002:timestamp",
  // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  // may be omitted altogether, resulting in a date format. In such a case, the time part is
  // assumed to be 00:00:00Z (start of day, UTC).
  test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
  resolve(str) {
    const match2 = str.match(timestamp.test);
    if (!match2)
      throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
    const [, year, month, day, hour, minute, second] = match2.map(Number);
    const millisec = match2[7] ? Number((match2[7] + "00").substr(1, 3)) : 0;
    let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
    const tz = match2[8];
    if (tz && tz !== "Z") {
      let d3 = parseSexagesimal(tz, false);
      if (Math.abs(d3) < 30)
        d3 *= 60;
      date -= 6e4 * d3;
    }
    return new Date(date);
  },
  stringify: ({ value: value2 }) => value2?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
};

// node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js
var schema3 = [
  map3,
  seq,
  string2,
  nullTag,
  trueTag,
  falseTag,
  intBin,
  intOct2,
  int2,
  intHex2,
  floatNaN2,
  floatExp2,
  float2,
  binary,
  merge3,
  omap,
  pairs2,
  set3,
  intTime,
  floatTime,
  timestamp
];

// node_modules/yaml/browser/dist/schema/tags.js
var schemas = /* @__PURE__ */ new Map([
  ["core", schema],
  ["failsafe", [map3, seq, string2]],
  ["json", schema2],
  ["yaml11", schema3],
  ["yaml-1.1", schema3]
]);
var tagsByName = {
  binary,
  bool: boolTag,
  float,
  floatExp,
  floatNaN,
  floatTime,
  int,
  intHex,
  intOct,
  intTime,
  map: map3,
  merge: merge3,
  null: nullTag,
  omap,
  pairs: pairs2,
  seq,
  set: set3,
  timestamp
};
var coreKnownTags = {
  "tag:yaml.org,2002:binary": binary,
  "tag:yaml.org,2002:merge": merge3,
  "tag:yaml.org,2002:omap": omap,
  "tag:yaml.org,2002:pairs": pairs2,
  "tag:yaml.org,2002:set": set3,
  "tag:yaml.org,2002:timestamp": timestamp
};
function getTags(customTags, schemaName, addMergeTag) {
  const schemaTags = schemas.get(schemaName);
  if (schemaTags && !customTags) {
    return addMergeTag && !schemaTags.includes(merge3) ? schemaTags.concat(merge3) : schemaTags.slice();
  }
  let tags2 = schemaTags;
  if (!tags2) {
    if (Array.isArray(customTags))
      tags2 = [];
    else {
      const keys5 = Array.from(schemas.keys()).filter((key2) => key2 !== "yaml11").map((key2) => JSON.stringify(key2)).join(", ");
      throw new Error(`Unknown schema "${schemaName}"; use one of ${keys5} or define customTags array`);
    }
  }
  if (Array.isArray(customTags)) {
    for (const tag of customTags)
      tags2 = tags2.concat(tag);
  } else if (typeof customTags === "function") {
    tags2 = customTags(tags2.slice());
  }
  if (addMergeTag)
    tags2 = tags2.concat(merge3);
  return tags2.reduce((tags3, tag) => {
    const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
    if (!tagObj) {
      const tagName = JSON.stringify(tag);
      const keys5 = Object.keys(tagsByName).map((key2) => JSON.stringify(key2)).join(", ");
      throw new Error(`Unknown custom tag ${tagName}; use one of ${keys5}`);
    }
    if (!tags3.includes(tagObj))
      tags3.push(tagObj);
    return tags3;
  }, []);
}

// node_modules/yaml/browser/dist/schema/Schema.js
var sortMapEntriesByKey = (a3, b3) => a3.key < b3.key ? -1 : a3.key > b3.key ? 1 : 0;
var Schema3 = class _Schema {
  constructor({ compat, customTags, merge: merge4, resolveKnownTags, schema: schema7, sortMapEntries, toStringDefaults }) {
    this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null;
    this.name = typeof schema7 === "string" && schema7 || "core";
    this.knownTags = resolveKnownTags ? coreKnownTags : {};
    this.tags = getTags(customTags, this.name, merge4);
    this.toStringOptions = toStringDefaults ?? null;
    Object.defineProperty(this, MAP, { value: map3 });
    Object.defineProperty(this, SCALAR, { value: string2 });
    Object.defineProperty(this, SEQ, { value: seq });
    this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
  }
  clone() {
    const copy2 = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
    copy2.tags = this.tags.slice();
    return copy2;
  }
};

// node_modules/yaml/browser/dist/stringify/stringifyDocument.js
function stringifyDocument(doc4, options2) {
  const lines = [];
  let hasDirectives = options2.directives === true;
  if (options2.directives !== false && doc4.directives) {
    const dir = doc4.directives.toString(doc4);
    if (dir) {
      lines.push(dir);
      hasDirectives = true;
    } else if (doc4.directives.docStart)
      hasDirectives = true;
  }
  if (hasDirectives)
    lines.push("---");
  const ctx = createStringifyContext(doc4, options2);
  const { commentString } = ctx.options;
  if (doc4.commentBefore) {
    if (lines.length !== 1)
      lines.unshift("");
    const cs = commentString(doc4.commentBefore);
    lines.unshift(indentComment(cs, ""));
  }
  let chompKeep = false;
  let contentComment = null;
  if (doc4.contents) {
    if (isNode(doc4.contents)) {
      if (doc4.contents.spaceBefore && hasDirectives)
        lines.push("");
      if (doc4.contents.commentBefore) {
        const cs = commentString(doc4.contents.commentBefore);
        lines.push(indentComment(cs, ""));
      }
      ctx.forceBlockIndent = !!doc4.comment;
      contentComment = doc4.contents.comment;
    }
    const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
    let body3 = stringify4(doc4.contents, ctx, () => contentComment = null, onChompKeep);
    if (contentComment)
      body3 += lineComment(body3, "", commentString(contentComment));
    if ((body3[0] === "|" || body3[0] === ">") && lines[lines.length - 1] === "---") {
      lines[lines.length - 1] = `--- ${body3}`;
    } else
      lines.push(body3);
  } else {
    lines.push(stringify4(doc4.contents, ctx));
  }
  if (doc4.directives?.docEnd) {
    if (doc4.comment) {
      const cs = commentString(doc4.comment);
      if (cs.includes("\n")) {
        lines.push("...");
        lines.push(indentComment(cs, ""));
      } else {
        lines.push(`... ${cs}`);
      }
    } else {
      lines.push("...");
    }
  } else {
    let dc = doc4.comment;
    if (dc && chompKeep)
      dc = dc.replace(/^\n+/, "");
    if (dc) {
      if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
        lines.push("");
      lines.push(indentComment(commentString(dc), ""));
    }
  }
  return lines.join("\n") + "\n";
}

// node_modules/yaml/browser/dist/doc/Document.js
var Document = class _Document {
  constructor(value2, replacer, options2) {
    this.commentBefore = null;
    this.comment = null;
    this.errors = [];
    this.warnings = [];
    Object.defineProperty(this, NODE_TYPE, { value: DOC });
    let _replacer = null;
    if (typeof replacer === "function" || Array.isArray(replacer)) {
      _replacer = replacer;
    } else if (options2 === void 0 && replacer) {
      options2 = replacer;
      replacer = void 0;
    }
    const opt = Object.assign({
      intAsBigInt: false,
      keepSourceTokens: false,
      logLevel: "warn",
      prettyErrors: true,
      strict: true,
      stringKeys: false,
      uniqueKeys: true,
      version: "1.2"
    }, options2);
    this.options = opt;
    let { version } = opt;
    if (options2?._directives) {
      this.directives = options2._directives.atDocument();
      if (this.directives.yaml.explicit)
        version = this.directives.yaml.version;
    } else
      this.directives = new Directives({ version });
    this.setSchema(version, options2);
    this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options2);
  }
  /**
   * Create a deep copy of this Document and its contents.
   *
   * Custom Node values that inherit from `Object` still refer to their original instances.
   */
  clone() {
    const copy2 = Object.create(_Document.prototype, {
      [NODE_TYPE]: { value: DOC }
    });
    copy2.commentBefore = this.commentBefore;
    copy2.comment = this.comment;
    copy2.errors = this.errors.slice();
    copy2.warnings = this.warnings.slice();
    copy2.options = Object.assign({}, this.options);
    if (this.directives)
      copy2.directives = this.directives.clone();
    copy2.schema = this.schema.clone();
    copy2.contents = isNode(this.contents) ? this.contents.clone(copy2.schema) : this.contents;
    if (this.range)
      copy2.range = this.range.slice();
    return copy2;
  }
  /** Adds a value to the document. */
  add(value2) {
    if (assertCollection(this.contents))
      this.contents.add(value2);
  }
  /** Adds a value to the document. */
  addIn(path, value2) {
    if (assertCollection(this.contents))
      this.contents.addIn(path, value2);
  }
  /**
   * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
   *
   * If `node` already has an anchor, `name` is ignored.
   * Otherwise, the `node.anchor` value will be set to `name`,
   * or if an anchor with that name is already present in the document,
   * `name` will be used as a prefix for a new unique anchor.
   * If `name` is undefined, the generated anchor will use 'a' as a prefix.
   */
  createAlias(node, name2) {
    if (!node.anchor) {
      const prev = anchorNames(this);
      node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      !name2 || prev.has(name2) ? findNewAnchor(name2 || "a", prev) : name2;
    }
    return new Alias(node.anchor);
  }
  createNode(value2, replacer, options2) {
    let _replacer = void 0;
    if (typeof replacer === "function") {
      value2 = replacer.call({ "": value2 }, "", value2);
      _replacer = replacer;
    } else if (Array.isArray(replacer)) {
      const keyToStr = (v3) => typeof v3 === "number" || v3 instanceof String || v3 instanceof Number;
      const asStr = replacer.filter(keyToStr).map(String);
      if (asStr.length > 0)
        replacer = replacer.concat(asStr);
      _replacer = replacer;
    } else if (options2 === void 0 && replacer) {
      options2 = replacer;
      replacer = void 0;
    }
    const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options2 ?? {};
    const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(
      this,
      // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      anchorPrefix || "a"
    );
    const ctx = {
      aliasDuplicateObjects: aliasDuplicateObjects ?? true,
      keepUndefined: keepUndefined ?? false,
      onAnchor,
      onTagObj,
      replacer: _replacer,
      schema: this.schema,
      sourceObjects
    };
    const node = createNode(value2, tag, ctx);
    if (flow && isCollection(node))
      node.flow = true;
    setAnchors();
    return node;
  }
  /**
   * Convert a key and a value into a `Pair` using the current schema,
   * recursively wrapping all values as `Scalar` or `Collection` nodes.
   */
  createPair(key2, value2, options2 = {}) {
    const k2 = this.createNode(key2, null, options2);
    const v3 = this.createNode(value2, null, options2);
    return new Pair(k2, v3);
  }
  /**
   * Removes a value from the document.
   * @returns `true` if the item was found and removed.
   */
  delete(key2) {
    return assertCollection(this.contents) ? this.contents.delete(key2) : false;
  }
  /**
   * Removes a value from the document.
   * @returns `true` if the item was found and removed.
   */
  deleteIn(path) {
    if (isEmptyPath(path)) {
      if (this.contents == null)
        return false;
      this.contents = null;
      return true;
    }
    return assertCollection(this.contents) ? this.contents.deleteIn(path) : false;
  }
  /**
   * Returns item at `key`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  get(key2, keepScalar) {
    return isCollection(this.contents) ? this.contents.get(key2, keepScalar) : void 0;
  }
  /**
   * Returns item at `path`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  getIn(path, keepScalar) {
    if (isEmptyPath(path))
      return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents;
    return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0;
  }
  /**
   * Checks if the document includes a value with the key `key`.
   */
  has(key2) {
    return isCollection(this.contents) ? this.contents.has(key2) : false;
  }
  /**
   * Checks if the document includes a value at `path`.
   */
  hasIn(path) {
    if (isEmptyPath(path))
      return this.contents !== void 0;
    return isCollection(this.contents) ? this.contents.hasIn(path) : false;
  }
  /**
   * Sets a value in this document. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  set(key2, value2) {
    if (this.contents == null) {
      this.contents = collectionFromPath(this.schema, [key2], value2);
    } else if (assertCollection(this.contents)) {
      this.contents.set(key2, value2);
    }
  }
  /**
   * Sets a value in this document. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  setIn(path, value2) {
    if (isEmptyPath(path)) {
      this.contents = value2;
    } else if (this.contents == null) {
      this.contents = collectionFromPath(this.schema, Array.from(path), value2);
    } else if (assertCollection(this.contents)) {
      this.contents.setIn(path, value2);
    }
  }
  /**
   * Change the YAML version and schema used by the document.
   * A `null` version disables support for directives, explicit tags, anchors, and aliases.
   * It also requires the `schema` option to be given as a `Schema` instance value.
   *
   * Overrides all previously set schema options.
   */
  setSchema(version, options2 = {}) {
    if (typeof version === "number")
      version = String(version);
    let opt;
    switch (version) {
      case "1.1":
        if (this.directives)
          this.directives.yaml.version = "1.1";
        else
          this.directives = new Directives({ version: "1.1" });
        opt = { resolveKnownTags: false, schema: "yaml-1.1" };
        break;
      case "1.2":
      case "next":
        if (this.directives)
          this.directives.yaml.version = version;
        else
          this.directives = new Directives({ version });
        opt = { resolveKnownTags: true, schema: "core" };
        break;
      case null:
        if (this.directives)
          delete this.directives;
        opt = null;
        break;
      default: {
        const sv = JSON.stringify(version);
        throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
      }
    }
    if (options2.schema instanceof Object)
      this.schema = options2.schema;
    else if (opt)
      this.schema = new Schema3(Object.assign(opt, options2));
    else
      throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  }
  // json & jsonArg are only used from toJSON()
  toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
    const ctx = {
      anchors: /* @__PURE__ */ new Map(),
      doc: this,
      keep: !json2,
      mapAsMap: mapAsMap === true,
      mapKeyWarned: false,
      maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
    };
    const res = toJS(this.contents, jsonArg ?? "", ctx);
    if (typeof onAnchor === "function")
      for (const { count, res: res2 } of ctx.anchors.values())
        onAnchor(res2, count);
    return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
  }
  /**
   * A JSON representation of the document `contents`.
   *
   * @param jsonArg Used by `JSON.stringify` to indicate the array index or
   *   property name.
   */
  toJSON(jsonArg, onAnchor) {
    return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  }
  /** A YAML representation of the document. */
  toString(options2 = {}) {
    if (this.errors.length > 0)
      throw new Error("Document with errors cannot be stringified");
    if ("indent" in options2 && (!Number.isInteger(options2.indent) || Number(options2.indent) <= 0)) {
      const s3 = JSON.stringify(options2.indent);
      throw new Error(`"indent" option must be a positive integer, not ${s3}`);
    }
    return stringifyDocument(this, options2);
  }
};
function assertCollection(contents) {
  if (isCollection(contents))
    return true;
  throw new Error("Expected a YAML collection as document contents");
}

// node_modules/yaml/browser/dist/errors.js
var YAMLError = class extends Error {
  constructor(name2, pos, code2, message) {
    super();
    this.name = name2;
    this.code = code2;
    this.message = message;
    this.pos = pos;
  }
};
var YAMLParseError = class extends YAMLError {
  constructor(pos, code2, message) {
    super("YAMLParseError", pos, code2, message);
  }
};
var YAMLWarning = class extends YAMLError {
  constructor(pos, code2, message) {
    super("YAMLWarning", pos, code2, message);
  }
};
var prettifyError = (src, lc) => (error2) => {
  if (error2.pos[0] === -1)
    return;
  error2.linePos = error2.pos.map((pos) => lc.linePos(pos));
  const { line, col } = error2.linePos[0];
  error2.message += ` at line ${line}, column ${col}`;
  let ci = col - 1;
  let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
  if (ci >= 60 && lineStr.length > 80) {
    const trimStart = Math.min(ci - 39, lineStr.length - 79);
    lineStr = "\u2026" + lineStr.substring(trimStart);
    ci -= trimStart - 1;
  }
  if (lineStr.length > 80)
    lineStr = lineStr.substring(0, 79) + "\u2026";
  if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
    let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
    if (prev.length > 80)
      prev = prev.substring(0, 79) + "\u2026\n";
    lineStr = prev + lineStr;
  }
  if (/[^ ]/.test(lineStr)) {
    let count = 1;
    const end = error2.linePos[1];
    if (end?.line === line && end.col > col) {
      count = Math.max(1, Math.min(end.col - col, 80 - ci));
    }
    const pointer = " ".repeat(ci) + "^".repeat(count);
    error2.message += `:

${lineStr}
${pointer}
`;
  }
};

// node_modules/yaml/browser/dist/compose/resolve-props.js
function resolveProps(tokens, { flow, indicator, next: next2, offset, onError, parentIndent, startOnNewline }) {
  let spaceBefore = false;
  let atNewline = startOnNewline;
  let hasSpace = startOnNewline;
  let comment4 = "";
  let commentSep = "";
  let hasNewline = false;
  let reqSpace = false;
  let tab = null;
  let anchor = null;
  let tag = null;
  let newlineAfterProp = null;
  let comma = null;
  let found2 = null;
  let start = null;
  for (const token of tokens) {
    if (reqSpace) {
      if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
        onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
      reqSpace = false;
    }
    if (tab) {
      if (atNewline && token.type !== "comment" && token.type !== "newline") {
        onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
      }
      tab = null;
    }
    switch (token.type) {
      case "space":
        if (!flow && (indicator !== "doc-start" || next2?.type !== "flow-collection") && token.source.includes("	")) {
          tab = token;
        }
        hasSpace = true;
        break;
      case "comment": {
        if (!hasSpace)
          onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
        const cb2 = token.source.substring(1) || " ";
        if (!comment4)
          comment4 = cb2;
        else
          comment4 += commentSep + cb2;
        commentSep = "";
        atNewline = false;
        break;
      }
      case "newline":
        if (atNewline) {
          if (comment4)
            comment4 += token.source;
          else if (!found2 || indicator !== "seq-item-ind")
            spaceBefore = true;
        } else
          commentSep += token.source;
        atNewline = true;
        hasNewline = true;
        if (anchor || tag)
          newlineAfterProp = token;
        hasSpace = true;
        break;
      case "anchor":
        if (anchor)
          onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
        if (token.source.endsWith(":"))
          onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
        anchor = token;
        start ?? (start = token.offset);
        atNewline = false;
        hasSpace = false;
        reqSpace = true;
        break;
      case "tag": {
        if (tag)
          onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
        tag = token;
        start ?? (start = token.offset);
        atNewline = false;
        hasSpace = false;
        reqSpace = true;
        break;
      }
      case indicator:
        if (anchor || tag)
          onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
        if (found2)
          onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
        found2 = token;
        atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
        hasSpace = false;
        break;
      case "comma":
        if (flow) {
          if (comma)
            onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
          comma = token;
          atNewline = false;
          hasSpace = false;
          break;
        }
      // else fallthrough
      default:
        onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
        atNewline = false;
        hasSpace = false;
    }
  }
  const last3 = tokens[tokens.length - 1];
  const end = last3 ? last3.offset + last3.source.length : offset;
  if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) {
    onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
  }
  if (tab && (atNewline && tab.indent <= parentIndent || next2?.type === "block-map" || next2?.type === "block-seq"))
    onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
  return {
    comma,
    found: found2,
    spaceBefore,
    comment: comment4,
    hasNewline,
    anchor,
    tag,
    newlineAfterProp,
    end,
    start: start ?? end
  };
}

// node_modules/yaml/browser/dist/compose/util-contains-newline.js
function containsNewline(key2) {
  if (!key2)
    return null;
  switch (key2.type) {
    case "alias":
    case "scalar":
    case "double-quoted-scalar":
    case "single-quoted-scalar":
      if (key2.source.includes("\n"))
        return true;
      if (key2.end) {
        for (const st of key2.end)
          if (st.type === "newline")
            return true;
      }
      return false;
    case "flow-collection":
      for (const it2 of key2.items) {
        for (const st of it2.start)
          if (st.type === "newline")
            return true;
        if (it2.sep) {
          for (const st of it2.sep)
            if (st.type === "newline")
              return true;
        }
        if (containsNewline(it2.key) || containsNewline(it2.value))
          return true;
      }
      return false;
    default:
      return true;
  }
}

// node_modules/yaml/browser/dist/compose/util-flow-indent-check.js
function flowIndentCheck(indent, fc, onError) {
  if (fc?.type === "flow-collection") {
    const end = fc.end[0];
    if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) {
      const msg2 = "Flow end indicator should be more indented than parent";
      onError(end, "BAD_INDENT", msg2, true);
    }
  }
}

// node_modules/yaml/browser/dist/compose/util-map-includes.js
function mapIncludes(ctx, items, search) {
  const { uniqueKeys } = ctx.options;
  if (uniqueKeys === false)
    return false;
  const isEqual2 = typeof uniqueKeys === "function" ? uniqueKeys : (a3, b3) => a3 === b3 || isScalar(a3) && isScalar(b3) && a3.value === b3.value;
  return items.some((pair2) => isEqual2(pair2.key, search));
}

// node_modules/yaml/browser/dist/compose/resolve-block-map.js
var startColMsg = "All mapping items must start at the same column";
function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) {
  const NodeClass = tag?.nodeClass ?? YAMLMap;
  const map5 = new NodeClass(ctx.schema);
  if (ctx.atRoot)
    ctx.atRoot = false;
  let offset = bm.offset;
  let commentEnd = null;
  for (const collItem of bm.items) {
    const { start, key: key2, sep, value: value2 } = collItem;
    const keyProps = resolveProps(start, {
      indicator: "explicit-key-ind",
      next: key2 ?? sep?.[0],
      offset,
      onError,
      parentIndent: bm.indent,
      startOnNewline: true
    });
    const implicitKey = !keyProps.found;
    if (implicitKey) {
      if (key2) {
        if (key2.type === "block-seq")
          onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
        else if ("indent" in key2 && key2.indent !== bm.indent)
          onError(offset, "BAD_INDENT", startColMsg);
      }
      if (!keyProps.anchor && !keyProps.tag && !sep) {
        commentEnd = keyProps.end;
        if (keyProps.comment) {
          if (map5.comment)
            map5.comment += "\n" + keyProps.comment;
          else
            map5.comment = keyProps.comment;
        }
        continue;
      }
      if (keyProps.newlineAfterProp || containsNewline(key2)) {
        onError(key2 ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
      }
    } else if (keyProps.found?.indent !== bm.indent) {
      onError(offset, "BAD_INDENT", startColMsg);
    }
    ctx.atKey = true;
    const keyStart = keyProps.end;
    const keyNode = key2 ? composeNode2(ctx, key2, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError);
    if (ctx.schema.compat)
      flowIndentCheck(bm.indent, key2, onError);
    ctx.atKey = false;
    if (mapIncludes(ctx, map5.items, keyNode))
      onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
    const valueProps = resolveProps(sep ?? [], {
      indicator: "map-value-ind",
      next: value2,
      offset: keyNode.range[2],
      onError,
      parentIndent: bm.indent,
      startOnNewline: !key2 || key2.type === "block-scalar"
    });
    offset = valueProps.end;
    if (valueProps.found) {
      if (implicitKey) {
        if (value2?.type === "block-map" && !valueProps.hasNewline)
          onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
        if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
          onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
      }
      const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError);
      if (ctx.schema.compat)
        flowIndentCheck(bm.indent, value2, onError);
      offset = valueNode.range[2];
      const pair2 = new Pair(keyNode, valueNode);
      if (ctx.options.keepSourceTokens)
        pair2.srcToken = collItem;
      map5.items.push(pair2);
    } else {
      if (implicitKey)
        onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
      if (valueProps.comment) {
        if (keyNode.comment)
          keyNode.comment += "\n" + valueProps.comment;
        else
          keyNode.comment = valueProps.comment;
      }
      const pair2 = new Pair(keyNode);
      if (ctx.options.keepSourceTokens)
        pair2.srcToken = collItem;
      map5.items.push(pair2);
    }
  }
  if (commentEnd && commentEnd < offset)
    onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
  map5.range = [bm.offset, offset, commentEnd ?? offset];
  return map5;
}

// node_modules/yaml/browser/dist/compose/resolve-block-seq.js
function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) {
  const NodeClass = tag?.nodeClass ?? YAMLSeq;
  const seq2 = new NodeClass(ctx.schema);
  if (ctx.atRoot)
    ctx.atRoot = false;
  if (ctx.atKey)
    ctx.atKey = false;
  let offset = bs.offset;
  let commentEnd = null;
  for (const { start, value: value2 } of bs.items) {
    const props2 = resolveProps(start, {
      indicator: "seq-item-ind",
      next: value2,
      offset,
      onError,
      parentIndent: bs.indent,
      startOnNewline: true
    });
    if (!props2.found) {
      if (props2.anchor || props2.tag || value2) {
        if (value2?.type === "block-seq")
          onError(props2.end, "BAD_INDENT", "All sequence items must start at the same column");
        else
          onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
      } else {
        commentEnd = props2.end;
        if (props2.comment)
          seq2.comment = props2.comment;
        continue;
      }
    }
    const node = value2 ? composeNode2(ctx, value2, props2, onError) : composeEmptyNode2(ctx, props2.end, start, null, props2, onError);
    if (ctx.schema.compat)
      flowIndentCheck(bs.indent, value2, onError);
    offset = node.range[2];
    seq2.items.push(node);
  }
  seq2.range = [bs.offset, offset, commentEnd ?? offset];
  return seq2;
}

// node_modules/yaml/browser/dist/compose/resolve-end.js
function resolveEnd(end, offset, reqSpace, onError) {
  let comment4 = "";
  if (end) {
    let hasSpace = false;
    let sep = "";
    for (const token of end) {
      const { source, type } = token;
      switch (type) {
        case "space":
          hasSpace = true;
          break;
        case "comment": {
          if (reqSpace && !hasSpace)
            onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
          const cb2 = source.substring(1) || " ";
          if (!comment4)
            comment4 = cb2;
          else
            comment4 += sep + cb2;
          sep = "";
          break;
        }
        case "newline":
          if (comment4)
            sep += source;
          hasSpace = true;
          break;
        default:
          onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
      }
      offset += source.length;
    }
  }
  return { comment: comment4, offset };
}

// node_modules/yaml/browser/dist/compose/resolve-flow-collection.js
var blockMsg = "Block collections are not allowed within flow collections";
var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) {
  const isMap2 = fc.start.source === "{";
  const fcName = isMap2 ? "flow map" : "flow sequence";
  const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq);
  const coll = new NodeClass(ctx.schema);
  coll.flow = true;
  const atRoot = ctx.atRoot;
  if (atRoot)
    ctx.atRoot = false;
  if (ctx.atKey)
    ctx.atKey = false;
  let offset = fc.offset + fc.start.source.length;
  for (let i3 = 0; i3 < fc.items.length; ++i3) {
    const collItem = fc.items[i3];
    const { start, key: key2, sep, value: value2 } = collItem;
    const props2 = resolveProps(start, {
      flow: fcName,
      indicator: "explicit-key-ind",
      next: key2 ?? sep?.[0],
      offset,
      onError,
      parentIndent: fc.indent,
      startOnNewline: false
    });
    if (!props2.found) {
      if (!props2.anchor && !props2.tag && !sep && !value2) {
        if (i3 === 0 && props2.comma)
          onError(props2.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
        else if (i3 < fc.items.length - 1)
          onError(props2.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
        if (props2.comment) {
          if (coll.comment)
            coll.comment += "\n" + props2.comment;
          else
            coll.comment = props2.comment;
        }
        offset = props2.end;
        continue;
      }
      if (!isMap2 && ctx.options.strict && containsNewline(key2))
        onError(
          key2,
          // checked by containsNewline()
          "MULTILINE_IMPLICIT_KEY",
          "Implicit keys of flow sequence pairs need to be on a single line"
        );
    }
    if (i3 === 0) {
      if (props2.comma)
        onError(props2.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
    } else {
      if (!props2.comma)
        onError(props2.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
      if (props2.comment) {
        let prevItemComment = "";
        loop: for (const st of start) {
          switch (st.type) {
            case "comma":
            case "space":
              break;
            case "comment":
              prevItemComment = st.source.substring(1);
              break loop;
            default:
              break loop;
          }
        }
        if (prevItemComment) {
          let prev = coll.items[coll.items.length - 1];
          if (isPair(prev))
            prev = prev.value ?? prev.key;
          if (prev.comment)
            prev.comment += "\n" + prevItemComment;
          else
            prev.comment = prevItemComment;
          props2.comment = props2.comment.substring(prevItemComment.length + 1);
        }
      }
    }
    if (!isMap2 && !sep && !props2.found) {
      const valueNode = value2 ? composeNode2(ctx, value2, props2, onError) : composeEmptyNode2(ctx, props2.end, sep, null, props2, onError);
      coll.items.push(valueNode);
      offset = valueNode.range[2];
      if (isBlock(value2))
        onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
    } else {
      ctx.atKey = true;
      const keyStart = props2.end;
      const keyNode = key2 ? composeNode2(ctx, key2, props2, onError) : composeEmptyNode2(ctx, keyStart, start, null, props2, onError);
      if (isBlock(key2))
        onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
      ctx.atKey = false;
      const valueProps = resolveProps(sep ?? [], {
        flow: fcName,
        indicator: "map-value-ind",
        next: value2,
        offset: keyNode.range[2],
        onError,
        parentIndent: fc.indent,
        startOnNewline: false
      });
      if (valueProps.found) {
        if (!isMap2 && !props2.found && ctx.options.strict) {
          if (sep)
            for (const st of sep) {
              if (st === valueProps.found)
                break;
              if (st.type === "newline") {
                onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
                break;
              }
            }
          if (props2.start < valueProps.found.offset - 1024)
            onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
        }
      } else if (value2) {
        if ("source" in value2 && value2.source?.[0] === ":")
          onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`);
        else
          onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
      }
      const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null;
      if (valueNode) {
        if (isBlock(value2))
          onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
      } else if (valueProps.comment) {
        if (keyNode.comment)
          keyNode.comment += "\n" + valueProps.comment;
        else
          keyNode.comment = valueProps.comment;
      }
      const pair2 = new Pair(keyNode, valueNode);
      if (ctx.options.keepSourceTokens)
        pair2.srcToken = collItem;
      if (isMap2) {
        const map5 = coll;
        if (mapIncludes(ctx, map5.items, keyNode))
          onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
        map5.items.push(pair2);
      } else {
        const map5 = new YAMLMap(ctx.schema);
        map5.flow = true;
        map5.items.push(pair2);
        const endRange = (valueNode ?? keyNode).range;
        map5.range = [keyNode.range[0], endRange[1], endRange[2]];
        coll.items.push(map5);
      }
      offset = valueNode ? valueNode.range[2] : valueProps.end;
    }
  }
  const expectedEnd = isMap2 ? "}" : "]";
  const [ce, ...ee] = fc.end;
  let cePos = offset;
  if (ce?.source === expectedEnd)
    cePos = ce.offset + ce.source.length;
  else {
    const name2 = fcName[0].toUpperCase() + fcName.substring(1);
    const msg2 = atRoot ? `${name2} must end with a ${expectedEnd}` : `${name2} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
    onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg2);
    if (ce && ce.source.length !== 1)
      ee.unshift(ce);
  }
  if (ee.length > 0) {
    const end = resolveEnd(ee, cePos, ctx.options.strict, onError);
    if (end.comment) {
      if (coll.comment)
        coll.comment += "\n" + end.comment;
      else
        coll.comment = end.comment;
    }
    coll.range = [fc.offset, cePos, end.offset];
  } else {
    coll.range = [fc.offset, cePos, cePos];
  }
  return coll;
}

// node_modules/yaml/browser/dist/compose/compose-collection.js
function resolveCollection(CN2, ctx, token, onError, tagName, tag) {
  const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag);
  const Coll = coll.constructor;
  if (tagName === "!" || tagName === Coll.tagName) {
    coll.tag = Coll.tagName;
    return coll;
  }
  if (tagName)
    coll.tag = tagName;
  return coll;
}
function composeCollection(CN2, ctx, token, props2, onError) {
  const tagToken = props2.tag;
  const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg2) => onError(tagToken, "TAG_RESOLVE_FAILED", msg2));
  if (token.type === "block-seq") {
    const { anchor, newlineAfterProp: nl } = props2;
    const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
    if (lastProp && (!nl || nl.offset < lastProp.offset)) {
      const message = "Missing newline after block sequence props";
      onError(lastProp, "MISSING_CHAR", message);
    }
  }
  const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
  if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") {
    return resolveCollection(CN2, ctx, token, onError, tagName);
  }
  let tag = ctx.schema.tags.find((t3) => t3.tag === tagName && t3.collection === expType);
  if (!tag) {
    const kt = ctx.schema.knownTags[tagName];
    if (kt?.collection === expType) {
      ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
      tag = kt;
    } else {
      if (kt) {
        onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
      } else {
        onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
      }
      return resolveCollection(CN2, ctx, token, onError, tagName);
    }
  }
  const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag);
  const res = tag.resolve?.(coll, (msg2) => onError(tagToken, "TAG_RESOLVE_FAILED", msg2), ctx.options) ?? coll;
  const node = isNode(res) ? res : new Scalar(res);
  node.range = coll.range;
  node.tag = tagName;
  if (tag?.format)
    node.format = tag.format;
  return node;
}

// node_modules/yaml/browser/dist/compose/resolve-block-scalar.js
function resolveBlockScalar(ctx, scalar, onError) {
  const start = scalar.offset;
  const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
  if (!header)
    return { value: "", type: null, comment: "", range: [start, start, start] };
  const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
  const lines = scalar.source ? splitLines2(scalar.source) : [];
  let chompStart = lines.length;
  for (let i3 = lines.length - 1; i3 >= 0; --i3) {
    const content2 = lines[i3][1];
    if (content2 === "" || content2 === "\r")
      chompStart = i3;
    else
      break;
  }
  if (chompStart === 0) {
    const value3 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
    let end2 = start + header.length;
    if (scalar.source)
      end2 += scalar.source.length;
    return { value: value3, type, comment: header.comment, range: [start, end2, end2] };
  }
  let trimIndent = scalar.indent + header.indent;
  let offset = scalar.offset + header.length;
  let contentStart = 0;
  for (let i3 = 0; i3 < chompStart; ++i3) {
    const [indent, content2] = lines[i3];
    if (content2 === "" || content2 === "\r") {
      if (header.indent === 0 && indent.length > trimIndent)
        trimIndent = indent.length;
    } else {
      if (indent.length < trimIndent) {
        const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
        onError(offset + indent.length, "MISSING_CHAR", message);
      }
      if (header.indent === 0)
        trimIndent = indent.length;
      contentStart = i3;
      if (trimIndent === 0 && !ctx.atRoot) {
        const message = "Block scalar values in collections must be indented";
        onError(offset, "BAD_INDENT", message);
      }
      break;
    }
    offset += indent.length + content2.length + 1;
  }
  for (let i3 = lines.length - 1; i3 >= chompStart; --i3) {
    if (lines[i3][0].length > trimIndent)
      chompStart = i3 + 1;
  }
  let value2 = "";
  let sep = "";
  let prevMoreIndented = false;
  for (let i3 = 0; i3 < contentStart; ++i3)
    value2 += lines[i3][0].slice(trimIndent) + "\n";
  for (let i3 = contentStart; i3 < chompStart; ++i3) {
    let [indent, content2] = lines[i3];
    offset += indent.length + content2.length + 1;
    const crlf = content2[content2.length - 1] === "\r";
    if (crlf)
      content2 = content2.slice(0, -1);
    if (content2 && indent.length < trimIndent) {
      const src = header.indent ? "explicit indentation indicator" : "first line";
      const message = `Block scalar lines must not be less indented than their ${src}`;
      onError(offset - content2.length - (crlf ? 2 : 1), "BAD_INDENT", message);
      indent = "";
    }
    if (type === Scalar.BLOCK_LITERAL) {
      value2 += sep + indent.slice(trimIndent) + content2;
      sep = "\n";
    } else if (indent.length > trimIndent || content2[0] === "	") {
      if (sep === " ")
        sep = "\n";
      else if (!prevMoreIndented && sep === "\n")
        sep = "\n\n";
      value2 += sep + indent.slice(trimIndent) + content2;
      sep = "\n";
      prevMoreIndented = true;
    } else if (content2 === "") {
      if (sep === "\n")
        value2 += "\n";
      else
        sep = "\n";
    } else {
      value2 += sep + content2;
      sep = " ";
      prevMoreIndented = false;
    }
  }
  switch (header.chomp) {
    case "-":
      break;
    case "+":
      for (let i3 = chompStart; i3 < lines.length; ++i3)
        value2 += "\n" + lines[i3][0].slice(trimIndent);
      if (value2[value2.length - 1] !== "\n")
        value2 += "\n";
      break;
    default:
      value2 += "\n";
  }
  const end = start + header.length + scalar.source.length;
  return { value: value2, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset, props: props2 }, strict, onError) {
  if (props2[0].type !== "block-scalar-header") {
    onError(props2[0], "IMPOSSIBLE", "Block scalar header not found");
    return null;
  }
  const { source } = props2[0];
  const mode = source[0];
  let indent = 0;
  let chomp = "";
  let error2 = -1;
  for (let i3 = 1; i3 < source.length; ++i3) {
    const ch = source[i3];
    if (!chomp && (ch === "-" || ch === "+"))
      chomp = ch;
    else {
      const n4 = Number(ch);
      if (!indent && n4)
        indent = n4;
      else if (error2 === -1)
        error2 = offset + i3;
    }
  }
  if (error2 !== -1)
    onError(error2, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
  let hasSpace = false;
  let comment4 = "";
  let length = source.length;
  for (let i3 = 1; i3 < props2.length; ++i3) {
    const token = props2[i3];
    switch (token.type) {
      case "space":
        hasSpace = true;
      // fallthrough
      case "newline":
        length += token.source.length;
        break;
      case "comment":
        if (strict && !hasSpace) {
          const message = "Comments must be separated from other tokens by white space characters";
          onError(token, "MISSING_CHAR", message);
        }
        length += token.source.length;
        comment4 = token.source.substring(1);
        break;
      case "error":
        onError(token, "UNEXPECTED_TOKEN", token.message);
        length += token.source.length;
        break;
      /* istanbul ignore next should not happen */
      default: {
        const message = `Unexpected token in block scalar header: ${token.type}`;
        onError(token, "UNEXPECTED_TOKEN", message);
        const ts = token.source;
        if (ts && typeof ts === "string")
          length += ts.length;
      }
    }
  }
  return { mode, indent, chomp, comment: comment4, length };
}
function splitLines2(source) {
  const split3 = source.split(/\n( *)/);
  const first2 = split3[0];
  const m3 = first2.match(/^( *)/);
  const line0 = m3?.[1] ? [m3[1], first2.slice(m3[1].length)] : ["", first2];
  const lines = [line0];
  for (let i3 = 1; i3 < split3.length; i3 += 2)
    lines.push([split3[i3], split3[i3 + 1]]);
  return lines;
}

// node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js
function resolveFlowScalar(scalar, strict, onError) {
  const { offset, type, source, end } = scalar;
  let _type;
  let value2;
  const _onError = (rel, code2, msg2) => onError(offset + rel, code2, msg2);
  switch (type) {
    case "scalar":
      _type = Scalar.PLAIN;
      value2 = plainValue(source, _onError);
      break;
    case "single-quoted-scalar":
      _type = Scalar.QUOTE_SINGLE;
      value2 = singleQuotedValue(source, _onError);
      break;
    case "double-quoted-scalar":
      _type = Scalar.QUOTE_DOUBLE;
      value2 = doubleQuotedValue(source, _onError);
      break;
    /* istanbul ignore next should not happen */
    default:
      onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
      return {
        value: "",
        type: null,
        comment: "",
        range: [offset, offset + source.length, offset + source.length]
      };
  }
  const valueEnd = offset + source.length;
  const re2 = resolveEnd(end, valueEnd, strict, onError);
  return {
    value: value2,
    type: _type,
    comment: re2.comment,
    range: [offset, valueEnd, re2.offset]
  };
}
function plainValue(source, onError) {
  let badChar = "";
  switch (source[0]) {
    /* istanbul ignore next should not happen */
    case "	":
      badChar = "a tab character";
      break;
    case ",":
      badChar = "flow indicator character ,";
      break;
    case "%":
      badChar = "directive indicator character %";
      break;
    case "|":
    case ">": {
      badChar = `block scalar indicator ${source[0]}`;
      break;
    }
    case "@":
    case "`": {
      badChar = `reserved character ${source[0]}`;
      break;
    }
  }
  if (badChar)
    onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
  return foldLines(source);
}
function singleQuotedValue(source, onError) {
  if (source[source.length - 1] !== "'" || source.length === 1)
    onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
  return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
  let first2, line;
  try {
    first2 = new RegExp("(.*?)(?<![ 	])[ 	]*\r?\n", "sy");
    line = new RegExp("[ 	]*(.*?)(?:(?<![ 	])[ 	]*)?\r?\n", "sy");
  } catch {
    first2 = /(.*?)[ \t]*\r?\n/sy;
    line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
  }
  let match2 = first2.exec(source);
  if (!match2)
    return source;
  let res = match2[1];
  let sep = " ";
  let pos = first2.lastIndex;
  line.lastIndex = pos;
  while (match2 = line.exec(source)) {
    if (match2[1] === "") {
      if (sep === "\n")
        res += sep;
      else
        sep = "\n";
    } else {
      res += sep + match2[1];
      sep = " ";
    }
    pos = line.lastIndex;
  }
  const last3 = /[ \t]*(.*)/sy;
  last3.lastIndex = pos;
  match2 = last3.exec(source);
  return res + sep + (match2?.[1] ?? "");
}
function doubleQuotedValue(source, onError) {
  let res = "";
  for (let i3 = 1; i3 < source.length - 1; ++i3) {
    const ch = source[i3];
    if (ch === "\r" && source[i3 + 1] === "\n")
      continue;
    if (ch === "\n") {
      const { fold, offset } = foldNewline(source, i3);
      res += fold;
      i3 = offset;
    } else if (ch === "\\") {
      let next2 = source[++i3];
      const cc = escapeCodes[next2];
      if (cc)
        res += cc;
      else if (next2 === "\n") {
        next2 = source[i3 + 1];
        while (next2 === " " || next2 === "	")
          next2 = source[++i3 + 1];
      } else if (next2 === "\r" && source[i3 + 1] === "\n") {
        next2 = source[++i3 + 1];
        while (next2 === " " || next2 === "	")
          next2 = source[++i3 + 1];
      } else if (next2 === "x" || next2 === "u" || next2 === "U") {
        const length = { x: 2, u: 4, U: 8 }[next2];
        res += parseCharCode(source, i3 + 1, length, onError);
        i3 += length;
      } else {
        const raw2 = source.substr(i3 - 1, 2);
        onError(i3 - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`);
        res += raw2;
      }
    } else if (ch === " " || ch === "	") {
      const wsStart = i3;
      let next2 = source[i3 + 1];
      while (next2 === " " || next2 === "	")
        next2 = source[++i3 + 1];
      if (next2 !== "\n" && !(next2 === "\r" && source[i3 + 2] === "\n"))
        res += i3 > wsStart ? source.slice(wsStart, i3 + 1) : ch;
    } else {
      res += ch;
    }
  }
  if (source[source.length - 1] !== '"' || source.length === 1)
    onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
  return res;
}
function foldNewline(source, offset) {
  let fold = "";
  let ch = source[offset + 1];
  while (ch === " " || ch === "	" || ch === "\n" || ch === "\r") {
    if (ch === "\r" && source[offset + 2] !== "\n")
      break;
    if (ch === "\n")
      fold += "\n";
    offset += 1;
    ch = source[offset + 1];
  }
  if (!fold)
    fold = " ";
  return { fold, offset };
}
var escapeCodes = {
  "0": "\0",
  // null character
  a: "\x07",
  // bell character
  b: "\b",
  // backspace
  e: "\x1B",
  // escape character
  f: "\f",
  // form feed
  n: "\n",
  // line feed
  r: "\r",
  // carriage return
  t: "	",
  // horizontal tab
  v: "\v",
  // vertical tab
  N: "\x85",
  // Unicode next line
  _: "\xA0",
  // Unicode non-breaking space
  L: "\u2028",
  // Unicode line separator
  P: "\u2029",
  // Unicode paragraph separator
  " ": " ",
  '"': '"',
  "/": "/",
  "\\": "\\",
  "	": "	"
};
function parseCharCode(source, offset, length, onError) {
  const cc = source.substr(offset, length);
  const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
  const code2 = ok ? parseInt(cc, 16) : NaN;
  if (isNaN(code2)) {
    const raw2 = source.substr(offset - 2, length + 2);
    onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`);
    return raw2;
  }
  return String.fromCodePoint(code2);
}

// node_modules/yaml/browser/dist/compose/compose-scalar.js
function composeScalar(ctx, token, tagToken, onError) {
  const { value: value2, type, comment: comment4, range: range2 } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError);
  const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg2) => onError(tagToken, "TAG_RESOLVE_FAILED", msg2)) : null;
  let tag;
  if (ctx.options.stringKeys && ctx.atKey) {
    tag = ctx.schema[SCALAR];
  } else if (tagName)
    tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError);
  else if (token.type === "scalar")
    tag = findScalarTagByTest(ctx, value2, token, onError);
  else
    tag = ctx.schema[SCALAR];
  let scalar;
  try {
    const res = tag.resolve(value2, (msg2) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg2), ctx.options);
    scalar = isScalar(res) ? res : new Scalar(res);
  } catch (error2) {
    const msg2 = error2 instanceof Error ? error2.message : String(error2);
    onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg2);
    scalar = new Scalar(value2);
  }
  scalar.range = range2;
  scalar.source = value2;
  if (type)
    scalar.type = type;
  if (tagName)
    scalar.tag = tagName;
  if (tag.format)
    scalar.format = tag.format;
  if (comment4)
    scalar.comment = comment4;
  return scalar;
}
function findScalarTagByName(schema7, value2, tagName, tagToken, onError) {
  if (tagName === "!")
    return schema7[SCALAR];
  const matchWithTest = [];
  for (const tag of schema7.tags) {
    if (!tag.collection && tag.tag === tagName) {
      if (tag.default && tag.test)
        matchWithTest.push(tag);
      else
        return tag;
    }
  }
  for (const tag of matchWithTest)
    if (tag.test?.test(value2))
      return tag;
  const kt = schema7.knownTags[tagName];
  if (kt && !kt.collection) {
    schema7.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
    return kt;
  }
  onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
  return schema7[SCALAR];
}
function findScalarTagByTest({ atKey, directives, schema: schema7 }, value2, token, onError) {
  const tag = schema7.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema7[SCALAR];
  if (schema7.compat) {
    const compat = schema7.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema7[SCALAR];
    if (tag.tag !== compat.tag) {
      const ts = directives.tagString(tag.tag);
      const cs = directives.tagString(compat.tag);
      const msg2 = `Value may be parsed as either ${ts} or ${cs}`;
      onError(token, "TAG_RESOLVE_FAILED", msg2, true);
    }
  }
  return tag;
}

// node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js
function emptyScalarPosition(offset, before2, pos) {
  if (before2) {
    pos ?? (pos = before2.length);
    for (let i3 = pos - 1; i3 >= 0; --i3) {
      let st = before2[i3];
      switch (st.type) {
        case "space":
        case "comment":
        case "newline":
          offset -= st.source.length;
          continue;
      }
      st = before2[++i3];
      while (st?.type === "space") {
        offset += st.source.length;
        st = before2[++i3];
      }
      break;
    }
  }
  return offset;
}

// node_modules/yaml/browser/dist/compose/compose-node.js
var CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props2, onError) {
  const atKey = ctx.atKey;
  const { spaceBefore, comment: comment4, anchor, tag } = props2;
  let node;
  let isSrcToken = true;
  switch (token.type) {
    case "alias":
      node = composeAlias(ctx, token, onError);
      if (anchor || tag)
        onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
      break;
    case "scalar":
    case "single-quoted-scalar":
    case "double-quoted-scalar":
    case "block-scalar":
      node = composeScalar(ctx, token, tag, onError);
      if (anchor)
        node.anchor = anchor.source.substring(1);
      break;
    case "block-map":
    case "block-seq":
    case "flow-collection":
      node = composeCollection(CN, ctx, token, props2, onError);
      if (anchor)
        node.anchor = anchor.source.substring(1);
      break;
    default: {
      const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
      onError(token, "UNEXPECTED_TOKEN", message);
      node = composeEmptyNode(ctx, token.offset, void 0, null, props2, onError);
      isSrcToken = false;
    }
  }
  if (anchor && node.anchor === "")
    onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
  if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
    const msg2 = "With stringKeys, all keys must be strings";
    onError(tag ?? token, "NON_STRING_KEY", msg2);
  }
  if (spaceBefore)
    node.spaceBefore = true;
  if (comment4) {
    if (token.type === "scalar" && token.source === "")
      node.comment = comment4;
    else
      node.commentBefore = comment4;
  }
  if (ctx.options.keepSourceTokens && isSrcToken)
    node.srcToken = token;
  return node;
}
function composeEmptyNode(ctx, offset, before2, pos, { spaceBefore, comment: comment4, anchor, tag, end }, onError) {
  const token = {
    type: "scalar",
    offset: emptyScalarPosition(offset, before2, pos),
    indent: -1,
    source: ""
  };
  const node = composeScalar(ctx, token, tag, onError);
  if (anchor) {
    node.anchor = anchor.source.substring(1);
    if (node.anchor === "")
      onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
  }
  if (spaceBefore)
    node.spaceBefore = true;
  if (comment4) {
    node.comment = comment4;
    node.range[2] = end;
  }
  return node;
}
function composeAlias({ options: options2 }, { offset, source, end }, onError) {
  const alias = new Alias(source.substring(1));
  if (alias.source === "")
    onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
  if (alias.source.endsWith(":"))
    onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
  const valueEnd = offset + source.length;
  const re2 = resolveEnd(end, valueEnd, options2.strict, onError);
  alias.range = [offset, valueEnd, re2.offset];
  if (re2.comment)
    alias.comment = re2.comment;
  return alias;
}

// node_modules/yaml/browser/dist/compose/compose-doc.js
function composeDoc(options2, directives, { offset, start, value: value2, end }, onError) {
  const opts = Object.assign({ _directives: directives }, options2);
  const doc4 = new Document(void 0, opts);
  const ctx = {
    atKey: false,
    atRoot: true,
    directives: doc4.directives,
    options: doc4.options,
    schema: doc4.schema
  };
  const props2 = resolveProps(start, {
    indicator: "doc-start",
    next: value2 ?? end?.[0],
    offset,
    onError,
    parentIndent: 0,
    startOnNewline: true
  });
  if (props2.found) {
    doc4.directives.docStart = true;
    if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props2.hasNewline)
      onError(props2.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
  }
  doc4.contents = value2 ? composeNode(ctx, value2, props2, onError) : composeEmptyNode(ctx, props2.end, start, null, props2, onError);
  const contentEnd = doc4.contents.range[2];
  const re2 = resolveEnd(end, contentEnd, false, onError);
  if (re2.comment)
    doc4.comment = re2.comment;
  doc4.range = [offset, contentEnd, re2.offset];
  return doc4;
}

// node_modules/yaml/browser/dist/compose/composer.js
function getErrorPos(src) {
  if (typeof src === "number")
    return [src, src + 1];
  if (Array.isArray(src))
    return src.length === 2 ? src : [src[0], src[1]];
  const { offset, source } = src;
  return [offset, offset + (typeof source === "string" ? source.length : 1)];
}
function parsePrelude(prelude) {
  let comment4 = "";
  let atComment = false;
  let afterEmptyLine = false;
  for (let i3 = 0; i3 < prelude.length; ++i3) {
    const source = prelude[i3];
    switch (source[0]) {
      case "#":
        comment4 += (comment4 === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
        atComment = true;
        afterEmptyLine = false;
        break;
      case "%":
        if (prelude[i3 + 1]?.[0] !== "#")
          i3 += 1;
        atComment = false;
        break;
      default:
        if (!atComment)
          afterEmptyLine = true;
        atComment = false;
    }
  }
  return { comment: comment4, afterEmptyLine };
}
var Composer = class {
  constructor(options2 = {}) {
    this.doc = null;
    this.atDirectives = false;
    this.prelude = [];
    this.errors = [];
    this.warnings = [];
    this.onError = (source, code2, message, warning2) => {
      const pos = getErrorPos(source);
      if (warning2)
        this.warnings.push(new YAMLWarning(pos, code2, message));
      else
        this.errors.push(new YAMLParseError(pos, code2, message));
    };
    this.directives = new Directives({ version: options2.version || "1.2" });
    this.options = options2;
  }
  decorate(doc4, afterDoc) {
    const { comment: comment4, afterEmptyLine } = parsePrelude(this.prelude);
    if (comment4) {
      const dc = doc4.contents;
      if (afterDoc) {
        doc4.comment = doc4.comment ? `${doc4.comment}
${comment4}` : comment4;
      } else if (afterEmptyLine || doc4.directives.docStart || !dc) {
        doc4.commentBefore = comment4;
      } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) {
        let it2 = dc.items[0];
        if (isPair(it2))
          it2 = it2.key;
        const cb2 = it2.commentBefore;
        it2.commentBefore = cb2 ? `${comment4}
${cb2}` : comment4;
      } else {
        const cb2 = dc.commentBefore;
        dc.commentBefore = cb2 ? `${comment4}
${cb2}` : comment4;
      }
    }
    if (afterDoc) {
      Array.prototype.push.apply(doc4.errors, this.errors);
      Array.prototype.push.apply(doc4.warnings, this.warnings);
    } else {
      doc4.errors = this.errors;
      doc4.warnings = this.warnings;
    }
    this.prelude = [];
    this.errors = [];
    this.warnings = [];
  }
  /**
   * Current stream status information.
   *
   * Mostly useful at the end of input for an empty stream.
   */
  streamInfo() {
    return {
      comment: parsePrelude(this.prelude).comment,
      directives: this.directives,
      errors: this.errors,
      warnings: this.warnings
    };
  }
  /**
   * Compose tokens into documents.
   *
   * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
   * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
   */
  *compose(tokens, forceDoc = false, endOffset = -1) {
    for (const token of tokens)
      yield* this.next(token);
    yield* this.end(forceDoc, endOffset);
  }
  /** Advance the composer by one CST token. */
  *next(token) {
    switch (token.type) {
      case "directive":
        this.directives.add(token.source, (offset, message, warning2) => {
          const pos = getErrorPos(token);
          pos[0] += offset;
          this.onError(pos, "BAD_DIRECTIVE", message, warning2);
        });
        this.prelude.push(token.source);
        this.atDirectives = true;
        break;
      case "document": {
        const doc4 = composeDoc(this.options, this.directives, token, this.onError);
        if (this.atDirectives && !doc4.directives.docStart)
          this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
        this.decorate(doc4, false);
        if (this.doc)
          yield this.doc;
        this.doc = doc4;
        this.atDirectives = false;
        break;
      }
      case "byte-order-mark":
      case "space":
        break;
      case "comment":
      case "newline":
        this.prelude.push(token.source);
        break;
      case "error": {
        const msg2 = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
        const error2 = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg2);
        if (this.atDirectives || !this.doc)
          this.errors.push(error2);
        else
          this.doc.errors.push(error2);
        break;
      }
      case "doc-end": {
        if (!this.doc) {
          const msg2 = "Unexpected doc-end without preceding document";
          this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg2));
          break;
        }
        this.doc.directives.docEnd = true;
        const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
        this.decorate(this.doc, true);
        if (end.comment) {
          const dc = this.doc.comment;
          this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
        }
        this.doc.range[2] = end.offset;
        break;
      }
      default:
        this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
    }
  }
  /**
   * Call at end of input to yield any remaining document.
   *
   * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
   * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
   */
  *end(forceDoc = false, endOffset = -1) {
    if (this.doc) {
      this.decorate(this.doc, true);
      yield this.doc;
      this.doc = null;
    } else if (forceDoc) {
      const opts = Object.assign({ _directives: this.directives }, this.options);
      const doc4 = new Document(void 0, opts);
      if (this.atDirectives)
        this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
      doc4.range = [0, endOffset, endOffset];
      this.decorate(doc4, false);
      yield doc4;
    }
  }
};

// node_modules/yaml/browser/dist/parse/cst.js
var cst_exports = {};
__export(cst_exports, {
  BOM: () => BOM,
  DOCUMENT: () => DOCUMENT,
  FLOW_END: () => FLOW_END,
  SCALAR: () => SCALAR2,
  createScalarToken: () => createScalarToken,
  isCollection: () => isCollection2,
  isScalar: () => isScalar2,
  prettyToken: () => prettyToken,
  resolveAsScalar: () => resolveAsScalar,
  setScalarValue: () => setScalarValue,
  stringify: () => stringify5,
  tokenType: () => tokenType,
  visit: () => visit2
});

// node_modules/yaml/browser/dist/parse/cst-scalar.js
function resolveAsScalar(token, strict = true, onError) {
  if (token) {
    const _onError = (pos, code2, message) => {
      const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
      if (onError)
        onError(offset, code2, message);
      else
        throw new YAMLParseError([offset, offset + 1], code2, message);
    };
    switch (token.type) {
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
        return resolveFlowScalar(token, strict, _onError);
      case "block-scalar":
        return resolveBlockScalar({ options: { strict } }, token, _onError);
    }
  }
  return null;
}
function createScalarToken(value2, context) {
  const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context;
  const source = stringifyString({ type, value: value2 }, {
    implicitKey,
    indent: indent > 0 ? " ".repeat(indent) : "",
    inFlow,
    options: { blockQuote: true, lineWidth: -1 }
  });
  const end = context.end ?? [
    { type: "newline", offset: -1, indent, source: "\n" }
  ];
  switch (source[0]) {
    case "|":
    case ">": {
      const he = source.indexOf("\n");
      const head2 = source.substring(0, he);
      const body3 = source.substring(he + 1) + "\n";
      const props2 = [
        { type: "block-scalar-header", offset, indent, source: head2 }
      ];
      if (!addEndtoBlockProps(props2, end))
        props2.push({ type: "newline", offset: -1, indent, source: "\n" });
      return { type: "block-scalar", offset, indent, props: props2, source: body3 };
    }
    case '"':
      return { type: "double-quoted-scalar", offset, indent, source, end };
    case "'":
      return { type: "single-quoted-scalar", offset, indent, source, end };
    default:
      return { type: "scalar", offset, indent, source, end };
  }
}
function setScalarValue(token, value2, context = {}) {
  let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
  let indent = "indent" in token ? token.indent : null;
  if (afterKey && typeof indent === "number")
    indent += 2;
  if (!type)
    switch (token.type) {
      case "single-quoted-scalar":
        type = "QUOTE_SINGLE";
        break;
      case "double-quoted-scalar":
        type = "QUOTE_DOUBLE";
        break;
      case "block-scalar": {
        const header = token.props[0];
        if (header.type !== "block-scalar-header")
          throw new Error("Invalid block scalar header");
        type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
        break;
      }
      default:
        type = "PLAIN";
    }
  const source = stringifyString({ type, value: value2 }, {
    implicitKey: implicitKey || indent === null,
    indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
    inFlow,
    options: { blockQuote: true, lineWidth: -1 }
  });
  switch (source[0]) {
    case "|":
    case ">":
      setBlockScalarValue(token, source);
      break;
    case '"':
      setFlowScalarValue(token, source, "double-quoted-scalar");
      break;
    case "'":
      setFlowScalarValue(token, source, "single-quoted-scalar");
      break;
    default:
      setFlowScalarValue(token, source, "scalar");
  }
}
function setBlockScalarValue(token, source) {
  const he = source.indexOf("\n");
  const head2 = source.substring(0, he);
  const body3 = source.substring(he + 1) + "\n";
  if (token.type === "block-scalar") {
    const header = token.props[0];
    if (header.type !== "block-scalar-header")
      throw new Error("Invalid block scalar header");
    header.source = head2;
    token.source = body3;
  } else {
    const { offset } = token;
    const indent = "indent" in token ? token.indent : -1;
    const props2 = [
      { type: "block-scalar-header", offset, indent, source: head2 }
    ];
    if (!addEndtoBlockProps(props2, "end" in token ? token.end : void 0))
      props2.push({ type: "newline", offset: -1, indent, source: "\n" });
    for (const key2 of Object.keys(token))
      if (key2 !== "type" && key2 !== "offset")
        delete token[key2];
    Object.assign(token, { type: "block-scalar", indent, props: props2, source: body3 });
  }
}
function addEndtoBlockProps(props2, end) {
  if (end)
    for (const st of end)
      switch (st.type) {
        case "space":
        case "comment":
          props2.push(st);
          break;
        case "newline":
          props2.push(st);
          return true;
      }
  return false;
}
function setFlowScalarValue(token, source, type) {
  switch (token.type) {
    case "scalar":
    case "double-quoted-scalar":
    case "single-quoted-scalar":
      token.type = type;
      token.source = source;
      break;
    case "block-scalar": {
      const end = token.props.slice(1);
      let oa = source.length;
      if (token.props[0].type === "block-scalar-header")
        oa -= token.props[0].source.length;
      for (const tok of end)
        tok.offset += oa;
      delete token.props;
      Object.assign(token, { type, source, end });
      break;
    }
    case "block-map":
    case "block-seq": {
      const offset = token.offset + source.length;
      const nl = { type: "newline", offset, indent: token.indent, source: "\n" };
      delete token.items;
      Object.assign(token, { type, source, end: [nl] });
      break;
    }
    default: {
      const indent = "indent" in token ? token.indent : -1;
      const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
      for (const key2 of Object.keys(token))
        if (key2 !== "type" && key2 !== "offset")
          delete token[key2];
      Object.assign(token, { type, indent, source, end });
    }
  }
}

// node_modules/yaml/browser/dist/parse/cst-stringify.js
var stringify5 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst);
function stringifyToken(token) {
  switch (token.type) {
    case "block-scalar": {
      let res = "";
      for (const tok of token.props)
        res += stringifyToken(tok);
      return res + token.source;
    }
    case "block-map":
    case "block-seq": {
      let res = "";
      for (const item of token.items)
        res += stringifyItem(item);
      return res;
    }
    case "flow-collection": {
      let res = token.start.source;
      for (const item of token.items)
        res += stringifyItem(item);
      for (const st of token.end)
        res += st.source;
      return res;
    }
    case "document": {
      let res = stringifyItem(token);
      if (token.end)
        for (const st of token.end)
          res += st.source;
      return res;
    }
    default: {
      let res = token.source;
      if ("end" in token && token.end)
        for (const st of token.end)
          res += st.source;
      return res;
    }
  }
}
function stringifyItem({ start, key: key2, sep, value: value2 }) {
  let res = "";
  for (const st of start)
    res += st.source;
  if (key2)
    res += stringifyToken(key2);
  if (sep)
    for (const st of sep)
      res += st.source;
  if (value2)
    res += stringifyToken(value2);
  return res;
}

// node_modules/yaml/browser/dist/parse/cst-visit.js
var BREAK2 = Symbol("break visit");
var SKIP2 = Symbol("skip children");
var REMOVE2 = Symbol("remove item");
function visit2(cst, visitor) {
  if ("type" in cst && cst.type === "document")
    cst = { start: cst.start, value: cst.value };
  _visit(Object.freeze([]), cst, visitor);
}
visit2.BREAK = BREAK2;
visit2.SKIP = SKIP2;
visit2.REMOVE = REMOVE2;
visit2.itemAtPath = (cst, path) => {
  let item = cst;
  for (const [field2, index2] of path) {
    const tok = item?.[field2];
    if (tok && "items" in tok) {
      item = tok.items[index2];
    } else
      return void 0;
  }
  return item;
};
visit2.parentCollection = (cst, path) => {
  const parent = visit2.itemAtPath(cst, path.slice(0, -1));
  const field2 = path[path.length - 1][0];
  const coll = parent?.[field2];
  if (coll && "items" in coll)
    return coll;
  throw new Error("Parent collection not found");
};
function _visit(path, item, visitor) {
  let ctrl = visitor(item, path);
  if (typeof ctrl === "symbol")
    return ctrl;
  for (const field2 of ["key", "value"]) {
    const token = item[field2];
    if (token && "items" in token) {
      for (let i3 = 0; i3 < token.items.length; ++i3) {
        const ci = _visit(Object.freeze(path.concat([[field2, i3]])), token.items[i3], visitor);
        if (typeof ci === "number")
          i3 = ci - 1;
        else if (ci === BREAK2)
          return BREAK2;
        else if (ci === REMOVE2) {
          token.items.splice(i3, 1);
          i3 -= 1;
        }
      }
      if (typeof ctrl === "function" && field2 === "key")
        ctrl = ctrl(item, path);
    }
  }
  return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
}

// node_modules/yaml/browser/dist/parse/cst.js
var BOM = "\uFEFF";
var DOCUMENT = "";
var FLOW_END = "";
var SCALAR2 = "";
var isCollection2 = (token) => !!token && "items" in token;
var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
function prettyToken(token) {
  switch (token) {
    case BOM:
      return "<BOM>";
    case DOCUMENT:
      return "<DOC>";
    case FLOW_END:
      return "<FLOW_END>";
    case SCALAR2:
      return "<SCALAR>";
    default:
      return JSON.stringify(token);
  }
}
function tokenType(source) {
  switch (source) {
    case BOM:
      return "byte-order-mark";
    case DOCUMENT:
      return "doc-mode";
    case FLOW_END:
      return "flow-error-end";
    case SCALAR2:
      return "scalar";
    case "---":
      return "doc-start";
    case "...":
      return "doc-end";
    case "":
    case "\n":
    case "\r\n":
      return "newline";
    case "-":
      return "seq-item-ind";
    case "?":
      return "explicit-key-ind";
    case ":":
      return "map-value-ind";
    case "{":
      return "flow-map-start";
    case "}":
      return "flow-map-end";
    case "[":
      return "flow-seq-start";
    case "]":
      return "flow-seq-end";
    case ",":
      return "comma";
  }
  switch (source[0]) {
    case " ":
    case "	":
      return "space";
    case "#":
      return "comment";
    case "%":
      return "directive-line";
    case "*":
      return "alias";
    case "&":
      return "anchor";
    case "!":
      return "tag";
    case "'":
      return "single-quoted-scalar";
    case '"':
      return "double-quoted-scalar";
    case "|":
    case ">":
      return "block-scalar-header";
  }
  return null;
}

// node_modules/yaml/browser/dist/parse/lexer.js
function isEmpty4(ch) {
  switch (ch) {
    case void 0:
    case " ":
    case "\n":
    case "\r":
    case "	":
      return true;
    default:
      return false;
  }
}
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r	");
var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
var Lexer2 = class {
  constructor() {
    this.atEnd = false;
    this.blockScalarIndent = -1;
    this.blockScalarKeep = false;
    this.buffer = "";
    this.flowKey = false;
    this.flowLevel = 0;
    this.indentNext = 0;
    this.indentValue = 0;
    this.lineEndPos = null;
    this.next = null;
    this.pos = 0;
  }
  /**
   * Generate YAML tokens from the `source` string. If `incomplete`,
   * a part of the last line may be left as a buffer for the next call.
   *
   * @returns A generator of lexical tokens
   */
  *lex(source, incomplete = false) {
    if (source) {
      if (typeof source !== "string")
        throw TypeError("source is not a string");
      this.buffer = this.buffer ? this.buffer + source : source;
      this.lineEndPos = null;
    }
    this.atEnd = !incomplete;
    let next2 = this.next ?? "stream";
    while (next2 && (incomplete || this.hasChars(1)))
      next2 = yield* this.parseNext(next2);
  }
  atLineEnd() {
    let i3 = this.pos;
    let ch = this.buffer[i3];
    while (ch === " " || ch === "	")
      ch = this.buffer[++i3];
    if (!ch || ch === "#" || ch === "\n")
      return true;
    if (ch === "\r")
      return this.buffer[i3 + 1] === "\n";
    return false;
  }
  charAt(n4) {
    return this.buffer[this.pos + n4];
  }
  continueScalar(offset) {
    let ch = this.buffer[offset];
    if (this.indentNext > 0) {
      let indent = 0;
      while (ch === " ")
        ch = this.buffer[++indent + offset];
      if (ch === "\r") {
        const next2 = this.buffer[indent + offset + 1];
        if (next2 === "\n" || !next2 && !this.atEnd)
          return offset + indent + 1;
      }
      return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
    }
    if (ch === "-" || ch === ".") {
      const dt2 = this.buffer.substr(offset, 3);
      if ((dt2 === "---" || dt2 === "...") && isEmpty4(this.buffer[offset + 3]))
        return -1;
    }
    return offset;
  }
  getLine() {
    let end = this.lineEndPos;
    if (typeof end !== "number" || end !== -1 && end < this.pos) {
      end = this.buffer.indexOf("\n", this.pos);
      this.lineEndPos = end;
    }
    if (end === -1)
      return this.atEnd ? this.buffer.substring(this.pos) : null;
    if (this.buffer[end - 1] === "\r")
      end -= 1;
    return this.buffer.substring(this.pos, end);
  }
  hasChars(n4) {
    return this.pos + n4 <= this.buffer.length;
  }
  setNext(state) {
    this.buffer = this.buffer.substring(this.pos);
    this.pos = 0;
    this.lineEndPos = null;
    this.next = state;
    return null;
  }
  peek(n4) {
    return this.buffer.substr(this.pos, n4);
  }
  *parseNext(next2) {
    switch (next2) {
      case "stream":
        return yield* this.parseStream();
      case "line-start":
        return yield* this.parseLineStart();
      case "block-start":
        return yield* this.parseBlockStart();
      case "doc":
        return yield* this.parseDocument();
      case "flow":
        return yield* this.parseFlowCollection();
      case "quoted-scalar":
        return yield* this.parseQuotedScalar();
      case "block-scalar":
        return yield* this.parseBlockScalar();
      case "plain-scalar":
        return yield* this.parsePlainScalar();
    }
  }
  *parseStream() {
    let line = this.getLine();
    if (line === null)
      return this.setNext("stream");
    if (line[0] === BOM) {
      yield* this.pushCount(1);
      line = line.substring(1);
    }
    if (line[0] === "%") {
      let dirEnd = line.length;
      let cs = line.indexOf("#");
      while (cs !== -1) {
        const ch = line[cs - 1];
        if (ch === " " || ch === "	") {
          dirEnd = cs - 1;
          break;
        } else {
          cs = line.indexOf("#", cs + 1);
        }
      }
      while (true) {
        const ch = line[dirEnd - 1];
        if (ch === " " || ch === "	")
          dirEnd -= 1;
        else
          break;
      }
      const n4 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
      yield* this.pushCount(line.length - n4);
      this.pushNewline();
      return "stream";
    }
    if (this.atLineEnd()) {
      const sp = yield* this.pushSpaces(true);
      yield* this.pushCount(line.length - sp);
      yield* this.pushNewline();
      return "stream";
    }
    yield DOCUMENT;
    return yield* this.parseLineStart();
  }
  *parseLineStart() {
    const ch = this.charAt(0);
    if (!ch && !this.atEnd)
      return this.setNext("line-start");
    if (ch === "-" || ch === ".") {
      if (!this.atEnd && !this.hasChars(4))
        return this.setNext("line-start");
      const s3 = this.peek(3);
      if ((s3 === "---" || s3 === "...") && isEmpty4(this.charAt(3))) {
        yield* this.pushCount(3);
        this.indentValue = 0;
        this.indentNext = 0;
        return s3 === "---" ? "doc" : "stream";
      }
    }
    this.indentValue = yield* this.pushSpaces(false);
    if (this.indentNext > this.indentValue && !isEmpty4(this.charAt(1)))
      this.indentNext = this.indentValue;
    return yield* this.parseBlockStart();
  }
  *parseBlockStart() {
    const [ch0, ch1] = this.peek(2);
    if (!ch1 && !this.atEnd)
      return this.setNext("block-start");
    if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty4(ch1)) {
      const n4 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
      this.indentNext = this.indentValue + 1;
      this.indentValue += n4;
      return yield* this.parseBlockStart();
    }
    return "doc";
  }
  *parseDocument() {
    yield* this.pushSpaces(true);
    const line = this.getLine();
    if (line === null)
      return this.setNext("doc");
    let n4 = yield* this.pushIndicators();
    switch (line[n4]) {
      case "#":
        yield* this.pushCount(line.length - n4);
      // fallthrough
      case void 0:
        yield* this.pushNewline();
        return yield* this.parseLineStart();
      case "{":
      case "[":
        yield* this.pushCount(1);
        this.flowKey = false;
        this.flowLevel = 1;
        return "flow";
      case "}":
      case "]":
        yield* this.pushCount(1);
        return "doc";
      case "*":
        yield* this.pushUntil(isNotAnchorChar);
        return "doc";
      case '"':
      case "'":
        return yield* this.parseQuotedScalar();
      case "|":
      case ">":
        n4 += yield* this.parseBlockScalarHeader();
        n4 += yield* this.pushSpaces(true);
        yield* this.pushCount(line.length - n4);
        yield* this.pushNewline();
        return yield* this.parseBlockScalar();
      default:
        return yield* this.parsePlainScalar();
    }
  }
  *parseFlowCollection() {
    let nl, sp;
    let indent = -1;
    do {
      nl = yield* this.pushNewline();
      if (nl > 0) {
        sp = yield* this.pushSpaces(false);
        this.indentValue = indent = sp;
      } else {
        sp = 0;
      }
      sp += yield* this.pushSpaces(true);
    } while (nl + sp > 0);
    const line = this.getLine();
    if (line === null)
      return this.setNext("flow");
    if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty4(line[3])) {
      const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
      if (!atFlowEndMarker) {
        this.flowLevel = 0;
        yield FLOW_END;
        return yield* this.parseLineStart();
      }
    }
    let n4 = 0;
    while (line[n4] === ",") {
      n4 += yield* this.pushCount(1);
      n4 += yield* this.pushSpaces(true);
      this.flowKey = false;
    }
    n4 += yield* this.pushIndicators();
    switch (line[n4]) {
      case void 0:
        return "flow";
      case "#":
        yield* this.pushCount(line.length - n4);
        return "flow";
      case "{":
      case "[":
        yield* this.pushCount(1);
        this.flowKey = false;
        this.flowLevel += 1;
        return "flow";
      case "}":
      case "]":
        yield* this.pushCount(1);
        this.flowKey = true;
        this.flowLevel -= 1;
        return this.flowLevel ? "flow" : "doc";
      case "*":
        yield* this.pushUntil(isNotAnchorChar);
        return "flow";
      case '"':
      case "'":
        this.flowKey = true;
        return yield* this.parseQuotedScalar();
      case ":": {
        const next2 = this.charAt(1);
        if (this.flowKey || isEmpty4(next2) || next2 === ",") {
          this.flowKey = false;
          yield* this.pushCount(1);
          yield* this.pushSpaces(true);
          return "flow";
        }
      }
      // fallthrough
      default:
        this.flowKey = false;
        return yield* this.parsePlainScalar();
    }
  }
  *parseQuotedScalar() {
    const quote = this.charAt(0);
    let end = this.buffer.indexOf(quote, this.pos + 1);
    if (quote === "'") {
      while (end !== -1 && this.buffer[end + 1] === "'")
        end = this.buffer.indexOf("'", end + 2);
    } else {
      while (end !== -1) {
        let n4 = 0;
        while (this.buffer[end - 1 - n4] === "\\")
          n4 += 1;
        if (n4 % 2 === 0)
          break;
        end = this.buffer.indexOf('"', end + 1);
      }
    }
    const qb = this.buffer.substring(0, end);
    let nl = qb.indexOf("\n", this.pos);
    if (nl !== -1) {
      while (nl !== -1) {
        const cs = this.continueScalar(nl + 1);
        if (cs === -1)
          break;
        nl = qb.indexOf("\n", cs);
      }
      if (nl !== -1) {
        end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
      }
    }
    if (end === -1) {
      if (!this.atEnd)
        return this.setNext("quoted-scalar");
      end = this.buffer.length;
    }
    yield* this.pushToIndex(end + 1, false);
    return this.flowLevel ? "flow" : "doc";
  }
  *parseBlockScalarHeader() {
    this.blockScalarIndent = -1;
    this.blockScalarKeep = false;
    let i3 = this.pos;
    while (true) {
      const ch = this.buffer[++i3];
      if (ch === "+")
        this.blockScalarKeep = true;
      else if (ch > "0" && ch <= "9")
        this.blockScalarIndent = Number(ch) - 1;
      else if (ch !== "-")
        break;
    }
    return yield* this.pushUntil((ch) => isEmpty4(ch) || ch === "#");
  }
  *parseBlockScalar() {
    let nl = this.pos - 1;
    let indent = 0;
    let ch;
    loop: for (let i4 = this.pos; ch = this.buffer[i4]; ++i4) {
      switch (ch) {
        case " ":
          indent += 1;
          break;
        case "\n":
          nl = i4;
          indent = 0;
          break;
        case "\r": {
          const next2 = this.buffer[i4 + 1];
          if (!next2 && !this.atEnd)
            return this.setNext("block-scalar");
          if (next2 === "\n")
            break;
        }
        // fallthrough
        default:
          break loop;
      }
    }
    if (!ch && !this.atEnd)
      return this.setNext("block-scalar");
    if (indent >= this.indentNext) {
      if (this.blockScalarIndent === -1)
        this.indentNext = indent;
      else {
        this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
      }
      do {
        const cs = this.continueScalar(nl + 1);
        if (cs === -1)
          break;
        nl = this.buffer.indexOf("\n", cs);
      } while (nl !== -1);
      if (nl === -1) {
        if (!this.atEnd)
          return this.setNext("block-scalar");
        nl = this.buffer.length;
      }
    }
    let i3 = nl + 1;
    ch = this.buffer[i3];
    while (ch === " ")
      ch = this.buffer[++i3];
    if (ch === "	") {
      while (ch === "	" || ch === " " || ch === "\r" || ch === "\n")
        ch = this.buffer[++i3];
      nl = i3 - 1;
    } else if (!this.blockScalarKeep) {
      do {
        let i4 = nl - 1;
        let ch2 = this.buffer[i4];
        if (ch2 === "\r")
          ch2 = this.buffer[--i4];
        const lastChar = i4;
        while (ch2 === " ")
          ch2 = this.buffer[--i4];
        if (ch2 === "\n" && i4 >= this.pos && i4 + 1 + indent > lastChar)
          nl = i4;
        else
          break;
      } while (true);
    }
    yield SCALAR2;
    yield* this.pushToIndex(nl + 1, true);
    return yield* this.parseLineStart();
  }
  *parsePlainScalar() {
    const inFlow = this.flowLevel > 0;
    let end = this.pos - 1;
    let i3 = this.pos - 1;
    let ch;
    while (ch = this.buffer[++i3]) {
      if (ch === ":") {
        const next2 = this.buffer[i3 + 1];
        if (isEmpty4(next2) || inFlow && flowIndicatorChars.has(next2))
          break;
        end = i3;
      } else if (isEmpty4(ch)) {
        let next2 = this.buffer[i3 + 1];
        if (ch === "\r") {
          if (next2 === "\n") {
            i3 += 1;
            ch = "\n";
            next2 = this.buffer[i3 + 1];
          } else
            end = i3;
        }
        if (next2 === "#" || inFlow && flowIndicatorChars.has(next2))
          break;
        if (ch === "\n") {
          const cs = this.continueScalar(i3 + 1);
          if (cs === -1)
            break;
          i3 = Math.max(i3, cs - 2);
        }
      } else {
        if (inFlow && flowIndicatorChars.has(ch))
          break;
        end = i3;
      }
    }
    if (!ch && !this.atEnd)
      return this.setNext("plain-scalar");
    yield SCALAR2;
    yield* this.pushToIndex(end + 1, true);
    return inFlow ? "flow" : "doc";
  }
  *pushCount(n4) {
    if (n4 > 0) {
      yield this.buffer.substr(this.pos, n4);
      this.pos += n4;
      return n4;
    }
    return 0;
  }
  *pushToIndex(i3, allowEmpty) {
    const s3 = this.buffer.slice(this.pos, i3);
    if (s3) {
      yield s3;
      this.pos += s3.length;
      return s3.length;
    } else if (allowEmpty)
      yield "";
    return 0;
  }
  *pushIndicators() {
    switch (this.charAt(0)) {
      case "!":
        return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
      case "&":
        return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
      case "-":
      // this is an error
      case "?":
      // this is an error outside flow collections
      case ":": {
        const inFlow = this.flowLevel > 0;
        const ch1 = this.charAt(1);
        if (isEmpty4(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
          if (!inFlow)
            this.indentNext = this.indentValue + 1;
          else if (this.flowKey)
            this.flowKey = false;
          return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
        }
      }
    }
    return 0;
  }
  *pushTag() {
    if (this.charAt(1) === "<") {
      let i3 = this.pos + 2;
      let ch = this.buffer[i3];
      while (!isEmpty4(ch) && ch !== ">")
        ch = this.buffer[++i3];
      return yield* this.pushToIndex(ch === ">" ? i3 + 1 : i3, false);
    } else {
      let i3 = this.pos + 1;
      let ch = this.buffer[i3];
      while (ch) {
        if (tagChars.has(ch))
          ch = this.buffer[++i3];
        else if (ch === "%" && hexDigits.has(this.buffer[i3 + 1]) && hexDigits.has(this.buffer[i3 + 2])) {
          ch = this.buffer[i3 += 3];
        } else
          break;
      }
      return yield* this.pushToIndex(i3, false);
    }
  }
  *pushNewline() {
    const ch = this.buffer[this.pos];
    if (ch === "\n")
      return yield* this.pushCount(1);
    else if (ch === "\r" && this.charAt(1) === "\n")
      return yield* this.pushCount(2);
    else
      return 0;
  }
  *pushSpaces(allowTabs) {
    let i3 = this.pos - 1;
    let ch;
    do {
      ch = this.buffer[++i3];
    } while (ch === " " || allowTabs && ch === "	");
    const n4 = i3 - this.pos;
    if (n4 > 0) {
      yield this.buffer.substr(this.pos, n4);
      this.pos = i3;
    }
    return n4;
  }
  *pushUntil(test2) {
    let i3 = this.pos;
    let ch = this.buffer[i3];
    while (!test2(ch))
      ch = this.buffer[++i3];
    return yield* this.pushToIndex(i3, false);
  }
};

// node_modules/yaml/browser/dist/parse/line-counter.js
var LineCounter = class {
  constructor() {
    this.lineStarts = [];
    this.addNewLine = (offset) => this.lineStarts.push(offset);
    this.linePos = (offset) => {
      let low = 0;
      let high = this.lineStarts.length;
      while (low < high) {
        const mid = low + high >> 1;
        if (this.lineStarts[mid] < offset)
          low = mid + 1;
        else
          high = mid;
      }
      if (this.lineStarts[low] === offset)
        return { line: low + 1, col: 1 };
      if (low === 0)
        return { line: 0, col: offset };
      const start = this.lineStarts[low - 1];
      return { line: low, col: offset - start + 1 };
    };
  }
};

// node_modules/yaml/browser/dist/parse/parser.js
function includesToken(list2, type) {
  for (let i3 = 0; i3 < list2.length; ++i3)
    if (list2[i3].type === type)
      return true;
  return false;
}
function findNonEmptyIndex(list2) {
  for (let i3 = 0; i3 < list2.length; ++i3) {
    switch (list2[i3].type) {
      case "space":
      case "comment":
      case "newline":
        break;
      default:
        return i3;
    }
  }
  return -1;
}
function isFlowToken(token) {
  switch (token?.type) {
    case "alias":
    case "scalar":
    case "single-quoted-scalar":
    case "double-quoted-scalar":
    case "flow-collection":
      return true;
    default:
      return false;
  }
}
function getPrevProps(parent) {
  switch (parent.type) {
    case "document":
      return parent.start;
    case "block-map": {
      const it2 = parent.items[parent.items.length - 1];
      return it2.sep ?? it2.start;
    }
    case "block-seq":
      return parent.items[parent.items.length - 1].start;
    /* istanbul ignore next should not happen */
    default:
      return [];
  }
}
function getFirstKeyStartProps(prev) {
  if (prev.length === 0)
    return [];
  let i3 = prev.length;
  loop: while (--i3 >= 0) {
    switch (prev[i3].type) {
      case "doc-start":
      case "explicit-key-ind":
      case "map-value-ind":
      case "seq-item-ind":
      case "newline":
        break loop;
    }
  }
  while (prev[++i3]?.type === "space") {
  }
  return prev.splice(i3, prev.length);
}
function fixFlowSeqItems(fc) {
  if (fc.start.type === "flow-seq-start") {
    for (const it2 of fc.items) {
      if (it2.sep && !it2.value && !includesToken(it2.start, "explicit-key-ind") && !includesToken(it2.sep, "map-value-ind")) {
        if (it2.key)
          it2.value = it2.key;
        delete it2.key;
        if (isFlowToken(it2.value)) {
          if (it2.value.end)
            Array.prototype.push.apply(it2.value.end, it2.sep);
          else
            it2.value.end = it2.sep;
        } else
          Array.prototype.push.apply(it2.start, it2.sep);
        delete it2.sep;
      }
    }
  }
}
var Parser3 = class {
  /**
   * @param onNewLine - If defined, called separately with the start position of
   *   each new line (in `parse()`, including the start of input).
   */
  constructor(onNewLine) {
    this.atNewLine = true;
    this.atScalar = false;
    this.indent = 0;
    this.offset = 0;
    this.onKeyLine = false;
    this.stack = [];
    this.source = "";
    this.type = "";
    this.lexer = new Lexer2();
    this.onNewLine = onNewLine;
  }
  /**
   * Parse `source` as a YAML stream.
   * If `incomplete`, a part of the last line may be left as a buffer for the next call.
   *
   * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
   *
   * @returns A generator of tokens representing each directive, document, and other structure.
   */
  *parse(source, incomplete = false) {
    if (this.onNewLine && this.offset === 0)
      this.onNewLine(0);
    for (const lexeme of this.lexer.lex(source, incomplete))
      yield* this.next(lexeme);
    if (!incomplete)
      yield* this.end();
  }
  /**
   * Advance the parser by the `source` of one lexical token.
   */
  *next(source) {
    this.source = source;
    if (this.atScalar) {
      this.atScalar = false;
      yield* this.step();
      this.offset += source.length;
      return;
    }
    const type = tokenType(source);
    if (!type) {
      const message = `Not a YAML token: ${source}`;
      yield* this.pop({ type: "error", offset: this.offset, message, source });
      this.offset += source.length;
    } else if (type === "scalar") {
      this.atNewLine = false;
      this.atScalar = true;
      this.type = "scalar";
    } else {
      this.type = type;
      yield* this.step();
      switch (type) {
        case "newline":
          this.atNewLine = true;
          this.indent = 0;
          if (this.onNewLine)
            this.onNewLine(this.offset + source.length);
          break;
        case "space":
          if (this.atNewLine && source[0] === " ")
            this.indent += source.length;
          break;
        case "explicit-key-ind":
        case "map-value-ind":
        case "seq-item-ind":
          if (this.atNewLine)
            this.indent += source.length;
          break;
        case "doc-mode":
        case "flow-error-end":
          return;
        default:
          this.atNewLine = false;
      }
      this.offset += source.length;
    }
  }
  /** Call at end of input to push out any remaining constructions */
  *end() {
    while (this.stack.length > 0)
      yield* this.pop();
  }
  get sourceToken() {
    const st = {
      type: this.type,
      offset: this.offset,
      indent: this.indent,
      source: this.source
    };
    return st;
  }
  *step() {
    const top2 = this.peek(1);
    if (this.type === "doc-end" && top2?.type !== "doc-end") {
      while (this.stack.length > 0)
        yield* this.pop();
      this.stack.push({
        type: "doc-end",
        offset: this.offset,
        source: this.source
      });
      return;
    }
    if (!top2)
      return yield* this.stream();
    switch (top2.type) {
      case "document":
        return yield* this.document(top2);
      case "alias":
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
        return yield* this.scalar(top2);
      case "block-scalar":
        return yield* this.blockScalar(top2);
      case "block-map":
        return yield* this.blockMap(top2);
      case "block-seq":
        return yield* this.blockSequence(top2);
      case "flow-collection":
        return yield* this.flowCollection(top2);
      case "doc-end":
        return yield* this.documentEnd(top2);
    }
    yield* this.pop();
  }
  peek(n4) {
    return this.stack[this.stack.length - n4];
  }
  *pop(error2) {
    const token = error2 ?? this.stack.pop();
    if (!token) {
      const message = "Tried to pop an empty stack";
      yield { type: "error", offset: this.offset, source: "", message };
    } else if (this.stack.length === 0) {
      yield token;
    } else {
      const top2 = this.peek(1);
      if (token.type === "block-scalar") {
        token.indent = "indent" in top2 ? top2.indent : 0;
      } else if (token.type === "flow-collection" && top2.type === "document") {
        token.indent = 0;
      }
      if (token.type === "flow-collection")
        fixFlowSeqItems(token);
      switch (top2.type) {
        case "document":
          top2.value = token;
          break;
        case "block-scalar":
          top2.props.push(token);
          break;
        case "block-map": {
          const it2 = top2.items[top2.items.length - 1];
          if (it2.value) {
            top2.items.push({ start: [], key: token, sep: [] });
            this.onKeyLine = true;
            return;
          } else if (it2.sep) {
            it2.value = token;
          } else {
            Object.assign(it2, { key: token, sep: [] });
            this.onKeyLine = !it2.explicitKey;
            return;
          }
          break;
        }
        case "block-seq": {
          const it2 = top2.items[top2.items.length - 1];
          if (it2.value)
            top2.items.push({ start: [], value: token });
          else
            it2.value = token;
          break;
        }
        case "flow-collection": {
          const it2 = top2.items[top2.items.length - 1];
          if (!it2 || it2.value)
            top2.items.push({ start: [], key: token, sep: [] });
          else if (it2.sep)
            it2.value = token;
          else
            Object.assign(it2, { key: token, sep: [] });
          return;
        }
        /* istanbul ignore next should not happen */
        default:
          yield* this.pop();
          yield* this.pop(token);
      }
      if ((top2.type === "document" || top2.type === "block-map" || top2.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
        const last3 = token.items[token.items.length - 1];
        if (last3 && !last3.sep && !last3.value && last3.start.length > 0 && findNonEmptyIndex(last3.start) === -1 && (token.indent === 0 || last3.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
          if (top2.type === "document")
            top2.end = last3.start;
          else
            top2.items.push({ start: last3.start });
          token.items.splice(-1, 1);
        }
      }
    }
  }
  *stream() {
    switch (this.type) {
      case "directive-line":
        yield { type: "directive", offset: this.offset, source: this.source };
        return;
      case "byte-order-mark":
      case "space":
      case "comment":
      case "newline":
        yield this.sourceToken;
        return;
      case "doc-mode":
      case "doc-start": {
        const doc4 = {
          type: "document",
          offset: this.offset,
          start: []
        };
        if (this.type === "doc-start")
          doc4.start.push(this.sourceToken);
        this.stack.push(doc4);
        return;
      }
    }
    yield {
      type: "error",
      offset: this.offset,
      message: `Unexpected ${this.type} token in YAML stream`,
      source: this.source
    };
  }
  *document(doc4) {
    if (doc4.value)
      return yield* this.lineEnd(doc4);
    switch (this.type) {
      case "doc-start": {
        if (findNonEmptyIndex(doc4.start) !== -1) {
          yield* this.pop();
          yield* this.step();
        } else
          doc4.start.push(this.sourceToken);
        return;
      }
      case "anchor":
      case "tag":
      case "space":
      case "comment":
      case "newline":
        doc4.start.push(this.sourceToken);
        return;
    }
    const bv = this.startBlockValue(doc4);
    if (bv)
      this.stack.push(bv);
    else {
      yield {
        type: "error",
        offset: this.offset,
        message: `Unexpected ${this.type} token in YAML document`,
        source: this.source
      };
    }
  }
  *scalar(scalar) {
    if (this.type === "map-value-ind") {
      const prev = getPrevProps(this.peek(2));
      const start = getFirstKeyStartProps(prev);
      let sep;
      if (scalar.end) {
        sep = scalar.end;
        sep.push(this.sourceToken);
        delete scalar.end;
      } else
        sep = [this.sourceToken];
      const map5 = {
        type: "block-map",
        offset: scalar.offset,
        indent: scalar.indent,
        items: [{ start, key: scalar, sep }]
      };
      this.onKeyLine = true;
      this.stack[this.stack.length - 1] = map5;
    } else
      yield* this.lineEnd(scalar);
  }
  *blockScalar(scalar) {
    switch (this.type) {
      case "space":
      case "comment":
      case "newline":
        scalar.props.push(this.sourceToken);
        return;
      case "scalar":
        scalar.source = this.source;
        this.atNewLine = true;
        this.indent = 0;
        if (this.onNewLine) {
          let nl = this.source.indexOf("\n") + 1;
          while (nl !== 0) {
            this.onNewLine(this.offset + nl);
            nl = this.source.indexOf("\n", nl) + 1;
          }
        }
        yield* this.pop();
        break;
      /* istanbul ignore next should not happen */
      default:
        yield* this.pop();
        yield* this.step();
    }
  }
  *blockMap(map5) {
    const it2 = map5.items[map5.items.length - 1];
    switch (this.type) {
      case "newline":
        this.onKeyLine = false;
        if (it2.value) {
          const end = "end" in it2.value ? it2.value.end : void 0;
          const last3 = Array.isArray(end) ? end[end.length - 1] : void 0;
          if (last3?.type === "comment")
            end?.push(this.sourceToken);
          else
            map5.items.push({ start: [this.sourceToken] });
        } else if (it2.sep) {
          it2.sep.push(this.sourceToken);
        } else {
          it2.start.push(this.sourceToken);
        }
        return;
      case "space":
      case "comment":
        if (it2.value) {
          map5.items.push({ start: [this.sourceToken] });
        } else if (it2.sep) {
          it2.sep.push(this.sourceToken);
        } else {
          if (this.atIndentedComment(it2.start, map5.indent)) {
            const prev = map5.items[map5.items.length - 2];
            const end = prev?.value?.end;
            if (Array.isArray(end)) {
              Array.prototype.push.apply(end, it2.start);
              end.push(this.sourceToken);
              map5.items.pop();
              return;
            }
          }
          it2.start.push(this.sourceToken);
        }
        return;
    }
    if (this.indent >= map5.indent) {
      const atMapIndent = !this.onKeyLine && this.indent === map5.indent;
      const atNextItem = atMapIndent && (it2.sep || it2.explicitKey) && this.type !== "seq-item-ind";
      let start = [];
      if (atNextItem && it2.sep && !it2.value) {
        const nl = [];
        for (let i3 = 0; i3 < it2.sep.length; ++i3) {
          const st = it2.sep[i3];
          switch (st.type) {
            case "newline":
              nl.push(i3);
              break;
            case "space":
              break;
            case "comment":
              if (st.indent > map5.indent)
                nl.length = 0;
              break;
            default:
              nl.length = 0;
          }
        }
        if (nl.length >= 2)
          start = it2.sep.splice(nl[1]);
      }
      switch (this.type) {
        case "anchor":
        case "tag":
          if (atNextItem || it2.value) {
            start.push(this.sourceToken);
            map5.items.push({ start });
            this.onKeyLine = true;
          } else if (it2.sep) {
            it2.sep.push(this.sourceToken);
          } else {
            it2.start.push(this.sourceToken);
          }
          return;
        case "explicit-key-ind":
          if (!it2.sep && !it2.explicitKey) {
            it2.start.push(this.sourceToken);
            it2.explicitKey = true;
          } else if (atNextItem || it2.value) {
            start.push(this.sourceToken);
            map5.items.push({ start, explicitKey: true });
          } else {
            this.stack.push({
              type: "block-map",
              offset: this.offset,
              indent: this.indent,
              items: [{ start: [this.sourceToken], explicitKey: true }]
            });
          }
          this.onKeyLine = true;
          return;
        case "map-value-ind":
          if (it2.explicitKey) {
            if (!it2.sep) {
              if (includesToken(it2.start, "newline")) {
                Object.assign(it2, { key: null, sep: [this.sourceToken] });
              } else {
                const start2 = getFirstKeyStartProps(it2.start);
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: start2, key: null, sep: [this.sourceToken] }]
                });
              }
            } else if (it2.value) {
              map5.items.push({ start: [], key: null, sep: [this.sourceToken] });
            } else if (includesToken(it2.sep, "map-value-ind")) {
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start, key: null, sep: [this.sourceToken] }]
              });
            } else if (isFlowToken(it2.key) && !includesToken(it2.sep, "newline")) {
              const start2 = getFirstKeyStartProps(it2.start);
              const key2 = it2.key;
              const sep = it2.sep;
              sep.push(this.sourceToken);
              delete it2.key;
              delete it2.sep;
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start: start2, key: key2, sep }]
              });
            } else if (start.length > 0) {
              it2.sep = it2.sep.concat(start, this.sourceToken);
            } else {
              it2.sep.push(this.sourceToken);
            }
          } else {
            if (!it2.sep) {
              Object.assign(it2, { key: null, sep: [this.sourceToken] });
            } else if (it2.value || atNextItem) {
              map5.items.push({ start, key: null, sep: [this.sourceToken] });
            } else if (includesToken(it2.sep, "map-value-ind")) {
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start: [], key: null, sep: [this.sourceToken] }]
              });
            } else {
              it2.sep.push(this.sourceToken);
            }
          }
          this.onKeyLine = true;
          return;
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar": {
          const fs = this.flowScalar(this.type);
          if (atNextItem || it2.value) {
            map5.items.push({ start, key: fs, sep: [] });
            this.onKeyLine = true;
          } else if (it2.sep) {
            this.stack.push(fs);
          } else {
            Object.assign(it2, { key: fs, sep: [] });
            this.onKeyLine = true;
          }
          return;
        }
        default: {
          const bv = this.startBlockValue(map5);
          if (bv) {
            if (bv.type === "block-seq") {
              if (!it2.explicitKey && it2.sep && !includesToken(it2.sep, "newline")) {
                yield* this.pop({
                  type: "error",
                  offset: this.offset,
                  message: "Unexpected block-seq-ind on same line with key",
                  source: this.source
                });
                return;
              }
            } else if (atMapIndent) {
              map5.items.push({ start });
            }
            this.stack.push(bv);
            return;
          }
        }
      }
    }
    yield* this.pop();
    yield* this.step();
  }
  *blockSequence(seq2) {
    const it2 = seq2.items[seq2.items.length - 1];
    switch (this.type) {
      case "newline":
        if (it2.value) {
          const end = "end" in it2.value ? it2.value.end : void 0;
          const last3 = Array.isArray(end) ? end[end.length - 1] : void 0;
          if (last3?.type === "comment")
            end?.push(this.sourceToken);
          else
            seq2.items.push({ start: [this.sourceToken] });
        } else
          it2.start.push(this.sourceToken);
        return;
      case "space":
      case "comment":
        if (it2.value)
          seq2.items.push({ start: [this.sourceToken] });
        else {
          if (this.atIndentedComment(it2.start, seq2.indent)) {
            const prev = seq2.items[seq2.items.length - 2];
            const end = prev?.value?.end;
            if (Array.isArray(end)) {
              Array.prototype.push.apply(end, it2.start);
              end.push(this.sourceToken);
              seq2.items.pop();
              return;
            }
          }
          it2.start.push(this.sourceToken);
        }
        return;
      case "anchor":
      case "tag":
        if (it2.value || this.indent <= seq2.indent)
          break;
        it2.start.push(this.sourceToken);
        return;
      case "seq-item-ind":
        if (this.indent !== seq2.indent)
          break;
        if (it2.value || includesToken(it2.start, "seq-item-ind"))
          seq2.items.push({ start: [this.sourceToken] });
        else
          it2.start.push(this.sourceToken);
        return;
    }
    if (this.indent > seq2.indent) {
      const bv = this.startBlockValue(seq2);
      if (bv) {
        this.stack.push(bv);
        return;
      }
    }
    yield* this.pop();
    yield* this.step();
  }
  *flowCollection(fc) {
    const it2 = fc.items[fc.items.length - 1];
    if (this.type === "flow-error-end") {
      let top2;
      do {
        yield* this.pop();
        top2 = this.peek(1);
      } while (top2?.type === "flow-collection");
    } else if (fc.end.length === 0) {
      switch (this.type) {
        case "comma":
        case "explicit-key-ind":
          if (!it2 || it2.sep)
            fc.items.push({ start: [this.sourceToken] });
          else
            it2.start.push(this.sourceToken);
          return;
        case "map-value-ind":
          if (!it2 || it2.value)
            fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
          else if (it2.sep)
            it2.sep.push(this.sourceToken);
          else
            Object.assign(it2, { key: null, sep: [this.sourceToken] });
          return;
        case "space":
        case "comment":
        case "newline":
        case "anchor":
        case "tag":
          if (!it2 || it2.value)
            fc.items.push({ start: [this.sourceToken] });
          else if (it2.sep)
            it2.sep.push(this.sourceToken);
          else
            it2.start.push(this.sourceToken);
          return;
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar": {
          const fs = this.flowScalar(this.type);
          if (!it2 || it2.value)
            fc.items.push({ start: [], key: fs, sep: [] });
          else if (it2.sep)
            this.stack.push(fs);
          else
            Object.assign(it2, { key: fs, sep: [] });
          return;
        }
        case "flow-map-end":
        case "flow-seq-end":
          fc.end.push(this.sourceToken);
          return;
      }
      const bv = this.startBlockValue(fc);
      if (bv)
        this.stack.push(bv);
      else {
        yield* this.pop();
        yield* this.step();
      }
    } else {
      const parent = this.peek(2);
      if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
        yield* this.pop();
        yield* this.step();
      } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
        const prev = getPrevProps(parent);
        const start = getFirstKeyStartProps(prev);
        fixFlowSeqItems(fc);
        const sep = fc.end.splice(1, fc.end.length);
        sep.push(this.sourceToken);
        const map5 = {
          type: "block-map",
          offset: fc.offset,
          indent: fc.indent,
          items: [{ start, key: fc, sep }]
        };
        this.onKeyLine = true;
        this.stack[this.stack.length - 1] = map5;
      } else {
        yield* this.lineEnd(fc);
      }
    }
  }
  flowScalar(type) {
    if (this.onNewLine) {
      let nl = this.source.indexOf("\n") + 1;
      while (nl !== 0) {
        this.onNewLine(this.offset + nl);
        nl = this.source.indexOf("\n", nl) + 1;
      }
    }
    return {
      type,
      offset: this.offset,
      indent: this.indent,
      source: this.source
    };
  }
  startBlockValue(parent) {
    switch (this.type) {
      case "alias":
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
        return this.flowScalar(this.type);
      case "block-scalar-header":
        return {
          type: "block-scalar",
          offset: this.offset,
          indent: this.indent,
          props: [this.sourceToken],
          source: ""
        };
      case "flow-map-start":
      case "flow-seq-start":
        return {
          type: "flow-collection",
          offset: this.offset,
          indent: this.indent,
          start: this.sourceToken,
          items: [],
          end: []
        };
      case "seq-item-ind":
        return {
          type: "block-seq",
          offset: this.offset,
          indent: this.indent,
          items: [{ start: [this.sourceToken] }]
        };
      case "explicit-key-ind": {
        this.onKeyLine = true;
        const prev = getPrevProps(parent);
        const start = getFirstKeyStartProps(prev);
        start.push(this.sourceToken);
        return {
          type: "block-map",
          offset: this.offset,
          indent: this.indent,
          items: [{ start, explicitKey: true }]
        };
      }
      case "map-value-ind": {
        this.onKeyLine = true;
        const prev = getPrevProps(parent);
        const start = getFirstKeyStartProps(prev);
        return {
          type: "block-map",
          offset: this.offset,
          indent: this.indent,
          items: [{ start, key: null, sep: [this.sourceToken] }]
        };
      }
    }
    return null;
  }
  atIndentedComment(start, indent) {
    if (this.type !== "comment")
      return false;
    if (this.indent <= indent)
      return false;
    return start.every((st) => st.type === "newline" || st.type === "space");
  }
  *documentEnd(docEnd) {
    if (this.type !== "doc-mode") {
      if (docEnd.end)
        docEnd.end.push(this.sourceToken);
      else
        docEnd.end = [this.sourceToken];
      if (this.type === "newline")
        yield* this.pop();
    }
  }
  *lineEnd(token) {
    switch (this.type) {
      case "comma":
      case "doc-start":
      case "doc-end":
      case "flow-seq-end":
      case "flow-map-end":
      case "map-value-ind":
        yield* this.pop();
        yield* this.step();
        break;
      case "newline":
        this.onKeyLine = false;
      // fallthrough
      case "space":
      case "comment":
      default:
        if (token.end)
          token.end.push(this.sourceToken);
        else
          token.end = [this.sourceToken];
        if (this.type === "newline")
          yield* this.pop();
    }
  }
};

// node_modules/yaml/browser/dist/public-api.js
function parseOptions(options2) {
  const prettyErrors = options2.prettyErrors !== false;
  const lineCounter = options2.lineCounter || prettyErrors && new LineCounter() || null;
  return { lineCounter, prettyErrors };
}
function parseAllDocuments(source, options2 = {}) {
  const { lineCounter, prettyErrors } = parseOptions(options2);
  const parser4 = new Parser3(lineCounter?.addNewLine);
  const composer = new Composer(options2);
  const docs = Array.from(composer.compose(parser4.parse(source)));
  if (prettyErrors && lineCounter)
    for (const doc4 of docs) {
      doc4.errors.forEach(prettifyError(source, lineCounter));
      doc4.warnings.forEach(prettifyError(source, lineCounter));
    }
  if (docs.length > 0)
    return docs;
  return Object.assign([], { empty: true }, composer.streamInfo());
}
function parseDocument(source, options2 = {}) {
  const { lineCounter, prettyErrors } = parseOptions(options2);
  const parser4 = new Parser3(lineCounter?.addNewLine);
  const composer = new Composer(options2);
  let doc4 = null;
  for (const _doc of composer.compose(parser4.parse(source), true, source.length)) {
    if (!doc4)
      doc4 = _doc;
    else if (doc4.options.logLevel !== "silent") {
      doc4.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
      break;
    }
  }
  if (prettyErrors && lineCounter) {
    doc4.errors.forEach(prettifyError(source, lineCounter));
    doc4.warnings.forEach(prettifyError(source, lineCounter));
  }
  return doc4;
}
function parse3(src, reviver, options2) {
  let _reviver = void 0;
  if (typeof reviver === "function") {
    _reviver = reviver;
  } else if (options2 === void 0 && reviver && typeof reviver === "object") {
    options2 = reviver;
  }
  const doc4 = parseDocument(src, options2);
  if (!doc4)
    return null;
  doc4.warnings.forEach((warning2) => warn(doc4.options.logLevel, warning2));
  if (doc4.errors.length > 0) {
    if (doc4.options.logLevel !== "silent")
      throw doc4.errors[0];
    else
      doc4.errors = [];
  }
  return doc4.toJS(Object.assign({ reviver: _reviver }, options2));
}
function stringify6(value2, replacer, options2) {
  let _replacer = null;
  if (typeof replacer === "function" || Array.isArray(replacer)) {
    _replacer = replacer;
  } else if (options2 === void 0 && replacer) {
    options2 = replacer;
  }
  if (typeof options2 === "string")
    options2 = options2.length;
  if (typeof options2 === "number") {
    const indent = Math.round(options2);
    options2 = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
  }
  if (value2 === void 0) {
    const { keepUndefined } = options2 ?? replacer ?? {};
    if (!keepUndefined)
      return void 0;
  }
  if (isDocument(value2) && !_replacer)
    return value2.toString(options2);
  return new Document(value2, _replacer, options2).toString(options2);
}

// node_modules/yaml/browser/index.js
var browser_default = dist_exports;

// node_modules/codemirror-json-schema/dist/parsers/yaml-parser.js
function parseYAMLDocumentState(state) {
  let data2 = null;
  try {
    data2 = browser_default.parse(state.doc.toString());
  } catch (_a4) {
  }
  const pointers = getJsonPointers(state, MODES.YAML);
  return { data: data2, pointers };
}

// node_modules/codemirror-json-schema/dist/parsers/index.js
var getDefaultParser = (mode) => {
  switch (mode) {
    case MODES.JSON:
      return parseJSONDocumentState;
    case MODES.JSON5:
      return parseJSON5DocumentState;
    case MODES.YAML:
      return parseYAMLDocumentState;
  }
};

// node_modules/codemirror-json-schema/dist/utils/recordUtil.js
function getRecordEntries(record) {
  return Object.entries(record);
}
function replacePropertiesDeeply(object2, getReplacement) {
  if (typeof object2 === "string") {
    return object2;
  }
  if (typeof object2 !== "object" || object2 === null) {
    return object2;
  }
  if (Array.isArray(object2)) {
    return object2.map((element2) => replacePropertiesDeeply(element2, getReplacement));
  }
  if (object2 instanceof Map) {
    const newMap = /* @__PURE__ */ new Map();
    for (const [key2, value2] of object2) {
      const newKey = key2;
      const newValue = replacePropertiesDeeply(value2, getReplacement);
      newMap.set(newKey, newValue);
    }
    return newMap;
  }
  if (object2 instanceof Set) {
    const newSet = /* @__PURE__ */ new Set();
    for (const value2 of object2) {
      const newValue = replacePropertiesDeeply(value2, getReplacement);
      newSet.add(newValue);
    }
    return newSet;
  }
  const newObject = {};
  function handleReplacementEntry(oldKey, oldValue, newKey, newValue) {
    if (newKey === oldKey && newValue === oldValue) {
      newObject[newKey] = replacePropertiesDeeply(oldValue, getReplacement);
    } else {
      newObject[newKey] = newValue;
    }
  }
  for (const [key2, value2] of getRecordEntries(object2)) {
    const replacement = getReplacement(key2, value2);
    if (replacement.length === 2 && typeof replacement[0] === "string") {
      handleReplacementEntry(key2, value2, replacement[0], replacement[1]);
    } else {
      for (const [newKey, newValue] of replacement) {
        handleReplacementEntry(key2, value2, newKey, newValue);
      }
    }
  }
  return newObject;
}

// node_modules/codemirror-json-schema/dist/features/completion.js
var __rest2 = function(s3, e3) {
  var t3 = {};
  for (var p4 in s3) if (Object.prototype.hasOwnProperty.call(s3, p4) && e3.indexOf(p4) < 0)
    t3[p4] = s3[p4];
  if (s3 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p4 = Object.getOwnPropertySymbols(s3); i3 < p4.length; i3++) {
      if (e3.indexOf(p4[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p4[i3]))
        t3[p4[i3]] = s3[p4[i3]];
    }
  return t3;
};
var CompletionCollector = class {
  constructor() {
    this.completions = /* @__PURE__ */ new Map();
    this.reservedKeys = /* @__PURE__ */ new Set();
  }
  reserve(key2) {
    this.reservedKeys.add(key2);
  }
  add(completion) {
    if (this.reservedKeys.has(completion.label)) {
      return;
    }
    this.completions.set(completion.label, completion);
  }
};
function isRealSchema(subSchema) {
  return !(!subSchema || isJsonError(subSchema) || subSchema.name === "UnknownPropertyError" || subSchema.type === "undefined");
}
var JSONCompletion = class {
  // private lastKnownValidData: object | null = null;
  constructor(opts) {
    var _a4, _b, _c;
    this.opts = opts;
    this.originalSchema = null;
    this.schema = null;
    this.laxSchema = null;
    this.mode = MODES.JSON;
    this.mode = (_a4 = opts.mode) !== null && _a4 !== void 0 ? _a4 : MODES.JSON;
    this.parser = (_c = (_b = this.opts) === null || _b === void 0 ? void 0 : _b.jsonParser) !== null && _c !== void 0 ? _c : getDefaultParser(this.mode);
  }
  doComplete(ctx) {
    var _a4;
    const schemaFromState = getJSONSchema(ctx.state);
    if (this.originalSchema !== schemaFromState) {
      this.schema = (_a4 = expandSchemaProperty(schemaFromState, schemaFromState)) !== null && _a4 !== void 0 ? _a4 : schemaFromState;
      this.laxSchema = makeSchemaLax(this.schema);
    }
    if (!this.schema || !this.laxSchema) {
      return [];
    }
    debug.log("xxx", "trying with original schema");
    const completionResultForOriginalSchema = this.doCompleteForSchema(ctx, this.schema);
    if (completionResultForOriginalSchema.options.length !== 0) {
      return completionResultForOriginalSchema;
    }
    debug.log("xxx", "no completions with original schema, trying with lax schema");
    return this.doCompleteForSchema(ctx, this.laxSchema);
  }
  doCompleteForSchema(ctx, rootSchema) {
    var _a4, _b;
    const result2 = {
      from: ctx.pos,
      to: ctx.pos,
      options: [],
      filter: false
      // will be handled manually
    };
    const text3 = ctx.state.doc.sliceString(0);
    let node = getNodeAtPosition(ctx.state, ctx.pos);
    let prefix5 = ctx.state.sliceDoc(node.from, ctx.pos).replace(/^(["'])/, "");
    debug.log("xxx", "node", node, "prefix", prefix5, "ctx", ctx);
    if (!(isPrimitiveValueNode(node, this.mode) || isPropertyNameNode(node, this.mode)) && !ctx.explicit) {
      debug.log("xxx", "no completions for non-word/primitive", node);
      return result2;
    }
    const currentWord = getWord(ctx.state.doc, node);
    const rawWord = getWord(ctx.state.doc, node, false);
    if (node && (isPrimitiveValueNode(node, this.mode) || isPropertyNameNode(node, this.mode))) {
      result2.from = node.from;
      result2.to = node.to;
    } else {
      const word = ctx.matchBefore(/[A-Za-z0-9._]*/);
      const overwriteStart = ctx.pos - currentWord.length;
      debug.log("xxx", "overwriteStart after", overwriteStart, "ctx.pos", ctx.pos, "word", word, "currentWord", currentWord, "=>", text3[overwriteStart - 1], "..", text3[overwriteStart], "..", text3);
      result2.from = node.name === TOKENS.INVALID ? (_a4 = word === null || word === void 0 ? void 0 : word.from) !== null && _a4 !== void 0 ? _a4 : ctx.pos : overwriteStart;
      result2.to = ctx.pos;
    }
    const collector = new CompletionCollector();
    let addValue = true;
    const closestPropertyNameNode = getClosestNode(node, TOKENS.PROPERTY_NAME, this.mode);
    if (closestPropertyNameNode) {
      debug.log("xxx", "closestPropertyNameNode", closestPropertyNameNode, "node", node);
      node = closestPropertyNameNode;
    }
    if (isPropertyNameNode(node, this.mode)) {
      debug.log("xxx", "isPropertyNameNode", node);
      const parent = node.parent;
      if (parent) {
        const valueNode = getChildValueNode(parent, this.mode);
        addValue = !valueNode || valueNode.name === TOKENS.INVALID && valueNode.from - valueNode.to === 0 || // TODO: Verify this doesn't break anything else
        (valueNode.parent ? getChildrenNodes(valueNode.parent).length <= 1 : false);
        debug.log("xxx", "addValue", addValue, getChildValueNode(parent, this.mode), node);
        node = (_b = getClosestNode(parent, TOKENS.OBJECT, this.mode)) !== null && _b !== void 0 ? _b : null;
      }
    }
    debug.log("xxx", node, currentWord, ctx, "node at pos", getNodeAtPosition(ctx.state, ctx.pos));
    if (node && [TOKENS.OBJECT, TOKENS.JSON_TEXT].includes(resolveTokenName(node.name, this.mode)) && (isPropertyNameNode(getNodeAtPosition(ctx.state, ctx.pos), this.mode) || closestPropertyNameNode)) {
      if (node.from === ctx.pos) {
        debug.log("xxx", "no completions for just before opening brace");
        return result2;
      }
      this.getPropertyCompletions(rootSchema, ctx, node, collector, addValue, rawWord);
    } else {
      const types2 = {};
      const res = this.getValueCompletions(rootSchema, ctx, types2, collector);
      debug.log("xxx", "getValueCompletions res", res);
      if (res) {
      }
    }
    result2.options = Array.from(collector.completions.values()).filter((v3) => stripSurroundingQuotes(v3.label).startsWith(prefix5));
    debug.log("xxx", "result", result2, "prefix", prefix5, "collector.completions", collector.completions, "reservedKeys", collector.reservedKeys);
    return result2;
  }
  applySnippetCompletion(completion) {
    return snippetCompletion(typeof completion.apply !== "string" ? completion.label : completion.apply, completion);
  }
  getPropertyCompletions(rootSchema, ctx, node, collector, addValue, rawWord) {
    const properties = getMatchingChildrenNodes(node, TOKENS.PROPERTY, this.mode);
    debug.log("xxx", "getPropertyCompletions", node, ctx, properties);
    properties.forEach((p4) => {
      const key2 = getWord(ctx.state.doc, getMatchingChildNode(p4, TOKENS.PROPERTY_NAME, this.mode));
      collector.reserve(stripSurroundingQuotes(key2));
    });
    const schemas2 = this.getSchemas(rootSchema, ctx);
    debug.log("xxx", "propertyCompletion schemas", schemas2);
    schemas2.forEach((s3) => {
      if (typeof s3 !== "object") {
        return;
      }
      const properties2 = s3.properties;
      if (properties2) {
        Object.entries(properties2).forEach(([key2, value2]) => {
          var _a4, _b;
          if (typeof value2 === "object") {
            const description = (_a4 = value2.description) !== null && _a4 !== void 0 ? _a4 : "";
            const type = (_b = value2.type) !== null && _b !== void 0 ? _b : "";
            const typeStr = Array.isArray(type) ? type.toString() : type;
            const completion = {
              // label is the unquoted key which will be displayed.
              label: key2,
              apply: this.getInsertTextForProperty(key2, addValue, rawWord, rootSchema, value2),
              type: "property",
              detail: typeStr,
              info: () => el("div", {
                inner: renderMarkdown(description)
              })
            };
            collector.add(this.applySnippetCompletion(completion));
          }
        });
      }
      const propertyNames = s3.propertyNames;
      if (typeof propertyNames === "object") {
        if (propertyNames.enum) {
          propertyNames.enum.forEach((v3) => {
            const label = v3 === null || v3 === void 0 ? void 0 : v3.toString();
            if (label) {
              const completion = {
                label,
                apply: this.getInsertTextForProperty(label, addValue, rawWord, rootSchema),
                type: "property"
              };
              collector.add(this.applySnippetCompletion(completion));
            }
          });
        }
        if (propertyNames.const) {
          const label = propertyNames.const.toString();
          const completion = {
            label,
            apply: this.getInsertTextForProperty(label, addValue, rawWord, rootSchema),
            type: "property"
          };
          collector.add(this.applySnippetCompletion(completion));
        }
      }
    });
  }
  // apply is the quoted key which will be applied.
  // Normally the label needs to match the token
  // prefix i.e. if the token begins with `"to`, then the
  // label needs to have the quotes as well for it to match.
  // However we are manually filtering the results so we can
  // just use the unquoted key as the label, which is nicer
  // and gives us more control.
  // If no property value is present, then we add the colon as well.
  // Use snippetCompletion to handle insert value + position cursor e.g. "key": "#{}"
  // doc: https://codemirror.net/docs/ref/#autocomplete.snippetCompletion
  // idea: https://discuss.codemirror.net/t/autocomplete-cursor-position-in-apply-function/4088/3
  getInsertTextForProperty(key2, addValue, rawWord, rootSchema, propertySchema) {
    propertySchema = propertySchema ? expandSchemaProperty(propertySchema, rootSchema) : propertySchema;
    let resultText = this.getInsertTextForPropertyName(key2, rawWord);
    if (!addValue) {
      return resultText;
    }
    resultText += ": ";
    let value2;
    let nValueProposals = 0;
    if (typeof propertySchema === "object") {
      if (typeof propertySchema.default !== "undefined") {
        if (!value2) {
          value2 = this.getInsertTextForGuessedValue(propertySchema.default, "");
        }
        nValueProposals++;
      } else {
        if (propertySchema.enum) {
          if (!value2 && propertySchema.enum.length === 1) {
            value2 = this.getInsertTextForGuessedValue(propertySchema.enum[0], "");
          }
          nValueProposals += propertySchema.enum.length;
        }
        if (typeof propertySchema.const !== "undefined") {
          if (!value2) {
            value2 = this.getInsertTextForGuessedValue(propertySchema.const, "");
          }
          nValueProposals++;
        }
        if (Array.isArray(propertySchema.examples) && propertySchema.examples.length) {
          if (!value2) {
            value2 = this.getInsertTextForGuessedValue(propertySchema.examples[0], "");
          }
          nValueProposals += propertySchema.examples.length;
        }
        if (value2 === void 0 && nValueProposals === 0) {
          let type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
          if (!type) {
            if (propertySchema.properties) {
              type = "object";
            } else if (propertySchema.items) {
              type = "array";
            }
          }
          switch (type) {
            case "boolean":
              value2 = "#{}";
              break;
            case "string":
              value2 = this.getInsertTextForString("");
              break;
            case "object":
              switch (this.mode) {
                case MODES.JSON5:
                  value2 = "{#{}}";
                  break;
                case MODES.YAML:
                  value2 = "#{}";
                  break;
                default:
                  value2 = "{#{}}";
                  break;
              }
              break;
            case "array":
              value2 = "[#{}]";
              break;
            case "number":
            case "integer":
              value2 = "#{0}";
              break;
            case "null":
              value2 = "#{null}";
              break;
            default:
              value2 = "#{}";
              break;
          }
        }
      }
    }
    if (!value2 || nValueProposals > 1) {
      debug.log("xxx", "value", value2, "nValueProposals", nValueProposals, propertySchema);
      value2 = "#{}";
    }
    return resultText + value2;
  }
  getInsertTextForPropertyName(key2, rawWord) {
    switch (this.mode) {
      case MODES.JSON5:
      case MODES.YAML: {
        if (rawWord.startsWith('"')) {
          return `"${key2}"`;
        }
        if (rawWord.startsWith("'")) {
          return `'${key2}'`;
        }
        return key2;
      }
      default:
        return `"${key2}"`;
    }
  }
  getInsertTextForString(value2, prf = "#") {
    switch (this.mode) {
      case MODES.JSON5:
        return `'${prf}{${value2}}'`;
      case MODES.YAML:
        return `${prf}{${value2}}`;
      default:
        return `"${prf}{${value2}}"`;
    }
  }
  // TODO: Is this actually working?
  getInsertTextForGuessedValue(value2, separatorAfter = "") {
    switch (typeof value2) {
      case "object":
        if (value2 === null) {
          return "${null}" + separatorAfter;
        }
        return this.getInsertTextForValue(value2, separatorAfter);
      case "string": {
        let snippetValue = JSON.stringify(value2);
        snippetValue = snippetValue.substr(1, snippetValue.length - 2);
        snippetValue = this.getInsertTextForPlainText(snippetValue);
        return this.getInsertTextForString(snippetValue, "$") + separatorAfter;
      }
      case "number":
      case "boolean":
        return "${" + JSON.stringify(value2) + "}" + separatorAfter;
    }
    return this.getInsertTextForValue(value2, separatorAfter);
  }
  getInsertTextForPlainText(text3) {
    return text3.replace(/[\\$}]/g, "\\$&");
  }
  getInsertTextForValue(value2, separatorAfter) {
    const text3 = JSON.stringify(value2, null, "	");
    if (text3 === "{}") {
      return "{#{}}" + separatorAfter;
    } else if (text3 === "[]") {
      return "[#{}]" + separatorAfter;
    }
    return this.getInsertTextForPlainText(text3 + separatorAfter);
  }
  getValueCompletions(rootSchema, ctx, types2, collector) {
    let node = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
    let valueNode = null;
    let parentKey = void 0;
    debug.log("xxx", "getValueCompletions", node, ctx);
    if (node && isPrimitiveValueNode(node, this.mode)) {
      valueNode = node;
      node = node.parent;
    }
    if (!node) {
      this.addSchemaValueCompletions(rootSchema, types2, collector);
      return;
    }
    if (resolveTokenName(node.name, this.mode) === TOKENS.PROPERTY) {
      const keyNode = getMatchingChildNode(node, TOKENS.PROPERTY_NAME, this.mode);
      if (keyNode) {
        parentKey = getWord(ctx.state.doc, keyNode);
        node = node.parent;
      }
    }
    debug.log("xxx", "node", node, "parentKey", parentKey);
    if (node && (parentKey !== void 0 || resolveTokenName(node.name, this.mode) === TOKENS.ARRAY)) {
      const schemas2 = this.getSchemas(rootSchema, ctx);
      for (const s3 of schemas2) {
        if (typeof s3 !== "object") {
          return;
        }
        if (resolveTokenName(node.name, this.mode) === TOKENS.ARRAY && s3.items) {
          let c3 = collector;
          if (s3.uniqueItems) {
            c3 = Object.assign(Object.assign({}, c3), {
              add(completion) {
                if (!c3.completions.has(completion.label)) {
                  collector.add(completion);
                }
              },
              reserve(key2) {
                collector.reserve(key2);
              }
            });
          }
          if (Array.isArray(s3.items)) {
            let arrayIndex = 0;
            if (valueNode) {
              const foundIdx = findNodeIndexInArrayNode(node, valueNode, this.mode);
              if (foundIdx >= 0) {
                arrayIndex = foundIdx;
              }
            }
            const itemSchema = s3.items[arrayIndex];
            if (itemSchema) {
              this.addSchemaValueCompletions(itemSchema, types2, c3);
            }
          } else {
            this.addSchemaValueCompletions(s3.items, types2, c3);
          }
        }
        if (s3.type == null || s3.type !== "object") {
          this.addSchemaValueCompletions(s3, types2, collector);
        }
        if (parentKey !== void 0) {
          let propertyMatched = false;
          if (s3.properties) {
            const propertySchema = s3.properties[parentKey];
            if (propertySchema) {
              propertyMatched = true;
              this.addSchemaValueCompletions(propertySchema, types2, collector);
            }
          }
          if (s3.patternProperties && !propertyMatched) {
            for (const pattern2 of Object.keys(s3.patternProperties)) {
              const regex = this.extendedRegExp(pattern2);
              if (regex === null || regex === void 0 ? void 0 : regex.test(parentKey)) {
                propertyMatched = true;
                const propertySchema = s3.patternProperties[pattern2];
                if (propertySchema) {
                  this.addSchemaValueCompletions(propertySchema, types2, collector);
                }
              }
            }
          }
          if (s3.additionalProperties && !propertyMatched) {
            const propertySchema = s3.additionalProperties;
            this.addSchemaValueCompletions(propertySchema, types2, collector);
          }
        }
        if (types2["boolean"]) {
          this.addBooleanValueCompletion(true, collector);
          this.addBooleanValueCompletion(false, collector);
        }
        if (types2["null"]) {
          this.addNullValueCompletion(collector);
        }
      }
    }
    const valuePrefix = valueNode ? getWord(ctx.state.doc, valueNode, true, false) : "";
    return {
      valuePrefix
    };
  }
  addSchemaValueCompletions(schema7, types2, collector) {
    if (typeof schema7 === "object") {
      this.addEnumValueCompletions(schema7, collector);
      this.addDefaultValueCompletions(schema7, collector);
      this.collectTypes(schema7, types2);
      if (Array.isArray(schema7.allOf)) {
        schema7.allOf.forEach((s3) => this.addSchemaValueCompletions(s3, types2, collector));
      }
      if (Array.isArray(schema7.anyOf)) {
        schema7.anyOf.forEach((s3) => this.addSchemaValueCompletions(s3, types2, collector));
      }
      if (Array.isArray(schema7.oneOf)) {
        schema7.oneOf.forEach((s3) => this.addSchemaValueCompletions(s3, types2, collector));
      }
    }
  }
  addDefaultValueCompletions(schema7, collector, arrayDepth = 0) {
    let hasProposals = false;
    if (typeof schema7.default !== "undefined") {
      let type = schema7.type;
      let value2 = schema7.default;
      for (let i3 = arrayDepth; i3 > 0; i3--) {
        value2 = [value2];
        type = "array";
      }
      const completionItem = Object.assign(Object.assign({ type: type === null || type === void 0 ? void 0 : type.toString() }, this.getAppliedValue(value2)), { detail: "Default value" });
      collector.add(completionItem);
      hasProposals = true;
    }
    if (Array.isArray(schema7.examples)) {
      schema7.examples.forEach((example) => {
        let type = schema7.type;
        let value2 = example;
        for (let i3 = arrayDepth; i3 > 0; i3--) {
          value2 = [value2];
          type = "array";
        }
        collector.add(Object.assign({ type: type === null || type === void 0 ? void 0 : type.toString() }, this.getAppliedValue(value2)));
        hasProposals = true;
      });
    }
    if (!hasProposals && typeof schema7.items === "object" && !Array.isArray(schema7.items) && arrayDepth < 5) {
      this.addDefaultValueCompletions(schema7.items, collector, arrayDepth + 1);
    }
  }
  addEnumValueCompletions(schema7, collector) {
    var _a4, _b;
    if (typeof schema7.const !== "undefined") {
      collector.add(Object.assign(Object.assign({ type: (_a4 = schema7.type) === null || _a4 === void 0 ? void 0 : _a4.toString() }, this.getAppliedValue(schema7.const)), { info: schema7.description }));
    }
    if (Array.isArray(schema7.enum)) {
      for (let i3 = 0, length = schema7.enum.length; i3 < length; i3++) {
        const enm = schema7.enum[i3];
        collector.add(Object.assign(Object.assign({ type: (_b = schema7.type) === null || _b === void 0 ? void 0 : _b.toString() }, this.getAppliedValue(enm)), { info: schema7.description }));
      }
    }
  }
  addBooleanValueCompletion(value2, collector) {
    collector.add({
      type: "boolean",
      label: value2 ? "true" : "false"
    });
  }
  addNullValueCompletion(collector) {
    collector.add({
      type: "null",
      label: "null"
    });
  }
  collectTypes(schema7, types2) {
    if (Array.isArray(schema7.enum) || typeof schema7.const !== "undefined") {
      return;
    }
    const type = schema7.type;
    if (Array.isArray(type)) {
      type.forEach((t3) => types2[t3] = true);
    } else if (type) {
      types2[type] = true;
    }
  }
  getSchemas(rootSchema, ctx) {
    var _a4, _b, _c;
    const { data: documentData } = this.parser(ctx.state);
    const draft = new Draft07(rootSchema);
    let pointer = jsonPointerForPosition(ctx.state, ctx.pos, -1, this.mode);
    if (pointer === "")
      pointer = void 0;
    if (pointer != null && pointer.endsWith("/")) {
      pointer = pointer.substring(0, pointer.length - 1);
      const effectiveSchemaOfPointer = getEffectiveObjectWithPropertiesSchema(rootSchema, documentData, pointer);
      if (effectiveSchemaOfPointer != null) {
        return [effectiveSchemaOfPointer];
      }
    }
    let parentPointer = pointer != null ? pointer.replace(/\/[^/]*$/, "") : void 0;
    if (parentPointer === "")
      parentPointer = void 0;
    const effectiveSchemaOfParent = getEffectiveObjectWithPropertiesSchema(rootSchema, documentData, parentPointer);
    const deepestPropertyKey = pointer === null || pointer === void 0 ? void 0 : pointer.split("/").pop();
    const pointerPointsToKnownProperty = deepestPropertyKey == null || deepestPropertyKey in ((_a4 = effectiveSchemaOfParent === null || effectiveSchemaOfParent === void 0 ? void 0 : effectiveSchemaOfParent.properties) !== null && _a4 !== void 0 ? _a4 : {});
    let subSchema = draft.getSchema({
      pointer,
      data: documentData !== null && documentData !== void 0 ? documentData : void 0
    });
    if (!pointerPointsToKnownProperty && (subSchema === null || subSchema === void 0 ? void 0 : subSchema.type) === "null" && this.mode === "yaml") {
      subSchema = void 0;
    }
    debug.log("xxxx", "draft.getSchema", subSchema, "data", documentData, "pointer", pointer, "pointerPointsToKnownProperty", pointerPointsToKnownProperty);
    if (isJsonError(subSchema)) {
      subSchema = (_b = subSchema.data) === null || _b === void 0 ? void 0 : _b.schema;
    }
    if (!isRealSchema(subSchema)) {
      if (effectiveSchemaOfParent) {
        return [effectiveSchemaOfParent];
      }
    }
    if (!isRealSchema(subSchema)) {
      subSchema = draft.getSchema({ pointer: parentPointer });
      pointer = parentPointer;
    }
    debug.log("xxx", "pointer..", JSON.stringify(pointer));
    if (!isRealSchema(subSchema) && (!pointer || pointer === "/")) {
      subSchema = (_c = expandSchemaProperty(rootSchema, rootSchema)) !== null && _c !== void 0 ? _c : rootSchema;
    }
    debug.log("xxx", "subSchema..", subSchema);
    if (!subSchema) {
      return [];
    }
    if (Array.isArray(subSchema.allOf)) {
      return [
        subSchema,
        ...subSchema.allOf.map((s3) => expandSchemaProperty(s3, rootSchema))
      ];
    }
    if (Array.isArray(subSchema.oneOf)) {
      return [
        subSchema,
        ...subSchema.oneOf.map((s3) => expandSchemaProperty(s3, rootSchema))
      ];
    }
    if (Array.isArray(subSchema.anyOf)) {
      return [
        subSchema,
        ...subSchema.anyOf.map((s3) => expandSchemaProperty(s3, rootSchema))
      ];
    }
    return [subSchema];
  }
  getAppliedValue(value2) {
    const stripped = stripSurroundingQuotes(JSON.stringify(value2));
    switch (this.mode) {
      case MODES.JSON5:
        return {
          label: stripped,
          apply: surroundingDoubleQuotesToSingle(JSON.stringify(value2))
        };
      case MODES.YAML:
        return {
          label: stripped,
          apply: stripped
        };
      default:
        return {
          label: stripped,
          apply: JSON.stringify(value2)
        };
    }
  }
  getValueFromLabel(value2) {
    return JSON.parse(value2);
  }
  extendedRegExp(pattern2) {
    let flags = "";
    if (pattern2.startsWith("(?i)")) {
      pattern2 = pattern2.substring(4);
      flags = "i";
    }
    try {
      return new RegExp(pattern2, flags + "u");
    } catch (e3) {
      try {
        return new RegExp(pattern2, flags);
      } catch (e4) {
        return void 0;
      }
    }
  }
};
function jsonCompletion(opts = {}) {
  const completion = new JSONCompletion(opts);
  return function jsonDoCompletion(ctx) {
    return completion.doComplete(ctx);
  };
}
function makeSchemaLax(schema7) {
  return replacePropertiesDeeply(schema7, (key2, value2) => {
    if (key2 === "additionalProperties" && value2 === false) {
      return [];
    }
    if (key2 === "required" && Array.isArray(value2)) {
      return [];
    }
    if (key2 === "unevaluatedProperties" && value2 === false) {
      return [];
    }
    if (key2 === "unevaluatedItems" && value2 === false) {
      return [];
    }
    return [key2, value2];
  });
}
function getEffectiveObjectWithPropertiesSchema(schema7, data2, pointer) {
  const draft = new Draft07(schema7);
  const subSchema = draft.getSchema({
    pointer,
    data: data2 !== null && data2 !== void 0 ? data2 : void 0
  });
  if (!isRealSchema(subSchema)) {
    return void 0;
  }
  const possibleDirectPropertyNames = getAllPossibleDirectStaticPropertyNames(draft, subSchema);
  const effectiveProperties = {};
  for (let possibleDirectPropertyName of possibleDirectPropertyNames) {
    let propertyPointer = extendJsonPointer(pointer, possibleDirectPropertyName);
    const subSchemaForPropertyConsideringData = draft.getSchema({
      // TODO [performance] use subSchema and only check it's sub-properties
      pointer: propertyPointer,
      data: data2 !== null && data2 !== void 0 ? data2 : void 0
      // pointer: `/${possibleDirectPropertyName}`,
      // schema: subSchema
    });
    if (isRealSchema(subSchemaForPropertyConsideringData)) {
      Object.assign(effectiveProperties, {
        [possibleDirectPropertyName]: subSchemaForPropertyConsideringData
      });
    }
  }
  if (possibleDirectPropertyNames.length === 0 || Object.keys(effectiveProperties).length === 0) {
    return void 0;
  }
  const _a4 = subSchema, { allOf, anyOf, oneOf } = _a4, subSchemaRest = __rest2(_a4, ["allOf", "anyOf", "oneOf"]);
  return Object.assign(Object.assign({}, subSchemaRest), { properties: effectiveProperties });
}
function getAllPossibleDirectStaticPropertyNames(rootDraft, schema7) {
  schema7 = expandSchemaProperty(schema7, rootDraft.rootSchema);
  if (typeof schema7 !== "object" || schema7 == null) {
    return [];
  }
  const possiblePropertyNames = [];
  function addFrom(subSchema) {
    const possiblePropertyNamesOfSubSchema = getAllPossibleDirectStaticPropertyNames(rootDraft, subSchema);
    possiblePropertyNames.push(...possiblePropertyNamesOfSubSchema);
  }
  if (typeof schema7.properties === "object" && schema7.properties != null) {
    possiblePropertyNames.push(...Object.keys(schema7.properties));
  }
  if (typeof schema7.then === "object" && schema7.then != null) {
    addFrom(schema7.then);
  }
  if (Array.isArray(schema7.allOf)) {
    for (const subSchema of schema7.allOf) {
      addFrom(subSchema);
    }
  }
  if (Array.isArray(schema7.anyOf)) {
    for (const subSchema of schema7.anyOf) {
      addFrom(subSchema);
    }
  }
  if (Array.isArray(schema7.oneOf)) {
    for (const subSchema of schema7.oneOf) {
      addFrom(subSchema);
    }
  }
  return possiblePropertyNames;
}
function expandSchemaProperty(propertySchema, rootSchema) {
  if (typeof propertySchema === "object" && propertySchema.$ref) {
    const refSchema = getReferenceSchema(rootSchema, propertySchema.$ref);
    if (typeof refSchema === "object") {
      const dereferenced = Object.assign(Object.assign({}, propertySchema), refSchema);
      Reflect.deleteProperty(dereferenced, "$ref");
      return dereferenced;
    }
  }
  return propertySchema;
}
function getReferenceSchema(schema7, ref) {
  const refPath = ref.split("/");
  let curReference = schema7;
  refPath.forEach((cur2) => {
    if (!cur2) {
      return;
    }
    if (cur2 === "#") {
      curReference = schema7;
      return;
    }
    if (typeof curReference === "object") {
      curReference = curReference[cur2];
    }
  });
  return curReference;
}
function extendJsonPointer(pointer, key2) {
  return pointer === void 0 ? `/${key2}` : `${pointer}/${key2}`;
}

// node_modules/codemirror-json-schema/dist/utils/formatting.js
var joinWithOr = (arr, getPath2) => {
  const needsComma = arr.length > 2;
  let data2 = arr.map((err, i3) => {
    const result2 = `\`` + (getPath2 ? getPath2(err) : err) + `\``;
    if (i3 === arr.length - 1)
      return "or " + result2;
    return result2;
  });
  if (needsComma) {
    return data2.join(", ");
  }
  return data2.join(" ");
};

// node_modules/codemirror-json-schema/dist/features/validation.js
var getErrorPath = (error2) => {
  var _a4, _b, _c;
  if (((_a4 = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _a4 === void 0 ? void 0 : _a4.pointer) && ((_b = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _b === void 0 ? void 0 : _b.pointer) !== "#") {
    return error2.data.pointer.slice(1);
  }
  if ((_c = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _c === void 0 ? void 0 : _c.property) {
    return `/${error2.data.property}`;
  }
  return "";
};
var handleRefresh = (vu) => {
  return vu.startState.field(schemaStateField) !== vu.state.field(schemaStateField);
};
function jsonSchemaLinter(options2) {
  const validation = new JSONValidation(options2);
  return (view) => {
    return validation.doValidation(view);
  };
}
var positionalErrors = [
  "NoAdditionalPropertiesError",
  "RequiredPropertyError",
  "InvalidPropertyNameError",
  "ForbiddenPropertyError",
  "UndefinedValueError"
];
var JSONValidation = class {
  constructor(options2) {
    var _a4, _b, _c, _d;
    this.options = options2;
    this.schema = null;
    this.mode = MODES.JSON;
    this.rewriteError = (error2) => {
      var _a5, _b2, _c2, _d2, _e;
      const errorData = error2 === null || error2 === void 0 ? void 0 : error2.data;
      const errors3 = errorData === null || errorData === void 0 ? void 0 : errorData.errors;
      if (error2.code === "one-of-error" && (errors3 === null || errors3 === void 0 ? void 0 : errors3.length)) {
        return `Expected one of ${joinWithOr(errors3, (data2) => data2.data.expected)}`;
      }
      if (error2.code === "type-error") {
        return `Expected \`${((_a5 = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _a5 === void 0 ? void 0 : _a5.expected) && Array.isArray((_b2 = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _b2 === void 0 ? void 0 : _b2.expected) ? joinWithOr((_c2 = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _c2 === void 0 ? void 0 : _c2.expected) : (_d2 = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _d2 === void 0 ? void 0 : _d2.expected}\` but received \`${(_e = error2 === null || error2 === void 0 ? void 0 : error2.data) === null || _e === void 0 ? void 0 : _e.received}\``;
      }
      const message = error2.message.replaceAll("in `#` ", "").replaceAll("at `#`", "").replaceAll("/", ".").replaceAll("#.", "");
      return message;
    };
    this.mode = (_b = (_a4 = this.options) === null || _a4 === void 0 ? void 0 : _a4.mode) !== null && _b !== void 0 ? _b : MODES.JSON;
    this.parser = (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.jsonParser) !== null && _d !== void 0 ? _d : getDefaultParser(this.mode);
  }
  get schemaTitle() {
    var _a4, _b, _c;
    return (_c = (_b = (_a4 = this.schema) === null || _a4 === void 0 ? void 0 : _a4.getSchema()) === null || _b === void 0 ? void 0 : _b.title) !== null && _c !== void 0 ? _c : "json-schema";
  }
  // validate using view as the linter extension signature requires
  doValidation(view) {
    const schema7 = getJSONSchema(view.state);
    if (!schema7) {
      return [];
    }
    this.schema = new Draft04(schema7);
    if (!this.schema)
      return [];
    const text3 = view.state.doc.toString();
    if (!(text3 === null || text3 === void 0 ? void 0 : text3.length))
      return [];
    const json2 = this.parser(view.state);
    if (json2.data == null)
      return [];
    let errors3 = [];
    try {
      errors3 = this.schema.validate(json2.data);
    } catch (_a4) {
    }
    debug.log("xxx", "validation errors", errors3, json2.data);
    if (!errors3.length)
      return [];
    return errors3.reduce((acc, error2) => {
      const pushRoot = () => {
        const errorString = this.rewriteError(error2);
        acc.push({
          from: 0,
          to: 0,
          message: errorString,
          severity: "error",
          source: this.schemaTitle,
          renderMessage: () => {
            const dom = el("div", {});
            dom.innerHTML = renderMarkdown(errorString);
            return dom;
          }
        });
      };
      const errorPath = getErrorPath(error2);
      const pointer = json2.pointers.get(errorPath);
      if (error2.name === "MaxPropertiesError" || error2.name === "MinPropertiesError" || errorPath === "") {
        pushRoot();
      } else if (pointer) {
        const isKeyError = positionalErrors.includes(error2.name);
        const errorString = this.rewriteError(error2);
        const from2 = isKeyError ? pointer.keyFrom : pointer.valueFrom;
        const to = isKeyError ? pointer.keyTo : pointer.valueTo;
        if (to !== void 0 && from2 !== void 0) {
          acc.push({
            from: from2,
            to,
            message: errorString,
            renderMessage: () => {
              const dom = el("div", {});
              dom.innerHTML = renderMarkdown(errorString);
              return dom;
            },
            severity: "error",
            source: this.schemaTitle
          });
        }
      } else {
        pushRoot();
      }
      return acc;
    }, []);
  }
};

// public/app/ui/editors/options-editor/widgets/scalars.js
angular_default.module("kantree").component("optionsWidgetText", {
  template: `
    <input type="text" class="form-control" ng-required="$ctrl.isRequired" ng-attr-placeholder="{{$ctrl.options.placeholder}}"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)">
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
  }
});
angular_default.module("kantree").component("optionsWidgetTextarea", {
  template: `
    <textarea type="text" class="form-control" ng-required="$ctrl.isRequired" ng-model-options="{ debounce: $ctrl.debounce }"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      ng-attr-placeholder="{{$ctrl.options.placeholder}}">
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
      this.debounce = this.options.debounce || 0;
    }
  }
});
angular_default.module("kantree").component("optionsWidgetContent", {
  template: `
    <content-editor content="$ctrl.value" on-change="$ctrl.ngModel.$setViewValue($text)"
      ng-required="$ctrl.isRequired" ng-disabled="$ctrl.isDisabled" editor-data="$ctrl.editorData"
      editor-type="{{$ctrl.options.editor_type}}"></content-editor>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.editorData = {};
      if (this.options.project) {
        this.editorData.project_id = this.options.project.id;
      }
      if (this.options.card) {
        this.editorData.card_id = this.options.card.id;
      }
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
  }
});
angular_default.module("kantree").component("optionsWidgetNumber", {
  template: `
    <input type="number" class="form-control" ng-required="$ctrl.isRequired"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)">
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
  }
});
angular_default.module("kantree").component("optionsWidgetBool", {
  template: `
    <div class="form-check form-switch">
      <input class="form-check-input" type="checkbox" role="switch" ng-model="$ctrl.value"
        ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)" ng-disabled="$ctrl.isDisabled" id="{{::$ctrl.options.name}}">
      <label class="form-check-label" for="{{::$ctrl.options.name}}">{{::$ctrl.options.title}}</label>
    </div>
    `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || false;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
  }
});
angular_default.module("kantree").component("optionsWidgetArray", {
  template: `
    <textarea class="form-control" ng-list="&#10;" ng-trim="false" ng-required="$ctrl.isRequired"
      ng-model="$ctrl.value" ng-disabled="$ctrl.isDisabled" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)">
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || "";
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
  }
});
angular_default.module("kantree").component("optionsWidgetDropdown", {
  template: `
    <options-widget-select ng-model="$ctrl.value" ng-change="$ctrl.ngModel.$setViewValue($ctrl.value)"
      items="$ctrl.items" is-required="$ctrl.isRequired" is-disabled="$ctrl.isDisabled"></options-widget-select>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.items = this.options.items || null;
      this.ngModel.$render = () => {
        this.value = this.ngModel.$viewValue || null;
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.ngModel.$viewValue;
      });
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.items = this.options.items || null;
      }
    }
  }
});
angular_default.module("kantree").component("optionsWidgetJson", {
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      const container = this.$element[0];
      container.classList.add("form-control");
      container.classList.add("p-0");
      this.view = new EditorView({
        parent: container,
        doc: this.value,
        extensions: [
          foldGutter(),
          highlightSpecialChars(),
          history(),
          drawSelection(),
          dropCursor(),
          EditorState2.allowMultipleSelections.of(true),
          indentOnInput(),
          syntaxHighlighting(defaultHighlightStyle),
          bracketMatching(),
          closeBrackets(),
          rectangularSelection(),
          crosshairCursor(),
          highlightActiveLine(),
          highlightActiveLineGutter(),
          highlightSelectionMatches(),
          autocompletion(),
          keymap.of([
            ...closeBracketsKeymap,
            ...defaultKeymap,
            ...searchKeymap,
            ...historyKeymap,
            ...foldKeymap,
            ...completionKeymap,
            ...lintKeymap,
            indentWithTab
          ]),
          gutter({ class: "CodeMirror-lint-markers" }),
          lintGutter(),
          json(),
          linter(jsonParseLinter(), {
            delay: 750
            // default
          }),
          linter(jsonSchemaLinter(), {
            needsRefresh: handleRefresh
          }),
          jsonLanguage.data.of({
            autocomplete: jsonCompletion()
          }),
          stateExtensions({
            type: "object",
            properties: {
              example: {
                type: "boolean"
              }
            }
          }),
          EditorView.lineWrapping,
          EditorView.updateListener.of(function(e3) {
            if (e3.docChanged) {
              onChange(e3.state.doc.toString());
            }
          })
        ]
      });
      const onChange = (value2) => {
        const debounced = debounce2((value3) => {
          this.ngModel.$setViewValue(value3);
        }, this.options.debounce || 0);
        debounced(value2);
      };
      this.ngModel.$render = () => {
        this.view.dispatch({ changes: { from: 0, to: this.view.state.doc.length, insert: this.ngModel.$viewValue || "" } });
      };
    }
  }
});

// public/app/ui/editors/options-editor/widgets/scheduler.js
angular_default.module("kantree").component("optionsWidgetScheduler", {
  template: `
    <recurrence-editor recurrence="$ctrl.value" on-change="$ctrl.onChange($recurrence)"></recurrence-editor>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.ngModel.$render = () => {
        this.value = this.parseRecurrence(this.ngModel.$viewValue || "");
      };
      this.ngModel.$viewChangeListeners.push(() => {
        this.value = this.parseRecurrence(this.ngModel.$viewValue);
      });
    }
    parseRecurrence(value2) {
      return parseRecurrenceString(value2["schedule"], value2["time"]);
    }
    onChange(recurrence) {
      this.ngModel.$setViewValue(compressRecurrence(recurrence));
    }
  }
});

// public/app/ui/editors/options-editor/widgets/composite.js
angular_default.module("kantree").component("optionsWidgetList", {
  template: `
    <div class="options-widget-list">
      <div class="options-widget-list-item" ng-repeat="item in $ctrl.items track by $index">
        <options-editor-field option="$ctrl.valueOption" value="item.value" editable="!$ctrl.isDisabled"
          on-change="$ctrl.updateItem($index, $value)" hide-label="true" hide-description="true" compact="true">
        </options-editor-field>
        <button type="button" class="btn btn-sm btn-ghost text-danger" ng-click="$ctrl.removeItem($index)"
          ng-disabled="$ctrl.isDisabled" title="{{$ctrl.removeLabel}}"><i class="bi-x-lg"></i></button>
      </div>
      <button type="button" class="btn btn-sm btn-outline-secondary" ng-click="$ctrl.addItem()"
        ng-disabled="$ctrl.isDisabled"><i class="bi-plus"></i> {{$ctrl.addLabel}}</button>
    </div>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.items = [];
      this.valueOption = this.formatNestedOption(this.options.value);
      this.addLabel = _4("Add");
      this.removeLabel = _4("Remove");
      this.ngModel.$render = () => {
        const arr = this.ngModel.$viewValue || [];
        this.items = arr.map((v3) => ({ value: v3 }));
      };
      this.ngModel.$viewChangeListeners.push(() => {
        const arr = this.ngModel.$viewValue || [];
        this.items = arr.map((v3) => ({ value: v3 }));
      });
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.valueOption = this.formatNestedOption(this.options.value);
      }
    }
    /**
     * Format the nested option spec by injecting context (project, org, card)
     * into widget_options.
     */
    formatNestedOption(opt) {
      if (!opt) return { widget: "text", widget_options: {} };
      const formatted = { ...opt };
      formatted.widget_options = { ...formatted.widget_options || {} };
      if (this.options.project) {
        formatted.widget_options.project = this.options.project;
      }
      if (this.options.org) {
        formatted.widget_options.org = this.options.org;
      }
      if (this.options.card) {
        formatted.widget_options.card = this.options.card;
      }
      if (!formatted.widget) {
        formatted.widget = "text";
      }
      return formatted;
    }
    updateItem(index2, newValue) {
      this.items[index2].value = newValue;
      this.syncToModel();
    }
    addItem() {
      this.items.push({ value: this.valueOption.default || null });
      this.syncToModel();
    }
    removeItem(index2) {
      this.items.splice(index2, 1);
      this.syncToModel();
    }
    syncToModel() {
      this.ngModel.$setViewValue(this.items.map((item) => item.value));
    }
  }
});
angular_default.module("kantree").component("optionsWidgetMap", {
  template: `
    <div class="options-widget-map">
      <div class="options-widget-map-entry" ng-repeat="entry in $ctrl.items track by $index">
        <div class="options-widget-map-key">
          <options-editor-field option="$ctrl.keyOption" value="entry.key" editable="!$ctrl.isDisabled"
            on-change="$ctrl.updateKey($index, $value)" hide-label="true" hide-description="true" compact="true">
          </options-editor-field>
        </div>
        <div class="options-widget-map-value">
          <options-editor-field option="$ctrl.valueOption" value="entry.value" editable="!$ctrl.isDisabled"
            on-change="$ctrl.updateValue($index, $value)" hide-label="true" hide-description="true" compact="true">
          </options-editor-field>
        </div>
        <button type="button" class="btn btn-sm btn-ghost text-danger" ng-click="$ctrl.removeEntry($index)"
          ng-disabled="$ctrl.isDisabled" title="{{$ctrl.removeLabel}}"><i class="bi-x-lg"></i></button>
      </div>
      <button type="button" class="btn btn-sm btn-outline-secondary" ng-click="$ctrl.addEntry()"
        ng-disabled="$ctrl.isDisabled"><i class="bi-plus"></i> {{$ctrl.addLabel}}</button>
    </div>
  `,
  bindings: {
    options: "<",
    isRequired: "<?",
    isDisabled: "<?"
  },
  require: { ngModel: "?ngModel" },
  controller: class extends AngularClass {
    $onInit() {
      this.items = [];
      this.keyOption = this.formatNestedOption(this.options.key);
      this.valueOption = this.formatNestedOption(this.options.value);
      this.addLabel = _4("Add");
      this.removeLabel = _4("Remove");
      this.ngModel.$render = () => {
        const arr = this.ngModel.$viewValue || [];
        this.items = arr.map((tuple) => ({
          key: Array.isArray(tuple) ? tuple[0] : null,
          value: Array.isArray(tuple) ? tuple[1] : null
        }));
      };
      this.ngModel.$viewChangeListeners.push(() => {
        const arr = this.ngModel.$viewValue || [];
        this.items = arr.map((tuple) => ({
          key: Array.isArray(tuple) ? tuple[0] : null,
          value: Array.isArray(tuple) ? tuple[1] : null
        }));
      });
    }
    $onChanges(changes) {
      if (changes.options && !changes.options.isFirstChange()) {
        this.keyOption = this.formatNestedOption(this.options.key);
        this.valueOption = this.formatNestedOption(this.options.value);
      }
    }
    /**
     * Format the nested option spec by injecting context (project, org, card)
     * into widget_options.
     */
    formatNestedOption(opt) {
      if (!opt) return { widget: "text", widget_options: {} };
      const formatted = { ...opt };
      formatted.widget_options = { ...formatted.widget_options || {} };
      if (this.options.project) {
        formatted.widget_options.project = this.options.project;
      }
      if (this.options.org) {
        formatted.widget_options.org = this.options.org;
      }
      if (this.options.card) {
        formatted.widget_options.card = this.options.card;
      }
      if (!formatted.widget) {
        formatted.widget = "text";
      }
      return formatted;
    }
    updateKey(index2, newKey) {
      this.items[index2].key = newKey;
      this.syncToModel();
    }
    updateValue(index2, newValue) {
      this.items[index2].value = newValue;
      this.syncToModel();
    }
    addEntry() {
      this.items.push({
        key: this.keyOption.default || null,
        value: this.valueOption.default || null
      });
      this.syncToModel();
    }
    removeEntry(index2) {
      this.items.splice(index2, 1);
      this.syncToModel();
    }
    syncToModel() {
      this.ngModel.$setViewValue(this.items.map((entry) => [entry.key, entry.value]));
    }
  }
});

// public/app/ui/editors/prosemirror/pretty-menu-item.js
init_icons();
angular_default.module("kantree").factory("ProsemirrorPrettyMenuItem", [
  "$compile",
  function($compile) {
    return class {
      constructor(spec, parentScope) {
        this.spec = spec;
        this.parentScope = parentScope;
        this.parentScope.$on("$destroy", () => {
          if (this.scope) {
            this.scope.$destroy();
          }
          if (this.domElement) {
            this.domElement.remove();
            this.domElement = null;
          }
        });
      }
      // spec:: interface
      //
      // The configuration object that can be passed to a PrettyMenuItem.
      // It supports the following properties (only 'getMenu' is required).
      //
      //    getMenu:: (EditorView) => Object
      //    This is the prettyMenu factory that returns a prettyMenu config object
      //
      //    icon:: ?String
      //    Font Awesome icon name to use for the menu toggle button
      //
      //    dropConfig:: ?Object
      //    A Drop config Object
      //
      //    update:: (EditorState, EditorView, angular.dropMenuScope) => Any
      //    Called on any EditorState updates
      //
      //    onDropClosed:: (EditorView, angular.dropMenuScope) => Any
      //    Called when dropMenu is closed
      // :: (EditorView) => {dom: dom.Node, update: (EditorState)}
      // As other MenuItem (from prosemiror-menu library), we use render to
      // to display the menu item element in the DOM
      render(view) {
        if (this.scope) {
          this.scope.$destroy();
        }
        if (this.domElement) {
          this.domElement.remove();
        }
        this.scope = this.parentScope.$new();
        this.scope.menu = this.spec.getMenu(view);
        if (this.spec.onDropClosed) {
          this.scope.onDropClosed = this.spec.onDropClosed.bind(this, view, this.scope) || angular_default.noop;
        }
        if (this.spec.icon) {
          this.scope.icon = this.spec.icon;
        }
        if (this.spec.title) {
          this.scope.title = this.spec.title;
        }
        this.scope.dropConfig = this.spec.dropConfig || {};
        const compiledIcon = iconClass(this.scope.icon);
        this.domElement = $compile(`<div drop-menu="menu" drop-config="dropConfig" force-open="!!forceOpen" on-drop-closed="onDropClosed()"><div class="ProseMirror-icon" ng-if="icon" ng-attr-title="{{title}}"><i class="${compiledIcon}"></i></div></div>`)(this.scope);
        const update2 = (state) => {
          if (this.spec.update) {
            this.spec.update(state, view, this.scope);
          }
          return true;
        };
        return { dom: jquery_default(this.domElement).get(0), update: update2 };
      }
    };
  }
]);

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

// node_modules/prosemirror-markdown/dist/index.js
var import_markdown_it2 = __toESM(require_markdown_it(), 1);
var schema4 = new Schema({
  nodes: {
    doc: {
      content: "block+"
    },
    paragraph: {
      content: "inline*",
      group: "block",
      parseDOM: [{ tag: "p" }],
      toDOM() {
        return ["p", 0];
      }
    },
    blockquote: {
      content: "block+",
      group: "block",
      parseDOM: [{ tag: "blockquote" }],
      toDOM() {
        return ["blockquote", 0];
      }
    },
    horizontal_rule: {
      group: "block",
      parseDOM: [{ tag: "hr" }],
      toDOM() {
        return ["div", ["hr"]];
      }
    },
    heading: {
      attrs: { level: { default: 1 } },
      content: "(text | image)*",
      group: "block",
      defining: true,
      parseDOM: [
        { tag: "h1", attrs: { level: 1 } },
        { tag: "h2", attrs: { level: 2 } },
        { tag: "h3", attrs: { level: 3 } },
        { tag: "h4", attrs: { level: 4 } },
        { tag: "h5", attrs: { level: 5 } },
        { tag: "h6", attrs: { level: 6 } }
      ],
      toDOM(node) {
        return ["h" + node.attrs.level, 0];
      }
    },
    code_block: {
      content: "text*",
      group: "block",
      code: true,
      defining: true,
      marks: "",
      attrs: { params: { default: "" } },
      parseDOM: [{ tag: "pre", preserveWhitespace: "full", getAttrs: (node) => ({ params: node.getAttribute("data-params") || "" }) }],
      toDOM(node) {
        return ["pre", node.attrs.params ? { "data-params": node.attrs.params } : {}, ["code", 0]];
      }
    },
    ordered_list: {
      content: "list_item+",
      group: "block",
      attrs: { order: { default: 1 }, tight: { default: false } },
      parseDOM: [{ tag: "ol", getAttrs(dom) {
        return {
          order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1,
          tight: dom.hasAttribute("data-tight")
        };
      } }],
      toDOM(node) {
        return ["ol", {
          start: node.attrs.order == 1 ? null : node.attrs.order,
          "data-tight": node.attrs.tight ? "true" : null
        }, 0];
      }
    },
    bullet_list: {
      content: "list_item+",
      group: "block",
      attrs: { tight: { default: false } },
      parseDOM: [{ tag: "ul", getAttrs: (dom) => ({ tight: dom.hasAttribute("data-tight") }) }],
      toDOM(node) {
        return ["ul", { "data-tight": node.attrs.tight ? "true" : null }, 0];
      }
    },
    list_item: {
      content: "paragraph block*",
      defining: true,
      parseDOM: [{ tag: "li" }],
      toDOM() {
        return ["li", 0];
      }
    },
    text: {
      group: "inline"
    },
    image: {
      inline: true,
      attrs: {
        src: {},
        alt: { default: null },
        title: { default: null }
      },
      group: "inline",
      draggable: true,
      parseDOM: [{ tag: "img[src]", getAttrs(dom) {
        return {
          src: dom.getAttribute("src"),
          title: dom.getAttribute("title"),
          alt: dom.getAttribute("alt")
        };
      } }],
      toDOM(node) {
        return ["img", node.attrs];
      }
    },
    hard_break: {
      inline: true,
      group: "inline",
      selectable: false,
      parseDOM: [{ tag: "br" }],
      toDOM() {
        return ["br"];
      }
    }
  },
  marks: {
    em: {
      parseDOM: [
        { tag: "i" },
        { tag: "em" },
        { style: "font-style", getAttrs: (value2) => value2 == "italic" && null }
      ],
      toDOM() {
        return ["em"];
      }
    },
    strong: {
      parseDOM: [
        { tag: "b" },
        { tag: "strong" },
        { style: "font-weight", getAttrs: (value2) => /^(bold(er)?|[5-9]\d{2,})$/.test(value2) && null }
      ],
      toDOM() {
        return ["strong"];
      }
    },
    link: {
      attrs: {
        href: {},
        title: { default: null }
      },
      inclusive: false,
      parseDOM: [{ tag: "a[href]", getAttrs(dom) {
        return { href: dom.getAttribute("href"), title: dom.getAttribute("title") };
      } }],
      toDOM(node) {
        return ["a", node.attrs];
      }
    },
    code: {
      parseDOM: [{ tag: "code" }],
      toDOM() {
        return ["code"];
      }
    }
  }
});
function maybeMerge(a3, b3) {
  if (a3.isText && b3.isText && Mark.sameSet(a3.marks, b3.marks))
    return a3.withText(a3.text + b3.text);
}
var MarkdownParseState = class {
  constructor(schema7, tokenHandlers2) {
    this.schema = schema7;
    this.tokenHandlers = tokenHandlers2;
    this.stack = [{ type: schema7.topNodeType, attrs: null, content: [], marks: Mark.none }];
  }
  top() {
    return this.stack[this.stack.length - 1];
  }
  push(elt) {
    if (this.stack.length)
      this.top().content.push(elt);
  }
  // Adds the given text to the current position in the document,
  // using the current marks as styling.
  addText(text3) {
    if (!text3)
      return;
    let top2 = this.top(), nodes2 = top2.content, last3 = nodes2[nodes2.length - 1];
    let node = this.schema.text(text3, top2.marks), merged;
    if (last3 && (merged = maybeMerge(last3, node)))
      nodes2[nodes2.length - 1] = merged;
    else
      nodes2.push(node);
  }
  // Adds the given mark to the set of active marks.
  openMark(mark2) {
    let top2 = this.top();
    top2.marks = mark2.addToSet(top2.marks);
  }
  // Removes the given mark from the set of active marks.
  closeMark(mark2) {
    let top2 = this.top();
    top2.marks = mark2.removeFromSet(top2.marks);
  }
  parseTokens(toks) {
    for (let i3 = 0; i3 < toks.length; i3++) {
      let tok = toks[i3];
      let handler = this.tokenHandlers[tok.type];
      if (!handler)
        throw new Error("Token type `" + tok.type + "` not supported by Markdown parser");
      handler(this, tok, toks, i3);
    }
  }
  // Add a node at the current position.
  addNode(type, attrs2, content2) {
    let top2 = this.top();
    let node = type.createAndFill(attrs2, content2, top2 ? top2.marks : []);
    if (!node)
      return null;
    this.push(node);
    return node;
  }
  // Wrap subsequent content in a node of the given type.
  openNode(type, attrs2) {
    this.stack.push({ type, attrs: attrs2, content: [], marks: Mark.none });
  }
  // Close and return the node that is currently on top of the stack.
  closeNode() {
    let info = this.stack.pop();
    return this.addNode(info.type, info.attrs, info.content);
  }
};
function attrs(spec, token, tokens, i3) {
  if (spec.getAttrs)
    return spec.getAttrs(token, tokens, i3);
  else if (spec.attrs instanceof Function)
    return spec.attrs(token);
  else
    return spec.attrs;
}
function noCloseToken(spec, type) {
  return spec.noCloseToken || type == "code_inline" || type == "code_block" || type == "fence";
}
function withoutTrailingNewline(str) {
  return str[str.length - 1] == "\n" ? str.slice(0, str.length - 1) : str;
}
function noOp() {
}
function tokenHandlers(schema7, tokens) {
  let handlers3 = /* @__PURE__ */ Object.create(null);
  for (let type in tokens) {
    let spec = tokens[type];
    if (spec.block) {
      let nodeType = schema7.nodeType(spec.block);
      if (noCloseToken(spec, type)) {
        handlers3[type] = (state, tok, tokens2, i3) => {
          state.openNode(nodeType, attrs(spec, tok, tokens2, i3));
          state.addText(withoutTrailingNewline(tok.content));
          state.closeNode();
        };
      } else {
        handlers3[type + "_open"] = (state, tok, tokens2, i3) => state.openNode(nodeType, attrs(spec, tok, tokens2, i3));
        handlers3[type + "_close"] = (state) => state.closeNode();
      }
    } else if (spec.node) {
      let nodeType = schema7.nodeType(spec.node);
      handlers3[type] = (state, tok, tokens2, i3) => state.addNode(nodeType, attrs(spec, tok, tokens2, i3));
    } else if (spec.mark) {
      let markType = schema7.marks[spec.mark];
      if (noCloseToken(spec, type)) {
        handlers3[type] = (state, tok, tokens2, i3) => {
          state.openMark(markType.create(attrs(spec, tok, tokens2, i3)));
          state.addText(withoutTrailingNewline(tok.content));
          state.closeMark(markType);
        };
      } else {
        handlers3[type + "_open"] = (state, tok, tokens2, i3) => state.openMark(markType.create(attrs(spec, tok, tokens2, i3)));
        handlers3[type + "_close"] = (state) => state.closeMark(markType);
      }
    } else if (spec.ignore) {
      if (noCloseToken(spec, type)) {
        handlers3[type] = noOp;
      } else {
        handlers3[type + "_open"] = noOp;
        handlers3[type + "_close"] = noOp;
      }
    } else {
      throw new RangeError("Unrecognized parsing spec " + JSON.stringify(spec));
    }
  }
  handlers3.text = (state, tok) => state.addText(tok.content);
  handlers3.inline = (state, tok) => state.parseTokens(tok.children);
  handlers3.softbreak = handlers3.softbreak || ((state) => state.addText("\n"));
  return handlers3;
}
var MarkdownParser = class {
  /**
  Create a parser with the given configuration. You can configure
  the markdown-it parser to parse the dialect you want, and provide
  a description of the ProseMirror entities those tokens map to in
  the `tokens` object, which maps token names to descriptions of
  what to do with them. Such a description is an object, and may
  have the following properties:
  */
  constructor(schema7, tokenizer, tokens) {
    this.schema = schema7;
    this.tokenizer = tokenizer;
    this.tokens = tokens;
    this.tokenHandlers = tokenHandlers(schema7, tokens);
  }
  /**
  Parse a string as [CommonMark](http://commonmark.org/) markup,
  and create a ProseMirror document as prescribed by this parser's
  rules.
  */
  parse(text3) {
    let state = new MarkdownParseState(this.schema, this.tokenHandlers), doc4;
    state.parseTokens(this.tokenizer.parse(text3, {}));
    do {
      doc4 = state.closeNode();
    } while (state.stack.length);
    return doc4 || this.schema.topNodeType.createAndFill();
  }
};
function listIsTight(tokens, i3) {
  while (++i3 < tokens.length)
    if (tokens[i3].type != "list_item_open")
      return tokens[i3].hidden;
  return false;
}
var defaultMarkdownParser = new MarkdownParser(schema4, (0, import_markdown_it2.default)("commonmark", { html: false }), {
  blockquote: { block: "blockquote" },
  paragraph: { block: "paragraph" },
  list_item: { block: "list_item" },
  bullet_list: { block: "bullet_list", getAttrs: (_5, tokens, i3) => ({ tight: listIsTight(tokens, i3) }) },
  ordered_list: { block: "ordered_list", getAttrs: (tok, tokens, i3) => ({
    order: +tok.attrGet("start") || 1,
    tight: listIsTight(tokens, i3)
  }) },
  heading: { block: "heading", getAttrs: (tok) => ({ level: +tok.tag.slice(1) }) },
  code_block: { block: "code_block", noCloseToken: true },
  fence: { block: "code_block", getAttrs: (tok) => ({ params: tok.info || "" }), noCloseToken: true },
  hr: { node: "horizontal_rule" },
  image: { node: "image", getAttrs: (tok) => ({
    src: tok.attrGet("src"),
    title: tok.attrGet("title") || null,
    alt: tok.children[0] && tok.children[0].content || null
  }) },
  hardbreak: { node: "hard_break" },
  em: { mark: "em" },
  strong: { mark: "strong" },
  link: { mark: "link", getAttrs: (tok) => ({
    href: tok.attrGet("href"),
    title: tok.attrGet("title") || null
  }) },
  code_inline: { mark: "code", noCloseToken: true }
});
var MarkdownSerializer = class {
  /**
  Construct a serializer with the given configuration. The `nodes`
  object should map node names in a given schema to function that
  take a serializer state and such a node, and serialize the node.
  */
  constructor(nodes2, marks3, options2 = {}) {
    this.nodes = nodes2;
    this.marks = marks3;
    this.options = options2;
  }
  /**
  Serialize the content of the given node to
  [CommonMark](http://commonmark.org/).
  */
  serialize(content2, options2 = {}) {
    options2 = Object.assign(this.options, options2);
    let state = new MarkdownSerializerState(this.nodes, this.marks, options2);
    state.renderContent(content2);
    return state.out;
  }
};
var defaultMarkdownSerializer = new MarkdownSerializer({
  blockquote(state, node) {
    state.wrapBlock("> ", null, node, () => state.renderContent(node));
  },
  code_block(state, node) {
    state.write("```" + (node.attrs.params || "") + "\n");
    state.text(node.textContent, false);
    state.ensureNewLine();
    state.write("```");
    state.closeBlock(node);
  },
  heading(state, node) {
    state.write(state.repeat("#", node.attrs.level) + " ");
    state.renderInline(node);
    state.closeBlock(node);
  },
  horizontal_rule(state, node) {
    state.write(node.attrs.markup || "---");
    state.closeBlock(node);
  },
  bullet_list(state, node) {
    state.renderList(node, "  ", () => (node.attrs.bullet || "*") + " ");
  },
  ordered_list(state, node) {
    let start = node.attrs.order || 1;
    let maxW = String(start + node.childCount - 1).length;
    let space = state.repeat(" ", maxW + 2);
    state.renderList(node, space, (i3) => {
      let nStr = String(start + i3);
      return state.repeat(" ", maxW - nStr.length) + nStr + ". ";
    });
  },
  list_item(state, node) {
    state.renderContent(node);
  },
  paragraph(state, node) {
    state.renderInline(node);
    state.closeBlock(node);
  },
  image(state, node) {
    state.write("![" + state.esc(node.attrs.alt || "") + "](" + node.attrs.src.replace(/[\(\)]/g, "\\$&") + (node.attrs.title ? ' "' + node.attrs.title.replace(/"/g, '\\"') + '"' : "") + ")");
  },
  hard_break(state, node, parent, index2) {
    for (let i3 = index2 + 1; i3 < parent.childCount; i3++)
      if (parent.child(i3).type != node.type) {
        state.write("\\\n");
        return;
      }
  },
  text(state, node) {
    state.text(node.text, !state.inAutolink);
  }
}, {
  em: { open: "*", close: "*", mixable: true, expelEnclosingWhitespace: true },
  strong: { open: "**", close: "**", mixable: true, expelEnclosingWhitespace: true },
  link: {
    open(state, mark2, parent, index2) {
      state.inAutolink = isPlainURL(mark2, parent, index2);
      return state.inAutolink ? "<" : "[";
    },
    close(state, mark2, parent, index2) {
      let { inAutolink } = state;
      state.inAutolink = void 0;
      return inAutolink ? ">" : "](" + mark2.attrs.href.replace(/[\(\)"]/g, "\\$&") + (mark2.attrs.title ? ` "${mark2.attrs.title.replace(/"/g, '\\"')}"` : "") + ")";
    },
    mixable: true
  },
  code: {
    open(_state, _mark, parent, index2) {
      return backticksFor(parent.child(index2), -1);
    },
    close(_state, _mark, parent, index2) {
      return backticksFor(parent.child(index2 - 1), 1);
    },
    escape: false
  }
});
function backticksFor(node, side) {
  let ticks = /`+/g, m3, len = 0;
  if (node.isText)
    while (m3 = ticks.exec(node.text))
      len = Math.max(len, m3[0].length);
  let result2 = len > 0 && side > 0 ? " `" : "`";
  for (let i3 = 0; i3 < len; i3++)
    result2 += "`";
  if (len > 0 && side < 0)
    result2 += " ";
  return result2;
}
function isPlainURL(link2, parent, index2) {
  if (link2.attrs.title || !/^\w+:/.test(link2.attrs.href))
    return false;
  let content2 = parent.child(index2);
  if (!content2.isText || content2.text != link2.attrs.href || content2.marks[content2.marks.length - 1] != link2)
    return false;
  return index2 == parent.childCount - 1 || !link2.isInSet(parent.child(index2 + 1).marks);
}
var MarkdownSerializerState = class {
  /**
  @internal
  */
  constructor(nodes2, marks3, options2) {
    this.nodes = nodes2;
    this.marks = marks3;
    this.options = options2;
    this.delim = "";
    this.out = "";
    this.closed = null;
    this.inAutolink = void 0;
    this.atBlockStart = false;
    this.inTightList = false;
    if (typeof this.options.tightLists == "undefined")
      this.options.tightLists = false;
  }
  /**
  @internal
  */
  flushClose(size4 = 2) {
    if (this.closed) {
      if (!this.atBlank())
        this.out += "\n";
      if (size4 > 1) {
        let delimMin = this.delim;
        let trim = /\s+$/.exec(delimMin);
        if (trim)
          delimMin = delimMin.slice(0, delimMin.length - trim[0].length);
        for (let i3 = 1; i3 < size4; i3++)
          this.out += delimMin + "\n";
      }
      this.closed = null;
    }
  }
  /**
  Render a block, prefixing each line with `delim`, and the first
  line in `firstDelim`. `node` should be the node that is closed at
  the end of the block, and `f` is a function that renders the
  content of the block.
  */
  wrapBlock(delim, firstDelim, node, f3) {
    let old = this.delim;
    this.write(firstDelim || delim);
    this.delim += delim;
    f3();
    this.delim = old;
    this.closeBlock(node);
  }
  /**
  @internal
  */
  atBlank() {
    return /(^|\n)$/.test(this.out);
  }
  /**
  Ensure the current content ends with a newline.
  */
  ensureNewLine() {
    if (!this.atBlank())
      this.out += "\n";
  }
  /**
  Prepare the state for writing output (closing closed paragraphs,
  adding delimiters, and so on), and then optionally add content
  (unescaped) to the output.
  */
  write(content2) {
    this.flushClose();
    if (this.delim && this.atBlank())
      this.out += this.delim;
    if (content2)
      this.out += content2;
  }
  /**
  Close the block for the given node.
  */
  closeBlock(node) {
    this.closed = node;
  }
  /**
  Add the given text to the document. When escape is not `false`,
  it will be escaped.
  */
  text(text3, escape4 = true) {
    let lines = text3.split("\n");
    for (let i3 = 0; i3 < lines.length; i3++) {
      this.write();
      if (!escape4 && lines[i3][0] == "[" && /(^|[^\\])\!$/.test(this.out))
        this.out = this.out.slice(0, this.out.length - 1) + "\\!";
      this.out += escape4 ? this.esc(lines[i3], this.atBlockStart) : lines[i3];
      if (i3 != lines.length - 1)
        this.out += "\n";
    }
  }
  /**
  Render the given node as a block.
  */
  render(node, parent, index2) {
    if (typeof parent == "number")
      throw new Error("!");
    if (!this.nodes[node.type.name])
      throw new Error("Token type `" + node.type.name + "` not supported by Markdown renderer");
    this.nodes[node.type.name](this, node, parent, index2);
  }
  /**
  Render the contents of `parent` as block nodes.
  */
  renderContent(parent) {
    parent.forEach((node, _5, i3) => this.render(node, parent, i3));
  }
  /**
  Render the contents of `parent` as inline content.
  */
  renderInline(parent) {
    this.atBlockStart = true;
    let active = [], trailing = "";
    let progress2 = (node, offset, index2) => {
      let marks3 = node ? node.marks : [];
      if (node && node.type.name === "hard_break")
        marks3 = marks3.filter((m3) => {
          if (index2 + 1 == parent.childCount)
            return false;
          let next2 = parent.child(index2 + 1);
          return m3.isInSet(next2.marks) && (!next2.isText || /\S/.test(next2.text));
        });
      let leading = trailing;
      trailing = "";
      if (node && node.isText && marks3.some((mark2) => {
        let info = this.marks[mark2.type.name];
        return info && info.expelEnclosingWhitespace && !(mark2.isInSet(active) || index2 < parent.childCount - 1 && mark2.isInSet(parent.child(index2 + 1).marks));
      })) {
        let [_5, lead, inner2, trail] = /^(\s*)(.*?)(\s*)$/m.exec(node.text);
        leading += lead;
        trailing = trail;
        if (lead || trail) {
          node = inner2 ? node.withText(inner2) : null;
          if (!node)
            marks3 = active;
        }
      }
      let inner = marks3.length ? marks3[marks3.length - 1] : null;
      let noEsc = inner && this.marks[inner.type.name].escape === false;
      let len = marks3.length - (noEsc ? 1 : 0);
      outer: for (let i3 = 0; i3 < len; i3++) {
        let mark2 = marks3[i3];
        if (!this.marks[mark2.type.name].mixable)
          break;
        for (let j = 0; j < active.length; j++) {
          let other = active[j];
          if (!this.marks[other.type.name].mixable)
            break;
          if (mark2.eq(other)) {
            if (i3 > j)
              marks3 = marks3.slice(0, j).concat(mark2).concat(marks3.slice(j, i3)).concat(marks3.slice(i3 + 1, len));
            else if (j > i3)
              marks3 = marks3.slice(0, i3).concat(marks3.slice(i3 + 1, j)).concat(mark2).concat(marks3.slice(j, len));
            continue outer;
          }
        }
      }
      let keep = 0;
      while (keep < Math.min(active.length, len) && marks3[keep].eq(active[keep]))
        ++keep;
      while (keep < active.length)
        this.text(this.markString(active.pop(), false, parent, index2), false);
      if (leading)
        this.text(leading);
      if (node) {
        while (active.length < len) {
          let add4 = marks3[active.length];
          active.push(add4);
          this.text(this.markString(add4, true, parent, index2), false);
        }
        if (noEsc && node.isText)
          this.text(this.markString(inner, true, parent, index2) + node.text + this.markString(inner, false, parent, index2 + 1), false);
        else
          this.render(node, parent, index2);
      }
    };
    parent.forEach(progress2);
    progress2(null, 0, parent.childCount);
    this.atBlockStart = false;
  }
  /**
  Render a node's content as a list. `delim` should be the extra
  indentation added to all lines except the first in an item,
  `firstDelim` is a function going from an item index to a
  delimiter for the first line of the item.
  */
  renderList(node, delim, firstDelim) {
    if (this.closed && this.closed.type == node.type)
      this.flushClose(3);
    else if (this.inTightList)
      this.flushClose(1);
    let isTight = typeof node.attrs.tight != "undefined" ? node.attrs.tight : this.options.tightLists;
    let prevTight = this.inTightList;
    this.inTightList = isTight;
    node.forEach((child, _5, i3) => {
      if (i3 && isTight)
        this.flushClose(1);
      this.wrapBlock(delim, firstDelim(i3), node, () => this.render(child, node, i3));
    });
    this.inTightList = prevTight;
  }
  /**
  Escape the given string so that it can safely appear in Markdown
  content. If `startOfLine` is true, also escape characters that
  have special meaning only at the start of the line.
  */
  esc(str, startOfLine = false) {
    str = str.replace(/[`*\\~\[\]_]/g, (m3, i3) => m3 == "_" && i3 > 0 && i3 + 1 < str.length && str[i3 - 1].match(/\w/) && str[i3 + 1].match(/\w/) ? m3 : "\\" + m3);
    if (startOfLine)
      str = str.replace(/^[#\-*+>]/, "\\$&").replace(/^(\s*\d+)\./, "$1\\.");
    if (this.options.escapeExtraCharacters)
      str = str.replace(this.options.escapeExtraCharacters, "\\$&");
    return str;
  }
  /**
  @internal
  */
  quote(str) {
    let wrap4 = str.indexOf('"') == -1 ? '""' : str.indexOf("'") == -1 ? "''" : "()";
    return wrap4[0] + str + wrap4[1];
  }
  /**
  Repeat the given string `n` times.
  */
  repeat(str, n4) {
    let out = "";
    for (let i3 = 0; i3 < n4; i3++)
      out += str;
    return out;
  }
  /**
  Get the markdown string for a given opening or closing mark.
  */
  markString(mark2, open, parent, index2) {
    let info = this.marks[mark2.type.name];
    let value2 = open ? info.open : info.close;
    return typeof value2 == "string" ? value2 : value2(this, mark2, parent, index2);
  }
  /**
  Get leading and trailing whitespace from a string. Values of
  leading or trailing property of the return object will be undefined
  if there is no match.
  */
  getEnclosingWhitespace(text3) {
    return {
      leading: (text3.match(/^(\s+)/) || [void 0])[0],
      trailing: (text3.match(/(\s+)$/) || [void 0])[0]
    };
  }
};

// node_modules/prosemirror-commands/dist/index.js
var deleteSelection = (state, dispatch) => {
  if (state.selection.empty)
    return false;
  if (dispatch)
    dispatch(state.tr.deleteSelection().scrollIntoView());
  return true;
};
var joinBackward = (state, dispatch, view) => {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
    return false;
  let $cut = findCutBefore($cursor);
  if (!$cut) {
    let range2 = $cursor.blockRange(), target = range2 && liftTarget(range2);
    if (target == null)
      return false;
    if (dispatch)
      dispatch(state.tr.lift(range2, target).scrollIntoView());
    return true;
  }
  let before2 = $cut.nodeBefore;
  if (!before2.type.spec.isolating && deleteBarrier(state, $cut, dispatch))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(before2, "end") || NodeSelection.isSelectable(before2))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr2 = state.tr.step(delStep);
        tr2.setSelection(textblockAt(before2, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before2.nodeSize));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  if (before2.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos - before2.nodeSize, $cut.pos).scrollIntoView());
    return true;
  }
  return false;
};
function textblockAt(node, side, only = false) {
  for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
    if (scan.isTextblock)
      return true;
    if (only && scan.childCount != 1)
      return false;
  }
  return false;
}
var selectNodeBackward = (state, dispatch, view) => {
  let { $head, empty: empty4 } = state.selection, $cut = $head;
  if (!empty4)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
      return false;
    $cut = findCutBefore($head);
  }
  let node = $cut && $cut.nodeBefore;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
  return true;
};
function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i3 = $pos.depth - 1; i3 >= 0; i3--) {
      if ($pos.index(i3) > 0)
        return $pos.doc.resolve($pos.before(i3 + 1));
      if ($pos.node(i3).type.spec.isolating)
        break;
    }
  return null;
}
var joinForward = (state, dispatch, view) => {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
    return false;
  let $cut = findCutAfter($cursor);
  if (!$cut)
    return false;
  let after2 = $cut.nodeAfter;
  if (deleteBarrier(state, $cut, dispatch))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(after2, "start") || NodeSelection.isSelectable(after2))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr2 = state.tr.step(delStep);
        tr2.setSelection(textblockAt(after2, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos)));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  if (after2.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos, $cut.pos + after2.nodeSize).scrollIntoView());
    return true;
  }
  return false;
};
var selectNodeForward = (state, dispatch, view) => {
  let { $head, empty: empty4 } = state.selection, $cut = $head;
  if (!empty4)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
      return false;
    $cut = findCutAfter($head);
  }
  let node = $cut && $cut.nodeAfter;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  return true;
};
function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i3 = $pos.depth - 1; i3 >= 0; i3--) {
      let parent = $pos.node(i3);
      if ($pos.index(i3) + 1 < parent.childCount)
        return $pos.doc.resolve($pos.after(i3 + 1));
      if (parent.type.spec.isolating)
        break;
    }
  return null;
}
var joinUp = (state, dispatch) => {
  let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;
  if (nodeSel) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.from))
      return false;
    point = sel.from;
  } else {
    point = joinPoint(state.doc, sel.from, -1);
    if (point == null)
      return false;
  }
  if (dispatch) {
    let tr2 = state.tr.join(point);
    if (nodeSel)
      tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var joinDown = (state, dispatch) => {
  let sel = state.selection, point;
  if (sel instanceof NodeSelection) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.to))
      return false;
    point = sel.to;
  } else {
    point = joinPoint(state.doc, sel.to, 1);
    if (point == null)
      return false;
  }
  if (dispatch)
    dispatch(state.tr.join(point).scrollIntoView());
  return true;
};
var lift2 = (state, dispatch) => {
  let { $from, $to } = state.selection;
  let range2 = $from.blockRange($to), target = range2 && liftTarget(range2);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range2, target).scrollIntoView());
  return true;
};
var newlineInCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  if (dispatch)
    dispatch(state.tr.insertText("\n").scrollIntoView());
  return true;
};
function defaultBlockAt(match2) {
  for (let i3 = 0; i3 < match2.edgeCount; i3++) {
    let { type } = match2.edge(i3);
    if (type.isTextblock && !type.hasRequiredAttrs())
      return type;
  }
  return null;
}
var exitCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  let above = $head.node(-1), after2 = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after2));
  if (!type || !above.canReplaceWith(after2, after2, type))
    return false;
  if (dispatch) {
    let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var createParagraphNear = (state, dispatch) => {
  let sel = state.selection, { $from, $to } = sel;
  if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
    return false;
  let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
  if (!type || !type.isTextblock)
    return false;
  if (dispatch) {
    let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    let tr2 = state.tr.insert(side, type.createAndFill());
    tr2.setSelection(TextSelection.create(tr2.doc, side + 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var liftEmptyBlock = (state, dispatch) => {
  let { $cursor } = state.selection;
  if (!$cursor || $cursor.parent.content.size)
    return false;
  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    let before2 = $cursor.before();
    if (canSplit(state.doc, before2)) {
      if (dispatch)
        dispatch(state.tr.split(before2).scrollIntoView());
      return true;
    }
  }
  let range2 = $cursor.blockRange(), target = range2 && liftTarget(range2);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range2, target).scrollIntoView());
  return true;
};
var splitBlock = (state, dispatch) => {
  let { $from, $to } = state.selection;
  if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
    if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
      return false;
    if (dispatch)
      dispatch(state.tr.split($from.pos).scrollIntoView());
    return true;
  }
  if (!$from.parent.isBlock)
    return false;
  if (dispatch) {
    let atEnd = $to.parentOffset == $to.parent.content.size;
    let tr2 = state.tr;
    if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
      tr2.deleteSelection();
    let deflt = $from.depth == 0 ? null : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
    let types2 = atEnd && deflt ? [{ type: deflt }] : void 0;
    let can = canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, types2);
    if (!types2 && !can && canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
      if (deflt)
        types2 = [{ type: deflt }];
      can = true;
    }
    if (can) {
      tr2.split(tr2.mapping.map($from.pos), 1, types2);
      if (!atEnd && !$from.parentOffset && $from.parent.type != deflt) {
        let first2 = tr2.mapping.map($from.before()), $first = tr2.doc.resolve(first2);
        if (deflt && $from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt))
          tr2.setNodeMarkup(tr2.mapping.map($from.before()), deflt);
      }
    }
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var selectParentNode = (state, dispatch) => {
  let { $from, to } = state.selection, pos;
  let same = $from.sharedDepth(to);
  if (same == 0)
    return false;
  pos = $from.before(same);
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));
  return true;
};
var selectAll2 = (state, dispatch) => {
  if (dispatch)
    dispatch(state.tr.setSelection(new AllSelection(state.doc)));
  return true;
};
function joinMaybeClear(state, $pos, dispatch) {
  let before2 = $pos.nodeBefore, after2 = $pos.nodeAfter, index2 = $pos.index();
  if (!before2 || !after2 || !before2.type.compatibleContent(after2.type))
    return false;
  if (!before2.content.size && $pos.parent.canReplace(index2 - 1, index2)) {
    if (dispatch)
      dispatch(state.tr.delete($pos.pos - before2.nodeSize, $pos.pos).scrollIntoView());
    return true;
  }
  if (!$pos.parent.canReplace(index2, index2 + 1) || !(after2.isTextblock || canJoin(state.doc, $pos.pos)))
    return false;
  if (dispatch)
    dispatch(state.tr.clearIncompatible($pos.pos, before2.type, before2.contentMatchAt(before2.childCount)).join($pos.pos).scrollIntoView());
  return true;
}
function deleteBarrier(state, $cut, dispatch) {
  let before2 = $cut.nodeBefore, after2 = $cut.nodeAfter, conn, match2;
  if (before2.type.spec.isolating || after2.type.spec.isolating)
    return false;
  if (joinMaybeClear(state, $cut, dispatch))
    return true;
  let canDelAfter = $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  if (canDelAfter && (conn = (match2 = before2.contentMatchAt(before2.childCount)).findWrapping(after2.type)) && match2.matchType(conn[0] || after2.type).validEnd) {
    if (dispatch) {
      let end = $cut.pos + after2.nodeSize, wrap4 = Fragment.empty;
      for (let i3 = conn.length - 1; i3 >= 0; i3--)
        wrap4 = Fragment.from(conn[i3].create(null, wrap4));
      wrap4 = Fragment.from(before2.copy(wrap4));
      let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap4, 1, 0), conn.length, true));
      let joinAt = end + 2 * conn.length;
      if (canJoin(tr2.doc, joinAt))
        tr2.join(joinAt);
      dispatch(tr2.scrollIntoView());
    }
    return true;
  }
  let selAfter = Selection.findFrom($cut, 1);
  let range2 = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range2 && liftTarget(range2);
  if (target != null && target >= $cut.depth) {
    if (dispatch)
      dispatch(state.tr.lift(range2, target).scrollIntoView());
    return true;
  }
  if (canDelAfter && textblockAt(after2, "start", true) && textblockAt(before2, "end")) {
    let at = before2, wrap4 = [];
    for (; ; ) {
      wrap4.push(at);
      if (at.isTextblock)
        break;
      at = at.lastChild;
    }
    let afterText = after2, afterDepth = 1;
    for (; !afterText.isTextblock; afterText = afterText.firstChild)
      afterDepth++;
    if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
      if (dispatch) {
        let end = Fragment.empty;
        for (let i3 = wrap4.length - 1; i3 >= 0; i3--)
          end = Fragment.from(wrap4[i3].copy(end));
        let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap4.length, $cut.pos + after2.nodeSize, $cut.pos + afterDepth, $cut.pos + after2.nodeSize - afterDepth, new Slice(end, wrap4.length, 0), 0, true));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  return false;
}
function selectTextblockSide(side) {
  return function(state, dispatch) {
    let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
    let depth2 = $pos.depth;
    while ($pos.node(depth2).isInline) {
      if (!depth2)
        return false;
      depth2--;
    }
    if (!$pos.node(depth2).isTextblock)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth2) : $pos.end(depth2))));
    return true;
  };
}
var selectTextblockStart = selectTextblockSide(-1);
var selectTextblockEnd = selectTextblockSide(1);
function wrapIn(nodeType, attrs2 = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to), wrapping = range2 && findWrapping(range2, nodeType, attrs2);
    if (!wrapping)
      return false;
    if (dispatch)
      dispatch(state.tr.wrap(range2, wrapping).scrollIntoView());
    return true;
  };
}
function setBlockType2(nodeType, attrs2 = null) {
  return function(state, dispatch) {
    let { from: from2, to } = state.selection;
    let applicable = false;
    state.doc.nodesBetween(from2, to, (node, pos) => {
      if (applicable)
        return false;
      if (!node.isTextblock || node.hasMarkup(nodeType, attrs2))
        return;
      if (node.type == nodeType) {
        applicable = true;
      } else {
        let $pos = state.doc.resolve(pos), index2 = $pos.index();
        applicable = $pos.parent.canReplaceWith(index2, index2 + 1, nodeType);
      }
    });
    if (!applicable)
      return false;
    if (dispatch)
      dispatch(state.tr.setBlockType(from2, to, nodeType, attrs2).scrollIntoView());
    return true;
  };
}
function markApplies(doc4, ranges, type) {
  for (let i3 = 0; i3 < ranges.length; i3++) {
    let { $from, $to } = ranges[i3];
    let can = $from.depth == 0 ? doc4.inlineContent && doc4.type.allowsMarkType(type) : false;
    doc4.nodesBetween($from.pos, $to.pos, (node) => {
      if (can)
        return false;
      can = node.inlineContent && node.type.allowsMarkType(type);
    });
    if (can)
      return true;
  }
  return false;
}
function toggleMark(markType, attrs2 = null) {
  return function(state, dispatch) {
    let { empty: empty4, $cursor, ranges } = state.selection;
    if (empty4 && !$cursor || !markApplies(state.doc, ranges, markType))
      return false;
    if (dispatch) {
      if ($cursor) {
        if (markType.isInSet(state.storedMarks || $cursor.marks()))
          dispatch(state.tr.removeStoredMark(markType));
        else
          dispatch(state.tr.addStoredMark(markType.create(attrs2)));
      } else {
        let has4 = false, tr2 = state.tr;
        for (let i3 = 0; !has4 && i3 < ranges.length; i3++) {
          let { $from, $to } = ranges[i3];
          has4 = state.doc.rangeHasMark($from.pos, $to.pos, markType);
        }
        for (let i3 = 0; i3 < ranges.length; i3++) {
          let { $from, $to } = ranges[i3];
          if (has4) {
            tr2.removeMark($from.pos, $to.pos, markType);
          } else {
            let from2 = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;
            let spaceStart = start && start.isText ? /^\s*/.exec(start.text)[0].length : 0;
            let spaceEnd = end && end.isText ? /\s*$/.exec(end.text)[0].length : 0;
            if (from2 + spaceStart < to) {
              from2 += spaceStart;
              to -= spaceEnd;
            }
            tr2.addMark(from2, to, markType.create(attrs2));
          }
        }
        dispatch(tr2.scrollIntoView());
      }
    }
    return true;
  };
}
function chainCommands(...commands) {
  return function(state, dispatch, view) {
    for (let i3 = 0; i3 < commands.length; i3++)
      if (commands[i3](state, dispatch, view))
        return true;
    return false;
  };
}
var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
var del = chainCommands(deleteSelection, joinForward, selectNodeForward);
var pcBaseKeymap = {
  "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
  "Mod-Enter": exitCode,
  "Backspace": backspace,
  "Mod-Backspace": backspace,
  "Shift-Backspace": backspace,
  "Delete": del,
  "Mod-Delete": del,
  "Mod-a": selectAll2
};
var macBaseKeymap = {
  "Ctrl-h": pcBaseKeymap["Backspace"],
  "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  "Ctrl-d": pcBaseKeymap["Delete"],
  "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  "Alt-d": pcBaseKeymap["Mod-Delete"],
  "Ctrl-a": selectTextblockStart,
  "Ctrl-e": selectTextblockEnd
};
for (let key2 in pcBaseKeymap)
  macBaseKeymap[key2] = pcBaseKeymap[key2];
var mac3 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
var baseKeymap = mac3 ? macBaseKeymap : pcBaseKeymap;

// node_modules/rope-sequence/dist/index.es.js
var GOOD_LEAF_SIZE = 200;
var RopeSequence = function RopeSequence2() {
};
RopeSequence.prototype.append = function append(other) {
  if (!other.length) {
    return this;
  }
  other = RopeSequence.from(other);
  return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
};
RopeSequence.prototype.prepend = function prepend(other) {
  if (!other.length) {
    return this;
  }
  return RopeSequence.from(other).append(this);
};
RopeSequence.prototype.appendInner = function appendInner(other) {
  return new Append(this, other);
};
RopeSequence.prototype.slice = function slice2(from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 >= to) {
    return RopeSequence.empty;
  }
  return this.sliceInner(Math.max(0, from2), Math.min(this.length, to));
};
RopeSequence.prototype.get = function get6(i3) {
  if (i3 < 0 || i3 >= this.length) {
    return void 0;
  }
  return this.getInner(i3);
};
RopeSequence.prototype.forEach = function forEach3(f3, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 <= to) {
    this.forEachInner(f3, from2, to, 0);
  } else {
    this.forEachInvertedInner(f3, from2, to, 0);
  }
};
RopeSequence.prototype.map = function map4(f3, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  var result2 = [];
  this.forEach(function(elt, i3) {
    return result2.push(f3(elt, i3));
  }, from2, to);
  return result2;
};
RopeSequence.from = function from(values2) {
  if (values2 instanceof RopeSequence) {
    return values2;
  }
  return values2 && values2.length ? new Leaf(values2) : RopeSequence.empty;
};
var Leaf = /* @__PURE__ */ function(RopeSequence3) {
  function Leaf2(values2) {
    RopeSequence3.call(this);
    this.values = values2;
  }
  if (RopeSequence3) Leaf2.__proto__ = RopeSequence3;
  Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Leaf2.prototype.constructor = Leaf2;
  var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } };
  Leaf2.prototype.flatten = function flatten4() {
    return this.values;
  };
  Leaf2.prototype.sliceInner = function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    return new Leaf2(this.values.slice(from2, to));
  };
  Leaf2.prototype.getInner = function getInner(i3) {
    return this.values[i3];
  };
  Leaf2.prototype.forEachInner = function forEachInner(f3, from2, to, start) {
    for (var i3 = from2; i3 < to; i3++) {
      if (f3(this.values[i3], start + i3) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f3, from2, to, start) {
    for (var i3 = from2 - 1; i3 >= to; i3--) {
      if (f3(this.values[i3], start + i3) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.leafAppend = function leafAppend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(this.values.concat(other.flatten()));
    }
  };
  Leaf2.prototype.leafPrepend = function leafPrepend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(other.flatten().concat(this.values));
    }
  };
  prototypeAccessors.length.get = function() {
    return this.values.length;
  };
  prototypeAccessors.depth.get = function() {
    return 0;
  };
  Object.defineProperties(Leaf2.prototype, prototypeAccessors);
  return Leaf2;
}(RopeSequence);
RopeSequence.empty = new Leaf([]);
var Append = /* @__PURE__ */ function(RopeSequence3) {
  function Append2(left, right) {
    RopeSequence3.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }
  if (RopeSequence3) Append2.__proto__ = RopeSequence3;
  Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Append2.prototype.constructor = Append2;
  Append2.prototype.flatten = function flatten4() {
    return this.left.flatten().concat(this.right.flatten());
  };
  Append2.prototype.getInner = function getInner(i3) {
    return i3 < this.left.length ? this.left.get(i3) : this.right.get(i3 - this.left.length);
  };
  Append2.prototype.forEachInner = function forEachInner(f3, from2, to, start) {
    var leftLen = this.left.length;
    if (from2 < leftLen && this.left.forEachInner(f3, from2, Math.min(to, leftLen), start) === false) {
      return false;
    }
    if (to > leftLen && this.right.forEachInner(f3, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) {
      return false;
    }
  };
  Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f3, from2, to, start) {
    var leftLen = this.left.length;
    if (from2 > leftLen && this.right.forEachInvertedInner(f3, from2 - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) {
      return false;
    }
    if (to < leftLen && this.left.forEachInvertedInner(f3, Math.min(from2, leftLen), to, start) === false) {
      return false;
    }
  };
  Append2.prototype.sliceInner = function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    var leftLen = this.left.length;
    if (to <= leftLen) {
      return this.left.slice(from2, to);
    }
    if (from2 >= leftLen) {
      return this.right.slice(from2 - leftLen, to - leftLen);
    }
    return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen));
  };
  Append2.prototype.leafAppend = function leafAppend(other) {
    var inner = this.right.leafAppend(other);
    if (inner) {
      return new Append2(this.left, inner);
    }
  };
  Append2.prototype.leafPrepend = function leafPrepend(other) {
    var inner = this.left.leafPrepend(other);
    if (inner) {
      return new Append2(inner, this.right);
    }
  };
  Append2.prototype.appendInner = function appendInner2(other) {
    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {
      return new Append2(this.left, new Append2(this.right, other));
    }
    return new Append2(this, other);
  };
  return Append2;
}(RopeSequence);
var ropeSequence = RopeSequence;
var index_es_default = ropeSequence;

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

// node_modules/prosemirror-menu/dist/index.js
var SVG = "http://www.w3.org/2000/svg";
var XLINK = "http://www.w3.org/1999/xlink";
var prefix$2 = "ProseMirror-icon";
function hashPath(path) {
  let hash = 0;
  for (let i3 = 0; i3 < path.length; i3++)
    hash = (hash << 5) - hash + path.charCodeAt(i3) | 0;
  return hash;
}
function getIcon(icon) {
  let node = document.createElement("div");
  node.className = prefix$2;
  if (icon.path) {
    let { path, width, height } = icon;
    let name2 = "pm-icon-" + hashPath(path).toString(16);
    if (!document.getElementById(name2))
      buildSVG(name2, icon);
    let svg4 = node.appendChild(document.createElementNS(SVG, "svg"));
    svg4.style.width = width / height + "em";
    let use3 = svg4.appendChild(document.createElementNS(SVG, "use"));
    use3.setAttributeNS(XLINK, "href", /([^#]*)/.exec(document.location.toString())[1] + "#" + name2);
  } else if (icon.dom) {
    node.appendChild(icon.dom.cloneNode(true));
  } else {
    let { text: text3, css } = icon;
    node.appendChild(document.createElement("span")).textContent = text3 || "";
    if (css)
      node.firstChild.style.cssText = css;
  }
  return node;
}
function buildSVG(name2, data2) {
  let collection = document.getElementById(prefix$2 + "-collection");
  if (!collection) {
    collection = document.createElementNS(SVG, "svg");
    collection.id = prefix$2 + "-collection";
    collection.style.display = "none";
    document.body.insertBefore(collection, document.body.firstChild);
  }
  let sym = document.createElementNS(SVG, "symbol");
  sym.id = name2;
  sym.setAttribute("viewBox", "0 0 " + data2.width + " " + data2.height);
  let path = sym.appendChild(document.createElementNS(SVG, "path"));
  path.setAttribute("d", data2.path);
  collection.appendChild(sym);
}
var prefix$1 = "ProseMirror-menu";
var MenuItem = class {
  /**
  Create a menu item.
  */
  constructor(spec) {
    this.spec = spec;
  }
  /**
  Renders the icon according to its [display
  spec](https://prosemirror.net/docs/ref/#menu.MenuItemSpec.display), and adds an event handler which
  executes the command when the representation is clicked.
  */
  render(view) {
    let spec = this.spec;
    let dom = spec.render ? spec.render(view) : spec.icon ? getIcon(spec.icon) : spec.label ? crelt("div", null, translate(view, spec.label)) : null;
    if (!dom)
      throw new RangeError("MenuItem without icon or label property");
    if (spec.title) {
      const title = typeof spec.title === "function" ? spec.title(view.state) : spec.title;
      dom.setAttribute("title", translate(view, title));
    }
    if (spec.class)
      dom.classList.add(spec.class);
    if (spec.css)
      dom.style.cssText += spec.css;
    dom.addEventListener("mousedown", (e3) => {
      e3.preventDefault();
      if (!dom.classList.contains(prefix$1 + "-disabled"))
        spec.run(view.state, view.dispatch, view, e3);
    });
    function update2(state) {
      if (spec.select) {
        let selected = spec.select(state);
        dom.style.display = selected ? "" : "none";
        if (!selected)
          return false;
      }
      let enabled = true;
      if (spec.enable) {
        enabled = spec.enable(state) || false;
        setClass(dom, prefix$1 + "-disabled", !enabled);
      }
      if (spec.active) {
        let active = enabled && spec.active(state) || false;
        setClass(dom, prefix$1 + "-active", active);
      }
      return true;
    }
    return { dom, update: update2 };
  }
};
function translate(view, text3) {
  return view._props.translate ? view._props.translate(text3) : text3;
}
function combineUpdates(updates, nodes2) {
  return (state) => {
    let something = false;
    for (let i3 = 0; i3 < updates.length; i3++) {
      let up = updates[i3](state);
      nodes2[i3].style.display = up ? "" : "none";
      if (up)
        something = true;
    }
    return something;
  };
}
function renderGrouped(view, content2) {
  let result2 = document.createDocumentFragment();
  let updates = [], separators = [];
  for (let i3 = 0; i3 < content2.length; i3++) {
    let items = content2[i3], localUpdates = [], localNodes = [];
    for (let j = 0; j < items.length; j++) {
      let { dom, update: update3 } = items[j].render(view);
      let span = crelt("span", { class: prefix$1 + "item" }, dom);
      result2.appendChild(span);
      localNodes.push(span);
      localUpdates.push(update3);
    }
    if (localUpdates.length) {
      updates.push(combineUpdates(localUpdates, localNodes));
      if (i3 < content2.length - 1)
        separators.push(result2.appendChild(separator2()));
    }
  }
  function update2(state) {
    let something = false, needSep = false;
    for (let i3 = 0; i3 < updates.length; i3++) {
      let hasContent2 = updates[i3](state);
      if (i3)
        separators[i3 - 1].style.display = needSep && hasContent2 ? "" : "none";
      needSep = hasContent2;
      if (hasContent2)
        something = true;
    }
    return something;
  }
  return { dom: result2, update: update2 };
}
function separator2() {
  return crelt("span", { class: prefix$1 + "separator" });
}
var icons = {
  join: {
    width: 800,
    height: 900,
    path: "M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z"
  },
  lift: {
    width: 1024,
    height: 1024,
    path: "M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z"
  },
  selectParentNode: { text: "\u2B1A", css: "font-weight: bold" },
  undo: {
    width: 1024,
    height: 1024,
    path: "M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z"
  },
  redo: {
    width: 1024,
    height: 1024,
    path: "M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z"
  },
  strong: {
    width: 805,
    height: 1024,
    path: "M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z"
  },
  em: {
    width: 585,
    height: 1024,
    path: "M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z"
  },
  code: {
    width: 896,
    height: 1024,
    path: "M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z"
  },
  link: {
    width: 951,
    height: 1024,
    path: "M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z"
  },
  bulletList: {
    width: 768,
    height: 896,
    path: "M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z"
  },
  orderedList: {
    width: 768,
    height: 896,
    path: "M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z"
  },
  blockquote: {
    width: 640,
    height: 896,
    path: "M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z"
  }
};
var joinUpItem = new MenuItem({
  title: "Join with above block",
  run: joinUp,
  select: (state) => joinUp(state),
  icon: icons.join
});
var liftItem = new MenuItem({
  title: "Lift out of enclosing block",
  run: lift2,
  select: (state) => lift2(state),
  icon: icons.lift
});
var selectParentNodeItem = new MenuItem({
  title: "Select parent node",
  run: selectParentNode,
  select: (state) => selectParentNode(state),
  icon: icons.selectParentNode
});
var undoItem = new MenuItem({
  title: "Undo last change",
  run: undo2,
  enable: (state) => undo2(state),
  icon: icons.undo
});
var redoItem = new MenuItem({
  title: "Redo last undone change",
  run: redo2,
  enable: (state) => redo2(state),
  icon: icons.redo
});
function wrapItem(nodeType, options2) {
  let passedOptions = {
    run(state, dispatch) {
      return wrapIn(nodeType, options2.attrs)(state, dispatch);
    },
    select(state) {
      return wrapIn(nodeType, options2.attrs)(state);
    }
  };
  for (let prop2 in options2)
    passedOptions[prop2] = options2[prop2];
  return new MenuItem(passedOptions);
}
function blockTypeItem(nodeType, options2) {
  let command2 = setBlockType2(nodeType, options2.attrs);
  let passedOptions = {
    run: command2,
    enable(state) {
      return command2(state);
    },
    active(state) {
      let { $from, to, node } = state.selection;
      if (node)
        return node.hasMarkup(nodeType, options2.attrs);
      return to <= $from.end() && $from.parent.hasMarkup(nodeType, options2.attrs);
    }
  };
  for (let prop2 in options2)
    passedOptions[prop2] = options2[prop2];
  return new MenuItem(passedOptions);
}
function setClass(dom, cls, on2) {
  if (on2)
    dom.classList.add(cls);
  else
    dom.classList.remove(cls);
}
var prefix = "ProseMirror-menubar";
function isIOS() {
  if (typeof navigator == "undefined")
    return false;
  let agent2 = navigator.userAgent;
  return !/Edge\/\d/.test(agent2) && /AppleWebKit/.test(agent2) && /Mobile\/\w+/.test(agent2);
}
function menuBar(options2) {
  return new Plugin({
    view(editorView) {
      return new MenuBarView(editorView, options2);
    }
  });
}
var MenuBarView = class {
  constructor(editorView, options2) {
    this.editorView = editorView;
    this.options = options2;
    this.spacer = null;
    this.maxHeight = 0;
    this.widthForMaxHeight = 0;
    this.floating = false;
    this.scrollHandler = null;
    this.wrapper = crelt("div", { class: prefix + "-wrapper" });
    this.menu = this.wrapper.appendChild(crelt("div", { class: prefix }));
    this.menu.className = prefix;
    if (editorView.dom.parentNode)
      editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom);
    this.wrapper.appendChild(editorView.dom);
    let { dom, update: update2 } = renderGrouped(this.editorView, this.options.content);
    this.contentUpdate = update2;
    this.menu.appendChild(dom);
    this.update();
    if (options2.floating && !isIOS()) {
      this.updateFloat();
      let potentialScrollers = getAllWrapping(this.wrapper);
      this.scrollHandler = (e3) => {
        let root3 = this.editorView.root;
        if (!(root3.body || root3).contains(this.wrapper))
          potentialScrollers.forEach((el2) => el2.removeEventListener("scroll", this.scrollHandler));
        else
          this.updateFloat(e3.target.getBoundingClientRect ? e3.target : void 0);
      };
      potentialScrollers.forEach((el2) => el2.addEventListener("scroll", this.scrollHandler));
    }
  }
  update() {
    this.contentUpdate(this.editorView.state);
    if (this.floating) {
      this.updateScrollCursor();
    } else {
      if (this.menu.offsetWidth != this.widthForMaxHeight) {
        this.widthForMaxHeight = this.menu.offsetWidth;
        this.maxHeight = 0;
      }
      if (this.menu.offsetHeight > this.maxHeight) {
        this.maxHeight = this.menu.offsetHeight;
        this.menu.style.minHeight = this.maxHeight + "px";
      }
    }
  }
  updateScrollCursor() {
    let selection = this.editorView.root.getSelection();
    if (!selection.focusNode)
      return;
    let rects = selection.getRangeAt(0).getClientRects();
    let selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1];
    if (!selRect)
      return;
    let menuRect = this.menu.getBoundingClientRect();
    if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {
      let scrollable = findWrappingScrollable(this.wrapper);
      if (scrollable)
        scrollable.scrollTop -= menuRect.bottom - selRect.top;
    }
  }
  updateFloat(scrollAncestor) {
    let parent = this.wrapper, editorRect = parent.getBoundingClientRect(), top2 = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0;
    if (this.floating) {
      if (editorRect.top >= top2 || editorRect.bottom < this.menu.offsetHeight + 10) {
        this.floating = false;
        this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = "";
        this.menu.style.display = "";
        this.spacer.parentNode.removeChild(this.spacer);
        this.spacer = null;
      } else {
        let border = (parent.offsetWidth - parent.clientWidth) / 2;
        this.menu.style.left = editorRect.left + border + "px";
        this.menu.style.display = editorRect.top > window.innerHeight ? "none" : "";
        if (scrollAncestor)
          this.menu.style.top = top2 + "px";
      }
    } else {
      if (editorRect.top < top2 && editorRect.bottom >= this.menu.offsetHeight + 10) {
        this.floating = true;
        let menuRect = this.menu.getBoundingClientRect();
        this.menu.style.left = menuRect.left + "px";
        this.menu.style.width = menuRect.width + "px";
        if (scrollAncestor)
          this.menu.style.top = top2 + "px";
        this.menu.style.position = "fixed";
        this.spacer = crelt("div", { class: prefix + "-spacer", style: `height: ${menuRect.height}px` });
        parent.insertBefore(this.spacer, this.menu);
      }
    }
  }
  destroy() {
    if (this.wrapper.parentNode)
      this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper);
  }
};
function selectionIsInverted(selection) {
  if (selection.anchorNode == selection.focusNode)
    return selection.anchorOffset > selection.focusOffset;
  return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING;
}
function findWrappingScrollable(node) {
  for (let cur2 = node.parentNode; cur2; cur2 = cur2.parentNode)
    if (cur2.scrollHeight > cur2.clientHeight)
      return cur2;
}
function getAllWrapping(node) {
  let res = [window];
  for (let cur2 = node.parentNode; cur2; cur2 = cur2.parentNode)
    res.push(cur2);
  return res;
}

// public/app/ui/editors/prosemirror/prosemirror.js
var import_subscription2 = __toESM(require_subscription());
var import_markdown_it3 = __toESM(require_markdown_it());
var import_markdown_it_flowdock = __toESM(require_dist2());

// node_modules/prosemirror-keymap/dist/index.js
var mac4 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;
function normalizeKeyName2(name2) {
  let parts = name2.split(/-(?!$)/), result2 = parts[parts.length - 1];
  if (result2 == "Space")
    result2 = " ";
  let alt, ctrl, shift2, meta2;
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
    let mod = parts[i3];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta2 = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (mac4)
        meta2 = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result2 = "Alt-" + result2;
  if (ctrl)
    result2 = "Ctrl-" + result2;
  if (meta2)
    result2 = "Meta-" + result2;
  if (shift2)
    result2 = "Shift-" + result2;
  return result2;
}
function normalize4(map5) {
  let copy2 = /* @__PURE__ */ Object.create(null);
  for (let prop2 in map5)
    copy2[normalizeKeyName2(prop2)] = map5[prop2];
  return copy2;
}
function modifiers3(name2, event2, shift2) {
  if (event2.altKey)
    name2 = "Alt-" + name2;
  if (event2.ctrlKey)
    name2 = "Ctrl-" + name2;
  if (event2.metaKey)
    name2 = "Meta-" + name2;
  if (shift2 !== false && event2.shiftKey)
    name2 = "Shift-" + name2;
  return name2;
}
function keymap2(bindings) {
  return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
}
function keydownHandler(bindings) {
  let map5 = normalize4(bindings);
  return function(view, event2) {
    let name2 = keyName(event2), isChar = name2.length == 1 && name2 != " ", baseName;
    let direct = map5[modifiers3(name2, event2, !isChar)];
    if (direct && direct(view.state, view.dispatch, view))
      return true;
    if (isChar && (event2.shiftKey || event2.altKey || event2.metaKey || name2.charCodeAt(0) > 127) && (baseName = base[event2.keyCode]) && baseName != name2) {
      let fromCode = map5[modifiers3(baseName, event2, true)];
      if (fromCode && fromCode(view.state, view.dispatch, view))
        return true;
    } else if (isChar && event2.shiftKey) {
      let withShift = map5[modifiers3(name2, event2, true)];
      if (withShift && withShift(view.state, view.dispatch, view))
        return true;
    }
    return false;
  };
}

// node_modules/prosemirror-dropcursor/dist/index.js
function dropCursor2(options2 = {}) {
  return new Plugin({
    view(editorView) {
      return new DropCursorView(editorView, options2);
    }
  });
}
var DropCursorView = class {
  constructor(editorView, options2) {
    this.editorView = editorView;
    this.cursorPos = null;
    this.element = null;
    this.timeout = -1;
    this.width = options2.width || 1;
    this.color = options2.color || "black";
    this.class = options2.class;
    this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name2) => {
      let handler = (e3) => {
        this[name2](e3);
      };
      editorView.dom.addEventListener(name2, handler);
      return { name: name2, handler };
    });
  }
  destroy() {
    this.handlers.forEach(({ name: name2, handler }) => this.editorView.dom.removeEventListener(name2, handler));
  }
  update(editorView, prevState) {
    if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
      if (this.cursorPos > editorView.state.doc.content.size)
        this.setCursor(null);
      else
        this.updateOverlay();
    }
  }
  setCursor(pos) {
    if (pos == this.cursorPos)
      return;
    this.cursorPos = pos;
    if (pos == null) {
      this.element.parentNode.removeChild(this.element);
      this.element = null;
    } else {
      this.updateOverlay();
    }
  }
  updateOverlay() {
    let $pos = this.editorView.state.doc.resolve(this.cursorPos), rect;
    if (!$pos.parent.inlineContent) {
      let before2 = $pos.nodeBefore, after2 = $pos.nodeAfter;
      if (before2 || after2) {
        let nodeRect = this.editorView.nodeDOM(this.cursorPos - (before2 ? before2.nodeSize : 0)).getBoundingClientRect();
        let top2 = before2 ? nodeRect.bottom : nodeRect.top;
        if (before2 && after2)
          top2 = (top2 + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
        rect = { left: nodeRect.left, right: nodeRect.right, top: top2 - this.width / 2, bottom: top2 + this.width / 2 };
      }
    }
    if (!rect) {
      let coords = this.editorView.coordsAtPos(this.cursorPos);
      rect = { left: coords.left - this.width / 2, right: coords.left + this.width / 2, top: coords.top, bottom: coords.bottom };
    }
    let parent = this.editorView.dom.offsetParent;
    if (!this.element) {
      this.element = parent.appendChild(document.createElement("div"));
      if (this.class)
        this.element.className = this.class;
      this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none; background-color: " + this.color;
    }
    let parentLeft, parentTop;
    if (!parent || parent == document.body && getComputedStyle(parent).position == "static") {
      parentLeft = -pageXOffset;
      parentTop = -pageYOffset;
    } else {
      let rect2 = parent.getBoundingClientRect();
      parentLeft = rect2.left - parent.scrollLeft;
      parentTop = rect2.top - parent.scrollTop;
    }
    this.element.style.left = rect.left - parentLeft + "px";
    this.element.style.top = rect.top - parentTop + "px";
    this.element.style.width = rect.right - rect.left + "px";
    this.element.style.height = rect.bottom - rect.top + "px";
  }
  scheduleRemoval(timeout) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => this.setCursor(null), timeout);
  }
  dragover(event2) {
    if (!this.editorView.editable)
      return;
    let pos = this.editorView.posAtCoords({ left: event2.clientX, top: event2.clientY });
    let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
    let disableDropCursor = node && node.type.spec.disableDropCursor;
    let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event2) : disableDropCursor;
    if (pos && !disabled) {
      let target = pos.pos;
      if (this.editorView.dragging && this.editorView.dragging.slice) {
        target = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);
        if (target == null)
          return this.setCursor(null);
      }
      this.setCursor(target);
      this.scheduleRemoval(5e3);
    }
  }
  dragend() {
    this.scheduleRemoval(20);
  }
  drop() {
    this.scheduleRemoval(20);
  }
  dragleave(event2) {
    if (event2.target == this.editorView.dom || !this.editorView.dom.contains(event2.relatedTarget))
      this.setCursor(null);
  }
};

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

// node_modules/prosemirror-schema-list/dist/index.js
var olDOM = ["ol", 0];
var ulDOM = ["ul", 0];
var liDOM = ["li", 0];
var orderedList = {
  attrs: { order: { default: 1 } },
  parseDOM: [{ tag: "ol", getAttrs(dom) {
    return { order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1 };
  } }],
  toDOM(node) {
    return node.attrs.order == 1 ? olDOM : ["ol", { start: node.attrs.order }, 0];
  }
};
var bulletList = {
  parseDOM: [{ tag: "ul" }],
  toDOM() {
    return ulDOM;
  }
};
var listItem = {
  parseDOM: [{ tag: "li" }],
  toDOM() {
    return liDOM;
  },
  defining: true
};
function add3(obj, props2) {
  let copy2 = {};
  for (let prop2 in obj)
    copy2[prop2] = obj[prop2];
  for (let prop2 in props2)
    copy2[prop2] = props2[prop2];
  return copy2;
}
function addListNodes(nodes2, itemContent, listGroup) {
  return nodes2.append({
    ordered_list: add3(orderedList, { content: "list_item+", group: listGroup }),
    bullet_list: add3(bulletList, { content: "list_item+", group: listGroup }),
    list_item: add3(listItem, { content: itemContent })
  });
}
function wrapInList(listType, attrs2 = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to), doJoin = false, outerRange = range2;
    if (!range2)
      return false;
    if (range2.depth >= 2 && $from.node(range2.depth - 1).type.compatibleContent(listType) && range2.startIndex == 0) {
      if ($from.index(range2.depth - 1) == 0)
        return false;
      let $insert = state.doc.resolve(range2.start - 2);
      outerRange = new NodeRange($insert, $insert, range2.depth);
      if (range2.endIndex < range2.parent.childCount)
        range2 = new NodeRange($from, state.doc.resolve($to.end(range2.depth)), range2.depth);
      doJoin = true;
    }
    let wrap4 = findWrapping(outerRange, listType, attrs2, range2);
    if (!wrap4)
      return false;
    if (dispatch)
      dispatch(doWrapInList(state.tr, range2, wrap4, doJoin, listType).scrollIntoView());
    return true;
  };
}
function doWrapInList(tr2, range2, wrappers, joinBefore, listType) {
  let content2 = Fragment.empty;
  for (let i3 = wrappers.length - 1; i3 >= 0; i3--)
    content2 = Fragment.from(wrappers[i3].type.create(wrappers[i3].attrs, content2));
  tr2.step(new ReplaceAroundStep(range2.start - (joinBefore ? 2 : 0), range2.end, range2.start, range2.end, new Slice(content2, 0, 0), wrappers.length, true));
  let found2 = 0;
  for (let i3 = 0; i3 < wrappers.length; i3++)
    if (wrappers[i3].type == listType)
      found2 = i3 + 1;
  let splitDepth = wrappers.length - found2;
  let splitPos = range2.start + wrappers.length - (joinBefore ? 2 : 0), parent = range2.parent;
  for (let i3 = range2.startIndex, e3 = range2.endIndex, first2 = true; i3 < e3; i3++, first2 = false) {
    if (!first2 && canSplit(tr2.doc, splitPos, splitDepth)) {
      tr2.split(splitPos, splitDepth);
      splitPos += 2 * splitDepth;
    }
    splitPos += parent.child(i3).nodeSize;
  }
  return tr2;
}
function splitListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to, node } = state.selection;
    if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to))
      return false;
    let grandParent = $from.node(-1);
    if (grandParent.type != itemType)
      return false;
    if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {
      if ($from.depth == 3 || $from.node(-3).type != itemType || $from.index(-2) != $from.node(-2).childCount - 1)
        return false;
      if (dispatch) {
        let wrap4 = Fragment.empty;
        let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
        for (let d3 = $from.depth - depthBefore; d3 >= $from.depth - 3; d3--)
          wrap4 = Fragment.from($from.node(d3).copy(wrap4));
        let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;
        wrap4 = wrap4.append(Fragment.from(itemType.createAndFill()));
        let start = $from.before($from.depth - (depthBefore - 1));
        let tr3 = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap4, 4 - depthBefore, 0));
        let sel = -1;
        tr3.doc.nodesBetween(start, tr3.doc.content.size, (node2, pos) => {
          if (sel > -1)
            return false;
          if (node2.isTextblock && node2.content.size == 0)
            sel = pos + 1;
        });
        if (sel > -1)
          tr3.setSelection(Selection.near(tr3.doc.resolve(sel)));
        dispatch(tr3.scrollIntoView());
      }
      return true;
    }
    let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
    let tr2 = state.tr.delete($from.pos, $to.pos);
    let types2 = nextType ? [null, { type: nextType }] : void 0;
    if (!canSplit(tr2.doc, $from.pos, 2, types2))
      return false;
    if (dispatch)
      dispatch(tr2.split($from.pos, 2, types2).scrollIntoView());
    return true;
  };
}
function liftListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
    if (!range2)
      return false;
    if (!dispatch)
      return true;
    if ($from.node(range2.depth - 1).type == itemType)
      return liftToOuterList(state, dispatch, itemType, range2);
    else
      return liftOutOfList(state, dispatch, range2);
  };
}
function liftToOuterList(state, dispatch, itemType, range2) {
  let tr2 = state.tr, end = range2.end, endOfList = range2.$to.end(range2.depth);
  if (end < endOfList) {
    tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range2.parent.copy())), 1, 0), 1, true));
    range2 = new NodeRange(tr2.doc.resolve(range2.$from.pos), tr2.doc.resolve(endOfList), range2.depth);
  }
  const target = liftTarget(range2);
  if (target == null)
    return false;
  tr2.lift(range2, target);
  let after2 = tr2.mapping.map(end, -1) - 1;
  if (canJoin(tr2.doc, after2))
    tr2.join(after2);
  dispatch(tr2.scrollIntoView());
  return true;
}
function liftOutOfList(state, dispatch, range2) {
  let tr2 = state.tr, list2 = range2.parent;
  for (let pos = range2.end, i3 = range2.endIndex - 1, e3 = range2.startIndex; i3 > e3; i3--) {
    pos -= list2.child(i3).nodeSize;
    tr2.delete(pos - 1, pos + 1);
  }
  let $start = tr2.doc.resolve(range2.start), item = $start.nodeAfter;
  if (tr2.mapping.map(range2.end) != range2.start + $start.nodeAfter.nodeSize)
    return false;
  let atStart = range2.startIndex == 0, atEnd = range2.endIndex == list2.childCount;
  let parent = $start.node(-1), indexBefore = $start.index(-1);
  if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list2))))
    return false;
  let start = $start.pos, end = start + item.nodeSize;
  tr2.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  dispatch(tr2.scrollIntoView());
  return true;
}
function sinkListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
    if (!range2)
      return false;
    let startIndex = range2.startIndex;
    if (startIndex == 0)
      return false;
    let parent = range2.parent, nodeBefore = parent.child(startIndex - 1);
    if (nodeBefore.type != itemType)
      return false;
    if (dispatch) {
      let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;
      let inner = Fragment.from(nestedBefore ? itemType.create() : null);
      let slice3 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
      let before2 = range2.start, after2 = range2.end;
      dispatch(state.tr.step(new ReplaceAroundStep(before2 - (nestedBefore ? 3 : 1), after2, before2, after2, slice3, 1, true)).scrollIntoView());
    }
    return true;
  };
}

// node_modules/prosemirror-inputrules/dist/index.js
var InputRule = class {
  // :: (RegExp, union<string, (state: EditorState, match: [string], start: number, end: number) → ?Transaction>)
  /**
  Create an input rule. The rule applies when the user typed
  something and the text directly in front of the cursor matches
  `match`, which should end with `$`.
  
  The `handler` can be a string, in which case the matched text, or
  the first matched group in the regexp, is replaced by that
  string.
  
  Or a it can be a function, which will be called with the match
  array produced by
  [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
  as well as the start and end of the matched range, and which can
  return a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) that describes the
  rule's effect, or null to indicate the input was not handled.
  */
  constructor(match2, handler) {
    this.match = match2;
    this.match = match2;
    this.handler = typeof handler == "string" ? stringHandler(handler) : handler;
  }
};
function stringHandler(string3) {
  return function(state, match2, start, end) {
    let insert4 = string3;
    if (match2[1]) {
      let offset = match2[0].lastIndexOf(match2[1]);
      insert4 += match2[0].slice(offset + match2[1].length);
      start += offset;
      let cutOff = start - end;
      if (cutOff > 0) {
        insert4 = match2[0].slice(offset - cutOff, offset) + insert4;
        start = end;
      }
    }
    return state.tr.insertText(insert4, start, end);
  };
}
var MAX_MATCH = 500;
function inputRules({ rules }) {
  let plugin = new Plugin({
    state: {
      init() {
        return null;
      },
      apply(tr2, prev) {
        let stored = tr2.getMeta(this);
        if (stored)
          return stored;
        return tr2.selectionSet || tr2.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput(view, from2, to, text3) {
        return run2(view, from2, to, text3, rules, plugin);
      },
      handleDOMEvents: {
        compositionend: (view) => {
          setTimeout(() => {
            let { $cursor } = view.state.selection;
            if ($cursor)
              run2(view, $cursor.pos, $cursor.pos, "", rules, plugin);
          });
        }
      }
    },
    isInputRules: true
  });
  return plugin;
}
function run2(view, from2, to, text3, rules, plugin) {
  if (view.composing)
    return false;
  let state = view.state, $from = state.doc.resolve(from2);
  if ($from.parent.type.spec.code)
    return false;
  let textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, null, "\uFFFC") + text3;
  for (let i3 = 0; i3 < rules.length; i3++) {
    let match2 = rules[i3].match.exec(textBefore);
    let tr2 = match2 && rules[i3].handler(state, match2, from2 - (match2[0].length - text3.length), to);
    if (!tr2)
      continue;
    view.dispatch(tr2.setMeta(plugin, { transform: tr2, from: from2, to, text: text3 }));
    return true;
  }
  return false;
}
var undoInputRule = (state, dispatch) => {
  let plugins = state.plugins;
  for (let i3 = 0; i3 < plugins.length; i3++) {
    let plugin = plugins[i3], undoable;
    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
      if (dispatch) {
        let tr2 = state.tr, toUndo = undoable.transform;
        for (let j = toUndo.steps.length - 1; j >= 0; j--)
          tr2.step(toUndo.steps[j].invert(toUndo.docs[j]));
        if (undoable.text) {
          let marks3 = tr2.doc.resolve(undoable.from).marks();
          tr2.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks3));
        } else {
          tr2.delete(undoable.from, undoable.to);
        }
        dispatch(tr2);
      }
      return true;
    }
  }
  return false;
};
var emDash = new InputRule(/--$/, "\u2014");
var ellipsis = new InputRule(/\.\.\.$/, "\u2026");
var openDoubleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/, "\u201C");
var closeDoubleQuote = new InputRule(/"$/, "\u201D");
var openSingleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/, "\u2018");
var closeSingleQuote = new InputRule(/'$/, "\u2019");
var smartQuotes = [openDoubleQuote, closeDoubleQuote, openSingleQuote, closeSingleQuote];
function wrappingInputRule(regexp, nodeType, getAttrs2 = null, joinPredicate) {
  return new InputRule(regexp, (state, match2, start, end) => {
    let attrs2 = getAttrs2 instanceof Function ? getAttrs2(match2) : getAttrs2;
    let tr2 = state.tr.delete(start, end);
    let $start = tr2.doc.resolve(start), range2 = $start.blockRange(), wrapping = range2 && findWrapping(range2, nodeType, attrs2);
    if (!wrapping)
      return null;
    tr2.wrap(range2, wrapping);
    let before2 = tr2.doc.resolve(start - 1).nodeBefore;
    if (before2 && before2.type == nodeType && canJoin(tr2.doc, start - 1) && (!joinPredicate || joinPredicate(match2, before2)))
      tr2.join(start - 1);
    return tr2;
  });
}
function textblockTypeInputRule(regexp, nodeType, getAttrs2 = null) {
  return new InputRule(regexp, (state, match2, start, end) => {
    let $start = state.doc.resolve(start);
    let attrs2 = getAttrs2 instanceof Function ? getAttrs2(match2) : getAttrs2;
    if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), nodeType))
      return null;
    return state.tr.delete(start, end).setBlockType(start, start, nodeType, attrs2);
  });
}

// node_modules/prosemirror-example-setup/dist/index.js
var mac5 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;
function buildKeymap2(schema7, mapKeys) {
  let keys5 = {}, type;
  function bind2(key2, cmd2) {
    if (mapKeys) {
      let mapped = mapKeys[key2];
      if (mapped === false)
        return;
      if (mapped)
        key2 = mapped;
    }
    keys5[key2] = cmd2;
  }
  bind2("Mod-z", undo2);
  bind2("Shift-Mod-z", redo2);
  bind2("Backspace", undoInputRule);
  if (!mac5)
    bind2("Mod-y", redo2);
  bind2("Alt-ArrowUp", joinUp);
  bind2("Alt-ArrowDown", joinDown);
  bind2("Mod-BracketLeft", lift2);
  bind2("Escape", selectParentNode);
  if (type = schema7.marks.strong) {
    bind2("Mod-b", toggleMark(type));
    bind2("Mod-B", toggleMark(type));
  }
  if (type = schema7.marks.em) {
    bind2("Mod-i", toggleMark(type));
    bind2("Mod-I", toggleMark(type));
  }
  if (type = schema7.marks.code)
    bind2("Mod-`", toggleMark(type));
  if (type = schema7.nodes.bullet_list)
    bind2("Shift-Ctrl-8", wrapInList(type));
  if (type = schema7.nodes.ordered_list)
    bind2("Shift-Ctrl-9", wrapInList(type));
  if (type = schema7.nodes.blockquote)
    bind2("Ctrl->", wrapIn(type));
  if (type = schema7.nodes.hard_break) {
    let br = type, cmd2 = chainCommands(exitCode, (state, dispatch) => {
      if (dispatch)
        dispatch(state.tr.replaceSelectionWith(br.create()).scrollIntoView());
      return true;
    });
    bind2("Mod-Enter", cmd2);
    bind2("Shift-Enter", cmd2);
    if (mac5)
      bind2("Ctrl-Enter", cmd2);
  }
  if (type = schema7.nodes.list_item) {
    bind2("Enter", splitListItem(type));
    bind2("Mod-[", liftListItem(type));
    bind2("Mod-]", sinkListItem(type));
  }
  if (type = schema7.nodes.paragraph)
    bind2("Shift-Ctrl-0", setBlockType2(type));
  if (type = schema7.nodes.code_block)
    bind2("Shift-Ctrl-\\", setBlockType2(type));
  if (type = schema7.nodes.heading)
    for (let i3 = 1; i3 <= 6; i3++)
      bind2("Shift-Ctrl-" + i3, setBlockType2(type, { level: i3 }));
  if (type = schema7.nodes.horizontal_rule) {
    let hr2 = type;
    bind2("Mod-_", (state, dispatch) => {
      if (dispatch)
        dispatch(state.tr.replaceSelectionWith(hr2.create()).scrollIntoView());
      return true;
    });
  }
  return keys5;
}
function blockQuoteRule(nodeType) {
  return wrappingInputRule(/^\s*>\s$/, nodeType);
}
function orderedListRule(nodeType) {
  return wrappingInputRule(/^(\d+)\.\s$/, nodeType, (match2) => ({ order: +match2[1] }), (match2, node) => node.childCount + node.attrs.order == +match2[1]);
}
function bulletListRule(nodeType) {
  return wrappingInputRule(/^\s*([-+*])\s$/, nodeType);
}
function codeBlockRule(nodeType) {
  return textblockTypeInputRule(/^```$/, nodeType);
}
function headingRule(nodeType, maxLevel) {
  return textblockTypeInputRule(new RegExp("^(#{1," + maxLevel + "})\\s$"), nodeType, (match2) => ({ level: match2[1].length }));
}
function buildInputRules(schema7) {
  let rules = smartQuotes.concat(ellipsis, emDash), type;
  if (type = schema7.nodes.blockquote)
    rules.push(blockQuoteRule(type));
  if (type = schema7.nodes.ordered_list)
    rules.push(orderedListRule(type));
  if (type = schema7.nodes.bullet_list)
    rules.push(bulletListRule(type));
  if (type = schema7.nodes.code_block)
    rules.push(codeBlockRule(type));
  if (type = schema7.nodes.heading)
    rules.push(headingRule(type, 6));
  return inputRules({ rules });
}

// node_modules/prosemirror-schema-basic/dist/index.js
var pDOM = ["p", 0];
var blockquoteDOM = ["blockquote", 0];
var hrDOM = ["hr"];
var preDOM = ["pre", ["code", 0]];
var brDOM = ["br"];
var nodes = {
  /**
  NodeSpec The top level document node.
  */
  doc: {
    content: "block+"
  },
  /**
  A plain paragraph textblock. Represented in the DOM
  as a `<p>` element.
  */
  paragraph: {
    content: "inline*",
    group: "block",
    parseDOM: [{ tag: "p" }],
    toDOM() {
      return pDOM;
    }
  },
  /**
  A blockquote (`<blockquote>`) wrapping one or more blocks.
  */
  blockquote: {
    content: "block+",
    group: "block",
    defining: true,
    parseDOM: [{ tag: "blockquote" }],
    toDOM() {
      return blockquoteDOM;
    }
  },
  /**
  A horizontal rule (`<hr>`).
  */
  horizontal_rule: {
    group: "block",
    parseDOM: [{ tag: "hr" }],
    toDOM() {
      return hrDOM;
    }
  },
  /**
  A heading textblock, with a `level` attribute that
  should hold the number 1 to 6. Parsed and serialized as `<h1>` to
  `<h6>` elements.
  */
  heading: {
    attrs: { level: { default: 1 } },
    content: "inline*",
    group: "block",
    defining: true,
    parseDOM: [
      { tag: "h1", attrs: { level: 1 } },
      { tag: "h2", attrs: { level: 2 } },
      { tag: "h3", attrs: { level: 3 } },
      { tag: "h4", attrs: { level: 4 } },
      { tag: "h5", attrs: { level: 5 } },
      { tag: "h6", attrs: { level: 6 } }
    ],
    toDOM(node) {
      return ["h" + node.attrs.level, 0];
    }
  },
  /**
  A code listing. Disallows marks or non-text inline
  nodes by default. Represented as a `<pre>` element with a
  `<code>` element inside of it.
  */
  code_block: {
    content: "text*",
    marks: "",
    group: "block",
    code: true,
    defining: true,
    parseDOM: [{ tag: "pre", preserveWhitespace: "full" }],
    toDOM() {
      return preDOM;
    }
  },
  /**
  The text node.
  */
  text: {
    group: "inline"
  },
  /**
  An inline image (`<img>`) node. Supports `src`,
  `alt`, and `href` attributes. The latter two default to the empty
  string.
  */
  image: {
    inline: true,
    attrs: {
      src: {},
      alt: { default: null },
      title: { default: null }
    },
    group: "inline",
    draggable: true,
    parseDOM: [{ tag: "img[src]", getAttrs(dom) {
      return {
        src: dom.getAttribute("src"),
        title: dom.getAttribute("title"),
        alt: dom.getAttribute("alt")
      };
    } }],
    toDOM(node) {
      let { src, alt, title } = node.attrs;
      return ["img", { src, alt, title }];
    }
  },
  /**
  A hard line break, represented in the DOM as `<br>`.
  */
  hard_break: {
    inline: true,
    group: "inline",
    selectable: false,
    parseDOM: [{ tag: "br" }],
    toDOM() {
      return brDOM;
    }
  }
};
var emDOM = ["em", 0];
var strongDOM = ["strong", 0];
var codeDOM = ["code", 0];
var marks2 = {
  /**
  A link. Has `href` and `title` attributes. `title`
  defaults to the empty string. Rendered and parsed as an `<a>`
  element.
  */
  link: {
    attrs: {
      href: {},
      title: { default: null }
    },
    inclusive: false,
    parseDOM: [{ tag: "a[href]", getAttrs(dom) {
      return { href: dom.getAttribute("href"), title: dom.getAttribute("title") };
    } }],
    toDOM(node) {
      let { href, title } = node.attrs;
      return ["a", { href, title }, 0];
    }
  },
  /**
  An emphasis mark. Rendered as an `<em>` element. Has parse rules
  that also match `<i>` and `font-style: italic`.
  */
  em: {
    parseDOM: [{ tag: "i" }, { tag: "em" }, { style: "font-style=italic" }],
    toDOM() {
      return emDOM;
    }
  },
  /**
  A strong mark. Rendered as `<strong>`, parse rules also match
  `<b>` and `font-weight: bold`.
  */
  strong: {
    parseDOM: [
      { tag: "strong" },
      // This works around a Google Docs misbehavior where
      // pasted content will be inexplicably wrapped in `<b>`
      // tags with a font-weight normal.
      { tag: "b", getAttrs: (node) => node.style.fontWeight != "normal" && null },
      { style: "font-weight", getAttrs: (value2) => /^(bold(er)?|[5-9]\d{2,})$/.test(value2) && null }
    ],
    toDOM() {
      return strongDOM;
    }
  },
  /**
  Code font mark. Represented as a `<code>` element.
  */
  code: {
    parseDOM: [{ tag: "code" }],
    toDOM() {
      return codeDOM;
    }
  }
};
var schema5 = new Schema({ nodes, marks: marks2 });

// node_modules/crel/crel.es.js
function createCommonjsModule(fn, module) {
  return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var crel = createCommonjsModule(function(module, exports) {
  (function(exporter) {
    var func = "function", isNodeString = "isNode", isType = function(object2, type) {
      return typeof object2 === type;
    }, appendChild = function(element2, child) {
      if (child !== null) {
        if (Array.isArray(child)) {
          child.map(function(subChild) {
            return appendChild(element2, subChild);
          });
        } else {
          if (!crel2[isNodeString](child)) {
            child = document.createTextNode(child);
          }
          element2.appendChild(child);
        }
      }
    };
    function crel2(element2, settings) {
      var args = arguments, index2 = 1, key2, attribute2;
      element2 = crel2.isElement(element2) ? element2 : document.createElement(element2);
      if (isType(settings, "object") && !crel2[isNodeString](settings) && !Array.isArray(settings)) {
        index2++;
        for (key2 in settings) {
          attribute2 = settings[key2];
          key2 = crel2.attrMap[key2] || key2;
          if (isType(key2, func)) {
            key2(element2, attribute2);
          } else if (isType(attribute2, func)) {
            element2[key2] = attribute2;
          } else {
            element2.setAttribute(key2, attribute2);
          }
        }
      }
      for (; index2 < args.length; index2++) {
        appendChild(element2, args[index2]);
      }
      return element2;
    }
    crel2.attrMap = {};
    crel2.isElement = function(object2) {
      return object2 instanceof Element;
    };
    crel2[isNodeString] = function(node) {
      return node instanceof Node;
    };
    if (typeof Proxy != "undefined") {
      crel2.proxy = new Proxy(crel2, {
        get: function(target, key2) {
          !(key2 in crel2) && (crel2[key2] = crel2.bind(null, key2));
          return crel2[key2];
        }
      });
    }
    exporter(crel2, func);
  })(function(product, func) {
    {
      module.exports = product;
    }
  });
});
var crel_es_default = crel;

// public/app/ui/editors/prosemirror/ui/icons.js
var SVG2 = "http://www.w3.org/2000/svg";
var XLINK2 = "http://www.w3.org/1999/xlink";
var prefix2 = "ProseMirror-icon";
function hashPath2(path) {
  let hash = 0;
  for (let i3 = 0; i3 < path.length; i3++)
    hash = (hash << 5) - hash + path.charCodeAt(i3) | 0;
  return hash;
}
function getIcon2(icon) {
  let node = document.createElement("div");
  node.className = prefix2;
  if (icon.path) {
    let name2 = "pm-icon-" + hashPath2(icon.path).toString(16);
    if (!document.getElementById(name2)) buildSVG2(name2, icon);
    let svg4 = node.appendChild(document.createElementNS(SVG2, "svg"));
    svg4.style.width = icon.width / icon.height + "em";
    let use3 = svg4.appendChild(document.createElementNS(SVG2, "use"));
    use3.setAttributeNS(XLINK2, "href", /([^#]*)/.exec(document.location)[1] + "#" + name2);
  } else if (icon.dom) {
    node.appendChild(icon.dom.cloneNode(true));
  } else {
    node.appendChild(document.createElement("span")).textContent = icon.text || "";
    if (icon.css) node.firstChild.style.cssText = icon.css;
  }
  return node;
}
function buildSVG2(name2, data2) {
  let collection = document.getElementById(prefix2 + "-collection");
  if (!collection) {
    collection = document.createElementNS(SVG2, "svg");
    collection.id = prefix2 + "-collection";
    collection.style.display = "none";
    document.body.insertBefore(collection, document.body.firstChild);
  }
  let sym = document.createElementNS(SVG2, "symbol");
  sym.id = name2;
  sym.setAttribute("viewBox", "0 0 " + data2.width + " " + data2.height);
  let path = sym.appendChild(document.createElementNS(SVG2, "path"));
  path.setAttribute("d", data2.path);
  collection.appendChild(sym);
}

// public/app/ui/editors/prosemirror/ui/menu.js
var prefix3 = "ProseMirror-menu";
function translate2(view, text3) {
  return view._props.translate ? view._props.translate(text3) : text3;
}
function renderDropdownItems(items, view) {
  let rendered = [], updates = [];
  for (let i3 = 0; i3 < items.length; i3++) {
    let { dom, update: update2 } = items[i3].render(view);
    rendered.push(crel_es_default("div", { class: prefix3 + "-dropdown-item" }, dom));
    updates.push(update2);
  }
  return { dom: crel_es_default("div", null, rendered), update: combineUpdates2(updates, rendered) };
}
function combineUpdates2(updates, nodes2) {
  return (state) => {
    let something = false;
    for (let i3 = 0; i3 < updates.length; i3++) {
      let up = updates[i3](state);
      nodes2[i3].style.display = up ? "" : "none";
      if (up) something = true;
    }
    return something;
  };
}
function setClass2(dom, cls, on2) {
  if (on2) {
    dom.classList.add(cls);
  } else {
    dom.classList.remove(cls);
  }
}
var MenuDropItem = class {
  constructor(spec) {
    this.spec = spec;
  }
  render(view) {
    let spec = this.spec;
    let dom;
    if (spec.render) {
      dom = crel_es_default("div", null, spec.render(view));
    } else if (spec.icon) {
      dom = getIcon2(spec.icon);
    } else if (spec.label) {
      dom = crel_es_default("div", null, translate2(view, spec.label));
    } else {
      throw new RangeError("MenuDropItem without render, icon, or label property");
    }
    if (spec.caret) dom.classList.add(prefix3 + "-dropdown");
    if (spec.title) {
      const title = typeof spec.title === "function" ? spec.title(view.state) : spec.title;
      dom.setAttribute("title", translate2(view, title));
    }
    if (spec.class) dom.classList.add(spec.class);
    if (spec.css) dom.style.cssText += spec.css;
    let close2;
    let drop;
    dom.addEventListener(spec.execEvent || "mousedown", (e3) => {
      e3.preventDefault();
      e3.stopPropagation();
      if (close2 && close2()) {
        close2 = null;
        return;
      }
      if (spec.run && spec.run(view.state, view.dispatch, view, e3)) {
        return;
      }
      let tmp = this.open(view, dom);
      drop = tmp.drop;
      close2 = tmp.close;
      drop.on("close", function() {
        if (close2 && close2()) {
          close2 = null;
        }
      });
    });
    function update2(state) {
      if (spec.render) {
        while (dom.firstChild) {
          dom.removeChild(dom.firstChild);
        }
        dom.appendChild(spec.render(view));
      }
      if (spec.select) {
        let selected = spec.select(state);
        dom.style.display = selected ? "" : "none";
        if (!selected) {
          if (close2 && close2()) {
            close2 = null;
          }
          return false;
        }
      }
      let enabled = true;
      if (spec.enable) {
        enabled = spec.enable(state) || false;
        setClass2(dom, prefix3 + "-disabled", !enabled);
        if (!enabled) {
          if (close2 && close2()) {
            close2 = null;
          }
        }
      }
      if (spec.active) {
        let active = enabled && spec.active(state) || false;
        setClass2(dom, prefix3 + "-active", active);
      }
      return true;
    }
    return { dom, update: update2 };
  }
  open(view, dom) {
    let content2;
    if (this.spec.content instanceof Function) {
      content2 = this.spec.content(view);
    } else content2 = this.spec.content;
    if (content2.update) {
      content2.update(view.state);
    }
    let drop = new Drop({
      target: dom,
      content: content2.dom,
      position: "bottom left",
      classes: "drop-theme-prosemirror",
      constrainToScrollParent: false,
      openOn: null,
      remove: true
    });
    function stopEvent(e3) {
      e3.preventDefault();
      e3.stopPropagation();
    }
    drop.on("open", function() {
      drop.drop && drop.drop.addEventListener("mousedown", stopEvent);
    });
    drop.on("close", function() {
      drop.drop && drop.drop.removeEventListener("mousedown", stopEvent);
    });
    let hadFocus = view.hasFocus();
    function close2() {
      view.props.on.interaction.remove(close2);
      view.props.on.blur.remove(close2);
      view.props.on.editorDestroy.remove(close2);
      drop.close();
      if (hadFocus) setTimeout(() => view.focus(), 50);
      return true;
    }
    view.props.on.interaction.dispatch();
    drop.open();
    this.spec.afterOpened && this.spec.afterOpened(view, drop);
    view.props.on.interaction.add(close2);
    view.props.on.blur.add(close2);
    view.props.on.editorDestroy.add(close2);
    return { drop, close: close2 };
  }
};

// public/app/ui/editors/prosemirror/ui/form-prompt.js
var prefix4 = "ProseMirror-prompt";
function openPrompt(view, options2) {
  let wrapper = document.createElement("div");
  wrapper.className = prefix4;
  let hadFocus = view.hasFocus();
  let mouseOutside = (e3) => {
    if (!wrapper.contains(e3.target)) {
      close2();
    }
  };
  setTimeout(() => window.addEventListener("mousedown", mouseOutside), 50);
  let close2 = () => {
    window.removeEventListener("mousedown", mouseOutside);
    if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper);
    if (hadFocus) setTimeout(() => view.focus(), 50);
  };
  let domFields = [];
  for (let name2 in options2.fields) domFields.push(options2.fields[name2].render());
  let submitButton = document.createElement("button");
  submitButton.type = "submit";
  submitButton.className = prefix4 + "-submit";
  submitButton.textContent = "OK";
  let cancelButton = document.createElement("button");
  cancelButton.type = "button";
  cancelButton.className = prefix4 + "-cancel";
  cancelButton.textContent = "Cancel";
  cancelButton.addEventListener("click", close2);
  let form = wrapper.appendChild(document.createElement("form"));
  if (options2.title) form.appendChild(document.createElement("h5")).textContent = options2.title;
  domFields.forEach((field2) => {
    form.appendChild(document.createElement("div")).appendChild(field2);
  });
  let buttons = form.appendChild(document.createElement("div"));
  buttons.className = prefix4 + "-buttons";
  buttons.appendChild(submitButton);
  buttons.appendChild(document.createTextNode(" "));
  buttons.appendChild(cancelButton);
  let outerBox = view.dom.parentNode.getBoundingClientRect();
  view.dom.parentNode.appendChild(wrapper);
  let blockBox = wrapper.getBoundingClientRect();
  let cX = Math.max(0, outerBox.left) + Math.min(window.innerWidth, outerBox.right) - blockBox.width;
  let cY = Math.max(0, outerBox.top) + Math.min(window.innerHeight, outerBox.bottom) - blockBox.height;
  wrapper.style.left = cX / 2 - outerBox.left + "px";
  wrapper.style.top = cY / 2 - outerBox.top + "px";
  let submit = () => {
    let params = getValues2(options2.fields, domFields);
    if (params) {
      close2();
      options2.callback(params);
    }
  };
  form.addEventListener("submit", (e3) => {
    e3.preventDefault();
    submit();
  });
  form.addEventListener("keydown", (e3) => {
    if (e3.keyCode == 27) {
      e3.preventDefault();
      close2();
    } else if (e3.keyCode == 13 && !(e3.ctrlKey || e3.metaKey || e3.shiftKey)) {
      e3.preventDefault();
      submit();
    } else if (e3.keyCode == 9) {
      window.setTimeout(() => {
        if (!wrapper.contains(document.activeElement)) close2();
      }, 500);
    }
  });
  let input = form.elements[0];
  if (input) input.focus();
}
function getValues2(fields2, domFields) {
  let result2 = /* @__PURE__ */ Object.create(null), i3 = 0;
  for (let name2 in fields2) {
    let field2 = fields2[name2], dom = domFields[i3++];
    let value2 = field2.read(dom), bad = field2.validate(value2);
    if (bad) {
      reportInvalid(dom, bad);
      return null;
    }
    result2[name2] = field2.clean(value2);
  }
  return result2;
}
function reportInvalid(dom, message) {
  let parent = dom.parentNode;
  let msg2 = parent.appendChild(document.createElement("div"));
  msg2.style.left = dom.offsetLeft + dom.offsetWidth + 2 + "px";
  msg2.style.top = dom.offsetTop - 5 + "px";
  msg2.className = "ProseMirror-invalid";
  msg2.textContent = message;
  setTimeout(() => parent.removeChild(msg2), 1500);
}
var Field2 = class {
  // :: (Object)
  // Create a field with the given options. Options support by all
  // field types are:
  //
  // **`value`**`: ?any`
  //   : The starting value for the field.
  //
  // **`label`**`: string`
  //   : The label for the field.
  //
  // **`required`**`: ?bool`
  //   : Whether the field is required.
  //
  // **`validate`**`: ?(any) → ?string`
  //   : A function to validate the given value. Should return an
  //     error message if it is not valid.
  constructor(options2) {
    this.options = options2;
  }
  // render:: (state: EditorState, props: Object) → dom.Node
  // Render the field to the DOM. Should be implemented by all subclasses.
  // :: (dom.Node) → any
  // Read the field's value from its DOM node.
  read(dom) {
    return dom.value;
  }
  // :: (any) → ?string
  // A field-type-specific validation function.
  validateType(_value) {
  }
  validate(value2) {
    if (!value2 && this.options.required)
      return "Required field";
    return this.validateType(value2) || this.options.validate && this.options.validate(value2);
  }
  clean(value2) {
    return this.options.clean ? this.options.clean(value2) : value2;
  }
};
var TextField = class extends Field2 {
  render() {
    let input = document.createElement("input");
    input.type = "text";
    input.placeholder = this.options.label;
    input.value = this.options.value || "";
    input.autocomplete = "off";
    return input;
  }
};

// public/app/ui/editors/prosemirror/basic-setup/menu.js
function wrapListItem(nodeType, options2) {
  return cmdItem(wrapInList(nodeType, options2.attrs), options2);
}
function canInsert(state, nodeType, attrs2) {
  let $from = state.selection.$from;
  for (let d3 = $from.depth; d3 >= 0; d3--) {
    let index2 = $from.index(d3);
    if ($from.node(d3).canReplaceWith(index2, index2, nodeType, attrs2)) return true;
  }
  return false;
}
function insertImageItem(nodeType) {
  return new MenuItem({
    title: "Insert image",
    icon: { dom: crel_es_default("i", { class: "fa fa-image" }) },
    enable(state) {
      return canInsert(state, nodeType);
    },
    run(state, _5, view) {
      let { from: from2, to } = state.selection, attrs2 = null;
      if (state.selection instanceof NodeSelection && state.selection.node.type == nodeType)
        attrs2 = state.selection.node.attrs;
      openPrompt(view, {
        title: "Insert image",
        fields: {
          src: new TextField({ label: "Location", required: true, value: attrs2 && attrs2.src }),
          title: new TextField({ label: "Title", value: attrs2 && attrs2.title }),
          alt: new TextField({
            label: "Description",
            value: attrs2 ? attrs2.title : state.doc.textBetween(from2, to, " ")
          })
        },
        callback(attrs3) {
          view.dispatch(view.state.tr.replaceSelectionWith(nodeType.createAndFill(attrs3)));
          view.focus();
        }
      });
    }
  });
}
function cmdItem(cmd2, options2) {
  let passedOptions = {
    label: options2.title,
    run: cmd2
  };
  for (let prop2 in options2) passedOptions[prop2] = options2[prop2];
  if ((!options2.enable || options2.enable === true) && !options2.select)
    passedOptions[options2.enable ? "enable" : "select"] = (state) => cmd2(state);
  return new MenuItem(passedOptions);
}
function markActive(state, type) {
  let { from: from2, $from, to, empty: empty4 } = state.selection;
  if (empty4) return type.isInSet(state.storedMarks || $from.marks());
  else return state.doc.rangeHasMark(from2, to, type);
}
function markItem(markType, options2) {
  let passedOptions = {
    active(state) {
      return markActive(state, markType);
    },
    enable: true
  };
  for (let prop2 in options2) passedOptions[prop2] = options2[prop2];
  return cmdItem(toggleMark(markType), passedOptions);
}
function linkItem(markType) {
  return new MenuItem({
    title: "Add or remove link",
    icon: { dom: crel_es_default("i", { class: "fa fa-link" }) },
    active(state) {
      return markActive(state, markType);
    },
    enable(state) {
      return !state.selection.empty;
    },
    run(state, dispatch, view) {
      if (markActive(state, markType)) {
        toggleMark(markType)(state, dispatch);
        return true;
      }
      openPrompt(view, {
        title: "Create a link",
        fields: {
          href: new TextField({
            label: "Link target",
            required: true,
            clean: (val) => {
              if (!/^https?:\/\//i.test(val))
                val = "http://" + val;
              return val;
            }
          }),
          title: new TextField({ label: "Title" })
        },
        callback(attrs2) {
          toggleMark(markType, attrs2)(view.state, view.dispatch);
          view.focus();
        }
      });
    }
  });
}
function buildMenuItems(schema7) {
  let r3 = {};
  let type;
  if (type = schema7.marks.strong) {
    r3.toggleStrong = markItem(type, {
      title: "Bold",
      icon: { dom: crel_es_default("i", { class: "fa fa-bold" }) }
    });
  }
  if (type = schema7.marks.em) {
    r3.toggleEm = markItem(type, {
      title: "Italic",
      icon: { dom: crel_es_default("i", { class: "fa fa-italic" }) }
    });
  }
  if (type = schema7.marks.link) {
    r3.toggleLink = linkItem(type);
  }
  if (type = schema7.nodes.image) {
    r3.insertImage = insertImageItem(type);
  }
  if (type = schema7.nodes.bullet_list) {
    r3.wrapBulletList = wrapListItem(type, {
      title: "Bullet list",
      icon: { dom: crel_es_default("i", { class: "fa fa-list-ul" }) },
      enable: true
    });
  }
  if (type = schema7.nodes.ordered_list) {
    r3.wrapOrderedList = wrapListItem(type, {
      title: "Ordered list",
      icon: { dom: crel_es_default("i", { class: "fa fa-list-ol" }) },
      enable: true
    });
  }
  if (type = schema7.nodes.blockquote) {
    r3.wrapBlockQuote = wrapItem(type, {
      title: "Block quote",
      icon: { dom: crel_es_default("i", { class: "fa fa-quote-left" }) }
    });
  }
  if (type = schema7.nodes.code_block) {
    r3.makeCodeBlock = blockTypeItem(type, {
      label: "Code block"
    });
  }
  if (type = schema7.nodes.paragraph) {
    r3.makeParagraph = blockTypeItem(type, {
      label: "Normal"
    });
  }
  if (type = schema7.nodes.heading) {
    for (let i3 = 1; i3 <= 10; i3++) {
      r3["makeHead" + i3] = blockTypeItem(type, {
        label: "Header " + i3,
        attrs: { level: i3 }
      });
    }
  }
  function getActiveBlockLabels(view) {
    let labels = blockMenuItems.filter((item) => item.spec && item.spec.active && item.spec.active(view.state)).map((item) => item.spec && item.spec.label);
    let menuDropItemLabel = labels.length ? labels.reduce((previous, current) => previous + ", " + current) : "Normal";
    return crel_es_default("span", null, view.props.translate(menuDropItemLabel));
  }
  let cut = (arr) => arr.filter((x3) => x3);
  let blockMenuItems = cut([r3.makeParagraph, r3.makeHead1, r3.makeHead2, r3.makeHead3, r3.makeCodeBlock]);
  if (r3.makeHead1) {
    r3.headingMenu = new MenuDropItem({
      title: "Styles",
      content: (view) => renderDropdownItems(blockMenuItems, view),
      render: getActiveBlockLabels,
      caret: true
    });
  }
  r3.baseMenu = [r3.headingMenu].concat(cut([r3.toggleStrong, r3.toggleEm]));
  r3.insertMenu = cut([r3.wrapBlockQuote, r3.toggleLink, r3.insertImage]);
  r3.listMenu = cut([r3.wrapBulletList, r3.wrapOrderedList]);
  r3.fullMenu = [r3.baseMenu, r3.insertMenu, r3.listMenu];
  return r3;
}

// public/app/ui/editors/prosemirror/basic-setup/plugins/utils.js
var acceptedFileTypes = [
  "image/gif",
  "image/png",
  "image/jpeg",
  "image/bmp"
];
function getImage(items) {
  if (window.DragEvent || window.Clipboard || window.ClipboardEvent) {
    for (var i3 = 0; i3 < items.length; i3++) {
      if (acceptedFileTypes.indexOf(items[i3].type) !== -1) {
        var blob = items[i3].getAsFile() || items[i3].webkitGetAsEntry();
        if (blob) {
          return blob;
        }
      }
    }
  }
}
function isFileData(dataTransfer) {
  if (!dataTransfer) {
    return false;
  }
  return dataTransfer.types.length === 1 && dataTransfer.types[0] === "Files" || dataTransfer.types.length === 2 && dataTransfer.types[0] === "application/x-moz-file" && dataTransfer.types[1] === "Files";
}

// public/app/ui/editors/prosemirror/basic-setup/plugins/paste-image.js
var pasteImageKey = new PluginKey("pasteImage");
function getImageFromPasteEvent(event2) {
  if (!event2.clipboardData || !event2.clipboardData.items || !event2.clipboardData.items.length) {
    return;
  }
  var imageBlob = getImage(event2.clipboardData.items);
  if (imageBlob) {
    return imageBlob;
  }
}
function pasteImage() {
  return new Plugin({
    key: pasteImageKey,
    props: {
      handleDOMEvents: {
        paste: function(view, event2) {
          if (isFileData(event2.clipboardData)) {
            var imageBlob = getImageFromPasteEvent(event2);
            view.dispatch(view.state.tr.setMeta(pasteImageKey, imageBlob || null));
            if (imageBlob) {
              event2.preventDefault();
              event2.stopPropagation();
            }
          }
        }
      }
    },
    state: {
      init: function() {
        return {
          pastedImage: null
        };
      },
      apply: function(tr2) {
        return {
          pastedImage: tr2.getMeta(pasteImageKey) || null
        };
      }
    }
  });
}
function getPastedImage(state) {
  return pasteImageKey.getState(state).pastedImage;
}

// public/app/ui/editors/prosemirror/basic-setup/plugins/drag-and-drop-image.js
var dragAndDropImageKey = new PluginKey("dragAndDropImage");
function getImageFromDragAndDropEvent(event2) {
  if (!event2.dataTransfer || !event2.dataTransfer.items || !event2.dataTransfer.items.length) {
    return;
  }
  var imageBlob = getImage(event2.dataTransfer.items);
  if (imageBlob) {
    return imageBlob;
  }
}
function dragAndDropImage() {
  return new Plugin({
    key: dragAndDropImageKey,
    props: {
      handleDrop: function(view, event2, slice3, moved) {
        if (isFileData(event2.dataTransfer) && moved === false) {
          var imageBlob = getImageFromDragAndDropEvent(event2);
          view.dispatch(view.state.tr.setMeta(dragAndDropImageKey, imageBlob || null));
          if (imageBlob) {
            event2.preventDefault();
            event2.stopPropagation();
          }
        }
      }
    },
    state: {
      init: function() {
        return {
          dragAndDropImage: null
        };
      },
      apply: function(tr2) {
        return {
          dragAndDropImage: tr2.getMeta(dragAndDropImageKey) || null
        };
      }
    }
  });
}
function getDragAndDropImage(state) {
  return dragAndDropImageKey.getState(state).dragAndDropImage;
}

// public/app/ui/editors/prosemirror/basic-setup/index.js
function basicSetupPlugin(options2) {
  let plugins = [
    // basic input rules
    buildInputRules(options2.schema),
    dropCursor2(),
    gapCursor()
  ];
  if (options2.customKeymap) {
    Object.keys(options2.customKeymap).forEach(function(key2) {
      if (baseKeymap[key2]) {
        options2.customKeymap[key2] = chainCommands(baseKeymap[key2], options2.customKeymap[key2]);
      }
    });
    plugins.push(keymap2(options2.customKeymap));
  }
  plugins.push(
    keymap2(buildKeymap2(options2.schema, options2.mapKeys)),
    keymap2(baseKeymap)
  );
  if (options2.pasteImage !== false) plugins.push(pasteImage());
  if (options2.dragAndDropImage !== false) plugins.push(dragAndDropImage());
  if (options2.history !== false) plugins.push(history2());
  if (options2.menuBar !== false) {
    plugins.push(menuBar({
      floating: false,
      content: buildMenuItems(options2.schema).fullMenu
    }));
  }
  if (options2.class) {
    plugins.push(new Plugin({
      props: {
        attributes: { class: options2.class }
      }
    }));
  }
  return plugins;
}
var customNodes = nodes;
customNodes.uploading_image = {
  inline: true,
  attrs: {
    src: {},
    alt: { default: null },
    title: { default: null }
  },
  group: "inline",
  draggable: true,
  toDOM(node) {
    return [
      "span",
      { class: "ProseMirror-uploading-image" },
      ["img", node.attrs],
      ["i", { class: "fa fa-spinner fa-spin" }]
    ];
  }
};
var schema6 = new Schema({ nodes: customNodes, marks: marks2 });
var basicSchemaSpec = {
  nodes: addListNodes(schema6.spec.nodes, "paragraph block*", "block"),
  marks: schema6.spec.marks
};
var basicMarkdownParserTokens = {
  blockquote: { block: "blockquote" },
  paragraph: { block: "paragraph" },
  list_item: { block: "list_item" },
  bullet_list: { block: "bullet_list" },
  ordered_list: { block: "ordered_list", getAttrs: (tok) => ({ order: +tok.attrGet("order") || 1 }) },
  heading: { block: "heading", getAttrs: (tok) => ({ level: +tok.tag.slice(1) }) },
  code_block: { block: "code_block" },
  fence: { block: "code_block" },
  hr: { node: "horizontal_rule" },
  image: { node: "image", getAttrs: (tok) => ({
    src: tok.attrGet("src"),
    title: tok.attrGet("title") || null,
    alt: tok.children[0] && tok.children[0].content || null
  }) },
  hardbreak: { node: "hard_break" },
  em: { mark: "em" },
  strong: { mark: "strong" },
  link: { mark: "link", getAttrs: (tok) => ({
    href: tok.attrGet("href"),
    title: tok.attrGet("title") || null
  }) },
  code_inline: { mark: "code" }
};
var basicMarkdownSerializer = Object.assign(Object.create(defaultMarkdownSerializer), defaultMarkdownSerializer);
basicMarkdownSerializer.nodes.hard_break = function(state, node, parent, index2) {
  for (let i3 = index2 + 1; i3 < parent.childCount; i3++) {
    if (parent.child(i3).type != node.type) {
      state.write("\n");
      return;
    }
  }
};
basicMarkdownSerializer.nodes.uploading_image = function(state, node) {
  state.write("![" + state.esc(node.attrs.alt || "") + "](" + state.esc(node.attrs.src) + (node.attrs.title ? " " + state.quote(node.attrs.title) : "") + ")");
};

// public/app/ui/editors/prosemirror/ui/tooltip-drop.js
var TooltipDrop = class {
  constructor(view) {
    this.view = view;
    this.bindedDestroy = this.destroy.bind(this);
    this.view.props.on.editorDestroy.add(this.bindedDestroy);
  }
  close() {
    this.drop && this.drop.isOpened() && this.drop.close();
  }
  destroy() {
    this.view.props.on.editorDestroy.remove(this.bindedDestroy);
    this.close();
    this.drop && this.drop.drop && this.drop.destroy();
    this.drop = null;
    return true;
  }
  isOpened() {
    return this.drop && this.drop.isOpened();
  }
  open(content2, coord) {
    var self2 = this;
    let wrapperCoord = this.view.dom.getBoundingClientRect();
    let newCoord = {
      left: coord.left - wrapperCoord.left,
      top: coord.top - wrapperCoord.top
    };
    this.drop = new Drop({
      target: this.view.dom,
      content: content2,
      classes: "drop-theme-prosemirror tooltip-theme-prosemirror",
      constrainToScrollParent: false,
      openOn: null,
      remove: true,
      tetherOptions: {
        targetAttachment: "top left",
        attachment: "top left",
        targetOffset: newCoord.top + "px " + newCoord.left + "px",
        constraints: [
          {
            to: "window",
            attachment: "element",
            pin: true
          }
        ]
      }
    });
    function stopEvent(e3) {
      e3.preventDefault();
      e3.stopPropagation();
    }
    this.drop.on("open", function() {
      self2.drop.drop && self2.drop.drop.addEventListener("mousedown", stopEvent);
    });
    this.drop.on("close", function() {
      self2.drop.drop && self2.drop.drop.removeEventListener("mousedown", stopEvent);
    });
    this.drop.open();
  }
};

// public/app/ui/editors/prosemirror/mentions/tooltip-drop.js
var MentionTooltipDrop = class extends TooltipDrop {
  constructor(view, spec) {
    super(view);
    let self2 = this;
    this.spec = spec;
    this.items = this.createItems(spec.mentions);
    this.coords = spec.coords;
    this.selectedMentionIdx = -1;
    this.keymapPlugin = keymap2({
      "ArrowUp": function(state, dispatch, view2) {
        self2.selectMention("up");
        return true;
      },
      "ArrowDown": function(state, dispatch, view2) {
        self2.selectMention("down");
        return true;
      },
      "Enter": function(state, dispatch, view2) {
        if (self2.selectedMentionIdx > -1) {
          self2.applyCompletion(self2.spec.mentions[self2.selectedMentionIdx], state, dispatch);
          return true;
        }
        return false;
      },
      "Tab": function(state, dispatch, view2) {
        if (self2.selectedMentionIdx > -1) {
          self2.applyCompletion(self2.spec.mentions[self2.selectedMentionIdx], state, dispatch);
          return true;
        }
        return false;
      }
    });
  }
  open() {
    super.open(
      crel_es_default("div", {}, this.items),
      { left: this.coords.left, top: this.coords.bottom }
    );
    this.selectMention();
    let newState = this.view.state.reconfigure({
      plugins: [this.keymapPlugin].concat(this.view.state.plugins)
    });
    if (this.view.props.isIE) {
      this.view.state = newState;
    } else {
      this.view.updateState(newState);
      if (!this.view.hasFocus()) this.view.focus();
    }
  }
  close() {
    let self2 = this;
    super.close();
    let newState = this.view.state.reconfigure({
      plugins: this.view.state.plugins.filter(function(plugin) {
        return plugin.key !== self2.keymapPlugin.key;
      })
    });
    if (this.view.props.isIE) {
      this.view.state = newState;
    } else {
      this.view.updateState(newState);
      if (!this.view.hasFocus()) this.view.focus();
    }
  }
  destroy() {
    super.destroy();
    this.spec = null;
    this.view = null;
    this.coords = null;
    this.keymapPlugin = null;
    this.selectedMentionIdx = -1;
  }
  createItems(mentions) {
    let self2 = this;
    return mentions.map(function(mention) {
      let item;
      let name2 = crel_es_default("span", {}, mention.display_name);
      let markup = crel_es_default("span", { class: "mention-markup" }, "@" + mention.username);
      let nameContainer = crel_es_default("div", { class: "mention-name" }, name2, markup);
      if (mention.avatar) {
        let icon = crel_es_default("img", { src: mention.avatar, class: "mention-avatar", title: mention.username });
        item = crel_es_default("div", { class: "mention-item" }, icon, nameContainer);
      } else {
        item = crel_es_default("div", { class: "mention-item" }, nameContainer);
      }
      item.addEventListener("mousedown", function(e3) {
        e3.preventDefault();
        e3.stopPropagation();
        self2.applyCompletion(mention);
      });
      item.addEventListener("mouseenter", function(e3) {
        e3.preventDefault();
        e3.stopPropagation();
        self2.selectMention(mention);
      });
      return item;
    });
  }
  applyCompletion(mention, state, dispatch) {
    let from2 = this.spec.from;
    let to = this.spec.to;
    let currentState = state || this.view.state;
    let transaction = function(state2) {
      return state2.tr.delete(from2, to).insert(from2, state2.schema.node("mention", mention)).insertText(" ");
    };
    if (dispatch) {
      dispatch(transaction(currentState));
    } else {
      this.view.dispatch(transaction(currentState));
    }
    this.destroy();
  }
  selectMention(mention) {
    let oldSelectedMentionIdx = this.selectedMentionIdx;
    if (mention === "up") {
      if (this.selectedMentionIdx - 1 < 0) {
        this.selectedMentionIdx = this.spec.mentions.length - 1;
      } else {
        this.selectedMentionIdx -= 1;
      }
    } else if (mention === "down") {
      if (this.selectedMentionIdx + 1 >= this.spec.mentions.length) {
        this.selectedMentionIdx = 0;
      } else {
        this.selectedMentionIdx += 1;
      }
    } else if (mention && mention.username) {
      this.selectedMentionIdx = this.spec.mentions.findIndex(
        (m3) => m3.username === mention.username
      );
    } else {
      this.selectedMentionIdx = 0;
    }
    if (oldSelectedMentionIdx >= 0) {
      this.items[oldSelectedMentionIdx].classList.remove("selected");
    }
    if (this.selectedMentionIdx >= 0) {
      this.items[this.selectedMentionIdx].classList.add("selected");
    }
  }
};

// public/app/ui/editors/prosemirror/mentions/node-spec.js
var mentionSpec = {
  inline: true,
  group: "inline",
  draggable: false,
  attrs: {
    username: {}
  },
  toDOM: function(node) {
    return ["span", {
      "mention-username": node.attrs.username,
      class: "mention-node"
    }, "@" + node.attrs.username];
  },
  parseDOM: [{
    tag: "span[mention-username]",
    getAttrs: function(dom) {
      let attrs2 = {
        username: dom.getAttribute("mention-username")
      };
      let mentions = this.schema.data.mentions;
      if (Array.isArray(mentions) && mentions.find((m3) => m3.username === attrs2.username)) {
        return attrs2;
      }
    }
  }]
};

// public/app/ui/editors/prosemirror/mentions/index.js
function scanForMention(state, head2, text3, view) {
  head2 = head2 || state.selection.head;
  if (head2 === null) return;
  let $pos = state.doc.resolve(head2), line = "";
  for (let i3 = 0, rem = $pos.parentOffset; rem > 0; i3++) {
    let child = $pos.parent.child(i3);
    if (child.isText) line += child.text.slice(0, rem);
    else line = "";
    rem -= child.nodeSize;
  }
  if (text3) {
    line += text3;
  }
  if (!/(^|[\s\v])@\w*/.test(line)) return;
  let roleMentionBracket = line.lastIndexOf("@@");
  let userMentionBracket = line.lastIndexOf("@");
  if (userMentionBracket === -1 && roleMentionBracket === -1) return;
  let word = line.slice((roleMentionBracket === -1 ? userMentionBracket : roleMentionBracket) + 1);
  let completions = state.schema.data.mentions.filter((m3) => m3.username.toLowerCase().indexOf(word.toLowerCase()) === 0);
  if (completions.length) {
    if (currentTooltip && currentTooltip.spec && currentTooltip.spec.word === word) {
      currentTooltip.open();
    } else {
      if (currentTooltip && currentTooltip.spec) {
        currentTooltip.destroy();
      }
      currentTooltip = new MentionTooltipDrop(view, {
        mentions: completions,
        from: text3 ? head2 - word.length : head2 - word.length - 1,
        to: text3 ? head2 + 1 : head2,
        coords: view.coordsAtPos(head2 - word.length),
        word
      });
      currentTooltip.open();
    }
    return true;
  }
}
var currentTooltip;
var backspaceKeymapPlugin = keymap2({
  "Backspace": function(state, dispatch, view) {
    if (currentTooltip && currentTooltip.isOpened()) {
      let found2 = scanForMention(state, state.selection.head - 1, null, view);
      if (!found2) {
        currentTooltip.destroy();
      }
    }
    return false;
  }
});
var mentionAutocompletePlugin = new Plugin({
  props: {
    handleTextInput: function(view, from2, to, text3) {
      if (!/[@\w]/.test(text3)) return false;
      let found2 = scanForMention(view.state, null, text3, view);
      if (!found2 && currentTooltip && currentTooltip.spec) {
        currentTooltip.destroy();
      }
      return false;
    }
  }
});
function mentionAutocompletePlugins(config3) {
  return [backspaceKeymapPlugin, mentionAutocompletePlugin];
}
var mentionMarkdownParserToken = {
  node: "mention",
  attrs: (tok) => ({ username: tok.content })
};
function mentionMarkdownSerializer(state, node) {
  state.text("@" + node.attrs.username);
}

// public/app/ui/editors/prosemirror/prosemirror.js
var markdownit2 = (0, import_markdown_it3.default)("commonmark", { html: false }).use(import_markdown_it_flowdock.default).disable(["hashtag", "flowdock-url"]);
var simpleMarkdownIt = (0, import_markdown_it3.default)("commonmark", { html: false });
function getSchema2(type) {
  var nodes2 = basicSchemaSpec.nodes;
  if (type === "comment" || type === "content") {
    nodes2 = basicSchemaSpec.nodes.addBefore("text", "mention", mentionSpec);
  }
  return new Schema({
    nodes: nodes2,
    marks: basicSchemaSpec.marks
  });
}
function getPlugins(options2, type) {
  let plugins = basicSetupPlugin(options2);
  if (type === "comment" || type === "content") {
    plugins = mentionAutocompletePlugins().concat(plugins);
  }
  return plugins;
}
function getMarkdownParserTokens(type) {
  if (type === "comment" || type === "content") {
    return Object.assign({}, basicMarkdownParserTokens, {
      mention: mentionMarkdownParserToken
    });
  }
  return basicMarkdownParserTokens;
}
function getMarkdownItVersion(type) {
  if (type === "comment" || type === "content") {
    return markdownit2;
  }
  return simpleMarkdownIt;
}
function getMarkdownParser(schema7, type) {
  return new MarkdownParser(schema7, getMarkdownItVersion(type), getMarkdownParserTokens(type));
}
function getMarkdownSerializer(type) {
  let markdownSerializer = Object.assign(Object.create(basicMarkdownSerializer), basicMarkdownSerializer);
  if (type === "comment" || type === "content") {
    markdownSerializer.nodes.mention = mentionMarkdownSerializer;
  }
  return markdownSerializer;
}
angular_default.module("kantree").factory("prosemirror", [
  "ProsemirrorUploadImageToolbarItem",
  function(ProsemirrorUploadImageToolbarItem) {
    var prosemirror = {};
    var baseMentions = [{ display_name: _4("All workspace members"), username: "all" }];
    prosemirror.buildMentionsData = function(data2) {
      const mentions = [];
      const org2 = orgStore.tryGetForProject(projectStore.tryGet(data2.project_id));
      for (const member of projectMemberStore.scopedByProject({ id: data2.project_id }).query({}, { sortBy: "user.username" })) {
        mentions.push(member.user);
      }
      if (org2) {
        for (const role of roleStore.scopedByOrg(org2).query({}, { sortBy: "name" })) {
          mentions.push({
            display_name: _4("All {role} members", { role: role.name }),
            username: "@" + role.name.replace(" ", "").toLowerCase()
          });
        }
      }
      if (data2.project_id) {
        let project = projectStore.get(data2.project_id);
        let org3 = orgStore.tryGetForProject(project);
        if (org3?.ai_enabled) {
          mentions.push({
            display_name: _4("Kantree Assistant"),
            username: "kantree",
            avatar: makeUrlAbsolute("/static/assets/favicon.png")
          });
        }
      }
      return baseMentions.concat(mentions);
    };
    prosemirror.createEditor = function(element2, type, text3, data2, hotkeys, scope, onTransactionCallback) {
      type = type || "default";
      var customKeymap;
      if (hotkeys) {
        customKeymap = hotkeys.map(function(hotkey) {
          var newCombo = hotkey.combo.replace(/\+/g, "-").split("-").map(function(comboPart) {
            return comboPart.charAt(0).toUpperCase() + comboPart.slice(1);
          }).join("-");
          return {
            key: newCombo,
            cmd: hotkey.callback
          };
        }).reduce(function(accu, hotkey) {
          accu[hotkey.key] = hotkey.cmd;
          return accu;
        }, {});
      }
      var schema7 = getSchema2(type);
      if (type === "comment" || type === "content") {
        schema7.data = Object.assign(schema7.data || {}, {
          mentions: prosemirror.buildMentionsData(data2)
        });
      }
      var plugins = getPlugins({
        schema: schema7,
        class: "ProseMirror-kantree-style ProseMirror-content",
        menuBar: false,
        // we build the menubar later,
        // Remove Ctrl-Enter default map keys : (see prosemirror-example-setup/keymaps)
        // Only Shift-Enter remains to add hard_breaks (<br>)
        hotkeys: {
          "Mod-Enter": false,
          "Ctrl-Enter": false
        },
        customKeymap
      }, type);
      plugins.push(getMenuBarPlugin(scope, data2, schema7));
      var stateConfig = {
        schema: schema7,
        plugins
      };
      var markdownParser = getMarkdownParser(schema7, type);
      var markdownSerializer = getMarkdownSerializer(type);
      if (text3) {
        stateConfig.doc = markdownParser.parse(text3);
      }
      var view = new EditorView2(element2, {
        on: {
          editorDestroy: new import_subscription2.Subscription(),
          blur: new import_subscription2.Subscription(),
          interaction: new import_subscription2.Subscription()
        },
        state: EditorState.create(stateConfig),
        dispatchTransaction: function(tr2) {
          view.updateState(view.state.apply(tr2));
          view.props.on.interaction.dispatch();
          if (onTransactionCallback) onTransactionCallback(tr2, view);
        },
        handleDOMEvents: {
          blur: function() {
            view.props.on.blur.dispatch();
          }
        },
        translate: _4,
        isIE: isIE()
      });
      view.markdownParser = markdownParser;
      view.markdownSerializer = markdownSerializer;
      if (type === "comment" || type === "content") {
        var off = projectMemberStore.scopedByProject({ id: data2.project_id }).subscribe(() => {
          view.state.schema.data.mentions = prosemirror.buildMentionsData(data2);
        });
        view.props.on.editorDestroy.add(off);
      }
      return view;
    };
    prosemirror.fromMarkdown = function(pmView, text3) {
      return pmView.markdownParser.parse(text3);
    };
    prosemirror.toMarkdown = function(pmView) {
      return pmView.markdownSerializer.serialize(pmView.state.doc);
    };
    var getMenuBarPlugin = function(scope, data2, schema7) {
      var menuItemsFactory = buildMenuItems(schema7);
      menuItemsFactory.insertMenu = [
        menuItemsFactory.wrapBlockQuote,
        menuItemsFactory.toggleLink,
        ProsemirrorUploadImageToolbarItem(scope, data2, schema7)
      ];
      if (data2 && data2.toolbarItems) {
        data2.toolbarItems.forEach((item) => {
          menuItemsFactory.insertMenu.push(item(scope, data2, schema7));
        });
      }
      var menuItems = [
        menuItemsFactory.baseMenu,
        menuItemsFactory.insertMenu,
        menuItemsFactory.listMenu
      ];
      return menuBar({
        floating: false,
        content: menuItems
      });
    };
    return prosemirror;
  }
]);

// public/app/ui/editors/prosemirror/upload-image-toolbar-item.js
angular_default.module("kantree").factory("ProsemirrorUploadImageToolbarItem", [
  "ProsemirrorPrettyMenuItem",
  "$q",
  function(ProsemirrorPrettyMenuItem, $q) {
    function loadImage(element2, src) {
      return new Promise((resolve2, reject2) => {
        const retryInterval = 1e3;
        const retryDecay = 1.2;
        var retryAttempts = -1;
        function tryLoad() {
          retryAttempts++;
          if (retryAttempts > 15) return reject2();
          jquery_default(element2).attr("src", src + "?" + (/* @__PURE__ */ new Date()).getTime()).each(function() {
            if (this.complete) jquery_default(this).trigger("load");
          });
        }
        jquery_default(element2).on("load", () => resolve2()).on("error", () => setTimeout(tryLoad, retryInterval * Math.pow(retryDecay, retryAttempts)));
        tryLoad();
      });
    }
    return function(scope, data2, schema7) {
      let card;
      if (data2 && data2.card_id) {
        card = cardStore.get(data2.card_id);
      }
      var updateView2 = function(view, img) {
        var attrs2 = {
          src: img.url
        };
        if (img.name) {
          attrs2.alt = img.name;
          attrs2.title = img.name;
        }
        if (schema7.nodes.uploading_image) {
          view.dispatch(view.state.tr.replaceSelectionWith(schema7.nodes.uploading_image.create(attrs2, null)));
          view.focus();
          loadImage(jquery_default('.ProseMirror-content [src="' + img.url + '"]').get(0), img.url).finally(() => {
            var nodePos = [];
            view.state.doc.descendants((node, pos, parent) => {
              if (node.attrs.src === img.url) {
                nodePos.push(pos);
              }
            });
            nodePos.forEach((pos) => view.dispatch(view.state.tr.replaceRangeWith(pos, pos + 1, schema7.nodes.image.create(attrs2, null))));
          });
        } else {
          view.dispatch(view.state.tr.replaceSelectionWith(schema7.nodes.image.create(attrs2, null)));
          view.focus();
        }
      };
      var getImageTabItems = function(card2, view) {
        if (!card2) {
          return [];
        }
        var items = [];
        var model = getCardCompositeModel(card2, false);
        var attributeGroup = model.attributes;
        var attrs2 = attributeGroup.getObjAttributes(card2);
        var images = attrs2.filter(function(attr) {
          return attr.type === "files";
        }).reduce(function(accu, attr) {
          return accu.concat(attr.value.filter(function(file) {
            return file.mimetype && file.mimetype.match(/^image\//i);
          }));
        }, []);
        items.push({
          imagepicker: true,
          numberByRow: 2,
          images,
          action: function(event2, image2) {
            updateView2(view, image2);
          }
        });
        if (!images.length) {
          items.push({
            desc: _4("You haven't attached any images to this card yet"),
            classes: "menu-item-prosemirror-no-image"
          });
        }
        return items;
      };
      var pastedImage, dropedImage;
      var getUploadTabItems = function(card2, view) {
        if (!card2) {
          return [];
        }
        var items = [];
        var model = getCardCompositeModel(card2, false);
        var attrs2 = model.attributes.filter(function(attr) {
          return attr.type === "files";
        });
        var projectValue = {
          name: _4("Nothing"),
          id: -1
        };
        var currentStorage = projectValue;
        items.push({
          subheader: _4("Attach to"),
          help: _4("Whether to attach files to a field when uploading them.")
        });
        items.push({
          selectbox: true,
          select: function(obj) {
            currentStorage = obj;
          },
          selectOptions: [projectValue].concat(attrs2),
          optionsLabelProperty: "name",
          defaultValue: projectValue
        });
        items.push({
          label: "--"
        });
        var uploadProgress;
        var pickedFile = pastedImage || dropedImage;
        items.push({
          filepicker: true,
          readOnly: false,
          noCloseAfterAction: true,
          // File object type doesn't resist to prettymenu initialization
          // so passes it through a function
          initialFile: function() {
            return pickedFile;
          },
          action: function(event2, file) {
            pickedFile = file;
          }
        });
        items.push({
          buttons: [{
            label: _4("Upload and insert"),
            classes: "btn-success",
            disabled: function() {
              return !pickedFile;
            },
            noCloseAfterAction: true,
            action: function(event2) {
              var self2 = this;
              uploadProgress = 1;
              if (currentStorage.id === -1) {
                upload({
                  url: api_default.project_files.upload_file.url({ project_id: card2.project_id }),
                  data: { files: pickedFile },
                  arrayKey: ""
                }, function(evt) {
                  uploadProgress = parseInt(100 * evt.loaded / evt.total);
                }).then(function(r3) {
                  uploadProgress = false;
                  updateView2(view, r3.data[0]);
                  self2.close();
                }, function(resp) {
                  errorDialog(_4("An error occured while uploading your file"));
                });
              } else {
                $q.when(appendFilesToCardAttribute(card2, currentStorage.id, pickedFile, (evt) => {
                  uploadProgress = parseInt(100 * evt.loaded / evt.total);
                }), (attr) => {
                  const image2 = attr.value[attr.value.length - 1];
                  uploadProgress = false;
                  updateView2(view, image2);
                  self2.close();
                });
              }
            }
          }]
        });
        return items;
      };
      var getTabs = function(card2, view) {
        var url2;
        var name2;
        var tabs = [];
        if (card2) {
          tabs.push({
            title: _4("Upload"),
            isInline: true,
            items: getUploadTabItems(card2, view)
          });
          tabs.push({
            title: _4("From existing files"),
            isInline: true,
            items: getImageTabItems(card2, view)
          });
        }
        tabs.push({
          title: _4("Using Url"),
          isInline: true,
          items: [
            {
              subheader: _4("Paste an URL here")
            },
            {
              input: true,
              defaultValue: url2 || null,
              onChange: function(value2) {
                url2 = value2;
              },
              reset: function() {
                url2 = null;
              }
            },
            {
              label: _4("Insert"),
              classes: "menu-item-prosemirror-imagepicker menu-item-select-btn",
              action: function() {
                if (!url2 || jquery_default.trim(url2) === "") {
                  return;
                }
                updateView2(view, { url: url2 });
              },
              disabled: function() {
                return !url2 || jquery_default.trim(url2) === "";
              }
            }
          ]
        });
        return tabs;
      };
      return new ProsemirrorPrettyMenuItem({
        title: _4("Insert image"),
        icon: "image",
        dropConfig: {
          classes: "drop-theme-menu drop-theme-arrow drop-theme-prosemirror drop-theme-prosemirror-imagepicker"
        },
        getMenu: function(view) {
          var options2 = {
            title: _4("Insert image"),
            withTabs: true
          };
          if (card) {
            options2.watch = function(cb2, scope2) {
              var offs = [
                cardModelStore.scopedByEnabled(card).$watchAll(scope2, cb2, false),
                cardStore.$watch(scope2, card, "updated", cb2, false)
              ];
              return function() {
                return offs.forEach(function(off) {
                  off();
                });
              };
            };
            options2.fetchData = function(cb2) {
              $q.when(getOrLoadModelForCard(card, { ignoreErrorHandlers: true }), cb2, cb2);
            };
          }
          return {
            config: function() {
              return getTabs.bind(this, card, view);
            },
            options: options2
          };
        },
        update: function(state, view, scope2) {
          pastedImage = getPastedImage(state);
          dropedImage = getDragAndDropImage(state);
          if (pastedImage || dropedImage) {
            scope2.$evalAsync(function() {
              scope2.forceOpen = true;
            });
          }
        },
        onDropClosed: function(view, scope2) {
          pastedImage = null;
          dropedImage = null;
          if (scope2.forceOpen || dropedImage) {
            scope2.$evalAsync(function() {
              scope2.forceOpen = false;
            });
          }
        }
      }, scope);
    };
  }
]);

// public/app/ui/editors/recurrence-editor/recurrence-editor.js
angular_default.module("kantree").component("recurrenceEditor", {
  bindings: {
    recurrence: "<?",
    onChange: "&"
  },
  templateUrl: "/static/app/ui/editors/recurrence-editor/templates/recurrence-editor.html",
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.frequencies = [{
        name: "hourly",
        label: _4("Hourly")
      }, {
        name: "daily",
        label: _4("Daily")
      }, {
        name: "weekly",
        label: _4("Weekly")
      }, {
        name: "monthly",
        label: _4("Monthly")
      }];
      this.monthdays = Array.apply(null, Array(31)).map((_5, i3) => i3 + 1);
      this.weekdays = moment_default.weekdaysMin(true);
      const hours = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11"];
      const hours24 = hours.concat(["12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]);
      this.isHours24Selector = !isLocaleDisplayAmPm();
      this.hours = this.isHours24Selector ? hours24 : hours;
      this.minutes = ["00", "15", "30", "45"];
      this.amPm = ["AM", "PM"];
    }
    updateEditor() {
      this.onChange({ $recurrence: this.recurrence });
    }
    isFrequencySelected(frequency) {
      return this.recurrence.frequency === frequency;
    }
    selectFrequency(frequency) {
      this.recurrence.frequency = frequency;
      if (this.recurrence.frequency === "daily") {
        this.recurrence.weekdays = [];
      } else if (this.recurrence.frequency === "weekly") {
        this.recurrence.weekdays = [0];
      }
      this.updateEditor();
    }
    isMonthdaySelected(monthday) {
      return this.recurrence.monthdays.includes(monthday);
    }
    toggleMonthdays(selectedMonthday) {
      if (this.recurrence.monthdays.includes(selectedMonthday)) {
        this.recurrence.monthdays = this.recurrence.monthdays.filter((monthday) => monthday !== selectedMonthday);
      } else {
        this.recurrence.monthdays.push(selectedMonthday);
      }
      this.updateEditor();
    }
    isWeekdaySelected(weekdayIdx) {
      return this.recurrence.weekdays.includes(weekdayIdx);
    }
    toggleWeekdays(weekdayIdx) {
      if (this.recurrence.weekdays.includes(weekdayIdx)) {
        this.recurrence.weekdays = this.recurrence.weekdays.filter((weekday) => weekday !== weekdayIdx);
      } else {
        this.recurrence.weekdays.push(weekdayIdx);
      }
      this.updateEditor();
    }
    isAmPmSelected(amPm) {
      return this.recurrence.amPm === amPm;
    }
    selectAmPm(amPm) {
      this.recurrence.amPm = amPm;
      this.updateEditor();
    }
  }
});

// public/app/ui/editors/sharing-editor/sharing-editor.js
angular_default.module("kantree").component("sharingEditor", {
  bindings: {
    objectId: "<",
    objectType: "<",
    onShare: "&",
    onUnshare: "&",
    onEmbed: "&"
  },
  templateUrl: "/static/app/ui/editors/sharing-editor/templates/sharing-editor.html",
  controller: class extends AngularClass {
    static $inject = ["$state", "$scope", "$q", "shareEmbedModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.sharedObjectTypes = /* @__PURE__ */ new Map([
        ["view", {
          store: viewStore,
          emptyLabel: _4("This view is not shared"),
          linkLabel: _4("Anyone with the following link can access this view (read-only):"),
          onInit: () => {
            this.requestForms = [];
            const formStore = requestFormStore.scopedByProject(this.project).scoped({ "public_permission": 2 });
            formStore.$watchAll(this.$scope, () => {
              this.requestForms = formStore.query();
            });
            this.$q.digest(loadAllRequestFormsForProject(this.project));
          },
          canSelectShowFieldOption: (view) => {
            return ["list", "kanban", "table"].includes(view.mode);
          }
        }],
        ["card", {
          store: cardStore,
          emptyLabel: _4("This card is not shared"),
          linkLabel: _4("Anyone with the following link can view this card (read-only):")
        }]
      ]);
      this.store = this.sharedObjectTypes.get(this.objectType)?.store;
      this.object = this.store.get(this.objectId);
      this.project = projectStore.get(this.object.project_id);
      this.canEdit = canManageMembers(this.project);
      if (this.canEdit) {
        this.sharedObjectTypes.get(this.objectType)?.onInit?.();
      }
      this.selectedRequestFormIds = [];
      this.shareOptions = {};
      this.$scope.$watch(() => this.object.share_token, () => {
        if (this.object.share_token) {
          this.$q.when(api_default.share_objects.get.get({ token: this.object.share_token }), (sharing) => {
            this.selectedRequestFormIds = sharing.forms.map((form) => form.id);
            this.shareOptions = sharing.options;
          });
        } else {
          this.selectedRequestFormIds = [];
          this.shareOptions = {};
        }
      });
      if (this.object.share_token) {
        this.refreshLink();
      } else if (this.canEdit) {
        this.share();
      }
    }
    get emptyLabel() {
      return this.sharedObjectTypes.get(this.objectType)?.emptyLabel;
    }
    get linkLabel() {
      return this.sharedObjectTypes.get(this.objectType)?.linkLabel;
    }
    get canSelectShowFieldOption() {
      return this.sharedObjectTypes.get(this.objectType)?.canSelectShowFieldOption?.(this.object);
    }
    refreshLink() {
      this.link = makeUrlAbsolute(this.$state.href("share", { token: this.object.share_token }, { "absolute": true }));
    }
    share() {
      this.$q.when(api_default.share_objects.create.post({
        project_id: this.object.project_id,
        object_type: this.objectType,
        object_id: this.object.id
      }), (sharing) => {
        this.object = this.store.update(this.object, {
          share_token: sharing.token
        });
        this.refreshLink();
        this.onShare();
      });
    }
    unshare() {
      this.$q.when(api_default.share_objects.delete.delete({
        token: this.object.share_token
      }), () => {
        this.object = this.store.update(this.object, {
          share_token: null
        });
        this.link = null;
        this.onUnshare();
      });
    }
    toggleForm(form, isChecked) {
      const params = {
        token: this.object.share_token,
        request_form_id: form.id
      };
      let req;
      if (isChecked) {
        req = api_default.share_objects.add_form.post(params);
      } else {
        req = api_default.share_objects.remove_form.delete(params);
      }
      this.$q.when(req, (sharing) => {
        this.selectedRequestFormIds = sharing.forms.map((form2) => form2.id);
      });
    }
    updateOptions(optionName, value2) {
      this.$q.when(api_default.share_objects.update.put({
        token: this.object.share_token,
        options: { ...this.shareOptions, [optionName]: value2 }
      }), (sharing) => {
        this.shareOptions = sharing.options;
      });
    }
    embed() {
      this.$shareEmbedModal.open(this.link);
      this.onEmbed();
    }
  }
});
angular_default.module("kantree").component("sharingEditorMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&",
    onUpdate: "&"
  },
  template: `
    <sharing-editor
      object-id="$ctrl.params.object_id"
      object-type="$ctrl.params.object_type"
      on-share="$ctrl.onUpdate()"
      on-unshare="$ctrl.onClose()"
      on-embed="$ctrl.onClose({$forceClose: true})"
    ></sharing-editor>`
});

// public/app/ui/editors/actions-editor/actions-appearance-editor.js
var elementsInit = { withName: true, withIcon: true, withBackground: true };
angular_default.module("kantree").factory("actionsAppearanceEditorMenuFactory", [
  "$q",
  function($q) {
    const getAppearanceItems = function(rule, project, elements, actionCb) {
      const items = [];
      if (elements.withName) {
        items.push(
          { subheader: _4("Name") },
          {
            input: true,
            submit: function(name2) {
              if (rule.name === name2) {
                return;
              }
              if (actionCb) {
                return actionCb({ name: name2 });
              }
              return $q.digest(saveAutomationRule(project, Object.assign({}, rule, { name: name2 })));
            },
            defaultValue: rule && rule.name ? rule.name : null
          }
        );
      }
      if (elements.withIcon) {
        items.push(
          { subheader: _4("Icon"), help: _4("This icon will be displayed on the left of the action.") },
          {
            iconpicker: true,
            getValue: function() {
              return rule ? rule.icon : null;
            },
            emptyIcon: true,
            color: rule ? rule.background_color : null,
            action: function(event2, icon) {
              if (rule.icon === icon) {
                return;
              }
              if (actionCb) {
                return actionCb({ icon });
              }
              return $q.digest(saveAutomationRule(project, Object.assign({}, rule, { icon })));
            },
            noCloseAfterAction: true,
            extended: true,
            options: {
              watch: watchRule.bind(this, rule)
            }
          }
        );
      }
      if (elements.withBackground) {
        items.push(
          { subheader: _4("Background color"), help: _4("Choose the background color of the action.") },
          {
            colorpicker: true,
            getValue: function() {
              return rule ? rule.background_color : null;
            },
            action: function(event2, background_color) {
              if (rule.background_color === background_color) {
                return;
              }
              if (actionCb) {
                return actionCb({ background_color });
              }
              return $q.digest(saveAutomationRule(project, Object.assign({}, rule, { background_color })));
            },
            noCloseAfterAction: true,
            hasColorPalette: true,
            watcher: (callback, scope) => scope.$watch(() => scope.$ctrl.item.getValue(), callback)
          }
        );
      }
      return items;
    };
    const watchRule = function(rule, cb2, scope) {
      var off = automationRuleStore.$watch(scope, rule, "updated", function() {
        cb2 && cb2();
      }, false);
      return off;
    };
    const getTabs = function(rule, project, elements, actionCb) {
      return [{
        items: getAppearanceItems(rule, project, elements, actionCb)
      }];
    };
    return {
      getTabs,
      watch: watchRule,
      get: function(rule, project, elements = {}, actionCb = void 0) {
        var menuOpts = {
          withTabs: true,
          watch: watchRule.bind(this, rule),
          title: _4("Edit the action's appearance")
        };
        const elementsConfig = { ...elementsInit, ...elements };
        var menuConfig = function() {
          return getTabs.bind(this, rule, project, elementsConfig, actionCb);
        };
        return {
          config: menuConfig,
          options: menuOpts
        };
      }
    };
  }
]);

// public/app/config/automation.js
var automationActionsCategories = {
  "card": _lazy("Actions on cards"),
  "project": _lazy("Actions on the Workspace"),
  "remote": _lazy("External data sources"),
  "programming": _lazy("Programming"),
  "AI": _lazy("AI")
};
var automationEventsCategories = {
  "card": _lazy("Events related to cards"),
  "project": _lazy("Events related to the Workspace")
};

// public/app/ui/editors/automation-rule-editor/rule-editor.js
var CARD_VARIABLES = [
  ["Card ID", "card.id"],
  ["Card ref", "card.ref"],
  ["Card title", "card.title"],
  ["Card fields", "card.FIELD_NAME"]
];
angular_default.module("kantree").component("automationRuleEditor", {
  templateUrl: "/static/app/ui/editors/automation-rule-editor/templates/rule-editor.html",
  bindings: {
    rule: "<",
    project: "<?",
    onChange: "&",
    isNew: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q", "cardModal", "actionsAppearanceEditorMenuFactory"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.triggerEvent = { event: this.rule.trigger_event, options: this.rule.trigger_options };
      this.providedVariables = [];
      this.showErrors = false;
      this.errorStates = [];
      this.onTriggerEventChange(false);
      if (this.rule.id) {
        this.loadStates();
      }
      this.appearanceDropMenu = this.$actionsAppearanceEditorMenuFactory.get(
        this.rule,
        this.project,
        { withName: false },
        (data2) => {
          this.rule[Object.keys(data2)[0]] = Object.values(data2)[0];
          this.onChange({ $valid: true });
        }
      );
    }
    onTriggerEventChange(notifyChange = true, isFirstEventTypeSelection = false) {
      this.rule.trigger_event = this.triggerEvent.event;
      this.rule.trigger_options = this.triggerEvent.options;
      if (notifyChange) {
        this.triggerOnChange();
      }
      if (this.triggerEvent.event) {
        this.$q.when(loadAvailableAutomationEvents(), (eventTypes) => {
          this.triggerEventType = eventTypes.find((t3) => t3.name === this.triggerEvent.event);
          this.cardProvided = !!this.triggerEventType.provides_card || this.triggerEventType.name === "manual" && !!this.triggerEvent.options.card_only;
          this.providedVariables = [];
          if (this.cardProvided) {
            this.providedVariables.push(...CARD_VARIABLES);
          }
          this.providedVariables.push(...this.triggerEventType.provides_variables);
        });
      } else {
        this.cardProvided = false;
      }
      if (isFirstEventTypeSelection && !this.rule.sequence.length) {
        this.rule.sequence.push({ action: true, options: {} });
      }
    }
    triggerOnChange() {
      this.onChange({ $valid: this.ruleForm && this.ruleForm.$valid && this.rule.sequence.length > 0 });
    }
    $postLink() {
      this.$scope.$watch("$ctrl.ruleForm.$valid", (o3, n4) => {
        if (o3 !== n4) {
          this.triggerOnChange();
        }
      });
    }
    toggleShowErrors() {
      this.showErrors = !this.showErrors;
    }
    loadStates() {
      this.loadingStates = true;
      this.$q.when(api_default.project_automations.get_automation_states.get({ project_id: this.project.id, rule_id: this.rule.id }), (states) => {
        this.activeStates = states.filter((s3) => !s3.error).length;
        this.errorStates = states.filter((s3) => s3.error);
        this.$q.all(uniq(states.map((s3) => {
          if (s3.namespace && s3.namespace.match(/^card:/)) {
            return parseInt(s3.namespace.split(":")[1]);
          }
        }).filter(Boolean)).map((cardId) => {
          return loadCard(cardId, { ignoreErrorHandlers: true }).catch(() => {
          });
        })).then(() => {
          this.loadingStates = false;
          for (let s3 of this.errorStates) {
            if (s3.namespace && s3.namespace.match(/^card:/)) {
              s3 = Object.assign({}, s3, { card: cardStore.tryGet(parseInt(s3.namespace.split(":")[1])) });
            }
          }
        });
      });
    }
    clearErrors() {
      clearAllAutomationRuleErrors(this.project, this.rule);
      this.errorStates = [];
      this.showErrors = false;
      this.rule.is_erroring = false;
    }
  }
});
angular_default.module("kantree").component("automationRuleEditorSequence", {
  templateUrl: "/static/app/ui/editors/automation-rule-editor/templates/rule-editor-sequence.html",
  bindings: {
    sequence: "<",
    cardProvided: "<?",
    userProvided: "<?",
    project: "<?",
    onChange: "&",
    providedVariables: "<?",
    errorStates: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      this.addMenu = { config: [
        {
          label: _4("Action"),
          action: () => this.add({ action: true, options: {} })
        },
        {
          label: _4("Wait for user action"),
          action: () => this.add({ event: true, options: {} }),
          enabled: () => this.addAfterIndex >= 0 && this.cardProvided
        },
        {
          label: _4("Conditional branches"),
          action: () => this.add({ branches: [] }),
          enabled: () => this.sequence.length || this.addAfterIndex + 1 === this.sequence.length
        },
        {
          label: _4("Query"),
          action: () => this.add({ query: true, options: {}, sequence: [] })
        }
      ] };
      this.refreshSequence();
    }
    $onChanges(changes) {
      if (!!changes.sequence && !changes.sequence.isFirstChange()) {
        this.refreshSequence();
      } else if (changes.providedVariables && this.sequence) {
        this.collectVariables();
      }
    }
    refreshSequence() {
      this.$scope.$applyAsync(() => {
        this._sequence = this.sequence;
        this.collectVariables();
      });
    }
    canAddAfter(block3) {
      return (typeof block3.action !== "undefined" && block3.action !== true || typeof block3.event !== "undefined" && block3.event !== true || typeof block3.query !== "undefined" && block3.query !== true) && typeof block3.branches === "undefined";
    }
    hasError(block3) {
      return block3.id && this.errorStates.map((s3) => s3.failed_on?.id).includes(block3.id);
    }
    add(block3) {
      if ("branches" in block3 && this.addAfterIndex + 1 < this.sequence.length) {
        block3.branches = [["", this.sequence.slice(this.addAfterIndex + 1)]];
        this.sequence.splice(this.addAfterIndex + 1, this.sequence.length - this.addAfterIndex, block3);
      } else {
        this.sequence.splice(this.addAfterIndex + 1, 0, block3);
      }
      this.notifyChange();
    }
    delete(index2, deletedBranch = void 0) {
      this.sequence.splice(index2, 1);
      if (deletedBranch) {
        deletedBranch.forEach((action) => {
          this.sequence.push(action);
        });
      }
      this.notifyChange();
    }
    notifyChange() {
      this.onChange({ $sequence: this.sequence });
      this.collectVariables();
    }
    collectVariables() {
      const stepTypes = [
        ["action", loadAvailableAutomationActions],
        ["event", loadAvailableAutomationEvents],
        ["query", loadAvailableAutomationQueries]
      ];
      this.stepProvidedVariables = [[...this.providedVariables || []]];
      const promises = this.sequence.slice(0, -1).map((stepConfig) => new Promise((resolve2) => {
        for (const [key2, getter] of stepTypes) {
          if (stepConfig[key2] && stepConfig[key2] !== true) {
            getter.call(this.$automationTypes).then((types2) => {
              const step2 = types2.find((t3) => t3.name === stepConfig[key2]);
              if (step2) {
                resolve2(step2);
              } else {
                resolve2();
              }
            });
            return;
          }
        }
        resolve2();
      }));
      this.$q.all(promises).then((steps2) => {
        for (let i3 = 0; i3 < steps2.length; i3++) {
          if (steps2[i3]) {
            this.stepProvidedVariables.push(makeStepVariables(this.stepProvidedVariables[i3], steps2[i3]));
          } else {
            this.stepProvidedVariables.push(this.stepProvidedVariables[i3]);
          }
        }
      });
    }
  }
});
angular_default.module("kantree").component("automationRuleEditorEvent", {
  templateUrl: "/static/app/ui/editors/automation-rule-editor/templates/rule-editor-event.html",
  bindings: {
    event: "<",
    onChange: "&",
    onDelete: "&?",
    project: "<?",
    isTrigger: "<?",
    triggerEventName: "@",
    providedVariables: "<?",
    isNew: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.dropConfig = { classes: `automation-rule-editor-event drop-theme-menu drop-theme-arrow ${this.onDelete && "trash-margin"}` };
      this.descMenu = buildDescMenu(this.providedVariables);
      this.sequenceProvidedVariables = this.providedVariables;
      this.$q.when(loadAvailableAutomationEvents(), (eventTypes) => {
        const base3 = eventTypes.filter((e3) => !e3.deprecated && (!e3.trigger_only || this.isTrigger));
        if (this.isNew) {
          if (this.triggerEventName === "manual") {
            this.eventTypes = base3.filter((e3) => e3.name === "manual");
          } else if (this.triggerEventName === "manual_card") {
            this.eventTypes = base3.filter((e3) => e3.name === "manual_card");
          } else if (this.triggerEventName === "scheduled") {
            this.eventTypes = base3.filter((e3) => e3.name === "scheduled");
          } else {
            this.eventTypes = base3.filter(
              (e3) => !["manual", "manual_card", "scheduled"].includes(e3.name)
            );
          }
        } else {
          this.eventTypes = base3;
        }
        const drop = makeDropMenuConfig(
          this.eventTypes,
          automationEventsCategories,
          (e3) => this.select(e3),
          _4("Triggers when...")
        );
        if (!this.event.event && drop.singleItem) {
          this.select(drop.singleItem);
          this.dropMenu = null;
        } else {
          this.dropMenu = drop;
        }
        if (this.event.event && this.event.event !== true) {
          this.eventType = this.eventTypes.find((t3) => t3.name === this.event.event);
          this.refreshVariables();
        }
      });
    }
    $onChanges(changes) {
      if (changes.providedVariables) {
        this.refreshVariables();
      }
    }
    onOptionsChanged(values2) {
      this.event.options = values2;
      this.onChange({ $block: this.event });
    }
    select(eventType) {
      const isFirstEventTypeSelection = !this.eventType;
      this.eventType = eventType;
      this.refreshVariables();
      this.event.event = this.eventType.name;
      this.onChange({ $block: this.event, $isFirstEventTypeSelection: isFirstEventTypeSelection });
    }
    refreshVariables() {
      this.sequenceProvidedVariables = makeStepVariables(this.providedVariables, this.eventType);
    }
  }
});
angular_default.module("kantree").component("automationRuleEditorAction", {
  templateUrl: "/static/app/ui/editors/automation-rule-editor/templates/rule-editor-action.html",
  bindings: {
    action: "<",
    onChange: "&",
    onDelete: "&?",
    cardProvided: "<?",
    userProvided: "<?",
    project: "<?",
    providedVariables: "<?",
    errorStates: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.dropConfig = { classes: `automation-rule-editor-action drop-theme-menu drop-theme-arrow ${this.action.id && this.onDelete && "trash-margin"}` };
    }
    $onChanges(changes) {
      if (changes.cardProvided || changes.userProvided) {
        this.refreshAvailableActions();
      }
      if (changes.providedVariables) {
        this.refreshVariables();
      }
    }
    refreshAvailableActions() {
      this.$q.when(loadAvailableAutomationActions(), (actionTypes) => {
        this.actionTypes = actionTypes.filter((a3) => !a3.deprecated && (!a3.requires_card || this.cardProvided) && (!a3.requires_user || this.userProvided));
        const org2 = orgStore.tryGetForProject(this.project);
        if (!org2?.ai_enabled) {
          this.actionTypes = this.actionTypes.filter((a3) => a3.category !== "AI");
        } else if (!org2?.ai_assistant) {
          this.actionTypes = this.actionTypes.filter((a3) => a3.name !== "assistant");
        }
        this.dropMenu = makeDropMenuConfig(this.actionTypes, automationActionsCategories, (e3) => this.select(e3));
        if (this.action.action && this.action.action !== true) {
          this.actionType = actionTypes.find((t3) => t3.name === this.action.action);
          this.refreshVariables();
        }
      });
    }
    select(actionType) {
      this.actionType = actionType;
      this.refreshVariables();
      this.action.action = this.actionType.name;
      if (this.actionType.has_block && !this.action.sequence) {
        this.action.sequence = [];
      }
      this.onChange({ $block: this.action });
    }
    refreshVariables() {
      this.descMenu = buildDescMenu(this.providedVariables);
      if (this.actionType?.provides_card) {
        this.sequenceProvidedVariables = makeStepVariables(this.providedVariables, { provides_variables: CARD_VARIABLES });
      } else {
        this.sequenceProvidedVariables = this.providedVariables;
      }
      this.sequenceProvidedVariables = makeStepVariables(this.sequenceProvidedVariables, this.actionType);
    }
  }
});
angular_default.module("kantree").component("automationRuleEditorBranches", {
  templateUrl: "/static/app/ui/editors/automation-rule-editor/templates/rule-editor-branches.html",
  bindings: {
    branches: "<",
    cardProvided: "<?",
    userProvided: "<?",
    onChange: "&",
    onDelete: "&?",
    project: "<?",
    providedVariables: "<?",
    errorStates: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      if (!this.branches.branches.length) {
        this.branches.branches.push(["", []]);
      }
      this.addMenu = { config: [
        {
          label: _4("Add new branch based on condition"),
          action: () => this.add()
        },
        {
          label: _4("Add new branch for cards unmatched by other conditions"),
          action: () => this.add("__otherwise__")
        }
      ] };
      this.descMenu = buildDescMenu(this.providedVariables);
      const org2 = orgStore.tryGetForProject(this.project);
      this.stores = {
        "cardModel": cardModelStore.scopedByEnabled(this.project),
        "groupType": cardGroupTypeStore.scopedByEnabled(this.project),
        "projectMember": projectMemberStore.scopedByProject(this.project),
        "role": org2 ? roleStore.scopedByOrg(org2) : void 0,
        "group": (groupType) => {
          return groupType ? cardGroupStore.scopedByType(groupType, this.project.top_level_card) : cardGroupStore.scopedByAvailableForChildren(this.project.top_level_card);
        }
      };
    }
    add(filter4 = "") {
      this.branches.branches.push([filter4, []]);
      this.onChange({ $block: this.branches });
    }
    delete(index2) {
      const deleteProcess = () => {
        this.branches.branches.splice(index2, 1);
        this.onChange({ $block: this.branches });
        if (this.branches.branches.length === 0) {
          this.onDelete();
        }
      };
      if (this.branches.branches.length === 1) {
        dialog(Object.assign({
          type: "warning",
          title: _4("Warning"),
          text: _4("Would you like to delete all the actions attached as well ?"),
          closeOnConfirm: true,
          showCancelButton: true,
          cancelButtonText: _4("No, keep my actions"),
          cancelButtonColor: "#3062A8",
          confirmButtonColor: "#288628",
          confirmButtonText: _4("Yes"),
          allowOutsideClick: false
        })).then((isConfirm) => {
          if (isConfirm === true) {
            deleteProcess();
          } else {
            this.onDelete({ $deletedBranch: this.branches.branches[index2][1] });
          }
        });
      } else {
        if (this.branches.branches[index2][1].length > 0) {
          dialog(Object.assign({
            type: "warning",
            title: _4("Warning"),
            text: _4("Deleting this conditional branch will result in the deletion of all the actions attached to it. Would you like to proceed ?"),
            closeOnConfirm: true,
            showCancelButton: true,
            cancelButtonText: _4("No, don't delete anything"),
            cancelButtonColor: "#3062A8",
            confirmButtonColor: "#288628",
            confirmButtonText: _4("Yes")
          })).then((isConfirm) => {
            if (isConfirm === true) deleteProcess();
          });
        } else {
          deleteProcess();
        }
      }
    }
    get hasOtherwise() {
      return this.branches.branches.some((b3) => b3[0] === "__otherwise__");
    }
  }
});
angular_default.module("kantree").component("automationRuleEditorQuery", {
  templateUrl: "/static/app/ui/editors/automation-rule-editor/templates/rule-editor-query.html",
  bindings: {
    query: "<",
    cardProvided: "<?",
    onChange: "&",
    onDelete: "&?",
    project: "<?",
    providedVariables: "<?",
    errorStates: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      if (changes.cardProvided) {
        this.refreshAvailableQuery();
      }
      if (changes.providedVariables) {
        this.refreshVariables();
      }
    }
    refreshAvailableQuery() {
      this.$q.when(loadAvailableAutomationQueries(), (queryTypes) => {
        this.queryTypes = queryTypes.filter((q) => !q.deprecated && (!q.requires_card || this.cardProvided));
        if (this.query.query && this.query.query !== true) {
          this.queryType = queryTypes.find((t3) => t3.name === this.query.query);
          this.refreshVariables();
        } else if (this.query.query === true && this.queryTypes.length === 1) {
          this.select(this.queryTypes[0]);
        }
      });
    }
    select(queryType) {
      this.queryType = queryType;
      this.refreshVariables();
      this.query.query = this.queryType.name;
      this.onChange({ $block: this.query });
    }
    refreshVariables() {
      this.descMenu = buildDescMenu(this.providedVariables);
      this.sequenceProvidedVariables = makeStepVariables(this.providedVariables, this.queryType);
    }
  }
});
function buildDescMenu(providedVariables) {
  const menu = {
    config: [],
    options: {
      help: {
        label: _4("Learn more about variables"),
        guide: "kql",
        anchor: "variables"
      }
    }
  };
  if (providedVariables?.length) {
    menu.config.push({ header: _4("Available variables:") });
    for (const v3 of providedVariables) {
      menu.config.push({ label: "${" + v3[1] + "}", small: v3[0] });
    }
  }
  return menu;
}
function makeStepVariables(providedVariables, step2) {
  const vars = [...providedVariables || []];
  if (step2?.provides_variables) {
    for (const pv of step2.provides_variables) {
      if (!vars.some((v3) => v3[1] === pv[1])) {
        vars.push(pv);
      }
    }
  }
  return vars;
}
function makeDropMenuConfig(actions2, categoriesAttr, onClick, subheader = void 0) {
  const categories = Object.entries(categoriesAttr);
  const extra = Object.keys(categoriesAttr);
  const dropConfig = { config: [] };
  let totalItems = 0;
  for (const [key2, label] of categories) {
    const submenu = subheader ? [{ subheader }] : [];
    actions2.filter((event2) => event2.category === key2).forEach((event2) => {
      submenu.push({
        label: event2.triggers_when_label || event2.title,
        icon: event2.icon,
        action: () => onClick(event2)
      });
      if (event2.description) {
        submenu.push({ desc: event2.description });
      }
    });
    if (submenu.length > (subheader ? 1 : 0)) {
      dropConfig.config.push({ label, submenu });
      totalItems += submenu.length;
    }
  }
  actions2.filter((event2) => !extra.includes(event2?.category)).forEach((event2) => {
    dropConfig.config.push({
      label: event2.triggers_when_label || event2.title,
      icon: event2.icon,
      action: () => onClick(event2)
    });
    if (event2.description) {
      dropConfig.config.push({ desc: event2.description });
    }
    totalItems++;
  });
  if (totalItems === 1) {
    const singleItem = dropConfig.config.length === 1 ? dropConfig.config[0] : dropConfig.config[0].submenu.find((i3) => i3.label);
    return {
      config: [],
      singleItem
    };
  }
  if (dropConfig.config.length === 1) {
    const entry = dropConfig.config[0];
    if (entry.submenu && entry.submenu.filter((i3) => i3.label).length === 1) {
      const singleItem = entry.submenu.find((i3) => i3.label);
      return {
        config: [],
        singleItem
      };
    }
  }
  return dropConfig;
}

// public/app/ui/inbox/ng-components/inbox.js
angular_default.module("kantree").directive("inbox", [
  function() {
    return {
      replace: true,
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        rawFeed: "<feed",
        loading: "<?",
        unreadIds: "<?",
        unreadOnly: "<?",
        markAsReadWhenComment: "<?",
        markAsReadWhenScrolled: "<?",
        onMarkAsRead: "&?",
        onMarkAllAsRead: "&?"
      },
      templateUrl: "/static/app/ui/inbox/ng-components/templates/inbox.html",
      controller: class extends AngularClass {
        static $inject = ["$scope"];
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.feed = this.rawFeed || [];
          this.addUnreadFeedSeparator();
        }
        $onChanges(changes) {
          if (changes.unreadIds && !changes.unreadIds.isFirstChange() || changes.loading && !changes.loading.isFirstChange() && !this.loading || changes.rawFeed && !changes.rawFeed.isFirstChange()) {
            this.feed = Array.from(this.rawFeed);
            this.addUnreadFeedSeparator();
          }
        }
        get hasUnread() {
          return !!this.unreadIds?.length;
        }
        addUnreadFeedSeparator() {
          const earliestUnreadFeedItemId = getEarliestUnreadFeedItemId(this.feed, this.unreadIds);
          if (earliestUnreadFeedItemId === null) return;
          if (this.feed[earliestUnreadFeedItemId].card) {
            this.feed.splice(earliestUnreadFeedItemId + 1, 0, { id: "unread", separator: true, unread: true });
          } else {
            const earliestUnreadFeedItemActivities = this.feed[earliestUnreadFeedItemId].activities;
            const earliestUnreadFeedItemActivitiesIds = pluck(earliestUnreadFeedItemActivities, "id");
            const earliestUnreadId = Math.min(...this.unreadIds.filter((id) => earliestUnreadFeedItemActivitiesIds.includes(id)));
            if (Math.min(...earliestUnreadFeedItemActivitiesIds) !== earliestUnreadId) {
              const activitiesAfterEarliestUnread = earliestUnreadFeedItemActivities.filter((activity) => activity.id >= earliestUnreadId);
              const activitiesBeforeEarliestUnread = earliestUnreadFeedItemActivities.filter((activity) => activity.id < earliestUnreadId);
              this.feed[earliestUnreadFeedItemId] = {
                id: activitiesAfterEarliestUnread[O].id,
                latest_activity_id: activitiesAfterEarliestUnread[O].id,
                activities: activitiesAfterEarliestUnread
              };
              this.feed.splice(earliestUnreadFeedItemId + 1, 0, { id: "unread", separator: true, unread: true });
              this.feed.splice(earliestUnreadFeedItemId + 2, 0, {
                id: activitiesBeforeEarliestUnread[O].id,
                latest_activity_id: activitiesBeforeEarliestUnread[0].id,
                activities: activitiesBeforeEarliestUnread
              });
            } else {
              this.feed.splice(earliestUnreadFeedItemId + 1, 0, { id: "unread", separator: true, unread: true });
            }
          }
        }
        markAllAsRead() {
          this.onMarkAllAsRead();
        }
        markAsRead(activities) {
          this.onMarkAsRead({ $activities: activities });
        }
      }
    };
  }
]);

// public/app/ui/project/menus/actions.js
angular_default.module("kantree").factory("projectActionsMenuFactory", [
  "cardModal",
  "projectPage",
  "projectSettingsModal",
  "projectExportModal",
  "$state",
  "projectImportModal",
  "$q",
  "projectCreatorModal",
  "projectMoveModal",
  "projectSidePanel",
  function(cardModal, projectPage, projectSettingsModal, projectExportModal, $state, projectImportModal, $q, projectCreatorModal, projectMoveModal, projectSidePanel) {
    return {
      getItems,
      get: (project, options2) => {
        return {
          config: () => () => getItems(project, options2 || {}),
          options: {
            watch: watchProject.bind(null, project, options2),
            help: project.is_portfolio ? null : {
              guide: "customization",
              label: _4("Learn how to customize workspaces")
            }
          },
          params: { project }
        };
      }
    };
    function getItems(project, options2) {
      let items = [], _items = [];
      const card = cardStore.get(project.top_level_card_id);
      const owner = project.owner.type === "org" ? orgStore.tryGet(project.owner.id) || project.owner : project.owner;
      const isInProject = projectPage.isProjectActive(project);
      const projectTypeLabel = getProjectTypeLabel(project);
      if (isInProject) {
        _items.push(
          {
            component: "project-menu-header",
            params: {
              project,
              card,
              owner
            },
            options: {
              title: project.title
            },
            submenu: project.is_archived ? null : [
              {
                label: _4("Copy"),
                icon: "clone",
                action: () => {
                  if (!isCurrentUserOwnerOf(project) || isCurrentUserPersonalOrg(project.owner)) {
                    projectCreatorModal.open({ template: project });
                  } else {
                    $q.when(loadOrg(project.owner.id), (org2) => projectCreatorModal.open({ org: org2, template: project }));
                  }
                }
              },
              {
                label: _4("Move"),
                icon: "share",
                action: () => {
                  projectMoveModal.open(project);
                },
                enabled: () => !project.is_portfolio
              },
              {
                label: _4("Archive"),
                icon: "archive",
                action: () => {
                  confirmDeleteDialog2(_4("Are you sure you want to archive?"), null, _4("Archive")).then(() => {
                    $q.digest(archiveProject(project));
                  });
                },
                // TODO: remove this check when Manager role is clearly defined
                enabled: () => isCurrentUserAdminOf(owner)
              }
            ]
          }
        );
        if (canManageSettings(project)) {
          _items.push(
            {
              colorpicker: true,
              getValue: () => project.color || null,
              action: (event2, color) => {
                color = color || "";
                if (project.color === color) return;
                return $q.digest(updateProject(project, { color }));
              },
              noCloseAfterAction: true,
              hasColorPalette: true,
              noColorColor: themeColor() || "#f2f7f6",
              offline: false
            },
            { label: "--" }
          );
        }
      }
      if (isSettingsButtonVisible(project)) {
        _items.push({
          label: _4("Settings"),
          icon: "sliders",
          offline: false,
          action: () => projectSettingsModal.open(project, null)
        });
      }
      if (isInProject && !project.is_template) {
        _items.push({
          label: canManageMembers(project) ? _4("Manage members") : _4("{projectTypeLabel} members", { projectTypeLabel }),
          icon: "bi-people-fill",
          offline: false,
          action: () => projectSettingsModal.open(project, "members")
        });
        if (!project.is_portfolio) {
          _items.push({
            label: _4("View workspace card"),
            icon: "external-link",
            action: () => {
              if (options2.modalLoad) {
                cardModal.load(project.top_level_card_id);
              } else {
                cardModal.open(card);
              }
            }
          });
        }
      }
      if (_items.length) {
        items = items.concat(_items, [{ label: "--" }]);
      }
      _items = [];
      if (isInProject && canManageSettings(project)) {
        _items.push(
          {
            label: _4("Create guide"),
            icon: "bi-book",
            offline: false,
            action: () => projectSidePanel.panel = "guide",
            enabled: () => !project.has_guide
          },
          {
            label: _4("Edit guide"),
            icon: "bi-book",
            offline: false,
            action: () => projectSidePanel.panel = "guide",
            enabled: () => project.has_guide
          }
        );
      }
      if (isInProject && isAuthenticated() && canManageSettings(project)) {
        _items.push(...getAvailableApps(project).filter((app) => !!app.noView).sort((a3, b3) => (a3.priority || 100) - (b3.priority || 100)).map((app) => {
          const item = {
            label: app.title,
            icon: app.icon,
            offline: false,
            action: () => {
              projectPage.gotoApp(app.name);
            }
          };
          if (!app.hideFromSidebar) {
            item.buttons = [{
              icon: "bi-toggle-off",
              action: () => $q.when(toggleProjectSystemApp(project, app.name)),
              noCloseAfterAction: true,
              enabled: () => !(project.system_apps || []).includes(app.name),
              tooltip: _4("Add to {projectTypeLabel} sidebar", { projectTypeLabel })
            }, {
              icon: "bi-toggle-on",
              action: () => $q.when(toggleProjectSystemApp(project, app.name)),
              noCloseAfterAction: true,
              enabled: () => (project.system_apps || []).includes(app.name),
              tooltip: _4("Remove from {projectTypeLabel} sidebar", { projectTypeLabel })
            }];
          }
          return item;
        }));
      }
      if (_items.length) {
        items = items.concat(_items, [{ label: "--" }]);
      }
      _items = [];
      if (!project.is_template && !project.is_archived && !project.is_portfolio && isInProject) {
        if (canImportData(project)) {
          _items.push({
            label: _4("Import from spreadsheet"),
            icon: "cloud-upload",
            offline: false,
            action: () => projectImportModal.open(project)
          });
        }
        if (canExportData(project)) {
          _items.push({
            label: _4("Export"),
            icon: "download",
            offline: false,
            action: () => projectExportModal.open(
              project,
              projectPage.isProjectActive(project) && projectPage.context.appOptions.filter ? projectPage.context.appOptions.filter : null,
              null,
              card.parent_id,
              !projectPage.isProjectActive(project) || projectPage.context.appOptions.include_descendants
            )
          });
        }
      }
      if (_items.length) {
        items = items.concat(_items, [{ label: "--" }]);
      }
      if (!isEmbedded() && isCurrentUserMemberOfProject(project) && !project.is_template && !project.is_archived && options2.showLeave && owner.type === "org") {
        items.push({
          label: _4("Leave this {projectTypeLabel}", { projectTypeLabel }),
          icon: "sign-out",
          offline: false,
          action: () => {
            confirmDeleteDialog2(_4("Are you sure you want to leave this {projectTypeLabel}?", { projectTypeLabel }), null, _4("Leave")).then(() => {
              $q.when(api_default.project_members.leave_project.post({ project_id: project.id }), () => {
                cardStore.remove(card);
                projectStore.remove(project);
                $state.go("/");
              });
            });
          }
        });
      }
      if (items[items.length - 1].label === "--") {
        items.pop();
      }
      return items;
    }
    function watchProject(project, options2, cb2, scope) {
      return projectStore.$watch(scope, project.id, "updated", function() {
        cb2 && cb2();
      }, false);
    }
  }
]);
angular_default.module("kantree").component("projectMenuHeader", {
  templateUrl: "/static/app/ui/project/ng-components/templates/menu-header.html",
  bindings: {
    params: "<",
    onClose: "&",
    openSubmenu: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isEmbedded = isEmbedded;
      if (this.params.owner.type === "user") {
        this.ownerName = _4("@{username}'s workspaces", { username: this.params.owner.name });
      } else {
        this.ownerName = this.params.owner.name;
        if (this.params.project.team) {
          this.ownerName += " / " + this.params.project.team.name;
        }
      }
      this.editable = !this.params.project.is_archived && !this.params.project.is_template && isCurrentUserManagerOf(
        this.params.owner
        /* , this.params.project.team*/
      );
      this.canFavorite = isAuthenticated() && !this.params.project.is_template && !this.params.project.is_archived;
    }
    get favorited() {
      return isFavorite("project", this.params.project.id);
    }
    toggleFavorite() {
      this.$q.digest(toggleProjectAsFavorite(this.params.project));
    }
    gotoOwner() {
      if (isEmbedded()) {
        return;
      }
      if (this.params.owner.type === "user") {
        this.gotoUser();
      } else {
        this.gotoOrg();
      }
    }
    gotoUser() {
      this.$state.go("globalHome");
      this.onClose();
    }
    gotoOrg() {
      if (!isCurrentUserMemberOf(this.params.owner, this.params.project.team)) {
        return;
      }
      if (this.params.project.team) {
        this.$state.go("org.team.hub", { slug: this.params.owner.slug, teamSlug: this.params.project.team.slug });
      } else {
        this.$state.go("org.hub", { slug: this.params.owner.slug });
      }
      this.onClose();
    }
  }
});

// public/app/ui/project/menus/selector.js
angular_default.module("kantree").service("userProjectSelectorMenuFactory", class extends AngularClass {
  getMenuItems(options2) {
    return [
      {
        icon: "exclamation-triangle",
        label: _4("You must select at least one workspace."),
        enabled: () => options2.showEmptyWarning && (!options2.getSelectedProjects() && !options2.selectedProjectsIsNullForAll || options2.getSelectedProjects() && options2.getSelectedProjects().length === 0)
      },
      {
        component: "user-project-selector-menu-component",
        params: {
          ...options2
        }
      }
    ];
  }
  getMenu(options2) {
    return {
      config: () => () => this.getMenuItems(options2)
    };
  }
});
angular_default.module("kantree").component("userProjectSelectorMenuComponent", {
  template: `<user-project-selector selected-projects="$ctrl.params.getSelectedProjects()"
    selected-projects-is-null-for-all="$ctrl.params.selectedProjectsIsNullForAll" filter-scopes="$ctrl.params.getFilterScopes()"
    on-selected="$ctrl.params.onSelected($projects, $filterScopes)" show-portfolios="$ctrl.params.showPortfolios"
    readonly="$ctrl.params.readonly" is-multiple="$ctrl.params.isMultiple" on-render="$ctrl.onUpdate()"></user-project-selector>`,
  bindings: {
    params: "<",
    onUpdate: "&"
  }
});

// public/app/ui/project/modals/move-project.js
angular_default.module("kantree").service("projectMoveModal", class extends AngularClass {
  static $inject = ["$rootScope", "$uibModal"];
  open(project) {
    return this.$uibModal.open({
      windowClass: "project-move-modal",
      component: "projectMoveModal",
      resolve: {
        project: () => project
      }
    });
  }
});
angular_default.module("kantree").component("projectMoveModal", {
  templateUrl: "/static/app/ui/project/modals/templates/move-modal.html",
  bindings: {
    resolve: "<",
    close: "&",
    dismiss: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "$q", "cardMoveModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      const projectId = this.resolve.project.id;
      projectStore.$watch(this.$scope, projectId, () => {
        this.project = projectStore.get(projectId);
      });
      this.moveDisabledTooltip = _4("The workspace already exists here");
      this.selected = { org: this.project.owner, team: this.project.team };
      this.selectorOptions = {
        org: this.project.owner,
        withTeams: true,
        dropConfig: { classes: "drop-theme-menu drop-theme-project-move-modal-options-widget-orgs" }
      };
    }
    get isMoveDisabled() {
      return !this.withCopy && this.orgsEquals(this.project.owner, this.selected.org) && (this.project.owner.type === "user" || this.project.owner.type === "org" && this.teamsEqual(this.project.team, this.selected.team));
    }
    orgsEquals(org2, otherOrg) {
      if (!org2 && !otherOrg) return true;
      if (!org2 && otherOrg || org2 && !otherOrg) return false;
      if (org2.type === "user") {
        return otherOrg.type === "user" && org2.username === otherOrg.name;
      }
      if (org2.type === "org") {
        return otherOrg.type === "org" && otherOrg.id === org2.id;
      }
      return false;
    }
    teamsEqual(team, otherTeam) {
      if (!team && !otherTeam) return true;
      if (!team && otherTeam || team && !otherTeam) return false;
      return team.name === otherTeam.name;
    }
    get orgName() {
      if (this.project.owner.type === "user") {
        return !currentUser2.can_create_private_projects ? _4("Your Public Workspaces") : _4("Your Workspaces");
      }
      return this.project.owner.name + (this.project.team ? " / " + this.project.team.name : "");
    }
    moveTo() {
      if (this.isMoveDisabled) return;
      const move = () => {
        this.$q.when(moveProjectTo(this.project, this.selected.org, this.selected.team, this.withCopy, false), (newProject) => {
          this.close();
          if (newProject && newProject.slug) {
            this.$state.go("project", { projectId: newProject.slug });
          }
        }, autoCatchAsRequestErrorDialog([403, 409, 412]));
      };
      if (!this.withCopy) {
        if (this.orgsEquals(this.project.owner, this.selected.org) && !this.teamsEqual(this.project.team, this.selected.team)) {
          this.$q.digest(updateProject(this.project, { team_id: this.selected.team ? this.selected.team.id : null }));
          this.close();
          return;
        }
        confirmDialog({
          title: _4("Move information"),
          text: _4("This action will involve recomputing all card references. Note that access rights may also be impacted"),
          confirmButtonText: _4("Move")
        }).then(move);
      } else {
        move();
      }
    }
    openCardMoveModal() {
      let cardPromise;
      if (!this.project.top_level_card && cardStore.exists(this.project.top_level_card_id)) {
        cardPromise = this.$q.digest(getOrLoadCard(this.project.top_level_card_id));
      } else {
        cardPromise = this.$q.resolve(this.project.top_level_card);
      }
      return cardPromise.then(
        (card) => this.$cardMoveModal.open(card, () => this.dismiss()),
        (e3) => requestErrorDialog()
      );
    }
  }
});

// public/app/ui/project/modals/role-obj-exceptions.js
angular_default.module("kantree").factory("roleObjExceptionsModal", [
  "$uibModal",
  "$rootScope",
  "$q",
  function($uibModal, $rootScope, $q) {
    return {
      open: function(options2) {
        var scope = $rootScope.$new();
        injectI18nHelpersIntoScope(scope);
        Object.assign(scope, { title: _4("Object permissions") }, options2);
        const scopedRoleStore = roleStore.scopedByOrg(options2.project.owner);
        scopedRoleStore.$watchAll(scope, function() {
          scope.roles = scopedRoleStore.query();
        });
        $q.digest(loadAllRolesForProject(options2.project));
        var instance = $uibModal.open({
          templateUrl: "/static/app/ui/project/modals/templates/role-obj-exceptions.html",
          windowClass: "role-obj-exceptions-modal",
          controller: "roleObjExceptionsModalCtrl",
          scope
        });
        instance.result.finally(function() {
          scope.$destroy();
        });
        return instance;
      }
    };
  }
]);
angular_default.module("kantree").controller("roleObjExceptionsModalCtrl", [
  "$scope",
  "$uibModalInstance",
  "$state",
  "projectSettingsModal",
  "$q",
  function($scope2, $uibModalInstance, $state, projectSettingsModal, $q) {
    $scope2.permissions = {};
    $scope2.visibleObjects = $scope2.objects;
    if ($scope2.focusObject) {
      $scope2.visibleObjects = [$scope2.focusObject];
    }
    var initRole = function(role) {
      $scope2.permissions[role.id] = {};
      $scope2.objects.forEach((obj) => {
        $scope2.permissions[role.id][obj.id] = filterPermissionsForObject(
          role.permissions,
          $scope2.project,
          $scope2.objectType,
          obj.id
        );
      });
    };
    $scope2.$watchCollection("roles", (roles) => {
      roles.forEach(initRole);
      $scope2.builtinRoles = roles.filter((r3) => r3.is_builtin);
      $scope2.orgRoles = roles.filter((r3) => !r3.is_builtin);
      $scope2.showBuiltinRoles = true;
    });
    $scope2.update = function(role, obj, perms) {
      const permissions = role.permissions.concat(perms).filter((p4) => p4.project_id === $scope2.project.id);
      $q.when(updateProjectRolePermissions(role, $scope2.project, permissions), (role2) => {
        initRole(role2);
      });
    };
    $scope2.showAllObjects = function() {
      $scope2.visibleObjects = $scope2.objects;
    };
    $scope2.isOrgMember = isCurrentUserMemberOf($scope2.project.owner, $scope2.project.team);
    $scope2.openProjectSettings = function() {
      projectSettingsModal.open($scope2.project, "roles");
    };
    $scope2.gotoOrgRoles = function() {
      $uibModalInstance.close();
      $state.go("org.hub", { slug: $scope2.project.owner.slug, "#": "roles" });
    };
  }
]);

// public/app/ui/project/ng-components/importer.js
angular_default.module("kantree").component("projectImporter", {
  templateUrl: "/static/app/ui/project/ng-components/templates/importer.html",
  bindings: {
    forceImporter: "<?",
    project: "<?",
    hideImporters: "<?",
    onImporterSelected: "&",
    onImportReady: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.options = {};
      this.attributeTypes = attributeTypeRegistry.getAll().filter(
        (attrType) => !attrType.hidden && !attrType.decorative && !attrType.notConvertible
      ).map((attrType) => {
        return { name: attrType.alias || attrType.name, title: attrType.title };
      });
      this.$q.when(api_default.importers.list_available.get(), (importers) => {
        this.importers = importers.filter((imp) => (!this.project || !imp.new_projects_only) && (!this.hideImporters || !this.hideImporters.includes(imp.name)));
        if (this.forceImporter) {
          importers.forEach((imp) => {
            if (imp.name === this.forceImporter) {
              this.selectImporter(imp);
            }
          });
        }
      });
      this.debounceImportReady = debounce2(() => this.$scope.$applyAsync(() => this.importReady(null, true), 60));
    }
    selectImporter(imp) {
      this.importer = imp;
      this.canUpdate = imp.support_updates && this.project;
      let p4;
      if (this.importer.needs_authorization) {
        var url2 = api_default.importers.authorize.url({ name: this.importer.name }) + "?next=" + browserPopup.getCallbackUrl();
        p4 = browserPopup.open(url2);
      }
      this.$q.when(p4).then(() => {
        this.authorized = true;
        this.projects = null;
        this.onImporterSelected({ $importer: imp });
        if (this.importer.import_from === "remote") {
          this.$q.when(api_default.importers.list_projects.get({ name: this.importer.name }), (projects) => {
            this.projects = projects;
          });
        }
      });
    }
    selectRemoteImport(id, title) {
      this.importRemoteId = id;
      this.importRemoteTitle = title;
      if (this.importer.require_mapping) {
        this.$q.when(api_default.importers.discover.post({ name: this.importer.name, remote_id: id }), (data2) => {
          if (data2.error) {
            errorDialog(_4("Reading from remote provider failed"));
          } else {
            this.processMappingFields(data2);
          }
        });
      } else {
        this.importReady();
      }
    }
    selectFileImport(file) {
      if (this.importer.require_mapping) {
        this.uploading = true;
        this.$q.when(upload({
          url: api_default.importers.discover.url({ name: this.importer.name }),
          data: { file },
          arrayKey: ""
        })).then((resp) => {
          this.uploading = false;
          if (resp.data.error) {
            errorDialog(_4("Reading file failed. Check your file format"));
          } else {
            this.discoverFileId = resp.data.file_id;
            this.processMappingFields(resp.data);
          }
        }, () => {
          this.uploading = false;
          errorDialog(_4("An error occured while uploading your file"));
        });
      } else {
        this.importReady(file);
      }
    }
    processMappingFields(data2) {
      this.showMapping = true;
      this.previousMapping = jsonLocalStorage.getItem("importer:mapping") || {};
      this.fields = [];
      this.fieldMap = {};
      this.customMap = {};
      this.customTypeMap = {};
      this.updateField = null;
      this.updateOnly = false;
      this.suppressActivities = false;
      this.mapChoices = [
        { type: "title", section: _4("Special"), name: "Title", display_name: _4("Title") },
        { type: "comment", section: _4("Special"), name: "Add as comment", display_name: _4("Add as comment") },
        { type: "children", section: _4("Special"), name: "Add as child card", display_name: _4("Add as child card") },
        { type: "model", section: _4("Special"), name: "Type", display_name: _4("Type") },
        { type: "delete", section: _4("Special"), name: "Delete", display_name: _4("Delete") }
      ];
      const exists = (info, types2, name2) => {
        for (var i3 = 0; i3 < this.mapChoices.length; i3++) {
          if (types2.indexOf(this.mapChoices[i3][info]) !== -1 && this.mapChoices[i3].name.toLowerCase() === name2.toLowerCase()) {
            return this.mapChoices[i3];
          }
        }
        return false;
      };
      if (this.project) {
        this.mapChoices.push({ type: "ref", section: _4("Special"), name: "Card ref", display_name: _4("Card ref") });
        var availableContexts = unwrap(cardGroupTypeStore.scopedByEnabled(this.project).query());
        availableContexts.sort((a3, b3) => a3.name.localeCompare(b3.name));
        this.mapChoices = this.mapChoices.concat(availableContexts.map((gt) => {
          return { type: "context", section: _4("Existing contexts"), name: gt.name };
        }));
        var availableAttributes = unwrap(cardModelStore.scopedByEnabled(this.project).getAttributesFromModels().filter((attr) => {
          const attrType = attributeTypeRegistry.get(attr.type);
          return !attrType.hidden && !attrType.decorative && !attrType.notConvertible;
        }));
        availableAttributes.sort((a3, b3) => a3.name.localeCompare(b3.name));
        angular_default.forEach(availableAttributes, (attr) => {
          attr.display_name = attr.name;
          if (!attr.model_is_base) {
            attr.display_name = attr.display_name + " (" + attr.model_name + ")";
          }
          if (exists("type", ["attribute"], attr.display_name)) {
            return;
          }
          this.mapChoices.push({ type: "attribute", section: _4("Existing fields"), name: attr.name, display_name: attr.display_name, attr_type: attr.type });
        });
      }
      var customAttr = { type: "custom_attr", section: _4("New"), name: _4("New field") };
      this.mapChoices.push({ type: "custom_context", section: _4("New"), name: _4("New context") });
      this.mapChoices.push(customAttr);
      angular_default.forEach(this.mapChoices, (el2) => {
        if (!el2.display_name) {
          el2.display_name = el2.name;
        }
      });
      angular_default.forEach(data2.fields, (field2, i3) => {
        var choice;
        if (this.project) {
          choice = exists("type", ["attribute", "context"], field2[1]);
          if (!choice) {
            choice = exists("section", [_4("Special")], field2[1]);
          }
        }
        if (!choice) {
          choice = customAttr;
        }
        this.fields.push(field2);
        this.fieldMap[field2[0]] = choice;
        this.customMap[field2[0]] = field2[1];
        this.customTypeMap[field2[0]] = "text";
      });
      var titleFound = false;
      for (var prop2 in this.fieldMap) {
        if (this.fieldMap[prop2] == this.mapChoices[0]) {
          titleFound = true;
          break;
        }
      }
      if (!titleFound) {
        this.fieldMap[0] = this.mapChoices[0];
      }
      this.importReady();
    }
    isCustomField(fieldKey) {
      return this.fieldMap[fieldKey] && ["custom_context", "custom_attr"].includes(this.fieldMap[fieldKey].type);
    }
    canBeUpdateField(fieldKey) {
      if (!this.fieldMap[fieldKey]) {
        return false;
      }
      if (this.fieldMap[fieldKey].type === "attribute") {
        return ["number", "text", "phone", "email", "location", "url", "skype_username", "formula"].includes(this.fieldMap[fieldKey].attr_type);
      }
      return ["ref", "title"].includes(this.fieldMap[fieldKey].type);
    }
    onMappingChange() {
      if (!this.updateField) {
        for (let [key2, value2] of Object.entries(this.fieldMap)) {
          if (value2 && value2.type === "ref") {
            this.updateField = key2;
          }
        }
      } else if (!this.canBeUpdateField(this.updateField)) {
        this.updateField = null;
      }
      this.debounceImportReady();
    }
    applyPreviousMapping() {
      if (this.fields.length !== Object.keys(this.previousMapping).length) return;
      angular_default.forEach(this.previousMapping, (mappedField, fieldId) => {
        if (mappedField.type === "ignore") {
          this.fieldMap[fieldId] = null;
          return;
        }
        if (["context", "attribute"].includes(mappedField.type)) {
          let existingMapChoice;
          if (this.project) {
            existingMapChoice = this.mapChoices.filter((choice) => ["context", "attribute"].includes(choice.type)).find((choice) => {
              return choice.type === mappedField.type && choice.name === mappedField.name && (!mappedField.attr_type || mappedField.attr_type === choice.attr_type);
            });
            this.fieldMap[fieldId] = existingMapChoice;
          }
          if (!existingMapChoice) {
            if (mappedField.attr_type) {
              this.customTypeMap[fieldId] = mappedField.attr_type;
              this.fieldMap[fieldId] = this.mapChoices.find((choice) => choice.type === "custom_attr");
            } else {
              this.fieldMap[fieldId] = this.mapChoices.find((choice) => choice.type === "custom_context");
            }
            this.customMap[fieldId] = mappedField.name;
          }
        } else {
          this.fieldMap[fieldId] = this.mapChoices.find((choice) => mappedField.type === choice.type) || this.mapChoices[0];
        }
      });
    }
    formatMapping() {
      var mapping = {};
      var hasTitle = false, hasMissingName = false, errors3 = [];
      angular_default.forEach(this.fieldMap, (choice, fieldId) => {
        if (!choice) {
          mapping[fieldId] = { type: "ignore" };
          return;
        }
        if (choice.type === "title") {
          hasTitle = true;
        }
        mapping[fieldId] = { type: choice.type };
        if (["context", "attribute"].includes(choice.type)) {
          mapping[fieldId].name = choice.name;
          if (choice.type === "attribute") {
            mapping[fieldId].attr_type = choice.attr_type;
          }
        } else if (choice.type === "custom_attr") {
          mapping[fieldId] = { type: "attribute", name: this.customMap[fieldId], attr_type: this.customTypeMap[fieldId] };
        } else if (choice.type === "custom_context") {
          mapping[fieldId] = { type: "context", name: this.customMap[fieldId] };
        }
        if (["custom_attr", "custom_context"].includes(mapping[fieldId].type) && !mapping[fieldId].name) {
          hasMissingName = true;
        }
      });
      if (!hasTitle && (this.project && !this.updateOnly || !this.updateField)) {
        errors3.push(_4("You must select one field to map to the title. The card title cannot be empty."));
      }
      if (hasMissingName) {
        errors3.push(_4("Missing name for a new field"));
      }
      if (errors3.length) {
        return { "errors": errors3 };
      }
      return mapping;
    }
    importReady(file, saveMapping = false) {
      var data2 = { name: this.importer.name };
      if (this.importer.options.length) {
        data2.options = this.options;
      }
      this.errors = [];
      if (this.importer.require_mapping) {
        data2.mapping = this.formatMapping();
        data2.update_field = this.updateField;
        data2.update_only = this.updateOnly;
        data2.suppress_activities = this.suppressActivities;
        if (data2.mapping.errors) {
          this.errors = data2.mapping.errors;
          this.onImportReady({ $data: null, $errors: data2.mapping.errors });
          return;
        }
        if (saveMapping) {
          jsonLocalStorage.setItem("importer:mapping", data2.mapping);
        }
      }
      if (typeof this.importRemoteId !== "undefined") {
        data2.remote_id = this.importRemoteId;
        data2.title = this.importRemoteTitle;
      } else if (this.discoverFileId) {
        data2.discover_file_id = this.discoverFileId;
      } else if (file) {
        data2.file = file;
      }
      this.onImportReady({ $data: data2 });
    }
  }
});

// public/app/ui/project/ng-components/list-item.js
angular_default.module("kantree").component("projectListItem", {
  template: `
    <span class="item-color" ng-style="{'background-color': $ctrl.boardColor}"></span>
    <span class="item-title" ng-bind="$ctrl.board.title"></span>
    <span class="item-indicator" ng-if="::$ctrl.showIndicators" ng-show="$ctrl.project.is_public"
      uib-tooltip="{{::$ctrl.shareableTooltip}}"><i class="fa fa-globe"></i></span>
    <span class="item-indicator" ng-if="::$ctrl.showIndicators"
      ng-show="$ctrl.project && $ctrl.isProjectAvailableOffline($ctrl.project)"
      uib-tooltip="{{::$ctrl.offlineTooltip}}"><i class="fa fa-cloud-download"></i></span>
  `,
  bindings: {
    project: "<",
    board: "<",
    showIndicators: "<?"
  },
  controller: class extends AngularClass {
    $onInit() {
      this.isProjectAvailableOffline = isProjectAvailableOffline;
      if (!this.project) {
        this.project = projectStore.getForCard(this.board);
      } else if (!this.board) {
        this.board = this.project.top_level_card;
      }
      this.shareableTooltip = _4("Has shareable link");
      this.offlineTooltip = _4("Available offline");
    }
    get boardColor() {
      const color = themeColor() || "#0c6442";
      if (this.project) {
        return this.project.color || color;
      }
      return color;
    }
  }
});

// public/app/ui/project/ng-components/project-browser.js
angular_default.module("kantree").component("projectBrowser", {
  templateUrl: "/static/app/ui/project/ng-components/templates/project-browser.html",
  bindings: {
    org: "<?",
    team: "<?",
    defaultSelectedCard: "<?",
    withLeaves: "@",
    withLinks: "@",
    defaultIcon: "@",
    withSaveOption: "@",
    onChanged: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.browserTooltip = _4("Workspaces can only be selected in tree view mode.\n Archived cards are not listed or cannot be selected.");
      this.selected = {};
      this.teams = [];
      this.buildTeamList();
      if (this.defaultSelectedCard) {
        const defaultCardProject = projectStore.getForCard(this.defaultSelectedCard);
        this.selectTeam({
          project: defaultCardProject,
          org: defaultCardProject.owner,
          team: defaultCardProject.team
        });
      } else if (this.org) {
        this.selectTeam({ org: this.org, team: this.team });
      } else {
        this.selectTeam(this.teams[0]);
      }
    }
    buildTeamList() {
      this.teams = [];
      if (currentUser2.can_create_projects) {
        const myProjectsName = !currentUser2.can_create_private_projects ? _4("Your public workspaces") : _4("Your workspaces");
        this.teams.push({
          name: myProjectsName,
          org: {
            id: -1,
            name: myProjectsName,
            type: "user"
          },
          uuid: "user"
        });
      }
      if (sharedProjectStore.count()) {
        const sharedProjectsName = _4("Shared workspaces");
        this.teams.push({
          name: sharedProjectsName,
          org: {
            id: "shared",
            name: sharedProjectsName,
            type: "shared"
          },
          uuid: "shared"
        });
      }
      this.teams = this.teams.concat(appContext.teams);
    }
    selectTeam(spec) {
      this.selected = { org: spec.org, team: spec.team, project: null, card: { id: "new" } };
      this.saveOption = false;
      if (spec.org.type === "user") {
        this.saveOption = this.withSaveOption === "true";
        this.$q.when(api_default.user.list_projects.get(), (projects) => {
          this.projects = projects;
        });
      } else if (spec.org.type === "shared") {
        this.saveOption = false;
        this.$q.when(api_default.user.list_shared_projects.get(), (projects) => {
          this.projects = projects;
        });
      } else {
        if (this.withSaveOption === "true") {
          this.saveOption = isCurrentUserManagerOf(spec.org);
        }
        if (spec.team) {
          this.$q.when(api_default.teams.list_projects.get({ org_id: spec.org.id, team_id: spec.team.id }), (projects) => {
            this.projects = projects;
          });
        } else {
          this.$q.when(api_default.organizations.list_projects.get({ org_id: spec.org.id }), (projects) => {
            this.projects = projects;
          });
        }
      }
    }
    selectCard(project, card) {
      if (card && card.id === "new") {
        this.selected.project = null;
        this.selected.card = card;
      } else {
        this.selected.project = project;
        this.selected.card = card;
      }
      this.onChanged(this.selected);
    }
  }
});

// public/app/ui/project/ng-components/sharing-settings.jsx
angular_default.module("kantree").component("projectSharingSettings", {
  templateUrl: "/static/app/ui/project/ng-components/templates/sharing-settings.html",
  bindings: {
    "org": "<",
    "settings": "<?",
    "isTemplate": "<?",
    "isPortfolio": "<?",
    "project": "<?",
    "sharingSettingsExpanded": "<?",
    "canSelectDefaultRole": "<?",
    "onSettingsChanged": "&",
    "isForcedPublic": "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.showDefaultRoleSelection = false;
      this.typeLabel = getProjectTypeLabel(this.project);
      this.permLevelUnchanged = true;
      this.Tip = () => MethodTip({
        children: createMemo(() => _4("Sharing workspaces with your team promotes transparency. It facilitates collaboration and prevents information silos."))
      });
      this.permLevels = [{
        name: _4("Private"),
        icon: "bi-lock",
        description: _4("Only you and invited members can see and participate in the {projectType}", {
          projectType: this.typeLabel
        }),
        settings: {
          is_public: false,
          team_members_can_observe: false
        }
      }, {
        name: _4("Team visible"),
        icon: "bi-building",
        description: _4("Organization and/or team members can see and optionnally join the {projectType}", {
          projectType: this.typeLabel
        }),
        settings: {
          is_public: false,
          team_members_can_observe: true,
          team_members_can_autojoin: true
        },
        disabled: this.isUserOrg
      }, {
        name: _4("Shareable"),
        icon: "bi-globe",
        description: _4("The {projectType} is visible to anybody with the link", {
          projectType: this.typeLabel
        }),
        settings: {
          is_public: true
        }
      }];
      if (this.project && !this.settings) {
        this.isTemplate = this.project.is_template;
        this.isPortfolio = this.project.is_portfolio;
        this.settings = {
          is_public: !!this.project.is_public,
          team_members_can_observe: !!this.project.team_members_can_observe,
          team_members_can_autojoin: !!this.project.team_members_can_autojoin
        };
      } else {
        this.settings = Object.assign({
          is_public: !!this.isForcedPublic,
          team_members_can_observe: !this.isUserOrg && !this.isPortfolio,
          team_members_can_autojoin: !this.isUserOrg && !this.isPortfolio
        }, this.settings || {});
      }
      if (this.settings.is_public) {
        this.permLevel = this.permLevels[2];
      } else if (this.settings.team_members_can_observe) {
        this.permLevel = this.permLevels[1];
      } else {
        this.permLevel = this.permLevels[0];
      }
      if (this.sharingSettingsExpanded === void 0) {
        this.sharingSettingsExpanded = this.settings.is_public;
      }
      if (this.canSelectDefaultRole === void 0) {
        this.canSelectDefaultRole = true;
      }
      this.refreshOrg();
    }
    $onChanges(changes) {
      if (changes.org && !changes.org.isFirstChange()) {
        this.org = changes.org.currentValue;
        this.refreshOrg();
      }
    }
    get isUserOrg() {
      return !this.org || this.org.type == "user";
    }
    refreshOrg() {
      if (this.isTemplate) {
        this._onSettingsChanged(true);
        return;
      }
      this.isOrgProject = this.org && this.org.type === "org";
      Object.assign(this.settings, {
        default_org_member_role_id: this.isOrgProject ? this.org.default_org_member_role_id : null,
        public_role_id: this.isOrgProject ? this.org.default_public_role_id : null
      });
      this.refreshRoles();
    }
    refreshRoles() {
      if (this.isOrgProject) {
        roleStore.scopedByOrg(this.org).removeAll();
      } else {
        roleStore.scopedByUser().removeAll();
      }
      this.$q.when(loadAllRolesForOrg(this.org), () => {
        if (this.isOrgProject) {
          this.roles = roleStore.scopedByOrg(this.org).query({}, {
            sortBy: "name"
          });
        } else {
          this.roles = roleStore.scopedByUser().query({}, {
            sortBy: "name"
          });
          this.settings.public_role_id = this.roles[this.roles.length - 1].id;
        }
        this._onSettingsChanged(true);
      });
    }
    selectLevel(level) {
      this.permLevel = level;
      Object.assign(this.settings, level.settings);
      this.permLevelUnchanged = false;
      this._onSettingsChanged();
    }
    _onSettingsChanged(isFirst) {
      this.onSettingsChanged({
        $settings: this.settings,
        $isFirst: isFirst
      });
    }
  }
});

// public/app/ui/project/ng-components/perm-item.js
angular_default.module("kantree").component("permItem", {
  bindings: {
    label: "@",
    actions: "<",
    // Array
    permissions: "<",
    // Array
    project: "<?",
    objectId: "<?",
    editable: "<?",
    onUpdate: "&",
    allowAsToggle: "<?"
  },
  templateUrl: "/static/app/ui/project/ng-components/templates/perm-item.html",
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
    }
    $onChanges(changes) {
      if (this.actions) {
        this.mode = this.permMode;
        this.isToggleOnly = this.allowAsToggle && this.actions.length === 1;
      }
    }
    get permMode() {
      const perms = [];
      this.actions.forEach((action) => {
        const map5 = [...action.map];
        if (this.project) {
          map5.forEach((el2) => {
            el2.project_id = this.project.id;
          });
        }
        if (this.objectId) {
          map5.forEach((el2) => {
            el2.object_id = this.objectId;
          });
        }
        perms.push(...map5);
      });
      let matching = 0;
      for (let i3 = 0; i3 < perms.length; i3++) {
        if (matchingPerm(this.override(this.permissions), perms[i3])) {
          matching++;
        }
      }
      if (matching === 0) {
        return {
          name: "none",
          icon: "times",
          class: "no-access"
        };
      } else if (matching < perms.length) {
        return {
          name: "limited",
          icon: "adjust fa-rotate-180",
          class: "limited-access"
        };
      } else {
        return {
          name: "complete",
          icon: "check",
          class: "complete-access"
        };
      }
    }
    isOverriden(action) {
      if (!this.permissions || !this.project && !this.objectId) {
        return false;
      }
      if (!action && this.isToggleOnly && this.objectId) {
        action = { ...this.actions[0] };
        action.map.forEach((el2) => {
          Object.assign(el2, { project_id: this.project.id, object_id: this.objectId });
        });
        return isOverriden(this.permissions, "object", this.objectId, action);
      }
      return isOverriden(this.permissions, "project", this.project.id, action);
    }
    override(perms) {
      const objectPerms = perms.filter((a3) => a3.object_id !== null && a3.object_id === this.objectId);
      const projectPerms = perms.filter((a3) => a3.project_id === (this.project || {}).id && a3.object_id === null);
      const rolePerms = perms.filter((a3) => a3.project_id === null && a3.object_id === null);
      return override(rolePerms, override(projectPerms, objectPerms));
    }
    isAllowed(action) {
      let perms = [...this.permissions];
      if (!this.objectId) {
        perms = perms.filter((a3) => a3.object_id === null);
      }
      if (!this.project) {
        perms = perms.filter((a3) => a3.project_id === null);
      } else {
        perms = this.override(perms);
      }
      return matchingPerms(perms, action.map);
    }
    toggle(action, enabled, perms) {
      if (!this.editable) {
        return;
      }
      let inLoop = true;
      if (!perms) {
        perms = this.permissions;
        inLoop = false;
      }
      let newPerms = [];
      let toRemove = [];
      const project_id = this.project ? this.project.id : null;
      const object_id = this.objectId ? this.objectId : null;
      const updatePerm = (perm, _project_id = null, _object_id = null) => {
        for (let i3 = 0; i3 < perms.length; i3++) {
          let actions2;
          if (enabled) {
            actions2 = [...perms[i3].actions];
            perm.actions.forEach((a3) => {
              if (!actions2.includes(a3)) {
                actions2.push(a3);
              }
            });
          } else {
            actions2 = perms[i3].actions.filter((a3) => !perm.actions.includes(a3));
          }
          if (perm.object_type === perms[i3].object_type && _project_id === perms[i3].project_id && _object_id === perms[i3].object_id) {
            if (project_id && !object_id) {
              const basePerms = perms.find((a3) => a3.object_type === perm.object_type && a3.project_id === null && a3.object_id === null);
              const isEqual2 = basePerms === void 0 && actions2.length === 0 || basePerms && basePerms.actions.length === actions2.length && basePerms.actions.every((actions3) => actions3.includes(action));
              if (isEqual2) {
                toRemove.push(perm.object_type);
                return true;
              }
            }
            newPerms.push({ ...perms[i3], project_id, object_id, actions: actions2 });
            return true;
          }
        }
        if (!_project_id) {
          newPerms.push({ object_type: perm.object_type, project_id, object_id, actions: enabled ? perm.actions : [] });
          return true;
        }
        return false;
      };
      action.map.forEach((perm) => {
        const updated = updatePerm(perm, project_id, object_id);
        if (!updated) {
          updatePerm(perm);
        }
      });
      for (let i3 = 0; i3 < perms.length; i3++) {
        let found2 = false;
        for (let j = 0; j < newPerms.length; j++) {
          if (perms[i3].object_type === newPerms[j].object_type && perms[i3].project_id === newPerms[j].project_id && perms[i3].object_id === newPerms[j].object_id) {
            found2 = true;
            break;
          }
        }
        if (!found2) {
          let removed = false;
          for (let j = 0; j < toRemove.length; j++) {
            if (perms[i3].object_type === toRemove[j] && perms[i3].project_id === project_id && perms[i3].object_id === object_id) {
              removed = true;
              break;
            }
          }
          if (!removed) {
            newPerms.push(perms[i3]);
          }
        }
      }
      if (!inLoop)
        this.onUpdate({ $perms: newPerms });
      return newPerms;
    }
    toggleOnly() {
      if (!this.editable && !this.objectId) {
        return;
      }
      let perms = [...this.permissions];
      const mode = this.mode.name;
      this.actions.forEach((action) => {
        perms = this.toggle(action, mode === "none", perms);
      });
      this.onUpdate({ $perms: perms });
    }
  }
});

// public/app/ui/project/ng-components/role-editor.js
angular_default.module("kantree").directive("roleEditor", [
  function() {
    return {
      restrict: "E",
      templateUrl: "/static/app/ui/project/ng-components/templates/role-editor.html",
      replace: true,
      scope: {
        role: "<",
        editable: "<?",
        project: "<?"
      },
      controller: [
        "$scope",
        function($scope2) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.permissions = rolePermissionMap;
          $scope2.updatePerm = function(perms) {
            $scope2.role.permissions = perms;
          };
        }
      ]
    };
  }
]);

// public/app/ui/project/ng-components/role-exceptions.js
angular_default.module("kantree").component("roleExceptions", {
  bindings: {
    role: "<",
    project: "<",
    editable: "<?",
    onReset: "&"
  },
  templateUrl: "/static/app/ui/project/ng-components/templates/role-exceptions.html",
  controller: [
    "$scope",
    function($scope2) {
      var $ctrl = this;
      $ctrl.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
      };
      $ctrl.$onChanges = function() {
        $ctrl.permissions = $ctrl.role.permissions.filter(function(p4) {
          return p4.project_id === $ctrl.project.id && p4.object_id !== null;
        });
      };
      $ctrl.getTypeName = function(objectType) {
        return _4(objectType.charAt(0).toUpperCase() + objectType.substr(1));
      };
      $ctrl.getObjectName = function(objectType, objectId) {
        var store2 = null;
        var getObject = null;
        var nameProperty = "name";
        switch (objectType) {
          case "project":
            store2 = projectStore;
            getObject = projectStore.get;
            nameProperty = "title";
            break;
          case "card":
            store2 = cardStore;
            getObject = cardStore.get;
            nameProperty = "title";
            break;
          case "attribute":
            store2 = cardModelStore;
            getObject = cardModelStore.getAttribute;
            break;
          case "view":
            store2 = viewStore;
            getObject = viewStore.get;
            nameProperty = "name";
            break;
        }
        var object2 = getObject ? getObject.call(store2, objectId) : null;
        return object2 ? object2[nameProperty] : objectId;
      };
      $ctrl.getViewName = function(objectId) {
        return viewStore.get(objectId)?.name || "";
      };
      $ctrl.reset = function(perm) {
        $ctrl.role.permissions = $ctrl.role.permissions.filter(function(p4) {
          return p4.object_type !== perm.object_type || p4.object_id !== perm.object_id;
        });
        $ctrl.$onChanges();
      };
    }
  ]
});

// public/app/ui/project/ng-components/role-item.js
angular_default.module("kantree").component("roleItem", {
  bindings: {
    role: "<",
    editable: "<?",
    overriden: "<?",
    showDelete: "@?",
    showDuplicate: "@?",
    onRoleOpen: "&",
    onRoleDelete: "&?",
    onRoleDuplicate: "&?"
  },
  templateUrl: "/static/app/ui/project/ng-components/templates/role-item.html",
  controller: [
    "$scope",
    function($scope2) {
      var $ctrl = this;
      $ctrl.onClick = function() {
        $ctrl.onRoleOpen({ $role: $ctrl.role });
      };
      $ctrl.duplicate = function(event2) {
        if ($ctrl.editable) {
          event2.stopPropagation();
          $ctrl.onRoleDuplicate({ $role: $ctrl.role });
        }
      };
      $ctrl.delete = function(event2) {
        if ($ctrl.editable) {
          event2.stopPropagation();
          $ctrl.onRoleDelete({ $role: $ctrl.role });
        }
      };
      $ctrl.$onInit = function() {
        injectI18nHelpersIntoScope($scope2);
      };
    }
  ]
});

// public/app/ui/project/ng-components/project-selector.js
angular_default.module("kantree").directive("projectSelector", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        selectedProjects: "<",
        selectedProjectsIsNullForAll: "<?",
        filterScopes: "<",
        sectionsGetter: "<?",
        readonly: "<?",
        isMultiple: "<?",
        showAutoSelect: "<?",
        onSelected: "&",
        onRender: "&"
      },
      transclude: true,
      replace: true,
      templateUrl: "/static/app/ui/project/ng-components/templates/project-selector.html",
      controller: class extends AngularClass {
        static $inject = ["$scope", "$timeout"];
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
          this.autoSelect = "custom";
          this.availableProjects = [];
          this.filter = null;
          this.showAutoSelect = isBoolean(this.showAutoSelect) ? this.showAutoSelect : true;
          this.refreshSections();
          for (const section of this.sections) {
            this.availableProjects.push(...section.projects);
          }
          this.refreshAvailableProjectsFilteredCount();
          this.refreshSelectedProjectsFiltered();
          if (this.isMultiple) {
            this.refreshAutoSelect();
          }
          this.doFilter = debounce2(() => this.$scope.$applyAsync(() => {
            this.refresh();
          }), 200);
        }
        $onChanges(changes) {
          if (changes.selectedProjects && !changes.selectedProjects.isFirstChange()) {
            this.refreshSelectedProjectsFiltered();
          }
        }
        $postLink() {
          this.$timeout(() => {
            this.onRender();
          });
        }
        get _selectedProjects() {
          return this.selectedProjects || (this.selectedProjectsIsNullForAll ? this.availableProjects : []);
        }
        get allProjectsSelected() {
          return this._selectedProjectsFiltered.length === this.availableProjectsFilteredCount && this.availableProjectsFilteredCount > 0;
        }
        get allProjectsIndeterminate() {
          return this._selectedProjectsFiltered.length > 0 && this._selectedProjectsFiltered.length < this.availableProjectsFilteredCount;
        }
        isProjectSelected(project) {
          return this._selectedProjects.some((p4) => p4.id === project.id);
        }
        isProjectFiltered(project) {
          return project.title.toLowerCase().indexOf(this.filter.trim().toLowerCase()) > -1;
        }
        isProjectInSection(project, section) {
          return section.filtered.some((p4) => p4.id === project.id);
        }
        isSectionSelected(section) {
          return section.filtered.every((project) => this.isProjectSelected(project));
        }
        isSectionIndeterminate(section) {
          const count = section.filtered.filter((p4) => this.isProjectSelected(p4)).length;
          return count > 0 && section.filtered.length > count;
        }
        countSelectedProjectsInSection(section) {
          return section.projects.filter((p4) => this.isProjectSelected(p4)).length;
        }
        toggleProject(project) {
          this.autoSelect = "custom";
          if (!this.isMultiple) {
            this.select([project]);
            return;
          }
          if (this._selectedProjects.some((p4) => p4.id === project.id)) {
            this.select(this._selectedProjects.filter((p4) => p4.id !== project.id));
          } else {
            this.select(this._selectedProjects.concat([project]));
          }
        }
        toggleAll() {
          if (this.sections.some((s3) => s3.filtered.some((project) => this.isProjectSelected(project)))) {
            this.clearSelection();
          } else {
            this.selectAll();
          }
        }
        toggleSectionSelection(section) {
          this.autoSelect = "custom";
          if (section.filtered.some((project) => this.isProjectSelected(project))) {
            this.select(this._selectedProjects.filter((p4) => !this.isProjectInSection(p4, section)));
          } else {
            this.select(this._selectedProjects.filter((p4) => !this.isProjectInSection(p4, section)).concat(section.filtered));
          }
        }
        resetFilter() {
          this.filter = null;
          this.refresh();
        }
        select(projects, filterScopes) {
          if (!filterScopes) {
            const allSelected = projects.length === this.availableProjects.length;
            if (allSelected) {
              this.autoSelect = "all";
              projects = this.selectedProjectsIsNullForAll ? null : this.availableProjects;
              filterScopes = [["user", currentUser2.id]];
            } else {
              filterScopes = [];
              const projectIds = [];
              const addedSections = [];
              for (const project of projects) {
                const section = this.sections.find((s3) => s3.projects.find((p4) => p4.id === project.id));
                if (section && addedSections.includes(section.id)) continue;
                if (section && section.filterScope && this.isSectionSelected(section, projects)) {
                  filterScopes.push(section.filterScope);
                  addedSections.push(section.id);
                } else {
                  projectIds.push(project.id);
                }
              }
              if (projectIds.length) {
                filterScopes.push(["projects", ...projectIds]);
              }
            }
          }
          this.onSelected({ $projects: projects, $filterScopes: filterScopes });
        }
        selectAll() {
          if (this.filter === null) {
            this.autoSelect = "all";
            this.selectAuto();
          } else {
            const selectedProjectsFiltered = [];
            for (const section of this.sections) {
              selectedProjectsFiltered.push(...section.filtered);
            }
            this.select(uniq(this._selectedProjects.concat(selectedProjectsFiltered), false, (p4) => p4.id));
          }
        }
        selectAuto() {
          if (this.autoSelect === "all") {
            this.select(this.selectedProjectsIsNullForAll ? null : this.availableProjects, [["user", currentUser2.id]]);
          } else if (this.autoSelect === "favorites") {
            this.select(this.availableProjects.filter((p4) => isFavorite("project", p4.id)), [["favorites"]]);
          } else if (this.autoSelect === "pinned") {
            this.select(this.availableProjects.filter((p4) => p4.owner.type === "user" && p4.owner.id === currentUser2.id || p4.owner.type === "org" && !!appContext.pinnedOrgs.find((o3) => o3.id === p4.owner.id)), [["pinned"]]);
          }
          this.$timeout(() => this.resetFilter());
        }
        clearSelection() {
          this.autoSelect = "custom";
          if (this.filter === null) {
            this.select([]);
            this.$timeout(() => this.resetFilter());
          } else {
            let selectedProjects = this._selectedProjects;
            for (const section of this.sections) {
              selectedProjects = selectedProjects.filter((p4) => !this.isProjectInSection(p4, section));
            }
            this.select(selectedProjects);
          }
        }
        refreshAutoSelect() {
          if (this.filterScopes?.some((scope) => scope[0] === "user")) {
            this.autoSelect = "all";
            this.select(this.availableProjects);
            return;
          }
          if (this.filterScopes?.some((scope) => scope[0] === "favorites")) {
            this.autoSelect = "favorites";
            this.select(this._selectedProjects, [["favorites"]]);
            return;
          }
          if (this.filterScopes?.some((scope) => scope[0] === "pinned")) {
            this.autoSelect = "pinned";
            this.select(this._selectedProjects, [["pinned"]]);
            return;
          }
          this.autoSelect = "custom";
          this.select(this._selectedProjects);
        }
        refreshSections() {
          this.sections = [];
          const filterStore = (store2) => {
            const projects = store2.query();
            return [projects, projects.filter((p4) => !this.filter || this.isProjectFiltered(p4))];
          };
          this.sections = this.sectionsGetter?.(filterStore) || [];
          this.sections = this.sections.filter((section) => section.filtered.length);
        }
        refreshAvailableProjectsFilteredCount() {
          this.availableProjectsFilteredCount = this.filter === null ? this.availableProjects.length : this.sections.map((s3) => s3.filtered.length).reduce((accu, count) => accu + count, 0);
        }
        refreshSelectedProjectsFiltered() {
          if (this.filter === null) {
            this._selectedProjectsFiltered = this._selectedProjects;
          } else {
            this._selectedProjectsFiltered = this._selectedProjects.filter((p4) => this.isProjectFiltered(p4));
          }
        }
        refresh() {
          this.refreshSections();
          this.refreshAvailableProjectsFilteredCount();
          this.refreshSelectedProjectsFiltered();
        }
      }
    };
  }
]);
angular_default.module("kantree").component("userProjectSelector", {
  bindings: {
    selectedProjects: "<",
    selectedProjectsIsNullForAll: "<?",
    filterScopes: "<",
    readonly: "<?",
    isMultiple: "<?",
    showAutoSelect: "<?",
    showPortfolios: "<?",
    onSelected: "&",
    onRender: "&"
  },
  template: `<project-selector
    selected-projects="$ctrl.selectedProjects"
    selected-projects-is-null-for-all="$ctrl.selectedProjectsIsNullForAll"
    filter-scopes="$ctrl.filterScopes"
    sections-getter="$ctrl.sectionsGetter"
    readonly="$ctrl.readonly"
    is-multiple="$ctrl.isMultiple"
    show-auto-select="$ctrl.showAutoSelect"
    on-render="$ctrl.onRender()"
    on-selected="$ctrl.onSelected({ $projects: $projects, $filterScopes: $filterScopes })"
  ></project-selector>`,
  controller: class extends AngularClass {
    sectionsGetter = (filterStore) => {
      const sections = [];
      const [userProjects, userFiltered] = filterStore(personalProjectStore);
      const [sharedProjects, sharedFiltered] = filterStore(sharedProjectStore);
      sections.push(
        {
          id: "user",
          projects: userProjects,
          filtered: userFiltered,
          label: currentUser2.can_create_private_projects ? _4("My workspaces") : _4("My public workspaces")
        },
        {
          id: "shared",
          projects: sharedProjects,
          filtered: sharedFiltered,
          label: _4("Shared workspaces")
        }
      );
      sections.push(...appContext.teams.map((spec) => {
        let store2 = spec.store;
        if (!this.showPortfolios) {
          store2 = store2.scoped(() => ({ is_portfolio: false }));
        }
        const [projects, filtered] = filterStore(store2);
        return {
          id: spec.uuid,
          filterScope: spec.team ? ["team", spec.team.id] : ["org_no_team", spec.org.id],
          projects,
          filtered,
          label: spec.name
        };
      }));
      return sections;
    };
  }
});
angular_default.module("kantree").component("orgProjectSelector", {
  bindings: {
    org: "<",
    selectedProjects: "<",
    readonly: "<?",
    isMultiple: "<?",
    onSelected: "&",
    onRender: "&"
  },
  template: `<project-selector
    selected-projects="$ctrl.selectedProjects"
    selected-projects-is-null-for-all="$ctrl.selectedProjectsIsNullForAll"
    filter-scopes="$ctrl.filterScopes"
    sections-getter="$ctrl.sectionsGetter"
    readonly="$ctrl.readonly"
    is-multiple="$ctrl.isMultiple"
    show-auto-select="$ctrl.showAutoSelect"
    on-render="$ctrl.onRender()"
    on-selected="$ctrl.onSelected({ $projects: $projects, $filterScopes: $filterScopes })"
  ></project-selector>`,
  controller: class extends AngularClass {
    selectedProjectsIsNullForAll = false;
    showAutoSelect = false;
    sectionsGetter = (filterStore) => {
      const sections = [];
      const [projects, filtered] = filterStore(projectStore.scopedByTeam(false, this.org));
      sections.push({
        id: "noTeam",
        projects,
        filtered,
        label: _4("(no team)")
      });
      sections.push(...teamStore.scopedByOrg(this.org).query().map((team) => {
        const [projects2, filtered2] = filterStore(projectStore.scopedByTeam(team, this.org));
        return {
          id: team.id,
          projects: projects2,
          filtered: filtered2,
          label: team.name
        };
      }));
      return sections;
    };
  }
});
angular_default.module("kantree").component("teamProjectSelector", {
  bindings: {
    team: "<",
    selectedProjects: "<",
    readonly: "<?",
    isMultiple: "<?",
    onSelected: "&",
    onRender: "&"
  },
  template: `<project-selector
    selected-projects="$ctrl.selectedProjects"
    selected-projects-is-null-for-all="$ctrl.selectedProjectsIsNullForAll"
    filter-scopes="$ctrl.filterScopes"
    sections-getter="$ctrl.sectionsGetter"
    readonly="$ctrl.readonly"
    is-multiple="$ctrl.isMultiple"
    show-auto-select="$ctrl.showAutoSelect"
    on-render="$ctrl.onRender()"
    on-selected="$ctrl.onSelected({ $projects: $projects, $filterScopes: $filterScopes })"
  ></project-selector>`,
  controller: class extends AngularClass {
    selectedProjectsIsNullForAll = false;
    showAutoSelect = false;
    sectionsGetter = (filterStore) => {
      const [projects, filtered] = filterStore(projectStore.scopedByTeam(this.team, this.team.owner));
      return [{
        id: this.team.id,
        projects,
        filtered,
        label: this.team.name,
        showHeader: false
      }];
    };
  }
});

// public/app/ui/project/ng-components/project-selector-btn.js
angular_default.module("kantree").directive("userProjectSelectorBtn", function() {
  return {
    template: `
      <button ng-disabled="$ctrl.isDisabled">
        <i class="fa fa-exclamation-triangle" ng-show="$ctrl.showEmptyWarning && $ctrl.noProjectSelected"></i>
        {{$ctrl.btnLabel}} <span ng-if="::!!$ctrl.isMultiple">({{$ctrl.countLabel}})</span>
      </button>
    `,
    replace: true,
    bindToController: true,
    controllerAs: "$ctrl",
    scope: {
      // Menu options
      selectedProjects: "<?",
      selectedProjectsIsNullForAll: "<?",
      filterScopes: "<?",
      isMultiple: "<?",
      readonly: "<?",
      showEmptyWarning: "<?",
      showPortfolios: "<?",
      // Component options
      isDisabled: "<?",
      forceOpenMenu: "<?",
      dropConfig: "<?",
      emptyLabel: "@?",
      onChange: "&"
    },
    controller: class extends AngularClass {
      static $inject = ["$scope", "$element", "userProjectSelectorMenuFactory", "menuDropdown", "dropdown"];
      $onInit() {
        this.dropConfig = this.dropConfig || {
          tetherOptions: {
            attachment: "top left",
            offset: "0 22px"
          },
          classes: "drop-theme-menu drop-theme-arrow project-selector-dropdown"
        };
        this.menu = this.$userProjectSelectorMenuFactory.getMenu({
          getSelectedProjects: () => this.nextSelectedProjects,
          getFilterScopes: () => this.nextFilterScopes,
          selectedProjectsIsNullForAll: this.selectedProjectsIsNullForAll,
          isMultiple: this.isMultiple,
          readonly: this.readonly,
          showEmptyWarning: this.showEmptyWarning,
          showPortfolios: this.showPortfolios,
          onSelected: (projects, filterScopes) => {
            this.refresh(projects, filterScopes);
            if (!this.isMultiple) this.$dropdown.close(this.drop);
          }
        });
      }
      $onChanges(changes) {
        if (changes.selectedProjects || changes.filterScopes) {
          this.refresh(changes.selectedProjects?.currentValue, changes.filterScopes?.currentValue);
        }
      }
      refresh(projects, filterScopes) {
        this.nextSelectedProjects = projects || getProjectsFromFilterScopes(filterScopes, !!this.selectedProjectsIsNullForAll);
        this.nextFilterScopes = filterScopes;
        if (this.isMultiple) {
          this.countLabel = getLabelForFilterScopes2(this.nextFilterScopes, this.nextSelectedProjects?.length);
        }
      }
      $postLink() {
        this.$element.on("click", (event2) => {
          if (!this.drop || !this.drop.drop) {
            this.drop = this.$menuDropdown.open(this.$element[0], this.menu, this.$scope, this.dropConfig);
            this.drop.on("close", () => this.applySelection());
          } else {
            if (this.drop.isOpened()) {
              this.$dropdown.close(this.drop, event2);
            } else {
              this.$dropdown.updateOnNextFrame(this.drop, true);
            }
          }
        });
        if (this.forceOpenMenu) {
          this.$element.click();
        }
      }
      get btnLabel() {
        return this.nextSelectedProjects?.length === 1 && !this.isMultiple ? this.nextSelectedProjects[0].title : this.emptyLabel || _4("Workspaces");
      }
      get noProjectSelected() {
        return this.nextSelectedProjects && this.nextSelectedProjects.length === 0;
      }
      applySelection() {
        if (this.isMultiple && !equals(this.selectedProjects?.map((p4) => p4.id).sort(), this.nextSelectedProjects?.map((p4) => p4.id).sort()) || !this.isMultiple && this.selectedProjects?.[0]?.id !== this.nextSelectedProjects?.[0]?.id) {
          this.$scope.$applyAsync(() => {
            this.selectedProjects = this.nextSelectedProjects;
            this.filterScopes = this.nextFilterScopes;
            this.onChange({ $projects: this.selectedProjects, $filterScopes: this.filterScopes });
          });
        }
      }
    }
  };
});

// public/app/ui/project/ng-components/projectTileOptionsButton.js
angular_default.module("kantree").component("projectTileOptionsButton", {
  bindings: {
    project: "<"
  },
  template: `<button class="btn btn-link btn-icon" drop-menu="$ctrl.menuConfig">
      <i class="bi-three-dots-vertical"></i>
    </button>`,
  controller: class extends AngularClass {
    static $inject = ["$scope", "projectActionsMenuFactory"];
    $onInit() {
      this.menuConfig = this.project.id ? this.$projectActionsMenuFactory.get(this.project, { modalLoad: true }) : null;
    }
  }
});

// public/app/ui/project/ng-components/nav-members.js
angular_default.module("kantree").component("navMembers", {
  templateUrl: "/static/app/ui/project/ng-components/templates/nav-members.html",
  bindings: {
    context: "<",
    hideInviteButton: "<?",
    onClickShowMembers: "&?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "projectPage", "projectSettingsModal", "membersListMenuFactory"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.isEmbedded = isEmbedded;
      this.context.$watch(this.$scope, "project", () => {
        this.refresh();
      });
    }
    get presenceManager() {
      return this.$projectPage.scopeManager?.presenceManager;
    }
    $postLink() {
      if (this.onClickShowMembers) {
        this.$element.on("click touchstart", (event2) => {
          this.onClickShowMembers({ $event: event2 });
        });
      }
    }
    refresh() {
      if (this.deregisterWatchers) this.deregisterWatchers();
      if (this.context.project) {
        this.canManageMembers = canManageMembers(this.context.project);
      } else {
        this.canManageMembers = null;
        return;
      }
      this.deregisterWatchers = offMany([
        projectMemberStore.$watchAll(this.$scope, () => this.updateMembers()),
        this.$scope.$watch(() => this.presenceManager?.nbConnectedUsers, (newVal, oldVal) => {
          if (newVal === oldVal) return;
          this.updateMembers();
        })
      ]);
    }
    updateMembers() {
      this.members = projectMemberStore.scopedByProject(this.context.project).query().sort((a3, b3) => {
        if (!this.presenceManager) {
          return 0;
        }
        if (this.presenceManager.isUserConnected(a3.user) && !this.presenceManager.isUserConnected(b3.user)) {
          return 1;
        }
        if (!this.presenceManager.isUserConnected(a3.user) && this.presenceManager.isUserConnected(b3.user)) {
          return -1;
        }
        return 0;
      });
      this.displayedMembers = this.members.slice(-4);
      this.remainingMembersCount = this.members.length - this.displayedMembers.length + (this.presenceManager?.nbGuests || 0);
      if (!this.onClickShowMembers) {
        this.menuSpec = this.$membersListMenuFactory.get(this.context.project, !this.canManageMembers);
      }
    }
    openSharingSettingsModal() {
      if (this.context.project) {
        this.$projectSettingsModal.open(this.context.project, "members");
      }
    }
    $onDestroy = function() {
      if (this.deregisterWatchers) this.deregisterWatchers();
    };
  }
});
angular_default.module("kantree").factory("membersListMenuFactory", [
  "projectPage",
  "projectSettingsModal",
  function(projectPage, projectSettingsModal) {
    function getItems(project, hideManageMemberButtons) {
      var members = projectMemberStore.scopedByProject(project).query({}, { sortBy: "user.display_name" });
      const items = [];
      if (isAuthenticated() && !hideManageMemberButtons) {
        items.push(
          {
            label: _4("Manage {projectType} members", { projectType: getProjectTypeLabel(project) }),
            icon: "bi-people-fill",
            offline: false,
            action: function() {
              return projectSettingsModal.open(project, "members");
            }
          },
          {
            label: "--"
          }
        );
      }
      return items.concat(members.map(function(member) {
        return {
          label: member.user.display_name,
          small: member.is_unlicensed ? _4("Observer") : member.role ? roleStore.tryGet(member.role.id)?.name : null,
          img: userAvatarUrl(member.user),
          color: isConnected() && isAuthenticated() ? projectPage.scopeManager.presenceManager?.isUserConnected(member.user) ? "#27e642" : "#e2e2e2" : null,
          classes: "mod-nav-member"
        };
      })).concat(projectPage.scopeManager.presenceManager?.nbGuests ? [{
        label: _n("{count} guest", "{count} guests", projectPage.scopeManager.presenceManager.nbGuests),
        img: guestAvatarUrl(),
        color: "#27e642",
        classes: "mod-nav-member"
      }] : []);
    }
    function watch(callback, scope) {
      return offMany([
        projectMemberStore.$watchAll(scope, callback),
        scope.$watch(function() {
          return projectPage.scopeManager.presenceManager?.nbConnectedUsers;
        }, function(newVal, oldVal) {
          if (newVal === oldVal) return;
          callback();
        }),
        scope.$on("connectivityChanged", callback)
      ]);
    }
    return {
      get: function(project, hideManageMemberButtons) {
        return {
          config: function() {
            return getItems.bind(this, project, hideManageMemberButtons);
          },
          options: {
            classes: "nav-members-menu",
            watch
          }
        };
      }
    };
  }
]);
angular_default.module("kantree").component("navMembersMenuComponent", {
  bindings: {
    params: "<?",
    onClose: "&",
    openSubmenu: "&"
  },
  template: `
    <nav-members class="mod-mobile-menu" context="$ctrl.params.context"
      hide-invite-button="true" on-click-show-members="$ctrl.openSubmenu({$event: $event})"></nav-members>`
});

// public/app/ui/project/ng-components/view-save-btn.js
angular_default.module("kantree").component("viewSaveBtn", {
  template: `
    <button class="btn btn-topbar alert-danger ms-2" view-menu-toggle="$ctrl.draftView" drop-config="$ctrl.dropConfig"
      ng-if="$ctrl.draftView" ng-class="{'btn-icon': $ctrl.isScreensizeXS() || $ctrl.shrinked}">
      <i class="fa fa-asterisk"></i> <span class="hidden-xs" ng-hide="$ctrl.shrinked">{{::$ctrl.btnLabel}}</span>
    </button>
  `,
  bindings: {
    view: "<?",
    shrinked: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope"];
    $onInit() {
      this.isScreensizeXS = isScreensizeXS;
      this.dropConfig = {
        tetherOptions: {
          attachment: "top center",
          targetAttachment: "bottom center",
          offset: "0 0",
          constraints: [
            {
              to: "scrollParent",
              pin: "top, bottom",
              attachment: "together none"
            },
            {
              to: "window",
              attachment: "together",
              pin: true
            }
          ]
        }
      };
      this.btnLabel = _4("Unsaved view");
      viewStore.$watchAll(this.$scope, () => this.refresh());
    }
    $onChanges(changes) {
      if (changes.view && !changes.view.isFirstChange()) {
        this.refresh();
      }
    }
    refresh() {
      if (this.view && this.view._draft) {
        this.draftView = this.view;
      } else if (this.view) {
        this.draftView = viewStore.query({ _draft: true, from_view_id: this.view.id })?.[0];
      } else {
        this.draftView = null;
      }
    }
  }
});

// public/app/ui/project/ng-components/view-locked-btn.js
angular_default.module("kantree").directive("viewLockedBtn", [
  function() {
    return {
      template: `
        <button class="btn btn-icon btn-topbar">
          <i class="bi-question-circle-fill"></i>
        </button>
      `,
      restrict: "E",
      scope: {
        context: "<"
      },
      controllerAs: "$ctrl",
      bindToController: true,
      controller: class extends AngularClass {
        static $inject = ["$scope", "$element", "dropdown"];
        $onInit() {
          injectI18nHelpersIntoScope(this.$scope);
        }
        $postLink() {
          this.$element.on("click touchstart", () => this.openDrop());
        }
        openDrop() {
          const dropHtml = `
            <view-locked-btn-content drop="$ctrl.drop" context="$ctrl.context"></view-locked-btn-content>
          `;
          this.drop = this.$dropdown.openCompile(this.$element[0], dropHtml, this.$scope, {
            classes: "view-locked-btn-drop drop-theme-menu drop-theme-arrow",
            _useChildScope: true,
            tetherOptions: {
              constraints: [{
                to: "window",
                pin: true,
                attachment: "together none"
              }]
            }
          });
        }
      }
    };
  }
]);
angular_default.module("kantree").component("viewLockedBtnContent", {
  templateUrl: "/static/app/ui/project/ng-components/templates/view-locked-btn-content.html",
  bindings: {
    drop: "<",
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "projectPage"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      const mode = cardsAppRegistry.get(this.context.appOptions.mode) || this.context.app;
      this.titleMode = mode.title;
      this.icon = mode.icon;
      this.showFilters = mode.filterable || false;
      this.showGroups = mode.groupable || false;
      this.showSort = mode.sortable || false;
      if (this.showGroups) {
        let groupBySpecs = this.context.appOptions?.group_by;
        if (!this.groupableTwice || groupBySpecs && this.isNothing(groupBySpecs[1])) {
          groupBySpecs = groupBySpecs.slice(0, 1);
        }
        const groupby = formatSpecLabel(groupBySpecs);
        this.groupByText = this.isNothing(groupBySpecs[0]) ? _4("{groupby}", { groupby }) : _4("Grouped by {groupby}", { groupby });
      }
      if (this.showFilters) {
        const filter4 = this.getFilterLabel();
        this.filterText = !filter4 ? _4("Not filtered") : _4("Filtered by {filter}", { filter: filter4 });
      }
      if (this.showSort) {
        this.getSortByLabel();
      }
      this.canUnlock = this.$projectPage.project ? canManageViews(this.$projectPage.project) : false;
    }
    getFilterLabel() {
      let label = null;
      if (!this.context.appOptions.filter) return;
      if (!this.context.filterRepr) {
        label = _4("some fields");
        return;
      }
      label = this.context.filterRepr;
      return label;
    }
    getSortByLabel() {
      const sortChoices = getSortableAttributes(this.context.project, this.context.cardStore, true);
      const sortBy3 = getSortBy(this.context.appOptions);
      if (sortBy3) {
        let value2 = sortBy3.value;
        const builtin = cardGroupStaticSortBy.find((item) => item.value === value2);
        if (builtin) {
          value2 = builtin.label.toLowerCase();
        } else if (typeof value2 === "number") {
          value2 = sortChoices.find((item) => item.id === value2);
          if (value2) {
            value2 = value2.label.toLowerCase();
          } else {
            value2 = "?";
          }
        }
        this.sortText = _4("Sorted by {value}", { value: value2 });
        if (sortBy3.reverse) this.sortText = this.sortText + " " + _4("reversed");
      } else {
        this.sortText = _4("Sorted by Custom ordering");
      }
    }
    toggle() {
      this.$scope.$emit("appUnlocked");
      this.drop.close();
    }
    isNothing(spec) {
      return !spec || !spec.type || spec.type === "nothing";
    }
  }
});

// public/app/ui/project/ng-components/view-rules-btns.js
angular_default.module("kantree").component("viewRulesBtns", {
  template: `
    <view-single-rule-btn rule="rule" ng-repeat="rule in $ctrl.actions track by $index" project="$ctrl.project"/>
  `,
  bindings: {
    context: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$q", "$timeout", "$scope", "projectPage"];
    $onInit() {
      this.project = this.$projectPage.project;
      this.loadRules();
      automationRuleStore.subscribe(() => {
        this.loadRules();
        this.loadActions();
      });
      this.$scope.$watch("$ctrl.context.appOptions", () => {
        this.loadActions();
      });
    }
    loadRules() {
      this.rules = automationRuleStore.scopedByProject(this.project).query({ trigger_event: "manual" });
    }
    loadActions() {
      const _actions = [];
      if (this.rules.length) {
        this.context.appOptions.automations_rules?.forEach((ruleId) => {
          const rule = this.rules.find((rule2) => rule2.id === ruleId);
          if (rule) _actions.push(rule);
        });
      }
      this.actions = _actions;
    }
  }
});
angular_default.module("kantree").component("viewSingleRuleBtn", {
  template: `
    <button class="btn btn-topbar"
        ng-style="{'background-color':$ctrl.rule.background_color, 'color':$ctrl.colorText($ctrl.rule.background_color)}"
        ng-click="$ctrl.runRule()"
        ng-disabled="$ctrl.running"
      >
      <loading-indicator ng-if="$ctrl.running"></loading-indicator>
      <i ng-if="$ctrl.rule.icon && !$ctrl.running" class="{{$ctrl.rule.icon|iconClass}}" ng-style="{'color':$ctrl.colorText($ctrl.rule.background_color)}"></i>
      <i ng-if="!$ctrl.rule.icon && !$ctrl.running" class="bi-play-circle" ng-style="{'color':$ctrl.colorText($ctrl.rule.background_color)}"></i>
      <span>{{$ctrl.rule.name}}</span>
    </button>
  `,
  bindings: {
    rule: "<",
    project: "<"
  },
  controller: class extends AngularClass {
    static $inject = ["$q", "$timeout", "$element"];
    $onInit() {
      this.running = false;
    }
    runRule() {
      this.running = true;
      this.$q.when(runAutomationRule(this.project, this.rule), () => {
        this.$timeout(() => {
          toastNotify(_4("Triggered automation"), "success");
          this.running = false;
        }, 500);
      });
    }
    colorText(bgColor) {
      return textColor(bgColor);
    }
  }
});

// public/app/ui/project/local-storage.js
angular_default.module("kantree").factory("ProjectLocalStorageManager", [
  function() {
    return class ProjectLocalStorageManager {
      constructor(project) {
        this.project = project;
      }
      getStorageKey(store2) {
        return `${store2.options.typeName}-store-project-${this.project.id}`;
      }
      async load() {
        const stores = this.getStores();
        this.disposeSubscriptions = await Promise.all(stores.map(
          (store2) => store2.load(true, this.getStorageKey(store2), true).then(
            () => store2.subscribe("changed", () => store2.schedulePersist(this.getStorageKey(store2), true))
          )
        ));
        activityStore.removeManyMatching({ offline: true });
      }
      destroy() {
        this.disposeSubscriptions.forEach((dispose2) => dispose2());
        for (const store2 of this.getStores()) {
          const mapKey = JSON.stringify({ storagekey: this.getStorageKey(store2), scoped: true });
          if (store2.debouncedPersistMap.has(mapKey)) {
            const debouncedPersist = store2.debouncedPersistMap.get(mapKey);
            if (debouncedPersist.isRunning()) {
              debouncedPersist.immediate();
            }
          }
          if (store2 instanceof CardStore) {
            store2.scoped({ parent_id: query_exports.notNull() }).removeAll();
          } else {
            store2.removeAll();
          }
        }
      }
      getStores() {
        return [
          cardGroupSubscriptionStore,
          cardSubscriptionStore,
          cardStore.scopedByProject(this.project),
          activityStore.scoped({ project_id: this.project.id, stream_type: "activity" })
        ];
      }
    };
  }
]);

// public/app/ui/project/presence.js
angular_default.module("kantree").factory("ProjectPresenceManager", [
  "$location",
  "$timeout",
  function($location, $timeout2) {
    return class ProjectPresenceManager {
      constructor(room, board) {
        this.connectedUsers = [];
        this.nbGuests = 0;
        this.nbConnectedUsers = 0;
        this.updateCurrentLocation(board.title);
        room.addEventListener("membersUpdated", () => {
          this.angularDigestLoopTimer = $timeout2(() => this.updateConnectedUsers(room.members));
        });
        this.updateConnectedUsers(room.members);
      }
      updateConnectedUsers(members) {
        const connectedUsersById = {};
        this.nbGuests = 0;
        for (const [sid, info] of Object.entries(members)) {
          if (info.guest) {
            this.nbGuests++;
          } else if (!(info.id in connectedUsersById) || !("current" in connectedUsersById[info.id])) {
            connectedUsersById[info.id] = info;
          }
        }
        this.connectedUsers = Object.values(connectedUsersById).sort((a3, b3) => a3.display_name && a3.display_name.localeCompare(b3.display_name));
        this.nbConnectedUsers = this.connectedUsers.length + this.nbGuests;
      }
      isUserConnected(user) {
        return isConnected() && this.connectedUsers && this.connectedUsers.filter((u3) => u3.id === user.id).length === 1;
      }
      updateCurrentLocation(title) {
        getPushConnection().then((conn) => {
          conn.setUserInfo({
            id: currentUser2.id,
            avatar: currentUser2.avatar,
            username: currentUser2.username,
            display_name: currentUser2.display_name,
            current: [$location.url(), title]
          });
        });
      }
      destroy() {
        $timeout2.cancel(this.angularDigestLoopTimer);
        this.connectedUsers = [];
        this.nbGuests = 0;
        this.nbConnectedUsers = 0;
      }
    };
  }
]);

// public/app/loaders/view-categories.js
async function loadAllViewCategories(project) {
  const [categories, response] = await request(api_default.project_views.list_view_categories, { project_id: project.id });
  viewCategoryStore.scopedByProject(project).replace(categories);
  return categories;
}

// public/app/ui/project/push-listener.js
angular_default.module("kantree").factory("ProjectPushListener", [
  "$q",
  "$state",
  "$rootScope",
  function($q, $state, $rootScope) {
    return class ProjectPushListener {
      constructor(room, project) {
        this.room = room;
        this.project = project;
        this.debouncedRefreshCard = this.debouncedCard((card, cb2) => {
          cardStore.unlocked(card, () => {
            $q.digest(loadCard(card.id), cb2);
          });
        });
        this.listen();
      }
      listen() {
        const refreshCard = (cb2) => this.wrap((card, data2) => {
          this.debouncedRefreshCard(card, (card2) => {
            cb2 && cb2(card2, data2);
          });
        });
        const refreshGroup = (cb2, withoutLoad) => {
          withoutLoad = withoutLoad ? withoutLoad : false;
          return this.wrap((card, data2) => {
            if (withoutLoad) {
              cb2 && cb2(cardGroupStore.get(data2[0]), data2);
            } else {
              $q.when(loadGroupByCard(card, data2[0]), (group2) => cb2 && cb2(group2, data2));
            }
          });
        };
        const refreshStream = this.wrap((card) => {
          $q.digest(loadAllActivitiesForCard(card));
        });
        this.room.on("updated", () => $q.digest(loadProject(this.project.id)));
        this.room.on("top_level_card_attrs_updated", () => $q.digest(loadProject(this.project.id)));
        this.room.on("project_guide_updated", () => $q.digest(loadProjectGuide(this.project)));
        this.room.on("project_status_changed", () => {
          $state.reload();
        });
        this.room.on("project_import_errors", (data2) => {
          if (currentUser2.id === data2[0]) {
            projectStore.update(this.project, { "import_errors": data2[1] });
          }
        });
        this.room.on("project_batch_done", (data2) => {
          if (data2[0] === "cards" && ["subscribe", "unsubscribe"].includes(data2[1])) {
            if (data2[3] !== currentUser2.id) return;
            if (data2[1] === "subscribe") {
              cardStore.query({ id: query_exports.any(data2[2]) }).forEach((card) => {
                cardSubscriptionStore.subscribeTo(card);
              });
            } else {
              cardStore.query({ id: query_exports.any(data2[2]) }).forEach((card) => {
                cardSubscriptionStore.unsubscribeFrom(card);
              });
            }
          } else if (data2[0] === "cards" && data2[1] === "archive") {
            cardStore.query({ id: query_exports.any(data2[2]) }).forEach((card) => {
              cardStore.archive(card);
            });
          } else if (data2[0] === "cards" && data2[1] === "delete") {
            cardStore.query({ id: query_exports.any(data2[2]) }).forEach((card) => {
              cardStore.remove(card);
            });
          } else if (data2[0] === "cards" && data2[1] === "copy") {
            $q.digest(loadAllCardsOf(this.project));
          } else {
            $q.when(loadSomeCardsOfProject(this.project, data2[2]), (cards) => {
              let cardIds = cards.map((c3) => c3.id);
              data2[2].forEach((cardId) => {
                if (!cardIds.includes(cardId)) {
                  cardStore.removeById(cardId);
                }
              });
            });
          }
          $rootScope.$broadcast("projectBatchEnd");
        });
        this.room.on("project_attribute_recomputed", (cardIds) => {
          if (cardIds) {
            $q.digest(loadSomeCardsOfProject(this.project, cardIds));
          } else {
            $q.digest(loadAllCardsOf(this.project));
          }
        });
        this.room.on("project_attribute_compute_start", (data2) => {
          $rootScope.$applyAsync(() => {
            const [attr, model] = cardModelStore.getAttribute(data2[0], true);
            if (attr) {
              cardModelStore.updateAttribute(model, {
                ...attr,
                options: {
                  ...attr?.options,
                  computing: true,
                  parse_error: false,
                  type_hint: data2[1]
                }
              });
            }
          });
        });
        this.room.on("project_attribute_compute_end", (data2) => {
          $rootScope.$applyAsync(() => {
            const [attr, model] = cardModelStore.getAttribute(data2[0], true);
            if (attr) {
              cardModelStore.updateAttribute(model, {
                ...attr,
                options: {
                  ...attr?.options,
                  computing: false
                }
              });
            }
          });
        });
        this.room.on("project_attribute_compute_error", (data2) => {
          $rootScope.$applyAsync(() => {
            const [attr, model] = cardModelStore.getAttribute(data2[0], true);
            if (attr) {
              cardModelStore.updateAttribute(model, {
                ...attr,
                options: {
                  ...attr?.options,
                  type_hint: data2[1]
                }
              });
            }
          });
        });
        this.room.on("card_created", (data2) => {
          $q.when(api_default.cards.get_card.get({ card_id: data2[0] }), (card) => {
            cardStore.insert(card, true);
            card.groups.forEach((group2) => {
              if (!cardGroupStore.exists(group2.id)) {
                $q.digest(loadGroupByParent({ id: card.path[0].id, project_id: card.project_id }, group2.id));
              }
            });
            cardStore.reorderGroupsAfterCreation(card);
          });
        });
        this.room.on("card_updated", refreshCard((card, data2) => {
          if (data2) {
            $q.when(getOrLoadModelForCard(card), () => {
              const attrs2 = cardModelStore.getCardAvailableAttributes(card);
              if (attrs2.length > 0 && data2.length > 0 && data2[0] === "attributes") {
                const attr = attrs2.find((a3) => a3.id === data2[1]);
                if (attr && attr.type === "members") {
                  return loadSubscriptionForCard(card);
                }
              }
            });
          }
        }));
        this.room.on("card_relocated", this.wrap((card, data2) => {
          const [groupId, position, old_groups] = data2;
          cardStore.unlocked(card, () => {
            cardStore.transaction(() => {
              if (groupId) {
                const g3 = cardGroupStore.tryGet(groupId);
                if (g3) {
                  cardStore.relocate(card, g3, position, true, false);
                }
              }
              if (old_groups) {
                for (const [gId, _5] of old_groups) {
                  const g3 = cardGroupStore.tryGet(gId);
                  if (g3) {
                    cardStore.removeFromGroup(card, g3);
                  }
                }
              }
            });
            this.debouncedRefreshCard(card);
          });
        }));
        this.room.on("card_added_to_group", this.wrap((card, data2) => {
          cardStore.unlocked(card, () => {
            cardStore.transaction(() => {
              cardStore.reorderGroup(card, cardGroupStore.get(data2[0]), data2[1]);
            });
            this.debouncedRefreshCard(card);
          });
        }));
        this.room.on("card_archived", refreshCard((card) => {
          cardStore.archive(card);
        }));
        this.room.on("card_restored", refreshCard((card) => {
          cardStore.restore(card);
        }));
        this.room.on("card_deleted", this.wrap((card) => {
          cardStore.archive(card);
          cardStore.remove(card);
        }));
        this.room.on("card_root_changed", refreshCard());
        this.room.on("card_comment_posted", this.wrap((card, comment4) => {
          activityStore.insert(comment4);
          cardStore.update(card, { nb_comments: card.nb_comments + 1 });
        }));
        this.room.on("card_comment_edited", refreshStream);
        this.room.on("card_comment_pinned", refreshStream);
        this.room.on("card_comment_unpinned", refreshStream);
        this.room.on("card_comment_deleted", refreshStream);
        this.room.on("group_created", refreshGroup((group2) => {
          cardStateStore.createOrUpdateAliasFromGroup(group2);
          cardGroupStore.relocate(group2, group2.position);
        }));
        this.room.on("group_updated", refreshGroup((group2) => {
          cardStateStore.createOrUpdateAliasFromGroup(group2);
        }));
        this.room.on("group_moved", refreshGroup((group2, data2) => {
          cardGroupStore.reorder(group2, group2.position, data2[1]);
        }));
        this.room.on("group_relocated", refreshGroup((group2, data2) => {
          cardGroupStore.update(group2, { parent_id: data2[1] });
        }, true));
        this.room.on("group_archived", refreshGroup((group2, data2) => {
          cardStateStore.createOrUpdateAliasFromGroup(group2);
          cardStore.broadcast("changed");
          cardGroupStore.reorder(group2, null, group2.position);
          if (data2[1]) {
            cardStore.archiveAllFromGroup(group2);
          }
        }));
        this.room.on("group_restored", refreshGroup((group2) => {
          cardStateStore.createOrUpdateAliasFromGroup(group2);
          cardGroupStore.reorder(group2, group2.position);
        }));
        this.room.on("group_deleted", refreshGroup((group2) => {
          cardGroupStore.transaction(() => {
            cardGroupStore.reorder(group2, null, group2.position);
            cardGroupStore.remove(group2);
          });
          cardStore.clearGroupsAfterDeletion(group2);
        }, true));
        const refreshGrouptype = (data2) => {
          $q.digest(getOrLoadGroupType(this.project, data2));
        };
        this.room.on("group_type_created", refreshGrouptype);
        this.room.on("group_type_updated", refreshGrouptype);
        this.room.on("group_type_enabled", refreshGrouptype);
        const removeGrouptype = (data2) => {
          const groupType = cardGroupTypeStore.tryGet(data2);
          if (groupType) {
            cardGroupTypeStore.remove(groupType);
            cardGroupStore.removeManyMatching({ type_id: groupType.id });
          }
        };
        const disableGroupType = (data2) => {
          const groupType = cardGroupTypeStore.tryGet(data2);
          if (groupType) {
            if (groupType.used_by.includes(this.project.id)) {
              cardGroupTypeStore.upsert(groupType, { used_by: groupType.used_by.filter((id) => id !== this.project.id) });
            }
          }
        };
        this.room.on("group_type_deleted", removeGrouptype);
        this.room.on("group_type_disabled", disableGroupType);
        this.room.on("group_states_updated", this.wrap((card) => $q.digest(loadAvailableStatesForCard(card))));
        this.room.on("view_created", (view_id) => $q.digest(getOrLoadView(view_id)));
        this.room.on("view_updated", (view_id) => {
          const view = { ...viewStore.tryGet(view_id) || {} };
          $q.when(loadView(view_id), (v3) => {
            if (v3.position !== view?.position || v3.category_id !== view?.category_id) {
              let store2;
              if (v3.project_id) {
                store2 = viewStore.scopedByProject({ id: v3.project_id });
              } else {
                store2 = viewStore.scopedByGlobal();
              }
              store2.reorderAfterChange(v3, view?.position, view?.category_id);
            }
          });
        });
        this.room.on("view_deleted", (view_id) => {
          const view = viewStore.tryGet(view_id);
          if (view) {
            viewStore.remove(view);
          }
        });
        const refreshViewCategories = () => $q.digest(loadAllViewCategories(this.project));
        this.room.on("view_cat_created", refreshViewCategories);
        this.room.on("view_cat_updated", refreshViewCategories);
        this.room.on("view_cat_deleted", refreshViewCategories);
        const refreshModels = (modelId) => $q.digest(loadModel(modelId));
        this.room.on("model_enabled", refreshModels);
        this.room.on("model_disabled", refreshModels);
        this.room.on("model_created", refreshModels);
        this.room.on("model_updated", refreshModels);
        this.room.on("model_attribute_moved", () => {
          $q.all([
            loadAllEnabledModelsForProject(this.project),
            loadProject(this.project.id)
          ]);
        });
        this.room.on("model_deleted", (modelId) => {
          if (cardModelStore.exists(modelId)) {
            cardModelStore.remove(modelId);
          }
        });
        this.room.on("recurring_card_added", () => $q.digest(loadAllRecurringCardsForProject(this.project)));
        this.room.on("recurring_card_updated", () => $q.digest(loadAllRecurringCardsForProject(this.project)));
        this.room.on("recurring_card_deleted", (recurringId) => {
          const recurring = recurringCardStore.tryGet(recurringId);
          if (recurring) {
            cardStore.removeById(recurring.template_id);
            recurringCardStore.remove(recurring);
          }
        });
      }
      wrap(cb2) {
        return (data2) => {
          if (cardStore.exists(data2[0])) {
            cb2(cardStore.get(data2.shift()), data2);
          }
        };
      }
      debouncedCard(func) {
        const cards = /* @__PURE__ */ new Map();
        this.debouncedCardCallbacks = cards;
        return (card, cb2) => {
          if (cards.has(card.id)) {
            clearTimeout(cards.get(card.id)[0]);
          } else {
            cards.set(card.id, [null, []]);
          }
          if (cb2) {
            cards.get(card.id)[1].push(cb2);
          }
          cards.get(card.id)[0] = setTimeout(() => {
            func(card, (card2) => {
              if (cards.has(card2.id)) {
                cards.get(card2.id)[1].forEach((cb3) => cb3(card2));
                cards.delete(card2.id);
              }
            });
          }, 100);
        };
      }
      destroy() {
        this.room = null;
        this.project = null;
        for (const [timer] of this.debouncedCardCallbacks.values()) {
          clearTimeout(timer);
        }
        this.debouncedCardCallbacks.clear();
      }
    };
  }
]);

// public/app/ui/project/scope-manager.js
angular_default.module("kantree").factory("ProjectScopeManager", [
  "$injector",
  function($injector) {
    return class ProjectScopeManager extends AngularClass {
      static $inject = ["$q", "$timeout", "ProjectLocalStorageManager", "ProjectPushListener", "ProjectPresenceManager"];
      static init(ctrl, scope, projectSlug, boardRef) {
        const manager = $injector.instantiate(this);
        return manager.setup(ctrl, scope, projectSlug, boardRef).then(() => manager);
      }
      constructor() {
        super(...arguments);
        this.viewDefaultProps = projectViewsDefaultProps;
        this.viewAvailableProps = projectViewsAvailableProps;
        this.destroyed = false;
      }
      get availableApps() {
        return this.appRegistry.getAll();
      }
      get appRegistry() {
        return projectAppRegistry;
      }
      setup(ctrl, scope, projectSlug, boardRef) {
        this.ctrl = ctrl;
        this.scope = scope;
        ctrl.loaded = false;
        const [project, loadedPromise] = this.fetchProject(projectSlug, boardRef);
        if (project) {
          return this.$q.all([
            this.setupProject(project, boardRef),
            loadedPromise.then(() => {
              sideLoadBoard(this.project);
            })
          ]);
        }
        return loadedPromise.then((project2) => {
          this.projectHasBeenRefreshed = true;
          return this.setupProject(project2, boardRef);
        });
      }
      setupProject(project, boardRef) {
        this.ctrl.project = this.project = project;
        if (this.project.status) {
          return this.$q.resolve();
        }
        return this.fetchRelated({ boardRef }).then((board) => {
          this.ctrl.board = this.board = board;
          this.viewStore = viewStore.scopedByProject(this.project);
          this.localStorageManager = new this.$ProjectLocalStorageManager(this.project);
          return this.localStorageManager.load().then(() => {
            this.createContext();
            this.scope.$on("connectivityChanged", (e3, connected) => {
              if (connected) {
                this.$q.all([
                  loadProject(this.project.id, { ignoreErrorHandlers: true }),
                  loadCard(this.board.id, { ignoreErrorHandlers: true })
                ]);
              }
            });
            this.unregisterDestroy = this.scope.$on("$destroy", () => this.destroy());
            this.setupPush();
          });
        });
      }
      fetchProject(projectSlug, boardRef) {
        let cachedProject = projectStore.query({ slug: query_exports.optional(projectSlug), board: query_exports.isTruthy() })?.[0];
        if (cachedProject?.board?.ref !== (boardRef || 0) || !!cachedProject?.status) {
          cachedProject = null;
        }
        if (!cachedProject && !isConnected()) {
          return [null, this.$q.reject("Project not found or not available offline")];
        }
        let promise;
        if (isConnected()) {
          let req = api_default.projects.get_board.get({ project_id: projectSlug, with_members: 0 });
          if (boardRef) {
            req = api_default.projects.get_board.get({ project_id: projectSlug, ref: boardRef, with_members: 0 });
          }
          promise = this.$q.when(req.then(async (project) => {
            if (project.board.is_link) {
              project = await api_default.projects.get_board.get({ project_id: project.board.link.id, with_members: 0 });
            }
            project = projectStore.upsert(sideLoadProject(project));
            return project;
          }));
        } else {
          promise = this.$q.resolve();
        }
        return [cachedProject, promise];
      }
      async fetchRelated({ boardRef } = {}) {
        const board = this.fetchBoard(boardRef);
        if (projectMemberStore.scopedByProject(this.project).query().length > 0) {
          loadAllProjectMembers(this.project, false);
        } else {
          await loadAllProjectMembers(this.project, false);
        }
        return board;
      }
      fetchBoard(boardRef) {
        let board;
        if (this.project.board) {
          board = sideLoadBoard(this.project);
        } else if (boardRef) {
          board = cardStore.scopedByProject(this.project).query({ ref: parseInt(boardRef, 10) })?.[0];
        }
        if (!board) {
          board = cardStore.tryGet(this.project.top_level_card.id);
        }
        if (!board) {
          throw new Error("This board can't be loaded");
        }
        return board;
      }
      get cardStore() {
        return cardStore.scoped({
          is_template: query_exports.isFalsy(),
          is_archived: (v3) => this.context.appOptions?.include_archived ? true : !v3,
          path: (path) => this.context.appOptions?.include_descendants ? query_exports.matchArray(path, (card) => card.id === this.board.id.toString()) : true,
          parent_id: (id) => this.context.appOptions?.include_descendants ? true : this.board.id === id
        });
      }
      createContext() {
        this.ctrl.context = this.context = new ProjectContext2({
          project: this.project,
          board: this.board,
          cardStore: this.cardStore
        });
        this.context._shouldRenderFilteredCards = !this.context.appOptions?.filter;
        this.context.watch("app", (app) => {
          this.onAppChanged();
        }, false);
        this.context.watch("shouldRenderFilteredCards", (newVal) => {
          this.scope.$broadcast("shouldRenderFilteredCards", newVal);
        }, false);
        this.scope.$on("$destroy", () => {
          this.context.destroy();
        });
      }
      onAppChanged() {
        if (this.unregisterCardsAppOptionsWatcher) {
          this.unregisterCardsAppOptionsWatcher();
          this.unregisterCardsAppOptionsWatcher = null;
        }
        if (this.unregisterAppOptionsWatcher) {
          this.unregisterAppOptionsWatcher();
          this.unregisterAppOptionsWatcher = null;
        }
        if (this.context.app.name === "cards") {
          this.setupCardsApp();
        }
        if (!this.context.app.noView) {
          this.unregisterAppOptionsWatcher = this.context.watch("appOptions", (options2) => {
            if (this.preventNextAppOptionsChange) {
              this.preventNextAppOptionsChange = false;
              return;
            }
            this.updateViewFromAppOptionsChanges({ options: options2 });
          }, false);
        }
        if (this.context.app.filterable || this.context.app.name === "cards" && this.appRegistry.get(this.context.appOptions.mode, true, true)?.filterable) {
          if (!this.unregisterMatchingCardsListeners) {
            this.registerMatchingCardsListeners();
          }
        } else {
          if (this.unregisterMatchingCardsListeners) {
            this.unregisterMatchingCardsListeners();
            this.unregisterMatchingCardsListeners = null;
          }
        }
      }
      updateViewFromAppOptionsChanges(changes) {
        const viewChanges = transformAppChangesIntoViewProps(changes);
        if (this.viewStore.hasChanges(this.view, viewChanges)) {
          this.preventListeningToActiveViewRemoval = true;
          const draftView = this.viewStore.upsertDraftFromView(
            this.view,
            viewChanges,
            this.viewDefaultProps,
            this.viewAvailableProps
          );
          this.preventListeningToActiveViewRemoval = false;
          this.setActiveView(draftView.id);
        }
      }
      // Watching 'changed' event on stores to update visibility of cards matching current filter
      registerMatchingCardsListeners() {
        if (this.unregisterMatchingCardsListeners) this.unregisterMatchingCardsListeners();
        const off = offMany([
          cardStore.scopedByProject(this.project).subscribe(this.fetchMatchingCardsDebounced),
          cardGroupStore.scopedByAvailableForChildren(this.board).subscribe(this.fetchMatchingCardsDebounced),
          cardModelStore.scopedByEnabled(this.project).subscribe(this.fetchMatchingCardsDebounced),
          cardGroupTypeStore.scopedByEnabled(this.project).subscribe(this.fetchMatchingCardsDebounced),
          requestFormStore.scopedByProject(this.project).subscribe(this.fetchMatchingCardsDebounced),
          cardSubscriptionStore.subscribe(this.fetchMatchingCardsDebounced)
        ]);
        this.unregisterMatchingCardsListeners = () => {
          off();
          this.fetchMatchingCardsDebounced.clear();
        };
      }
      fetchMatchingCardsDebounced = debounce2(() => {
        if (this.cardsHaveBeenLoadedOnce) this.fetchCardsMatchingFilter(this.context.appOptions.filter);
      }, 500);
      setupCardsApp() {
        this.unregisterCardsAppOptionsWatcher = this.context.watch("appOptions", (options2, oldOptions) => {
          if (!equals(options2?.include_archived, oldOptions?.include_archived) && !!options2.include_archived && !this.archivesLoaded) {
            this.archivesLoaded = true;
            const toast = toastNotify(_4("Loading archived cards"), "loader");
            this.fetchArchivedGroups();
            this.$q.when(loadAllArchivedCardsOf(this.project), () => toast.close());
          }
          if (!equals(options2?.filter, oldOptions?.filter)) {
            this.fetchCardsMatchingFilter(options2?.filter);
          }
        });
      }
      setupPush() {
        return this.$q.when(getPushConnection().then((conn) => conn.join(this.project.push_id)), (room) => {
          if (this.destroyed) {
            room.leave();
            return;
          }
          this.pushRoom = room;
          this.projectPushListener = new this.$ProjectPushListener(this.pushRoom, this.project);
          this.presenceManager = new this.$ProjectPresenceManager(this.pushRoom, this.board);
          this.scope.$on("projectBatchStart", (event2, toast) => {
            if (this.currentBatchToast) this.currentBatchToast.close();
            this.currentBatchToast = toast;
          });
          this.scope.$on("projectBatchEnd", (event2, toast) => {
            this.$timeout(() => {
              if (this.currentBatchToast) this.currentBatchToast.close();
            }, 0, false);
          });
        });
      }
      closePushConnection() {
        if (!this.keepPushRoomOpenedOnDestroy) {
          this.pushRoom?.leave();
        }
        this.pushRoom = null;
      }
      preventDraftRemovalWatcher = false;
      setActiveView(viewId) {
        const oldView = this.view;
        if (pluck(this.availableApps.filter((app) => !!app.noView), "name").includes(viewId)) {
          this._setActiveView(null, oldView, viewId);
          return;
        }
        let view = this.getView(viewId);
        if (!view) {
          if (!!viewId) {
            this.gotoView();
            return;
          }
          const defaultView = this.getDefaultView();
          if (defaultView) {
            this.gotoView(defaultView);
            return;
          }
          this._setActiveView(null, oldView);
          return;
        }
        this._setActiveView(view, oldView);
      }
      _setActiveView(view, oldView, noViewAppFallback) {
        const {
          view: _view = view,
          noViewAppFallback: _noViewAppFallback = noViewAppFallback
        } = this._beforeSetActiveView(view, oldView, noViewAppFallback);
        if (_view && this.view?.id === _view?.id) {
          return;
        }
        if (this.unregisterViewStoreWatchers) this.unregisterViewStoreWatchers();
        this.ctrl.view = this.view = _view;
        if (!_view?._draft) {
          this.viewStore.removeManyMatching({ _draft: true });
        }
        if (_view) {
          const _fromView = this.viewStore.tryGetFromView(_view);
          let _fromViewPosition = _fromView?.position;
          let _fromViewCategoryId = _fromView?.category_id;
          this.unregisterViewStoreWatchers = offMany([
            this.viewStore.watch(_view, "updated", () => this.onActiveViewUpdated(), false),
            this.viewStore.watch(_view, "removed", () => this.onActiveViewRemoved(), false)
          ].concat(!_fromView ? [] : [
            this.viewStore.watch(_fromView, "updated", (newView) => {
              if (_fromViewPosition !== newView.position || _fromViewCategoryId !== newView.category_id) {
                _fromViewPosition = newView.position;
                _fromViewCategoryId = newView.category_id;
                return;
              }
              if (_view.locked) {
                this.viewStore.remove(_view);
                return;
              }
              onFromViewUpdatedDialog().then((isConfirm) => {
                if (isConfirm) {
                  this.$q.when(createFromLocalView(_view.name, _view, false), (v3) => $navigateToView(v3));
                } else {
                  this.viewStore.remove(_view);
                }
              });
            }, false),
            this.viewStore.watch(_fromView, "removed", () => {
              onFromViewDeletedDialog().then((isConfirm) => {
                if (isConfirm) {
                  this.$q.when(createFromLocalView(_view.name, _view, false), (v3) => $navigateToView(v3));
                } else {
                  this.gotoView();
                }
              });
            }, false)
          ]));
        } else if (_noViewAppFallback) {
          const app = this.appRegistry.get(_noViewAppFallback, true, true);
          if (!this.context.appEquals(app?.name)) {
            this.context.app = app;
            this.context.appOptions = {};
          }
        }
        this._afterSetActiveView(_view, oldView);
      }
      _beforeSetActiveView(view, oldView, noViewAppFallback) {
        if (!noViewAppFallback && !view) {
          const draftView = this.viewStore.tryGetDraftView();
          if (draftView) {
            if ((draftView.card_ref === null || draftView.card_ref === this.board.ref) && !draftView.from_view_id) {
              view = draftView;
            }
          }
          if (!view) {
            view = this.viewStore.upsertDraftView({
              ...this.viewDefaultProps,
              project_id: this.project.id,
              card_ref: this.board.ref
            });
          }
        }
        return { view, oldView, noViewAppFallback };
      }
      _afterSetActiveView(newView, oldView) {
        if (this.view) {
          this.updateContextWithActiveView();
        }
      }
      onActiveViewUpdated() {
        this.updateContextWithActiveView();
      }
      onActiveViewRemoved() {
        if (this.preventListeningToActiveViewRemoval) return;
        if (!!this.view._draft) {
          const originalView = this.viewStore.tryGet(this.view.from_view_id);
          if (originalView) {
            return this.setActiveView(originalView.id);
          }
        }
        this.gotoView();
      }
      getView(viewId) {
        if (viewId) {
          if (isString_default(viewId) && !viewId.includes("auto-")) {
            viewId = parseInt(viewId);
          }
          const perms = this.project.user_permissions?.find((perm) => perm.object_id === viewId);
          if (perms && perms.actions.indexOf("HIDDEN") > -1) {
            return null;
          }
          const view = this.viewStore.tryGet(viewId);
          if (view && (!view.card_ref || this.board.ref === view.card_ref)) {
            if (!view._draft) {
              const draftView = this.viewStore.tryGetDraftView(view);
              if (draftView) {
                return draftView;
              }
            }
            return view;
          }
        }
        return null;
      }
      getDefaultView() {
        let category_id = null;
        let is_public = true;
        if (!this.viewStore.scoped({
          card_ref: (ref) => ref === null || ref === this.board.ref,
          category_id,
          is_public
        }).count()) {
          const categories = viewCategoryStore.scopedByProject(this.project).query({}, { sortBy: "position" });
          for (let category of categories) {
            if (this.viewStore.scoped({ category_id: category.id, is_public }).count()) {
              category_id = category.id;
              break;
            }
          }
          if (category_id === null) {
            is_public = false;
          }
        }
        const hiddenViewIds = (this.project.user_permissions || []).filter((perm) => {
          return perm.object_type === "view" && perm.actions.indexOf("HIDDEN") > -1;
        }).map((perm) => perm.object_id);
        return this.viewStore.query({
          card_ref: (ref) => ref === null || ref === this.board.ref,
          category_id,
          is_public,
          id: query_exports.not(query_exports.any(hiddenViewIds))
        }, { sortBy: "position" })?.[0];
      }
      updateContextWithActiveView(preventNextAppOptionsChangeIfNeeded = false) {
        const { appName, appOptions } = getContextParamsFromView(this.view);
        this.context.transaction(() => {
          const newApp = this.appRegistry.get(appName, true, true);
          let appChanged = false;
          if (!this.context.appEquals(newApp?.name)) {
            this.context.app = newApp;
            appChanged = true;
          }
          if (!!appOptions && !this.context.appOptionsEquals(appOptions)) {
            if (!appChanged) {
              this.preventNextAppOptionsChange = preventNextAppOptionsChangeIfNeeded || this.unregisterAppOptionsWatcher;
            }
            this.context.appOptions = appOptions;
          }
        });
      }
      fetchCards() {
        this.cardsHaveBeenLoadedOnce = false;
        if (isConnected()) {
          this._fetchCards();
        }
        this.scope.$on("connectivityChanged", (e3, connected) => {
          if (connected && this.project) {
            this._fetchCards();
          }
        });
      }
      _fetchCards() {
        if (this.cardsHaveBeenLoadedOnce) {
          this.$q.digest(loadAllCardsOf(this.project, null, false, { ignoreErrorHandlers: true }));
        } else if (!this.fetchCardsRequest) {
          const toast = toastNotify(_4("Refreshing cards"), "loader");
          this.fetchCardsRequest = loadAllCardsOf(this.project, null, false, {}, () => {
            this.scope.cardsLoaded = true;
          });
          this.$q.when(this.fetchCardsRequest, () => {
            this.fetchCardsRequest = null;
            this.cardsHaveBeenLoadedOnce = true;
            toast.close();
            setKeepProjectOffline(this.project);
            if (!this.project.is_portfolio && this.context.cardStore.query().length === 0) {
              this.$timeout(() => this.scope.$broadcast("shouldOpenCardCreatorOnInit"), 100);
            }
          });
        }
      }
      filteringCounter = 0;
      filteringToast = null;
      fetchCardsMatchingFilter(filter4) {
        if (abortCtrl) abortCtrl.abort();
        if (!filter4 || $.trim(filter4) === "" || !isConnected() || !this.context.app?.cardsFilterable) {
          if (this.context.matchingCardIds) {
            this.context.matchingCardIds = null;
            this.context.filterRepr = null;
            this.scope.$applyAsync();
          }
          return;
        }
        this.filteringCounter++;
        this.$timeout(() => {
          if (this.filteringCounter > 0 && !this.filteringToast) {
            this.filteringToast = toastNotify(_4("Filtering cards"), "loader");
          }
        }, 1e3, false);
        var abortCtrl = new AbortController();
        this.$q.when(api_default.projects.list_cards.get({
          project_id: this.project.id,
          filter: filter4,
          with_archived: this.context.appOptions?.include_archived,
          only_ids: true
        }, { ignoreErrorHandlers: true, resolveWithResponse: true, signal: abortCtrl.signal }), ([data2, resp]) => {
          this.$timeout(() => {
            this.filteringCounter = Math.max(this.filteringCounter - 1, 0);
            if (this.filteringToast && this.filteringCounter === 0) {
              this.filteringToast.close();
              this.filteringToast = null;
            }
          }, 500, false);
          this.context.matchingCardIds = data2;
          this.context.filterRepr = decodeURIComponent(resp.headers.get("x-kantree-filterrepr"));
        }, () => {
          this.filteringCounter = Math.max(this.filteringCounter - 1, 0);
          if (this.filteringToast && this.filteringCounter === 0) {
            this.filteringToast.close();
            this.filteringToast = null;
          }
          this.context.matchingCardIds = [];
          this.context.filterRepr = null;
        });
      }
      fetchArchivedGroups() {
        this.$q.when(loadAllArchivedAvailableGroupsForCard(this.board), (archived_groups) => {
          cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(this.project, true).scoped({ scope: query_exports.not("org") })).join("parent_id", cardStore.scopedByProject(this.project)).scoped({ is_archived: true }).removeAll();
          cardGroupStore.join("type_id", cardGroupTypeStore.scopedByEnabled(this.project, true).scoped({ scope: "org" })).scoped({ is_archived: true }).removeAll();
          cardGroupStore.upsertMany(archived_groups);
        });
      }
      gotoNoViewApp(appName) {
        $navigateToProject(this.project, null, { id: appName });
      }
      gotoView(view) {
        $navigateToProject(this.project, !view?.card_ref ? this.board : null, view);
      }
      destroy() {
        this.destroyed = true;
        this.unregisterDestroy();
        this.closePushConnection();
        this.presenceManager.destroy();
        this.projectPushListener.destroy();
        if (this.currentBatchToast) this.currentBatchToast.close();
        if (this.unregisterViewStoreWatchers) this.unregisterViewStoreWatchers();
        if (this.unregisterMatchingCardsListeners) this.unregisterMatchingCardsListeners();
        if (this.fetchCardsRequest) this.fetchCardsRequest.cancelLoadPaginated();
        this.fetchMatchingCardsDebounced.clear();
        return this.$q((resolve2) => {
          this.$timeout(() => {
            if (this.viewStore) {
              this.viewStore.removeManyMatching({ _draft: true });
            }
            if (this.localStorageManager) this.localStorageManager.destroy();
            resolve2();
          });
        });
      }
    };
  }
]);
function onFromViewChangesDialog(text3) {
  return dialog({
    text: text3,
    type: "info",
    closeOnConfirm: true,
    showCancelButton: true,
    cancelButtonText: _4("Discard your changes"),
    confirmButtonColor: "#288628",
    confirmButtonText: _4("Save as a new private view")
  });
}
function onFromViewUpdatedDialog() {
  return onFromViewChangesDialog(_4("The current view has just been updated by someone else. You have unsaved changes. What do you do?"));
}
function onFromViewDeletedDialog() {
  return onFromViewChangesDialog(_4("The current view has just been deleted by someone else. You have unsaved changes. What do you do?"));
}

// public/app/ui/project/page.js
angular_default.module("kantree").service("projectPage", class extends AngularClass {
  activate($scope2, scopeManager) {
    this.scope = $scope2;
    this.scopeManager = scopeManager;
    this.selectedCards = [];
    this.highlightedCardIds = [];
    $scope2.$on("$destroy", () => {
      this.scope = null;
      this.scopeManager = null;
      this.selectedCards = null;
    });
  }
  get context() {
    return this.scopeManager.context;
  }
  get project() {
    return this.scopeManager.project;
  }
  get board() {
    return this.scopeManager.board;
  }
  get view() {
    return this.scopeManager.view;
  }
  get isActive() {
    return !!this.scopeManager && !!this.scopeManager.context;
  }
  isViewActive(view) {
    return this.isActive && !!view && !!this.view && (this.view.id === view.id || this.view._draft && view.id === this.view.from_view_id);
  }
  isProjectActive(project) {
    return this.isActive && (this.project.id === project?.id || this.project.slug === project?.slug);
  }
  gotoApp(appName) {
    this.isActive && this.scopeManager.gotoNoViewApp(appName);
  }
  trigger(...args) {
    return this.context.trigger(...args);
  }
  broadcast(...args) {
    this.scope.$broadcast(...args);
  }
  hightlightCards(cardIds) {
    this.highlightedCardIds = cardIds;
    this.broadcast("highlightCards", cardIds);
  }
  selectCard(card) {
    this.selectedCards.push(card.id);
    this.broadcast("selectCards", [card.id]);
  }
  selectAllCards() {
    this.selectedCards = [];
    this.broadcast("selectAllCards", null);
  }
  selectAllHighlightedCards() {
    this.selectedCards = [];
    this.broadcast("selectAllCards", this.highlightedCardIds);
  }
  unselectCard(card) {
    let idx = this.selectedCards.indexOf(card.id);
    if (idx !== -1) {
      this.selectedCards.splice(idx, 1);
      this.broadcast("unselectCard", card.id);
    }
  }
  isCardSelected(card) {
    return this.selectedCards.indexOf(card.id) !== -1;
  }
  clearSelectedCards() {
    this.selectedCards = [];
    this.broadcast("clearSelectedCards");
  }
});

// public/app/ui/project/theme.js
angular_default.module("kantree").service("projectTheme", class extends AngularClass {
  static $inject = ["cardViewTheme", "stylesheetManager"];
  activate($scope2, project) {
    let disposePageBackgroundImage;
    projectStore.$watch($scope2, project, (project2) => {
      disposePageBackgroundImage = setPageBackgroundImage(project2.image_cover_url);
      this.apply(project2);
    });
    cardModelStore.scopedByEnabled(project, true).query().forEach((model) => {
      if (model.card_color) {
        this.$cardViewTheme.create(model.card_color);
      }
    });
    $scope2.$on("$destroy", () => {
      jquery_default("body").removeClassRegex("board-theme-");
      disposePageBackgroundImage && disposePageBackgroundImage();
    });
  }
  apply(project) {
    jquery_default("body").removeClassRegex("board-theme-");
    if (project.color) {
      setPageColor(project.color, true);
    } else if (project.owner.color) {
      setPageColor(project.owner.color);
    } else {
      setPageColor();
    }
    const color = project.color || project.owner.color || themeColor();
    if (color) {
      const themeClass = `board-theme-${color.substr(1)}`;
      this.$stylesheetManager.createTheme(themeClass, color, "/static/app/routes/project/ng-components/templates/project.css.html", {
        "menu": tinycolor(color).lighten(20).toString()
      }).then(() => {
        jquery_default("body").removeClass("board-theme-default").addClass(themeClass);
      });
      this.$cardViewTheme.createFromProjectColor(color);
    } else {
      jquery_default("body").addClass("board-theme-default");
    }
  }
});

// public/app/ui/requests/ng-components/form.js
angular_default.module("kantree").directive("requestForm", [
  function() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "/static/app/ui/requests/ng-components/templates/form.html",
      scope: {
        form: "<",
        onSubmitted: "&",
        hideHeader: "<",
        onCancel: "&?",
        resetOnSubmit: "<?",
        disableSubmitBtn: "<?",
        disableSubmitMessage: "<?"
      },
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          injectI18nHelpersIntoScope($scope2);
          $scope2.isAuthenticated = isAuthenticated;
          $scope2.submitting = false;
          function reset3() {
            $scope2.formObj = { "attributes": [] };
            $scope2.data = {};
            $scope2.attributes = RequestFormAttributeGroup.fromRequestForm($scope2.form);
            $scope2.attributes.forEach(function(attr) {
              if (attr.type === "group_type" && !cardGroupTypeStore.exists(attr.group_type_id)) {
                cardGroupTypeStore.insert(attr.group_type);
              }
            });
            $scope2.shareMenuConfig = { config: [{
              component: "form-links-menu-component",
              params: { form: $scope2.form }
            }] };
          }
          $scope2.$watch("form.id", reset3);
          $scope2.submit = function() {
            if (!isAuthenticated() && $scope2.form.anonymous_email_field_idx === null && !$scope2.email && $scope2.form.email_required) {
              errorDialog(_4("Missing email address"));
              return;
            }
            for (var i3 = 0; i3 < $scope2.form.fields.length; i3++) {
              if ($scope2.form.fields[i3].required) {
                if ($scope2.data[$scope2.form.fields[i3].id] || attributeTypeRegistry.get($scope2.form.fields[i3].attribute.type).defaultValueIsUngrouped) {
                  continue;
                }
                errorDialog(_4("Missing required field: " + $scope2.form.fields[i3].label));
                return;
              }
            }
            $scope2.submitting = true;
            $q.when(submitRequestForm($scope2.form, $scope2.data, $scope2.email), (request2) => {
              $scope2.submitting = false;
              $scope2.onSubmitted({ request: request2 });
              if ($scope2.resetOnSubmit) {
                reset3();
              }
            }, (r3) => {
              $scope2.submitting = false;
              r3.json().then((data2) => errorDialog(_4(data2.error || _4("An error ocurred"))));
            });
          };
        }
      ]
    };
  }
]);

// public/app/ui/requests/ng-components/links-menu.js
angular_default.module("kantree").component("formLinksMenuComponent", {
  templateUrl: "/static/app/ui/requests/ng-components/templates/links-menu-component.html",
  bindings: {
    params: "<?",
    onClose: "&",
    onUpdate: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$state", "shareEmbedModal"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.form = this.params.form;
      this.url = makeUrlAbsolute(this.$state.href("request_form", { formSlug: this.form.slug }));
    }
    embed() {
      this.$shareEmbedModal.open(this.url);
      this.onClose();
    }
  }
});

// public/app/actions/request.ts
async function postRequestComment(request2, message) {
  const comment4 = await api_default.request.post_comment.post({ request_token: request2.token, message });
  requestStore.update(request2, (request3) => {
    return { ...request3, comments: [...request3.comments, comment4] };
  });
  return comment4;
}
async function updateRequestFields(request2, data2) {
  data2 = await convertManyFilesToBase64(data2);
  const req = await api_default.request.update_request_fields.put({ request_token: request2.token, data: data2 });
  return requestStore.update(request2, (request3) => {
    return { ...request3, ...req };
  });
}

// public/app/ui/requests/ng-components/request.js
angular_default.module("kantree").component("request", {
  templateUrl: "/static/app/ui/requests/ng-components/templates/request.html",
  bindings: {
    form: "<",
    request: "<",
    onSaved: "&",
    editingOnInit: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$q"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.attributes = RequestFormAttributeGroup.fromRequestForm(this.form);
      this.attributes.forEach((attr) => {
        if (attr.type === "group_type" && !cardGroupTypeStore.exists(attr.group_type_id)) {
          cardGroupTypeStore.insert(attr.group_type);
        }
      });
      this.computeObj();
      if (this.editingOnInit) {
        this.startEdit();
      }
    }
    computeObj() {
      this.obj = { attributes: [], groups: this.request.groups };
      this.form.fields.forEach((field2) => {
        if (field2.type === "title") {
          this.obj.attributes.push({
            id: field2.id,
            value: this.request.title
          });
        } else if (field2.type === "attribute" && field2.attribute.type !== "group_type") {
          for (var i3 = 0; i3 < this.request.attributes.length; i3++) {
            if (this.request.attributes[i3].id === field2.attribute.id) {
              this.obj.attributes.push({ ...this.request.attributes[i3], id: field2.id });
              break;
            }
          }
        } else if (field2.type === "attribute" && field2.attribute.type === "group_type") {
          this.obj.attributes.push({
            id: field2.id,
            type: "group_type",
            value: this.request.groups.filter((g3) => g3.type_id === field2.attribute.group_type_id)
          });
        }
      });
      this.activeGroups = [];
      if (this.form.tracking_groups && this.request.current_group_id) {
        let active = true;
        this.form.tracking_groups.sort((a3, b3) => a3.position - b3.position);
        this.form.tracking_groups.forEach((g3) => {
          if (active) {
            this.activeGroups.push(g3.id);
          }
          if (g3.id === this.request.current_group_id) {
            active = false;
          }
        });
        if (active) {
          this.activeGroups = [];
        }
      }
    }
    postComment(message) {
      this.$q.when(postRequestComment(this.request, message), () => {
        this.isCommentCreating = false;
      });
    }
    startEdit() {
      const data2 = {};
      for (const attr of this.obj.attributes) {
        if (attr.type === "group_type") {
          data2[attr.id] = attr.value.map((g3) => g3.id);
        } else {
          data2[attr.id] = attr.value;
        }
      }
      this.editing = { data: data2, obj: angular_default.copy(this.obj) };
    }
    cancelEdit() {
      this.editing = false;
    }
    get hasChanged() {
      return this.editing && this.editing.obj && !equals(this.editing.obj, this.obj);
    }
    update() {
      for (let i3 = 0; i3 < this.form.fields.length; i3++) {
        if (this.form.fields[i3].required) {
          if (this.editing.data[this.form.fields[i3].id] || attributeTypeRegistry.get(this.form.fields[i3].attribute.type).defaultValueIsUngrouped) {
            continue;
          }
          errorDialog(_4("Missing required field: " + this.form.fields[i3].label));
          return;
        }
      }
      this.submitting = true;
      this.$q.when(updateRequestFields(this.request, this.editing.data), (request2) => {
        this.submitting = false;
        this.onSaved({ request: request2 });
        this.editing = false;
        this.computeObj();
      }).catch((r3) => {
        this.submitting = false;
        r3.json().then((data2) => errorDialog(_4(data2.error || _4("An error ocurred"))));
      });
    }
  }
});

// public/app/ui/system/ng-components/connectivity.js
angular_default.module("kantree").directive("hideOffline", [
  function() {
    return {
      restrict: "A",
      link: function(scope, element2) {
        scope.$on("connectivityChanged", function(e3, connected) {
          if (connected) {
            element2.show();
          } else {
            element2.hide();
          }
        });
        if (!isConnected()) {
          element2.hide();
        }
      }
    };
  }
]);
angular_default.module("kantree").directive("showOffline", [
  function() {
    return {
      restrict: "A",
      link: function(scope, element2) {
        scope.$on("connectivityChanged", function(e3, connected) {
          if (connected) {
            element2.hide();
          } else {
            element2.show();
          }
        });
        if (isConnected()) {
          element2.hide();
        }
      }
    };
  }
]);
angular_default.module("kantree").directive("disableOffline", [
  function() {
    return {
      restrict: "A",
      link: function(scope, element2) {
        scope.$on("connectivityChanged", function(e3, connected) {
          element2.prop("disabled", !connected);
        });
        if (!isConnected()) {
          element2.prop("disabled", true);
        }
      }
    };
  }
]);

// public/app/ui/system/ng-components/embed.js
angular_default.module("kantree").directive("hideEmbedded", [
  function() {
    return {
      restrict: "A",
      link: function(scope, element2) {
        if (isEmbedded()) {
          element2.hide();
        }
      }
    };
  }
]);
angular_default.module("kantree").directive("embedBlankTarget", [
  function() {
    return {
      restrict: "A",
      link: function(scope, element2) {
        if (isEmbedded()) {
          element2.attr("target", "_blank");
        }
      }
    };
  }
]);

// public/app/ui/system/ng-components/feature-flags.js
angular_default.module("kantree").component("featureFlagLabel", {
  bindings: {
    org: "<",
    flag: "@"
  },
  controller: class extends AngularClass {
    static $inject = ["$element"];
    $postLink() {
      if (hasFeatureFlag(this.org, this.flag)) {
        this.$element.addClass("ng-hide");
      }
    }
  },
  template: `<i class="bi-stars"></i> Business`
});
angular_default.module("kantree").directive("ifFeatureFlag", function() {
  return {
    element: "A",
    link(scope, el2, attrs2) {
      el2.addClass("ng-hide");
      const flag = attrs2.ifFeatureFlag;
      let has4 = false;
      if (attrs2.featureFlagOrg) {
        const org2 = scope.$eval(attrs2.featureFlagOrg);
        has4 = hasFeatureFlag(org2, flag);
      } else {
        for (const spec of appContext.pinnedOrgs) {
          if (hasFeatureFlag(spec.org, flag)) {
            has4 = true;
            break;
          }
        }
      }
      if (has4) {
        el2.removeClass("ng-hide");
      }
    }
  };
});

// public/app/ui/system/ng-components/notifications-drop.js
angular_default.module("kantree").directive("openNotificationsDropdown", [
  "dropdown",
  function(dropdown) {
    return {
      restrict: "A",
      scope: {
        notificationStore: "<openNotificationsDropdown",
        notificationDropTitle: "@",
        onMarkAllAsRead: "&"
      },
      link: function(scope, element2) {
        let scrollTop;
        const dropScope = scope.$new();
        dropScope.opened = false;
        dropScope.store = scope.notificationStore;
        dropScope.dropTitle = scope.notificationDropTitle;
        dropScope.onMarkAllAsRead = scope.onMarkAllAsRead;
        dropScope.updateDrop = function() {
          dropdown.updateOnNextFrame(drop);
        };
        const drop = dropdown.openCompile(element2[0], `
          <notifications-dropdown opened="opened" drop-title="dropTitle" store="store" on-mark-all-as-read="onMarkAllAsRead()" update="updateDrop()">
          </notifications-dropdown>
        `, dropScope, {
          _destroyOnClose: false,
          _autoOpen: false,
          classes: "notifications-drop nav-drop drop-theme-arrow",
          tetherOptions: {
            attachment: "top right",
            offset: "0 -21px"
          },
          beforeClose: () => {
            scrollTop = jquery_default(".notifications-drop .drop-body")[0].scrollTop;
          }
        });
        drop.on("open", function() {
          if (scrollTop) {
            jquery_default(".notifications-drop .drop-body")[0].scrollTop = scrollTop;
          }
          dropScope.opened = true;
          dropScope.$evalAsync();
        });
        drop.on("close", () => {
          dropScope.opened = false;
        });
        function onCardClick(event2) {
          dropdown.close(drop);
        }
        jquery_default(drop.content).on("click", "a.card-activity-subject[rel], .js-drop-close", onCardClick);
        scope.$on("$destroy", function() {
          if (dropScope) {
            jquery_default(drop.content).off("click", onCardClick);
            dropScope.$destroy();
          }
        });
      }
    };
  }
]);
angular_default.module("kantree").component("notificationsDropdown", {
  templateUrl: "/static/app/ui/system/ng-components/templates/notifications-drop.html",
  bindings: {
    store: "<",
    dropTitle: "<",
    opened: "<",
    update: "&",
    onMarkAllAsRead: "&"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element"];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.hasNewNotifications = false;
      this.showNewNotifsButton = false;
      if (!this.dropTitle) {
        this.dropTitle = _4("Notifications");
      }
      this.store.$watchAll(this.$scope, () => this.refreshNotifs());
      $onEvent(this.$scope, onAppContextUpdate, () => this.refreshNotifs());
      $onEvent(this.$scope, onNewUnreadNotifications, () => {
        if (this.opened) {
          this.showNewNotifsButton = this.scrollTop > 50;
          if (!this.showNewNotifsButton) {
            this.onMarkAllAsRead();
          }
        } else {
          this.hasNewNotifications = true;
        }
      });
    }
    $onChanges(changes) {
      if (changes.opened && this.opened) {
        if (this.scrollTop > 50) {
          if (this.hasNewNotifications) {
            this.showNewNotifsButton = true;
          }
        }
        this.hasNewNotifications = false;
      }
      if (changes.store) {
        this.refreshNotifs();
      }
    }
    $postLink() {
      this.$element.find(".drop-body").on("scroll", () => {
        if (this.scrollTop < 50 && this.showNewNotifsButton) {
          this.showNewNotifsButton = false;
          this.$scope.$applyAsync();
        }
      });
    }
    get scrollTop() {
      if (!this.dropBody) {
        this.dropBody = this.$element.find(".drop-body")[0];
      }
      return this.dropBody ? this.dropBody.scrollTop : 0;
    }
    set scrollTop(scrollTop) {
      if (!this.dropBody) {
        this.dropBody = this.$element.find(".drop-body")[0];
      }
      if (this.dropBody) {
        this.dropBody.scrollTop = scrollTop;
      }
    }
    refreshNotifs() {
      if (this.store) {
        this.notifs = this.store.query();
      } else {
        this.notifs = [];
      }
    }
    showNewNotifs() {
      this.scrollTop = 0;
      this.showNewNotifsButton = false;
    }
  }
});

// public/app/ui/system/ng-components/search.js
function getProjectAndCardFromSelection(selection) {
  let card, project;
  if (selection) {
    if (!selection.__type__) {
      console.warn("Missing __type__ on stored object");
    }
    if (selection.__type__ ? selection.__type__ === cardStore.options.typeName : selection.project_id) {
      card = selection;
    } else {
      project = selection;
    }
  }
  if (!project) {
    project = projectStore.getForCard(card);
  } else if (!card) {
    card = project.top_level_card;
  }
  return { project, card };
}
var quickGlobalSearchCache = {
  filter: null,
  results: null
};
angular_default.module("kantree").directive("quickGlobalSearchToggle", [
  function() {
    return {
      //---act as component
      scope: {},
      controllerAs: "$ctrl",
      restrict: "E",
      //---
      bindToController: {
        searchObjTypes: "<?",
        initialFilter: "<?",
        filterScopes: "<?",
        showPreview: "<?",
        coverToggle: "<?",
        dropClass: "@?"
      },
      template: `
        <button type="button" class="btn btn-topbar mod-global-search js-drop-toggle">
          <i class="bi-search"></i> {{::$ctrl.dropScope.searchPlaceholder}}
        </button>
      `,
      controller: class extends AngularClass {
        static $inject = ["$scope", "dropdown", "$compile", "$timeout", "$element"];
        $postLink() {
          this.toggleElement = this.$element.find(".js-drop-toggle");
          this.dropScope = this.$scope.$new();
          this.dropScope.searchObjTypes = this.searchObjTypes;
          this.dropScope.initialFilter = this.initialFilter;
          this.dropScope.filterScopes = this.filterScopes;
          this.dropScope.showPreview = this.showPreview;
          this.dropScope.searchPlaceholder = this.getSearchPlaceholder();
          this.dropScope.goToSearch = this.goToSearch;
          this.dropScope.updateDrop = () => {
            this.$dropdown.updateOnNextFrame(this.drop);
          };
          this.dropScope.closeDrop = () => {
            this.$dropdown.close(this.drop);
          };
          this.dropDomElement = this.$compile(`
            <quick-global-search
              search_obj-types="searchObjTypes"
              initial-filter="initialFilter"
              filter-scopes="filterScopes"
              show-preview="showPreview"
              search-placeholder="searchPlaceholder"
              ${this.goToSearch ? 'go-to-search="goToSearch($filter)"' : ""}
              close-drop="closeDrop()"
              update-drop="updateDrop()"
            ></quick-global-search>
          `)(this.dropScope);
          let tetherOptions;
          if (!!this.coverToggle) {
            tetherOptions = {
              targetAttachment: "top left",
              attachment: "top left",
              constraints: [{
                to: "window",
                pin: true,
                attachment: "none"
              }],
              offset: "8px 10px",
              resizable: false
            };
          } else {
            tetherOptions = {
              attachment: "top right",
              offset: "0 -21px"
            };
          }
          this.drop = this.$dropdown.open(this.toggleElement[0], this.$scope, {
            _destroyOnClose: false,
            _autoOpen: false,
            content: this.dropDomElement[0],
            classes: "search-drop nav-drop " + this.dropClass,
            tetherOptions
          });
          this.drop.on("open", () => {
            this.dropScope.$broadcast("quickGlobalSearchDropOpen");
          });
          this.toggleElement.on("click", () => {
            this.$timeout(() => {
              this.drop.open();
            }, 10, false);
          });
          this.dropScope.$on("$destroy", () => {
            if (this.dropDomElement) {
              this.dropDomElement.remove();
              this.dropDomElement = null;
            }
          });
        }
        getSearchPlaceholder() {
          let org2;
          if (this.filterScopes?.[0]?.[0] === "org") {
            org2 = orgStore.tryGet(this.filterScopes[0][1]);
          }
          if (org2) {
            if (hasFeatureFlag(org2, "teams")) {
              return _4("Search across all workspaces of the organization...");
            } else {
              return _4("Search across all workspaces of the team...");
            }
          }
          if (this.filterScopes?.[0]?.[0] === "project") {
            return _4("Search across all cards of the workspace...");
          }
          return _4("Search across all workspaces...");
        }
        $onDestroy() {
          this.dropScope.$destroy();
          if (this.dropDomElement) {
            this.dropDomElement.remove();
            this.dropDomElement = null;
          }
        }
      }
    };
  }
]);
angular_default.module("kantree").component("quickGlobalSearch", {
  templateUrl: "/static/app/ui/system/ng-components/templates/search-drop.html",
  bindings: {
    searchObjTypes: "<?",
    intialFilter: "<?",
    filterScopes: "<?",
    showPreview: "<?",
    showOpenSearchBtn: "<?",
    searchPlaceholder: "<?",
    goToSearch: "&?",
    // Available when opened in a dropdown
    closeDrop: "&?",
    updateDrop: "&?",
    // Available when opened in a modal
    closeModal: "&?"
  },
  controller: class extends AngularClass {
    static $inject = [
      "$scope",
      "$timeout",
      "$element",
      "$q",
      "$state",
      "$rootScope",
      "dropdown"
    ];
    $onInit() {
      injectI18nHelpersIntoScope(this.$scope);
      this.loading = false;
      this.suggestedSearches = [
        { title: _4("Overdue cards assigned to me"), filter: "@me {$date}<today() state!=done" },
        { title: _4("Due cards assigned to me"), filter: "@me {$date}>= today() state!=done" },
        { title: _4("Assigned to me"), filter: "@me state!=done" }
      ];
      this.searchObjTypes = this.searchObjTypes || ["project", "card"];
      if (this.initialFilter) {
        this.filter = this.initialFilter;
        this.search();
      } else if (this.showPreview && (quickGlobalSearchCache.filter || "").trim().length > 0) {
        this.filter = quickGlobalSearchCache.filter;
        this.cards = quickGlobalSearchCache.results || [];
        this.updateContainer();
      }
      if (this.searchObjTypes.includes("project")) {
        this.matchingProjects = [];
        this.refreshMatchingProjects();
        this.$scope.$on("recentlyOpenedBoardsUpdated", () => this.refreshMatchingProjects());
        projectStore.$on(this.$scope, "inserted", () => this.refreshMatchingProjects());
        projectStore.$on(this.$scope, "removed", () => this.refreshMatchingProjects());
      }
    }
    $postLink() {
      this.focusSearchBox();
      this.$scope.$on("quickGlobalSearchDropOpen", () => {
        this.focusSearchBox();
      });
      this.$scope.$on("quickGlobalSearchModalOpen", () => {
        this.focusSearchBox();
      });
      jquery_default(this.$element).on("click", ".card-tile, .js-drop-close", () => {
        this.closeContainer();
      });
    }
    focusSearchBox() {
      const input = jquery_default(this.$element).find(".js-search-input");
      input[0].focus();
      if (input.val() !== "") {
        input[0].select();
      }
    }
    get formattedFilter() {
      return (this.filter || "").trim();
    }
    get _showOpenSearchBtn() {
      return !!this.showOpenSearchBtn || typeof this.showOpenSearchBtn === "undefined";
    }
    search() {
      quickGlobalSearchCache.filter = this.filter;
      if (this.showPreview) {
        if (this.formattedFilter.length === 0) {
          this.cards = null;
          quickGlobalSearchCache.filter = null;
          quickGlobalSearchCache.results = null;
          if (this.searchObjTypes.includes("project")) {
            this.refreshMatchingProjects();
          }
          this.updateContainer();
          return;
        }
        this.loading = true;
        this.$q.when(
          searchCards(this.formattedFilter, this.filterScopes, null, { ignoreErrorHandlers: true }),
          (cards) => {
            this.cards = cards;
            quickGlobalSearchCache.results = cards;
            this.loading = false;
            this.updateContainer();
          },
          () => {
            this.cards = null;
            quickGlobalSearchCache.results = null;
            this.loading = false;
            this.updateContainer();
          }
        );
      } else {
        this.openSearchPage();
      }
    }
    refreshMatchingProjects() {
      if (this.formattedFilter.length === 0) {
        this.matchingProjects = (recentlyOpenedBoards() || []).filter((c3) => projectStore.exists(c3.project_id));
        if (this.matchingProjects.length > 1 && ["project", "project_board"].includes(this.$state.current.name)) {
          this.matchingProjects = this.matchingProjects.slice(1);
        }
      } else {
        this.matchingProjects = userProjectStore.query({
          title: (v3) => v3.toLowerCase().indexOf(this.formattedFilter.toLowerCase()) !== -1
        });
      }
      if (this.selectedProject && !this.matchingProjects.find((p4) => p4.id === this.selectedProject.id)) {
        this.selectedProject = null;
      }
      if (!this.selectedProject) {
        if (this.matchingProjects.length > 0) {
          this.selectedProject = this.matchingProjects[0];
        } else {
          this.selectedProject = null;
        }
      }
    }
    onKeyUp(event2) {
      if (this.searchObjTypes.includes("project")) {
        if ([32, 38, 40].indexOf(event2.which) !== -1) {
          event2.preventDefault();
          event2.stopPropagation();
        }
        this.refreshMatchingProjects();
      }
    }
    onKeyDown(event2) {
      if (event2.which === 27) {
        if (this.filter) {
          this.clear(event2);
        } else {
          this.closeContainer();
        }
      }
      if (this.searchObjTypes.includes("project") || !this.cards) {
        if ((!this.filter || event2.ctrlKey) && event2.which === 13) {
          this.openSelectedProject();
        } else if (event2.which === 38) {
          this.selectNextProject(-1);
          event2.preventDefault();
        } else if (event2.which === 40) {
          this.selectNextProject(1);
          event2.preventDefault();
        }
      }
    }
    clear(event2) {
      if (this.showPreview) {
        if (this.filter) {
          event2.preventDefault();
          event2.stopPropagation();
        }
        this.filter = null;
        this.cards = null;
        quickGlobalSearchCache.filter = null;
        quickGlobalSearchCache.results = null;
        if (this.searchObjTypes.includes("project")) {
          this.refreshMatchingProjects();
        }
        this.updateContainer();
        this.$timeout(() => {
          this.$element.find(".js-search-input").focus();
        }, 0, false);
      } else {
        this.closeContainer();
      }
    }
    beforeOpenBoard(project, event2) {
      this.closeContainer();
    }
    openSearchPage() {
      if (this.formattedFilter.length > 0) {
        this.closeContainer();
        this._goToSearch(this.formattedFilter);
      } else {
        if (!this.$state.is("search")) {
          this.closeContainer();
          this._goToSearch();
        }
      }
    }
    updateContainer() {
      this.updateDrop?.();
    }
    closeContainer() {
      this.closeDrop?.() || this.closeModal?.();
    }
    _goToSearch(filter4 = "") {
      if (!!this.goToSearch) {
        return this.goToSearch?.({ $filter: filter4 });
      }
      this.$state.go("search", filter4.length ? { q: filter4 } : null);
    }
    onSuggestedSearchClick(suggestedSearch, event2) {
      event2.preventDefault();
      this.filter = suggestedSearch.filter;
      this.search();
    }
    selectNextProject(delta) {
      if (!this.matchingProjects.length) {
        this.selectedProject = null;
        return;
      }
      const itemIdx = this.matchingProjects.findIndex((item) => item.id === this.selectedProject.id);
      let nextIds = itemIdx >= 0 ? itemIdx + delta : 0;
      if (nextIds < 0) {
        nextIds = this.matchingProjects.length - 1;
      } else if (nextIds >= this.matchingProjects.length) {
        nextIds = 0;
      }
      this.selectedProject = this.matchingProjects[nextIds];
    }
    openSelectedProject() {
      const { project, card } = getProjectAndCardFromSelection(this.selectedProject);
      if (!project || (this.$state.current.name === "project" || this.$state.current.name === "project_board") && this.$state.params.projectId === project.slug) {
        return;
      }
      this.closeContainer();
      $navigateToProject(project, card);
    }
  }
});
angular_default.module("kantree").component("searchDropBoardLink", {
  template: `
    <a ng-click="$ctrl._beforeOpenBoard($event)" ng-attr-href="{{$ctrl.href}}">
      <project-list-item project="$ctrl.project" board="$ctrl.card" show-indicators="true"><project-list-item>
    </a>
  `,
  bindings: {
    item: "<",
    beforeOpenBoard: "&?"
  },
  controller: class extends AngularClass {
    static $inject = ["$scope", "$element", "$state"];
    $onInit() {
      const { project, card } = getProjectAndCardFromSelection(this.item);
      this.project = project;
      this.card = card;
      this.$scope.$watch(
        () => projectRouteHref(this.project, this.card),
        (href) => this.href = href
      );
      this.$scope.$on("connectivityChanged", (e3, connected) => {
        this.$element.toggleClass("disabled", !isProjectAccessible(this.project));
      });
    }
    _beforeOpenBoard(event2) {
      if (!isProjectAccessible(this.project)) {
        event2.preventDefault();
        return;
      }
      if (!this.project || (this.$state.current.name === "project" || this.$state.current.name === "project_board") && this.$state.params.projectId === this.project.slug) {
        event2.preventDefault();
        return;
      }
      if (this.beforeOpenBoard?.({ $event: event2 }) === false) {
        event2.preventDefault();
        return;
      }
    }
  }
});

// public/app/modals/product-updates/index.jsx
var _tmpl$168 = /* @__PURE__ */ template(`<a target="_blank" class="btn btn-ghost btn-link"></a>`, 2);
var _tmpl$282 = /* @__PURE__ */ template(`<div class="loading-state"><span></span></div>`, 4);
var _tmpl$357 = /* @__PURE__ */ template(`<div class="error-state"><span></span></div>`, 4);
var _tmpl$442 = /* @__PURE__ */ template(`<div class="empty-state"><span></span></div>`, 4);
var _tmpl$535 = /* @__PURE__ */ template(`<div class="load-more"></div>`, 2);
var _tmpl$628 = /* @__PURE__ */ template(`<div class="updates-feed"></div>`, 2);
var _tmpl$723 = /* @__PURE__ */ template(`<p class="version-description"></p>`, 2);
var _tmpl$820 = /* @__PURE__ */ template(`<div class="version-entry"><div class="version-header"><span class="version-number"></span><span class="version-date"></span></div></div>`, 8);
var _tmpl$918 = /* @__PURE__ */ template(`<div class="version-section"><h4 class="section-title"></h4><div class="section-content"></div></div>`, 6);
function openProductUpdatesModal() {
  return openModal(ProductUpdatesModal, {
    windowClass: "product-updates-modal"
  });
}
function ProductUpdatesModal() {
  const [showAll, setShowAll] = createSignal(false);
  const [loadingMore, setLoadingMore] = createSignal(false);
  const [allUpdates, setAllUpdates] = createSignal(null);
  const [updates] = createResource(async () => {
    const versions = await fetchProductUpdates(10);
    markReleaseAnnouncementAsRead(serverConfig.version);
    return versions;
  });
  const displayedUpdates = () => {
    if (showAll() && allUpdates()) {
      return allUpdates();
    }
    return updates();
  };
  const loadMore = async () => {
    setLoadingMore(true);
    try {
      const allVersions = await fetchProductUpdates();
      setAllUpdates(allVersions);
      setShowAll(true);
    } finally {
      setLoadingMore(false);
    }
  };
  return createComponent(Modal, {
    get children() {
      return [createComponent(ModalHeader, {
        get title() {
          return _4("Product Updates");
        },
        get children() {
          const _el$ = _tmpl$168.cloneNode(true);
          insert(_el$, createComponent(Icon, {
            name: "bi-rss-fill"
          }), null);
          insert(_el$, () => _4("Product blog"), null);
          createRenderEffect(() => setAttribute(_el$, "href", getLocalizedUrl("blog")));
          return _el$;
        }
      }), createComponent(ModalBody, {
        "class": "product-updates-content",
        get children() {
          return [createComponent(Show, {
            get when() {
              return updates.loading;
            },
            get children() {
              const _el$2 = _tmpl$282.cloneNode(true), _el$3 = _el$2.firstChild;
              insert(_el$2, createComponent(Icon, {
                name: "bi-arrow-repeat",
                "class": "spinning"
              }), _el$3);
              insert(_el$3, () => _4("Loading updates..."));
              return _el$2;
            }
          }), createComponent(Show, {
            get when() {
              return updates.error;
            },
            get children() {
              const _el$4 = _tmpl$357.cloneNode(true), _el$5 = _el$4.firstChild;
              insert(_el$4, createComponent(Icon, {
                name: "bi-exclamation-triangle"
              }), _el$5);
              insert(_el$5, () => _4("Failed to load product updates"));
              return _el$4;
            }
          }), createComponent(Show, {
            get when() {
              return !updates.loading && !updates.error;
            },
            get children() {
              const _el$6 = _tmpl$628.cloneNode(true);
              insert(_el$6, createComponent(For, {
                get each() {
                  return displayedUpdates();
                },
                children: (version) => createComponent(VersionEntry, {
                  version
                })
              }), null);
              insert(_el$6, createComponent(Show, {
                get when() {
                  return !displayedUpdates() || displayedUpdates().length === 0;
                },
                get children() {
                  const _el$7 = _tmpl$442.cloneNode(true), _el$8 = _el$7.firstChild;
                  insert(_el$7, createComponent(Icon, {
                    name: "bi-check-circle"
                  }), _el$8);
                  insert(_el$8, () => _4("No updates available"));
                  return _el$7;
                }
              }), null);
              insert(_el$6, createComponent(Show, {
                get when() {
                  return createMemo(() => displayedUpdates()?.length > 0)() && !showAll();
                },
                get children() {
                  const _el$9 = _tmpl$535.cloneNode(true);
                  insert(_el$9, createComponent(Button, {
                    style: "secondary",
                    onClick: loadMore,
                    get disabled() {
                      return loadingMore();
                    },
                    get children() {
                      return [createComponent(Show, {
                        get when() {
                          return loadingMore();
                        },
                        get children() {
                          return createComponent(Icon, {
                            name: "bi-arrow-repeat",
                            "class": "spinning"
                          });
                        }
                      }), createMemo(() => createMemo(() => !!loadingMore())() ? _4("Loading...") : _4("Load more"))];
                    }
                  }));
                  return _el$9;
                }
              }), null);
              return _el$6;
            }
          })];
        }
      })];
    }
  });
}
function VersionEntry(props2) {
  const formatDate3 = (dateStr) => {
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString(void 0, {
        year: "numeric",
        month: "long",
        day: "numeric"
      });
    } catch {
      return dateStr;
    }
  };
  const hideSections = [];
  const sections = createMemo(() => props2.version.sections.filter((s3) => !hideSections.includes(s3.title.toLowerCase())));
  return (() => {
    const _el$10 = _tmpl$820.cloneNode(true), _el$11 = _el$10.firstChild, _el$12 = _el$11.firstChild, _el$13 = _el$12.nextSibling;
    insert(_el$12, () => props2.version.version);
    insert(_el$13, () => formatDate3(props2.version.date));
    insert(_el$10, createComponent(Show, {
      get when() {
        return props2.version.description;
      },
      get children() {
        const _el$14 = _tmpl$723.cloneNode(true);
        insert(_el$14, () => props2.version.description);
        return _el$14;
      }
    }), null);
    insert(_el$10, createComponent(For, {
      get each() {
        return sections();
      },
      children: (section) => createComponent(VersionSection, {
        section
      })
    }), null);
    return _el$10;
  })();
}
function VersionSection(props2) {
  const icon = createMemo(() => {
    const lowerTitle = props2.section.title.toLowerCase();
    if (lowerTitle.includes("feature")) return "bi-stars";
    if (lowerTitle.includes("fix")) return "bi-bug";
    if (lowerTitle.includes("improvement")) return "bi-arrow-up-circle";
  });
  return (() => {
    const _el$15 = _tmpl$918.cloneNode(true), _el$16 = _el$15.firstChild, _el$17 = _el$16.nextSibling;
    insert(_el$16, createComponent(Show, {
      get when() {
        return icon();
      },
      get children() {
        return createComponent(Icon, {
          get name() {
            return icon();
          }
        });
      }
    }), null);
    insert(_el$16, () => props2.section.title, null);
    createRenderEffect(() => _el$17.innerHTML = convertMarkdownToHTML(props2.section.content));
    return _el$15;
  })();
}

// public/app/ui/system/ng-components/sidebar-system-service.js
angular_default.module("kantree").service("navSidebarSystemFactory", class extends AngularClass {
  static $inject = [
    "$state",
    "userMenuFactory",
    "projectPage",
    "searchModal",
    "syncMenuFactory",
    "orgCreatorModal",
    "helpModal",
    "$q"
  ];
  getFixedContentItems() {
    const items = [
      {
        id: "nav-sidebar-my-work",
        type: "link",
        options: {
          label: _4("My work"),
          icon: "bi-clipboard-check",
          href: this.$state.href("myWork.inbox"),
          dot: () => {
            return !!unreadNotifications();
          },
          dotLabel: () => unreadNotifications(),
          dotColor: () => "var(--theme-notif-primary)",
          dotBadge: true
        },
        active: () => this.$state.includes("myWork"),
        enabled: () => isAuthenticated() && !currentUser2.is_unlicensed
      },
      {
        type: "board-list",
        options: {
          label: _4("Favorites"),
          icon: "bi-star-fill",
          storageKey: "favorites",
          store: favoriteCardStore,
          subscribeEvent: "favorites",
          sorted: true,
          grouped: true,
          hideWhenEmpty: true
        }
      },
      {
        type: "recently-opened-list",
        enabled: () => appContext.projectsCount > 5
      }
    ];
    return items;
  }
  getContentItems() {
    const items = [];
    if (currentUser2.can_create_projects) {
      items.push({
        type: "project-list",
        options: {
          canCreateProjects: true,
          label: _4("Personal workspaces"),
          icon: "bi-person-fill",
          storageKey: "my-projects",
          store: personalProjectStore,
          sorted: true,
          itemsActivable: true,
          gotoState: ["globalHome", { "#": "personal-workspaces" }]
        },
        active: () => this.$projectPage.isActive && this.$projectPage.project.owner.type === "user" && this.$projectPage.project.owner.id === currentUser2.id
      });
    }
    items.push({
      type: "project-list",
      options: {
        label: _4("Shared workspaces"),
        icon: "bi-share-fill",
        storageKey: "shared-projects",
        store: sharedProjectStore,
        hideWhenEmpty: true,
        gotoState: ["globalHome", { "#": "shared-workspaces" }]
      }
    });
    appContext.pinnedOrgs.forEach((org2) => {
      items.push(...org2.teams.filter((spec) => appContext.pinnedOrgs.length === 1 || !spec.team).map((spec) => ({
        type: "team",
        options: {
          org: spec.org,
          team: spec.team,
          storageKey: spec.uuid,
          store: appContext.pinnedOrgs.length === 1 ? spec.store : spec.allProjectStore,
          sorted: true,
          showWhenEmpty: true,
          itemsActivable: true
        },
        active: () => spec.team && this.$state.includes("org.team", { slug: spec.org.slug, teamSlug: spec.team.slug }) || !spec.team && this.$state.includes("org", { slug: spec.org.slug }) && !this.$state.includes("org.team") || this.$projectPage.isActive && this.$projectPage.project.owner.type === "org" && this.$projectPage.project.owner.id === spec.org.id && (!spec.team && !this.$projectPage.project.team || spec.team && this.$projectPage.project.team?.id === spec.team.id || appContext.pinnedOrgs.length > 1)
      })));
    });
    const canCreateOrgs = !currentUser2.is_unlicensed && (currentUser2.is_kantree_admin || currentUser2.can_create_organizations);
    if (appContext.orgs.length > 1 || appContext.orgs.length > appContext.pinnedOrgs.length || canCreateOrgs) {
      items.push({
        type: "drop-menu-button",
        options: {
          label: _4("All organizations"),
          icon: "bi-plus",
          menu: { config: [
            {
              header: _4("Your organizations"),
              icon: "bi-building",
              small: _4("Select which orgs should appear in the sidebar.") + (appContext.orgs.length > 1 ? " " + _4("When only a single org is selected, teams will also appear in the sidebar.") : "")
            },
            {
              checkbox: true,
              label: _4("Personal workspaces"),
              value: true,
              disabled: () => true,
              enabled: () => currentUser2.can_create_projects,
              action: () => this.$state.go("globalHome", { "#": "personal-workspaces" })
            }
          ].concat(appContext.orgs.filter((o3) => o3.org.permission > 0).map((spec) => {
            return {
              checkbox: true,
              label: spec.org.name,
              value: () => !!appContext.pinnedOrgs.find((o3) => o3.id === spec.id),
              small: getRoleLabelForOrg(spec.org),
              toggle: (value2) => {
                let hiddenOrgs = get(currentUser2.app_params, "hiddenOrgs", []);
                if (value2 && hiddenOrgs.indexOf(spec.id) !== -1) {
                  hiddenOrgs = removeIndex(hiddenOrgs, hiddenOrgs.indexOf(spec.id));
                } else if (!value2 && hiddenOrgs.indexOf(spec.id) === -1) {
                  hiddenOrgs = [...hiddenOrgs, spec.id];
                }
                this.$q.digest(saveUserAppParams({ "hiddenOrgs": hiddenOrgs }));
                updateAppContext();
              },
              action: spec.org.permission > 0 ? () => this.$state.go("org.hub", { slug: spec.org.slug }) : void 0
            };
          })).concat([
            { label: "--" },
            {
              label: _4("All your workspaces"),
              icon: "bi-grid-3x3-gap-fill",
              action: () => this.$state.go("globalHome")
            },
            {
              label: _4("Create new organization"),
              icon: "bi-plus-lg",
              action: () => this.$orgCreatorModal.open(),
              enabled: () => canCreateOrgs
            }
          ]), options: {
            help: {
              guide: "teams",
              label: _4("Learn more about organizations")
            }
          } }
        }
      });
    }
    return items;
  }
  getHeaderItems() {
    return [{
      type: "logo",
      options: {
        logo: serverConfig.navbar_logo_url,
        href: "/"
      }
    }];
  }
  getFooterItems() {
    const releaseAnnouncementsNotRead = !isReleaseAnnouncementRead(serverConfig.version);
    return [
      {
        type: "drop-menu-button",
        options: {
          label: _4("Synchronization needed"),
          icon: "refresh",
          menu: this.$syncMenuFactory.get()
        },
        enabled: () => isSyncNeeded()
      },
      {
        type: "button",
        options: {
          label: _4("Search across all workspaces..."),
          icon: "bi-search",
          action: () => {
            this.$searchModal.open();
          }
        },
        hotkey: {
          combo: ["shift+s", "mod+k"],
          description: _4("Global search and quick workspace switch"),
          callback: () => {
            this.$searchModal.open();
          }
        }
      },
      {
        type: "button",
        options: {
          label: _4("Product Updates"),
          icon: "bi-rss-fill",
          action: () => {
            openProductUpdatesModal();
          },
          dot: () => releaseAnnouncementsNotRead,
          dotColor: () => "var(--theme-notif-primary)"
        },
        enabled: () => isAuthenticated()
      },
      {
        type: "button",
        options: {
          label: _4("Help"),
          icon: "bi-question-circle",
          action: () => {
            this.$helpModal.open();
          }
        }
      },
      {
        type: "drop-menu-button",
        options: {
          label: currentUser2.display_name,
          image: userAvatarUrl(currentUser2),
          menu: this.$userMenuFactory.get(),
          dot: () => true,
          dotColor: () => isConnected() ? "rgb(68, 202, 104)" : "#e42f28",
          dotClass: "user-connectivity-indicator"
        },
        active: () => this.$state.includes("account")
      }
    ];
  }
  get() {
    return {
      header: this.getHeaderItems(),
      fixedContent: this.getFixedContentItems(),
      content: this.getContentItems(),
      footer: this.getFooterItems()
    };
  }
});

// public/app/ui/system/ng-components/sidebar-system.js
angular_default.module("kantree").component("navSidebarSystem", {
  template: `
    <nav-sidebar config="$ctrl.sidebar" mode="icon"></nav-sidebar>
  `,
  controller: class extends AngularClass {
    static $inject = ["$scope", "navSidebarSystemFactory", "navSidebar", "$element"];
    $onInit() {
      this.updateSidebarConfig = debounce2(() => {
        this.$scope.$applyAsync(() => {
          this.sidebar = this.$navSidebarSystemFactory.get();
        });
      }, 60);
      this.updateSidebarConfig();
      $onEvent(this.$scope, onAppContextUpdate, () => this.updateSidebarConfig());
    }
  }
});

// public/app/ui/system/ng-components/system-message.js
angular_default.module("kantree").directive("systemMessage", [
  function() {
    return {
      restrict: "E",
      scope: true,
      template: `
        <div id="system-message" class="alert alert-info" ng-if="currentUser.system_message">
          <button type="button" class="btn-close" ng-click="dismissMessage()"></button>
          <i class="bi-info-square-fill"></i>
          <div ng-bind-html="currentUser.system_message|markdown"></div>
        </div>`,
      controller: [
        "$scope",
        "$q",
        function($scope2, $q) {
          $scope2.currentUser = currentUser2;
          $scope2.dismissMessage = function() {
            $q.when(api_default.user.dismiss_system_message.post(), () => {
              currentUser2.system_message = null;
            });
          };
        }
      ]
    };
  }
]);

// public/app/ui/system/menus/sync.js
angular_default.module("kantree").factory("syncMenuFactory", [
  function() {
    function getItems() {
      return [
        {
          subheader: _n(
            "{count} item needs to be synchronized",
            "{count} items need to be synchronized",
            numberOfQueuedSyncItems()
          )
        },
        {
          checkbox: true,
          label: _4("Sync when connection established"),
          value: () => autoSyncOnReconnect(),
          toggle() {
            setAutoSyncOnReconnect((prev) => !prev);
            if (autoSyncOnReconnect() && isConnected()) {
              sync();
            }
          }
        },
        {
          label: _4("Sync now"),
          action: () => sync(),
          enabled: () => !autoSyncOnReconnect() && isConnected()
        }
      ];
    }
    return {
      getItems,
      get: () => {
        return {
          config: () => getItems()
        };
      }
    };
  }
]);

// public/app/ui/system/menus/user.js
angular_default.module("kantree").service("userMenuFactory", class extends AngularClass {
  static $inject = ["$state"];
  getItems() {
    const items = [
      {
        subheader: _4("Connected as")
      },
      {
        label: currentUser2.display_name ? currentUser2.display_name + " (@" + currentUser2.username + ")" : currentUser2.username,
        img: userAvatarUrl(currentUser2)
      },
      {
        label: _4("Account settings"),
        icon: "bi-sliders2",
        offline: false,
        action: () => this.$state.go("account")
      },
      { label: "--" },
      {
        label: _4("Template library"),
        offline: false,
        action: () => this.$state.go("templates")
      },
      {
        label: _4("Blog"),
        action: () => window.open("https://kantree.io/blog")
      },
      {
        label: _4("Leave a review"),
        action: () => window.open("https://kantree.io/leave-review")
      }
    ];
    if (currentUser2.is_kantree_admin) {
      items.push({
        label: "--"
      }, {
        subheader: _4("Admin"),
        offline: false
      }, {
        label: _4("Overview"),
        offline: false,
        action: () => this.$state.go("admin.overview")
      }, {
        label: _4("Users"),
        offline: false,
        action: () => this.$state.go("admin.users")
      }, {
        label: _4("Organizations"),
        offline: false,
        action: () => this.$state.go("admin.orgs")
      });
    }
    if (!serverConfig.hide_logout) {
      items.push({
        label: "--"
      }, {
        label: _4("Logout"),
        offline: false,
        action: () => authSession.logout()
      });
    }
    return items;
  }
  get() {
    return { config: () => this.getItems() };
  }
});

// public/app/ui/utils/ng-filters/base-url.js
angular.module("kantree").filter("baseUrl", [
  function() {
    return function(url2) {
      return prependBaseUrl(url2);
    };
  }
]);

// public/app/ui/utils/ng-filters/colors.js
for (const fn of ["textColor", "darkenColor", "lightenColor", "slightlyDifferentColor", "isReadable"]) {
  angular_default.module("kantree").filter(fn, () => colors_exports[fn]);
}

// public/app/ui/utils/ng-filters/currency.js
angular_default.module("kantree").filter("formatAmount", [
  function() {
    return function(input, currency) {
      if (currency === "usd") {
        return "USD$" + input;
      }
      return input + "\u20AC";
    };
  }
]);

// public/app/ui/utils/ng-filters/date.js
angular_default.module("kantree").filter("dateDiffLabel", [
  function() {
    return function(input) {
      return getDateDiffLabel(input)[1];
    };
  }
]);
angular_default.module("kantree").filter("momentFormat", [
  function() {
    return function(input, formatString) {
      return formatDate(input, formatString);
    };
  }
]);
angular_default.module("kantree").filter("fromNow", [
  function() {
    return function(input) {
      return fromNow(input);
    };
  }
]);

// public/app/ui/utils/ng-filters/text.js
angular_default.module("kantree").filter("markdown", [
  "$sce",
  function($sce) {
    return function(input, convertReferences) {
      return $sce.trustAsHtml(convertMarkdownToHTML(input, convertReferences));
    };
  }
]);
angular_default.module("kantree").filter("markdownToPlainText", [
  function() {
    return function(input) {
      return convertMarkdownToPlainText(input);
    };
  }
]);
angular_default.module("kantree").filter("capitalize", [
  function() {
    return function(input) {
      return capitalize(input);
    };
  }
]);
angular_default.module("kantree").filter("jsonToText", [
  function() {
    return function(input) {
      if (typeof input === "string") {
        return input;
      }
      return JSON.stringify(input);
    };
  }
]);
angular_default.module("kantree").filter("ellipsis", [
  function() {
    return function(input, max3) {
      if (input && input.length > max3) {
        return input.substr(0, max3) + "...";
      }
      return input;
    };
  }
]);

// public/app/ui/utils/ng-components/clipboard.js
angular_default.module("kantree").directive("ngClipboard", [
  function() {
    return {
      restrict: "A",
      link: function(scope, element2, attrs2) {
        new clipboard_default(element2[0], { text: function() {
          return attrs2.ngClipboard;
        } });
      }
    };
  }
]);

// public/app/ui/utils/ng-components/compile-html.js
angular_default.module("kantree").directive("compileHtml", [
  "$compile",
  function($compile) {
    return {
      restrict: "A",
      link: function(scope, element2, attrs2) {
        let domElement;
        scope.$watch(() => scope.$eval(attrs2.compileHtml), (value2) => {
          if (domElement) {
            domElement.remove();
          }
          element2.html(value2 && value2.toString());
          domElement = $compile(element2.contents())(scope);
        });
        scope.$on("$destroy", () => {
          if (domElement) {
            domElement.remove();
            domElement = null;
          }
        });
      }
    };
  }
]);

// public/app/ui/utils/ng-components/custom-bgcolor.js
angular_default.module("kantree").directive("customBgcolor", function() {
  return {
    restrict: "A",
    link: function(scope, el2, attrs2) {
      let off;
      scope.$watch(() => attrs2.customBgcolor, () => {
        off && off();
        if (attrs2.customBgcolor) {
          off = colorizeElement(el2[0], attrs2.customBgcolor, null, !!attrs2.bgcolorHover);
        } else {
          off = null;
        }
      });
    }
  };
});
angular_default.module("kantree").directive("customFgcolor", function() {
  return {
    restrict: "A",
    link: function(scope, el2, attrs2) {
      let off;
      scope.$watch(() => attrs2.customFgcolor, () => {
        off && off();
        if (attrs2.customFgcolor) {
          off = colorizeElement(el2[0], null, tinycolor.mostReadable(attrs2.customFgcolor, ["#FFFFFF", "#000000"]).toHexString());
        } else {
          off = null;
        }
      });
    }
  };
});
angular_default.module("kantree").directive("customColor", function() {
  return {
    restrict: "A",
    link: function(scope, el2, attrs2) {
      let off;
      scope.$watch(() => attrs2.customColor, () => {
        off && off();
        if (attrs2.customColor) {
          off = colorizeElement(el2[0], null, attrs2.customColor);
        } else {
          off = null;
        }
      });
    }
  };
});

// public/app/ui/utils/ng-components/dynamic-directive.js
angular_default.module("kantree").directive("dynamicDirective", [
  "$compile",
  function($compile) {
    return {
      link: function(scope, el2, attrs2) {
        var childScope;
        var denormalized2 = function(attr) {
          return attr.replace(/[A-Z]/g, function(c3) {
            return "-" + c3.toLowerCase();
          });
        };
        scope.$watch(function() {
          return attrs2.directive;
        }, function(directive) {
          if (childScope) {
            childScope.$destroy();
          }
          if (!directive) {
            el2.empty();
            return;
          }
          var html5 = "<" + directive;
          angular_default.forEach(attrs2, function(value2, key2) {
            if (key2 !== "directive" && key2[0] !== "$") {
              html5 += " " + denormalized2(key2) + '="' + value2 + '"';
            }
          });
          html5 += "></" + directive.split(" ")[0] + ">";
          childScope = scope.$new();
          var newEl = jquery_default(html5);
          el2.replaceWith(newEl);
          newEl = $compile(newEl)(childScope);
          el2 = newEl;
        });
        scope.$on("$destroy", function() {
          if (childScope) {
            childScope.$destroy();
          }
        });
      }
    };
  }
]);

// public/app/ui/utils/ng-components/media-embed.js
angular_default.module("kantree").component("mediaEmbed", {
  bindings: {
    src: "<?"
  },
  controller: class extends AngularClass {
    static $inject = ["$element", "$scope", "$timeout"];
    $onChanges(changes) {
      if (changes.src && !changes.src.isFirstChange()) {
        this.render();
      }
    }
    $postLink() {
      this.el = this.$element;
      this.render();
    }
    render() {
      if (this.src.match(/\.(webm|mp4)$/)) {
        this.replaceElement(jquery_default(`<video autoplay loop muted><source src="${this.src}" type="video/${this.src.split(".").pop()}"></video>`));
      } else {
        this.replaceElement(jquery_default(`<img src="${this.src}">`));
      }
    }
    replaceElement(el2) {
      this.el.replaceWith(el2);
      this.el = el2;
    }
  }
});

// public/app/ui/utils/ng-components/open-links-in-tab.js
angular_default.module("kantree").directive("openLinksInTab", [
  function() {
    return {
      link: function(scope, el2, attrs2) {
        el2.on("click", "a", function(e3) {
          e3.stopPropagation();
          e3.preventDefault();
          window.open(this.href);
        });
      }
    };
  }
]);

// public/app/ui/utils/ng-components/processing-status.js
angular_default.module("kantree").service("processingStatus", class extends AngularClass {
  create(...args) {
    return new class Status {
      constructor(initial2) {
        this.set(initial2);
      }
      set(state) {
        if (this.state) {
          delete this[this.state];
        }
        this.state = state;
        if (state) {
          this[state] = true;
        }
      }
    }(...args);
  }
  _wrapOrCreateTwoPhase(initialStatus, finalStatus, fn) {
    let status = this.create(initialStatus);
    status.finalize = () => status.set(finalStatus);
    if (fn) {
      const r3 = fn(() => status.finalize());
      if (r3 && typeof r3.then !== "undefined") {
        r3.then(() => status.finalize());
      }
    }
    return status;
  }
  saver(fn) {
    return this._wrapOrCreateTwoPhase("processing", "saved", fn);
  }
  loader(fn) {
    return this._wrapOrCreateTwoPhase("loading", null, fn);
  }
});
angular_default.module("kantree").component("processingStatus", {
  bindings: {
    status: "<"
  },
  template: `
    <div ng-show="$ctrl.status.loading">
      <i class="fa fa-spinner fa-spin"></i>
    </div>
    <div ng-show="$ctrl.status.processing" class="ball-scale-ripple"><div></div></div>
    <div ng-show="$ctrl.status.saved">
      <i class="fa fa-check"></i>
    </div>
  `
});
angular_default.module("kantree").directive("disableWhenProcessing", function() {
  return {
    restrict: "A",
    scope: {
      status: "<disableWhenProcessing"
    },
    link: function(scope, el2) {
      scope.$watch("status", () => {
        el2.prop("disabled", scope.status.processing);
      });
    }
  };
});

// public/app/ui/utils/ng-components/recompile.js
angular_default.module("kantree").factory("compileOnWatch", [
  "$compile",
  "$parse",
  function($compile, $parse) {
    function removeChildrenWatchers(element2) {
      angular_default.forEach(element2.children(), function(childElement) {
        removeAllWatchers(angular_default.element(childElement));
      });
    }
    function removeAllWatchers(element2) {
      if (element2.data().hasOwnProperty("$scope")) {
        element2.data().$scope.$$watchers = [];
      }
      removeChildrenWatchers(element2);
    }
    return function(opts) {
      var recompile = function(scope) {
        removeChildrenWatchers(opts.el);
        if (opts.watcher && opts.useBoolean) {
          $parse(opts.watcher).assign(opts.scope, false);
        }
        if (!scope) {
          scope = opts.scope.$new();
        }
        if (typeof opts.preCompile !== "undefined") {
          opts.preCompile(scope);
        }
        var newEl = $compile(opts.template)(scope);
        opts.el.html(newEl);
        if (typeof opts.postRender !== "undefined") {
          opts.postRender(scope);
        }
      };
      if (opts.watcher) {
        opts.scope.$watch(opts.watcher, function(_new, _old) {
          if (opts.useBoolean && (!_new || _new === "false") || !opts.useBoolean && (!_new || _new === _old)) {
            return;
          }
          recompile();
        });
      }
      if (typeof opts.postRender != "undefined") {
        opts.postRender(opts.scope);
      }
      return recompile;
    };
  }
]);
angular_default.module("kantree").directive("watchCompile", [
  "compileOnWatch",
  function(compileOnWatch) {
    return {
      scope: true,
      // required to be able to clear watchers safely
      compile: function(el2) {
        var template3 = el2.html();
        return function link2(scope, $el, attrs2) {
          compileOnWatch({
            scope,
            watcher: attrs2.watchCompile,
            el: el2,
            template: template3,
            useBoolean: attrs2.hasOwnProperty("useBoolean")
          });
        };
      }
    };
  }
]);

// public/app/ui/utils/ng-components/scope-on-element.js
angular_default.module("kantree").directive("scopeOnElement", [
  function() {
    return {
      link: function(scope, el2, attrs2) {
        el2[0].scope = function() {
          return scope;
        };
      }
    };
  }
]);

// public/app/ui/utils/ng-components/solidjs-component.js
angular_default.module("kantree").directive("solidjsComponent", [
  function() {
    return {
      link: function(scope, el2, attrs2) {
        const Component = scope.$eval(attrs2.component);
        const [props2, setProps] = createStore({});
        function setProp(key2, value2) {
          if (isFunction_default(value2)) {
            setProps(key2, () => value2);
          } else {
            setProps(key2, value2);
          }
        }
        for (const key2 of Object.keys(attrs2.$attr)) {
          if (key2 !== "component") {
            setProp(key2, scope.$eval(attrs2[key2]));
            scope.$watch(attrs2[key2], (value2) => setProp(key2, value2));
          }
        }
        if (el2[0].childNodes.length > 1) {
          setProp("children", Array.from(el2[0].childNodes));
        }
        let solidOwner = null;
        let currentScope = scope;
        while (currentScope && !solidOwner) {
          solidOwner = currentScope.$solidOwner;
          currentScope = currentScope.$parent;
        }
        const dispose2 = createRoot((disposeRoot) => {
          insert(el2[0], Component(props2));
          return disposeRoot;
        }, solidOwner);
        scope.$on("$destroy", dispose2);
      }
    };
  }
]);

// public/app/ui/utils/ng-components/stylesheets.js
angular_default.module("kantree").factory("stylesheetManager", [
  "$templateCache",
  "$templateRequest",
  "$interpolate",
  "$q",
  function($templateCache, $templateRequest, $interpolate, $q) {
    var addedStyleSheets = {};
    function isBackgroundLight(backgroundColor) {
      return tinycolor.mostReadable(backgroundColor, ["#000000", "#ffffff"]).toString() === "#000000";
    }
    function isBackgroundDark(backgroundColor) {
      return !isBackgroundLight(backgroundColor);
    }
    return {
      createFromString: function(name2, template3, vars) {
        if (typeof addedStyleSheets[name2] !== "undefined") {
          return;
        }
        var tpl = $interpolate(template3);
        var css = tpl(Object.assign({
          realdarken: function(color, value2) {
            return tinycolor(color).darken(value2).toString();
          },
          darken: function(color, value2) {
            if (isBackgroundDark(color)) {
              return tinycolor(color).lighten(value2).toString();
            }
            return tinycolor(color).darken(value2).toString();
          },
          reallighten: function(color, value2) {
            return tinycolor(color).lighten(value2).toString();
          },
          lighten: function(color, value2) {
            if (isBackgroundDark(color)) {
              return tinycolor(color).darken(value2).toString();
            }
            return tinycolor(color).lighten(value2).toString();
          },
          brighten: function(color, value2) {
            return tinycolor(color).brighten(value2).toString();
          },
          desaturate: function(color, value2) {
            return tinycolor(color).desaturate(value2).toString();
          },
          realtint: function(color, value2) {
            return tinycolor.mix(color, "#fff", value2).toString();
          },
          tint: function(color, value2, darkValue) {
            if (isBackgroundDark(color)) {
              return tinycolor.mix(color, "#fff", value2).toString();
            }
            return tinycolor.mix(color, "#000", darkValue || value2).toString();
          },
          realshade: function(color, value2) {
            return tinycolor.mix(color, "#000", value2).toString();
          },
          shade: function(color, value2, darkValue) {
            if (isBackgroundDark(color)) {
              return tinycolor.mix(color, "#fff", value2).toString();
            }
            return tinycolor.mix(color, "#000", darkValue || value2).toString();
          },
          mostReadable: function(color, values2) {
            return tinycolor.mostReadable(color, values2).toString();
          },
          getBrightness: function(color) {
            return tinycolor(color).getBrightness();
          },
          setAlpha: function(color, alpha) {
            return tinycolor(color).setAlpha(alpha).toRgbString();
          },
          monochromatic: function(color) {
            var colors = tinycolor(color).monochromatic();
            return colors.map(function(t3) {
              return t3.toHexString();
            });
          },
          isLight: function(color) {
            return tinycolor(color).isLight();
          },
          isDark: function(color) {
            return tinycolor(color).isDark();
          },
          isBackgroundLight: function(color) {
            return isBackgroundLight(color);
          },
          isBackgroundDark: function(color) {
            return isBackgroundDark(color);
          },
          getReadableTransparentColor: function(color, alpha, darkAlpha) {
            var args = isBackgroundDark(color) ? ["#fff", alpha] : ["#000", darkAlpha !== void 0 ? darkAlpha : alpha];
            return this.setAlpha.apply(this, args);
          },
          getSameTransparentColor: function(color, alpha, darkAlpha) {
            var args = isBackgroundDark(color) ? ["#000", darkAlpha !== void 0 ? darkAlpha : alpha] : ["#fff", alpha];
            return this.setAlpha.apply(this, args);
          }
        }, vars));
        var styleElement = document.createElement("style");
        styleElement.appendChild(document.createTextNode(css));
        document.head.appendChild(styleElement);
        addedStyleSheets[name2] = styleElement;
      },
      create: function(name2, template3, vars) {
        var deferred = $q.defer();
        var self2 = this;
        var resolved = function(tpl2) {
          if ($.isArray(tpl2)) {
            tpl2 = tpl2[1];
          }
          self2.createFromString(name2, tpl2, vars);
          deferred.resolve(name2);
        };
        var tpl = $templateCache.get(template3);
        if (tpl) {
          if (typeof tpl === "string") {
            resolved(tpl);
          } else if ($.isArray(tpl)) {
            resolved(tpl[1]);
          } else {
            tpl.then(function(r3) {
              resolved(r3.data);
            });
          }
        } else {
          $templateRequest(template3).then(resolved);
        }
        return deferred.promise;
      },
      exists: function(name2) {
        return typeof addedStyleSheets[name2] !== "undefined";
      },
      remove: function(name2) {
        if (this.exists(name2)) {
          addedStyleSheets[name2].remove();
          delete addedStyleSheets[name2];
        }
      },
      createTheme: function(name2, color, stylesheet, vars) {
        if (!this.exists(name2)) {
          var textColor2 = tinycolor.mostReadable(color, ["#000000", "#ffffff"]).toString();
          return this.create(name2, stylesheet, Object.assign({
            "wrappercls": name2,
            "color": color,
            "textColor": textColor2
          }, vars || {}));
        }
        return $q.resolve(name2);
      }
    };
  }
]);

// public/app/templates-cache.js
angular_default.module("kantree").run(["$templateCache", function($templateCache) {
  $templateCache.put("/static/app/routes/portfolio/ng-components/templates/page.html", `<nav-sidebar config=$ctrl.sidebar with-toggle=true collapsable=true></nav-sidebar> <div class=page-container> <topbar with-auth=true> <portfolio-nav ng-if="$ctrl.scopeManager && $ctrl.project && $ctrl.project.id && ($ctrl.context.app.name === 'overview' ||
      $ctrl.project.portfolio_project_ids.length > 0)" context=$ctrl.context view=$ctrl.view with-settings=$ctrl.isEmbedded()></portfolio-nav> </topbar> <div id=board-view class="board page-container-view" ng-class="{'loading-error': $ctrl.loadingErrorMessage}"> <div class="board-notice board-notice-warning" ng-if=$ctrl.lockedOwner> <i class="fa fa-lock"></i> {{::_('The organization this portfolio belongs to is locked')}} </div> <div class=board-notice ng-if="$ctrl.project && $ctrl.project.can_join"> <i class="fa fa-sign-in"></i> {{::_('You are not a member of this portfolio, join to start editing now')}} <button type=button class="btn btn-cta" ng-click=$ctrl.joinPortfolio()>{{::_('Join')}}</button> </div> <div class=board-message-overlay ng-if=$ctrl.loadingErrorMessage> <div class="board-message-inner text-danger"> <i class="fa fa-warning"></i> <p>{{$ctrl.loadingErrorMessage}}</p> </div> </div> <div class=board-main ng-if="$ctrl.project && $ctrl.project.id && ($ctrl.context.app.name === 'overview' ||
      $ctrl.project.portfolio_project_ids.length > 0)"> <portfolio-placeholder ng-if=$ctrl.projectPlaceholderVisible></portfolio-placeholder> <div class=project-app-container> <dynamic-directive directive={{$ctrl.context.app.component}} context=$ctrl.context with-empty-notice=true on-change=$ctrl.updateView($changes)></dynamic-directive> </div> <card-modal-host resizable=true ng-if=!$ctrl.isScreensizeXS()></card-modal-host> </div> <div class=board-main ng-if="$ctrl.project && $ctrl.project.id && $ctrl.context.app.name !== 'overview' &&
      $ctrl.project.portfolio_project_ids.length === 0"> <div class=board-empty-notice> <p>{{::_("No Workspace selected. Start by selecting some Workspaces in the portoflio overview")}}</p> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/portfolio/ng-components/templates/nav.html", `<div class=board-nav> <div class="board-nav-info visible-xs-block" ng-class="{'mod-top-level': !$ctrl.$projectPage.board.parent_id}"> <div class=board-breadcrumb> <span class="btn title" title={{$ctrl.$projectPage.board.title}}> <span>{{$ctrl.$projectPage.board.title}}</span> </span> <i class="fa fa-globe indicator hidden-xs" ng-show=$ctrl.$projectPage.project.is_private uib-tooltip="{{::_('Private')}}" tooltip-placement=bottom></i> <i class="fa fa-globe indicator hidden-xs" ng-show=$ctrl.$projectPage.project.is_public uib-tooltip="{{::_('Has shareable link')}}" tooltip-placement=bottom></i> <span class="fa-stack indicator unapproved-domain-members" ng-show="$ctrl.notApprovedDomainMembers.length > 0" uib-tooltip="{{::_('Has unapproved members')}}" tooltip-placement=bottom> <i class=bi-person-x-fill></i> </span> </div> </div> <div class=board-nav-view-component-outer> <div class="board-nav-view-component hidden-xs"> <div class=board-nav-view-component-inner ng-if=!$ctrl.view.locked> <span class="btn btn-topbar hidden-xs app-nav-name" ng-show=!$ctrl.context.app.hideAppName> <i ng-class=$ctrl.context.app.icon|iconClass ng-show=$ctrl.context.app.icon></i> {{$ctrl.context.app.title}} </span> <dynamic-directive directive={{$ctrl.context.app.navComponent}} context=$ctrl.context shrinked=$ctrl.shrinked></dynamic-directive> </div> <view-locked-btn ng-if=$ctrl.view.locked context=$ctrl.context locked=$ctrl.view.locked></view-locked-btn> </div> <view-save-btn ng-show="$ctrl.showSaveBtn && !$ctrl.view.locked" ng-if=$ctrl.view view=$ctrl.view shrinked=$ctrl.shrinked></view-save-btn> </div> <div class=board-nav-right ng-if=!$ctrl.isScreensizeXS()> <nav-members context=$ctrl.$projectPage.scopeManager.portfolioContext ng-if="!$ctrl.$projectPage.scopeManager.portfolioContext.project.is_template &&
        !$ctrl.$projectPage.scopeManager.portfolioContext.shareMode"></nav-members> </div> <button class="btn btn-icon btn-topbar visible-xs-inline-block" drop-menu=$ctrl.mobileMenu drop-config="{classes: 'drop-theme-menu drop-theme-mobile-board-menu', tetherOptions: { resizable: false }}"><i class=bi-gear-fill></i></button> </div> `);
  $templateCache.put("/static/app/routes/admin/ng-components/templates/admin.html", "<nav-sidebar config=sidebarConfig></nav-sidebar> <dynamic-directive directive={{currentPanel.directive}}></dynamic-directive> ");
  $templateCache.put("/static/app/routes/admin/ng-components/templates/users-panel.html", `<div class=page-container> <topbar> <div class=admin-filter> <input type=text class=form-control placeholder="{{::_('Search by username, email, #id, org=orgname or workspace=name')}}" ng-model=userFilter.value> <button class="btn btn-default pull-right" drop-menu=filterShortcutsMenu> {{::_('Filters')}} <span class=bi-caret-down-fill></span> </button> <button class="btn btn-primary" drop-menu=addUserMenu ng-if=canAddUsers ng-hide=uploadInProgress> <i class=bi-plus-lg></i> {{::_('Add new user')}} <span class=bi-caret-down-fill></span> </button> <span class="btn btn-default" ng-show=uploadInProgress> <i class="fa fa-upload"></i> {{_("Uploading file ({pct}%)", {pct: uploadInProgress})}} </span> </div> </topbar> <div class="admin-view page-container-view" id=admin-users-panel> <div ng-show=!user> <admin-table loader="loadUsers(page, filter, sortBy, sortAsc, cb)" columns=columns filter=userFilter.value paginated=true sortable=true export="export(filter, sortBy, sortAsc)" selectable=true actions=userActions></admin-table> <p style="text-align: center;"> <a href={{::exportOrgMembershipsUrl}}> <i class="fa fa-download"></i> {{::_('Export organization memberships history (Excel)')}} </a> </p> </div> <div ng-show=user class=admin-form> <h1> <button type=button ng-click=selectUser() class="btn btn-default btn-icon"><i class="fa fa-arrow-left"></i></button> {{user.id ? _('User #{id}', {id: user.id}) : _('Add new user')}} </h1> <div class=nav-tabs ng-show=user.id> <div class=nav-tabs-tabs> <a class=nav-tab ng-class="{'active': userTab === 'user'}" href ng-click="userTab = 'user'">{{::_('User')}}</a> <a class=nav-tab ng-class="{'active': userTab === 'projects'}" href ng-click=showUserProjectsTab()>{{::_('Personal workspaces')}} ({{user.nb_perso_projects}})</a> <a class=nav-tab ng-class="{'active': userTab === 'orgs'}" href ng-click=showUserOrgsTab()>{{::_('Organization memberships')}} ({{user.nb_org_memberships}})</a> </div> </div> <div ng-switch=userTab> <div ng-switch-when=user class=row> <form ng-submit=saveUser() name=userForm class=col-md-8> <div class=form-group> <label class=form-label for=userName>{{::_('Username:')}}</label> <input type=text class=form-control ng-model=user.username id=userName required> </div> <div class=form-group> <label class=form-label for=userDisplayName>{{::_('Display name:')}}</label> <input type=text class=form-control ng-model=user.display_name placeholder="{{::_('Leave blank to use username')}}" id=userDisplayName> </div> <div class=form-group> <label class=form-label for=userEmail>{{::_('Email:')}}</label> <input type=email class=form-control ng-model=user.email id=userEmail required> </div> <div class=form-group ng-if=!user.id> <label class=form-label for=userPwd>{{::_('Password:')}}</label> <input type=password class=form-control ng-model=user.password id=userPwd> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=user.must_reset_password_at_login id=userMustResetPwd> <label class=form-check-label for=userMustResetPwd>{{::_('Force password reset at next login')}}</label> </div> <fieldset ng-if=user.id> <legend>{{::_("Account type")}}</legend> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=user.is_disabled ng-change="user.disabled_at = null" id=userDisabled> <label class=form-check-label for=userDisabled>{{::_('Disabled')}}</label> <span class=form-text ng-if="user.is_disabled && user.disabled_at">({{_('Since')}} {{user.disabled_at|momentFormat:'ll'}})</span> <span class=form-text ng-if="user.is_disabled && user.is_auto_disabled">(Auto disabled because of no activity)</span> <p class=form-text> {{::_("Disabled user will not be able to login and won't be included in your license count")}} </p> </div> <div class="form-group form-check"> <input class=form-check-input type=radio value=unlicensed ng-model=user.role ng-disabled=user.is_disabled id=roleUnlicensed> <label class=form-check-label for=roleUnlicensed>{{::_('Unlicensed')}}</label> <p class=form-text> {{::_("Unlicensed users cannot join teams and won't be able to edit anything. They can be invited to any workspaces to observe them but they cannot be assigned to cards and they will be tagged as free access user. They won't be included in your license count.")}} </p> </div> <div class="form-group form-check"> <input class=form-check-input type=radio value=user ng-model=user.role ng-disabled=user.is_disabled id=roleUser> <label class=form-check-label for=roleUser>{{::_('User (default when signing up)')}}</label> <p class=form-text> {{::_("User can create, join and edit workspaces and organizations")}} </p> </div> <div class="form-group form-check" ng-show=superAdminEnabled> <input class=form-check-input type=radio value=admin ng-model=user.role ng-disabled=user.is_disabled id=roleAdmin> <label class=form-check-label for=roleAdmin>{{::_('Admin')}}</label> <p class=form-text> {{::_("Admins can manage the Kantree installation")}} </p> </div> <div class="form-group form-check"> <input class=form-check-input type=radio value=superadmin ng-model=user.role ng-disabled=user.is_disabled id=roleSuperadmin> <label class=form-check-label for=roleSuperadmin>{{::_('Super Admin')}}</label> <p class=form-text> {{::_("Admins can manage the Kantree installation and access all workspaces")}} </p> </div> </fieldset> <fieldset ng-if=user.id> <legend>{{::_('Permissions')}}</legend> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=user.can_create_projects id=userCanCreateProjects> <label class=form-check-label for=userCanCreateProjects>{{::_('Can create personal workspaces (public only)')}}</label> <p class=form-text> {{::_("Whether this user can create personal workspaces outside of any organizations")}} </p> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=user.can_create_private_projects ng-disabled=!user.can_create_projects id=userCanCreatePrivateProjects> <label class=form-check-label for=userCanCreatePrivateProjects>{{::_('Can create private personal workspaces')}}</label> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=user.can_join_organizations id=userCanJoinOrg> <label class=form-check-label for=userCanJoinOrg>{{::_('Can join organizations')}}</label> <p class=form-text> {{::_("Whether this user can be invited to organizations. If not, only Kantree admins can add this user to an organization")}} </p> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=user.can_create_organizations id=canCreateOrg> <label class=form-check-label for=canCreateOrg>{{::_('Can create organizations')}}</label> <p class=form-text> {{::_("Whether this user can create organizations by himself/herself")}} </p> </div> <div class="form-group form-check form-switch" ng-show=paymentsEnabled> <input class=form-check-input type=checkbox role=switch ng-model=user.subscription_required id=userSubscriptionRequired> <label class=form-check-label for=userSubscriptionRequired>{{::_('Subscription required')}}</label> </div> </fieldset> <fieldset ng-if=user.id> <legend>{{::_('Other')}}</legend> <div class=form-group> <label class=form-label for=userSystemMessage>{{::_('Show system message:')}}</label> <textarea class=form-control ng-model=user.system_message id=userSystemMessage></textarea> </div> </fieldset> <button type=submit class="btn btn-primary" ng-disabled="userForm.$invalid || saving"> {{saving ? _('Saving...') : _('Save')}} </button> </form> <div class=col-md-4 ng-show=user.id> <p><strong>{{::_("Signup at:")}}</strong> {{user.signup_at|momentFormat:'ll'}}</p> <p ng-show=user.created_by><strong>{{::_("Created by:")}}</strong> {{user.created_by.username}}</p> <p ng-show=user.invited_by><strong>{{::_("Invited by:")}}</strong> {{user.invited_by.username}}</p> <p><strong>{{::_("Last login at:")}}</strong> {{user.last_login_at|momentFormat:'ll'}}</p> <p><strong>{{::_("Last active at:")}}</strong> {{user.last_activity_at|momentFormat:'ll'}}</p> <p><strong>{{::_("Last access at:")}}</strong> {{user.last_access_at|momentFormat:'ll'}}</p> <p><strong>{{::_("2FA authentification:")}}</strong> {{user['2fa_enabled'] ? _('Enabled') : _('Disabled')}}</p> <hr> <p ng-show="user['2fa_enabled']"><button ng-click=disable2FA() class="btn btn-default">{{::_('Disable 2FA')}}</button></p> <p><button ng-click=logoutUser() class="btn btn-default">{{::_('Logout from everywhere')}}</button></p> <p><button ng-click=resetPassword() class="btn btn-default" ng-if=canResetPassword>{{::_('Reset password')}}</button></p> <p><button ng-click=impersonate() class="btn btn-default" ng-if=isSuperAdmin>{{::_('Impersonate')}}</button></p> <p><button ng-click=deleteUser() class="btn btn-danger">{{::_('Delete user')}}</button></p> </div> </div> <div ng-switch-when=projects> <i class="fa fa-spin fa-spinner" ng-if="projects === null"></i> <admin-table rows=projects columns=projectColumns actions=projectActions ng-if="projects !== null"></admin-table> </div> <div ng-switch-when=orgs> <i class="fa fa-spin fa-spinner" ng-if="orgs === null"></i> <admin-table rows=orgs columns=orgColumns ng-if="orgs !== null"></admin-table> </div> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/admin/ng-components/templates/logs-panel.html", `<div class=page-container> <topbar></topbar> <div class="admin-view page-container-view" id=admin-logs-panel> <textarea ng-model=logs readonly id=logs class=form-control></textarea> <button type=button class="btn btn-default" ng-click=download()><i class="fa fa-download"></i> {{::_('Download full log file')}}</button> </div> </div> `);
  $templateCache.put("/static/app/routes/admin/ng-components/templates/table.html", `<div class=admin-table> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th ng-if=selectable></th> <th ng-repeat="col in columns"> <a href ng-click=toggleSort(col) ng-if="sortable && (col.sortable === undefined || col.sortable)"> {{col.title}} <i ng-class="'bi-caret-' + (sortAsc ? 'up' : 'down') + '-fill'" ng-if="col === sortBy"></i> </a> <span ng-if="!sortable || (col.sortable !== undefined && !col.sortable)">{{col.title}}</span> </th> <th ng-if="actions && !selectable"></th> </tr> </thead> <tbody> <tr ng-if=loading class=loader> <td colspan="{{columns.length + 2}}"> <i class="fa fa-spin fa-spinner"></i> {{::_('Loading')}} </td> </tr> <tr ng-repeat="row in rows"> <td ng-if=selectable><input class=form-check-input type=checkbox ng-click=toggleRowSelection(row)></td> <td ng-repeat="col in columns" uib-tooltip="{{col.tooltip ? col.tooltip(row[col.property], row) : ''}}"> <span ng-if="!col.widget && !col.link && !col.click">{{col.format ? col.format(row[col.property], row) : row[col.property]}}</span> <a href ng-click="col.click(row[col.property], row)" ng-if=col.click>{{col.format ? col.format(row[col.property], row) : row[col.property]}}</a> <a navigate-to="{{col.link(row[col.property], row)}}" ng-if=col.link>{{col.format ? col.format(row[col.property], row) : row[col.property]}}</a> <div ng-if=col.widget ng-bind-html="col.widget(row[col.property], row)"></div> </td> <td ng-if="actions && !selectable"> <button ng-repeat="action in actions" class="btn btn-default btn-icon" ng-click="doAction(action, row)" uib-tooltip={{::action.title}}> <i ng-class=action.icon|iconClass></i></button> </td> </tr> </tbody> <tfoot ng-show=selectedRows.length> <tr> <td colspan="{{columns.length + 2}}"> <div class=btn-group> <button ng-repeat="action in actions" class="btn btn-default" ng-click="doAction(action, selectedRows, true)"> <i ng-class=action.icon|iconClass ng-if=action.icon></i> {{::action.title}} </button> </div> </td> </tr> </tfoot> </table> <nav ng-if=paginated> <ul class=pagination> <li class=page-item ng-class="{'disabled': last_page === 1}"> <a class=page-link href ng-click=loadRows(1) uib-tooltip="{{::_('First page')}}"> <span>&laquo;&laquo;</span> </a> </li> <li class=page-item ng-class="{'disabled': !prev_page}"> <a class=page-link href ng-click=loadRows(prev_page) uib-tooltip="{{::_('Previous page')}}"> <span>&laquo;</span> </a> </li> <li class=page-item ng-repeat="p in pages" ng-class="{'active': p === page}"> <a class=page-link href ng-click=loadRows(p)> <span>{{p}}</span> </a> </li> <li class=page-item ng-class="{'disabled': !next_page}"> <a class=page-link href ng-click=loadRows(next_page) uib-tooltip="{{::_('Next page')}}"> <span>&raquo;</span> </a> </li> <li class=page-item ng-class="{'disabled': last_page === 1}"> <a class=page-link href ng-click=loadRows(last_page) ng-show=next_page uib-tooltip="{{::_('Last page')}}"> <span>&raquo;&raquo;</span> </a> </li> </ul> <p class=align-center> {{_('{total} results found', {"total": totalResults})}} <a href ng-click="export({filter: filter, sortBy: sortBy, sortAsc: sortAsc})" ng-show=export>{{::_('Export to XLSX')}}</a> </p> </nav> </div> `);
  $templateCache.put("/static/app/routes/admin/ng-components/templates/overview-panel.html", `<div class=page-container> <topbar></topbar> <div class="admin-view page-container-view" id=admin-overview-panel> <div ng-if=stats.licensed class=licensed> <h2>{{::_("Your license")}}</h2> {{_("Expires {date} ({fromNow})", {date: expiresAt, fromNow: expiresIn})}} <div class=progress> <div class=progress-bar ng-style="{'width': (stats.licensed_users / stats.allowed_licensed_users * 100) + '%'}"> {{_("{active}/{allowed} users", {active: stats.licensed_users, allowed: stats.allowed_licensed_users})}} </div> </div> <div ng-if=stats.billable_organizations.length style="margin-top: 15px;"> <a href ng-click="showLicensingDetails = !showLicensingDetails"> {{showLicensingDetails ? _('Hide') : _('Show')}} {{_('organization usage details')}} </a> <table class=table ng-if=showLicensingDetails> <thead> <tr> <th>{{::_("Organization")}}</th> <th>{{::_("Usage")}}</th> </tr> </thead> <tbody> <tr> <td>{{::_("Unassigned")}}</td> <td> <div class=progress> <div class=progress-bar ng-style="{'width': (stats.licensed_users_excluding_billable_orgs / stats.allowed_licensed_users_excluding_billable_orgs * 100) + '%'}"> {{_("{active}/{allowed} users", {active: stats.licensed_users_excluding_billable_orgs, allowed: stats.allowed_licensed_users_excluding_billable_orgs})}} </div> </div> </td> </tr> <tr ng-repeat="org in stats.billable_organizations"> <td><a ui-sref="org.hub({slug: org.slug})">{{org.name}}</a></td> <td> <div class=progress> <div class=progress-bar ng-style="{'width': (org.used / org.seats * 100) + '%'}"> {{_("{active}/{allowed} users", {active: org.used, allowed: org.seats})}} </div> </div> </td> </tr> </tbody> </table> </div> </div> <div class=counters> <div class=counter ng-repeat="counter in counters|filter:skipMissingCounters" custom-bgcolor={{counter.color}}> <span class=title>{{counter.title}}</span> <span class=value>{{stats[counter.property]}}</span> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/admin/ng-components/templates/oauth-panel.html", `<div class=page-container> <topbar> <div class=admin-filter> <button class="btn btn-primary" ng-click=createApp() ng-hide=app> <i class=bi-plus-lg></i> {{::_('Add new app')}} </button> </div> </topbar> <div class="admin-view page-container-view" id=admin-oauth-panel> <admin-table loader=load(cb) columns=columns ng-show=!app></admin-table> <oauth-app-editor ng-if=app app=app on-cancel="$parent.app = null" system-app=true></oauth-app-editor> </div> </div> `);
  $templateCache.put("/static/app/routes/admin/ng-components/templates/orgs-panel.html", `<div class=page-container> <topbar> <div class=admin-filter> <input type=text class=form-control placeholder="{{::_('Search or find by #id')}}" ng-model=orgFilter.value> <button class="btn btn-default" drop-menu=filterShortcutsMenu> {{::_('Filters')}} <span class=bi-caret-down-fill></span> </button> <button class="btn btn-primary" drop-menu=addMenu ng-hide=createOrgInProgress> <i class=bi-plus-lg></i> {{::_('Add new team')}} <span class=bi-caret-down-fill></span> </button> <span class="btn btn-default" ng-show=createOrgInProgress> <i class="fa fa-upload"></i> {{_("Uploading file ({pct}%)", {pct: createOrgInProgress})}} </span> </div> </topbar> <div class="admin-view page-container-view" id=admin-orgs-panel> <admin-table loader="loadOrgs(page, filter, sortBy, sortAsc, cb)" columns=columns filter=orgFilter.value paginated=true sortable=true export="export(filter, sortBy, sortAsc)" selectable=true actions=orgActions></admin-table> </div> </div> `);
  $templateCache.put("/static/app/routes/request/ng-components/templates/request-page.html", `<div class=page-container> <div id=request-form-view class=page-container-view> <div id=request-form-wrapper> <div class="alert alert-success mt-4" ng-show=$ctrl.confirmMessage> <i class=bi-check-circle-fill></i> <p ng-bind-html=$ctrl.confirmMessage class=d-inline></p> </div> <request class=request-form form=$ctrl.request.form request=$ctrl.request editing-on-init="!$ctrl.requestJustCreated && $ctrl.request.form.editable_after_submit" ng-if="!$ctrl.loading && !$ctrl.error"></request> <p class=powered-by><a href=https://kantree.io>{{::_('Powered by Kantree')}}</a></p> <div class=loader ng-if=$ctrl.loading><i class="fa fa-spinner fa-spin"></i></div> <div class=error ng-if=$ctrl.error>{{$ctrl.error}}</div> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/global-search/ng-components/templates/search.html", `<div class=page-container> <topbar> <dynamic-directive directive={{$ctrl.context.app.navComponent}} context=$ctrl.context with-filter-scopes-selector=true></dynamic-directive> <button class="btn btn-topbar" ng-class="{'btn-icon': $ctrl.isScreensizeXS()}" ng-click=$ctrl.saveAsDashboard() ng-if=!$ctrl.context.hideNav> <i class="fa fa-asterisk"></i> <span class=hidden-xs>{{::_("Save in my work")}}</span> </button> </topbar> <div id=global-search-view class=page-container-view> <dynamic-directive directive={{$ctrl.context.app.component}} context=$ctrl.context with-count=true with-empty-notice=true with-filter-scopes-selector=true></dynamic-directive> </div> </div> true `);
  $templateCache.put("/static/app/routes/onboarding/ng-components/templates/onboarding.html", `<img srcset="{{ '/static/assets/navbar-logo-black.png'|baseUrl }},
        {{ '/static/assets/navbar-logo-black1.5x.png'|baseUrl }} 1.5x,
        {{ '/static/assets/navbar-logo-black2x.png'|baseUrl }} 2x" src="{{ '/static/assets/navbar-logo-black.png'|baseUrl }}"> <div class=onboarding-flow-inner> <div class=onboarding-progress> <div ng-repeat="step in $ctrl.steps" ng-class="{'active': $index <= $ctrl.step}"></div> </div> <div ng-if="$ctrl.steps[$ctrl.step] === 'welcome'"> <h2>{{::_("Welcome to Kantree!")}}</h2> <p> <span ng-show=$ctrl.currentUser.was_invited>{{::_("Kantree is a work platform where teams can collaborate on workspaces.")}}</span> {{::_("Check out our short walkthrough video")}} </p> <iframe width=700 height=394 src="https://www.youtube.com/embed/DvxKdD2u7pY?controls=0&modestbranding=1" frameborder=0 allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <button class="btn btn-cta btn-lg" ng-click=$ctrl.nextStep()>{{::_("Get started")}} <i class="fa fa-arrow-right right"></i></button> </div> <org-creator-form class=mod-dashboard show-find-org=true on-success=$ctrl.handleOrgCreated($org) ng-if="$ctrl.steps[$ctrl.step] === 'create-org'"></org-creator-form> <div ng-if="$ctrl.steps[$ctrl.step] === 'customize-owner'"> <h2>{{::_("Let's customize Kantree for you")}}</h2> <p>{{::_("This will help us create a tailor made experience for you")}}</p> <form ng-submit=$ctrl.submitCustomizations()> <div class=form-group> <label class=form-label for=userDisplayName>{{::_("Full name:")}}</label> <input type=text class="form-control form-control-lg" ng-model=$ctrl.displayName placeholder="{{::_('This is how you will appear to your team mates')}}" id=userDisplayName> <div class=form-text>{{::_("Your username will always be @{username}", {username: $ctrl.currentUser.username})}}</div> </div> <div class=form-group ng-hide="!$ctrl.templateTags.length || $ctrl.serverConfig.onboarding_hide_preferred_template_tag"> <label class=form-label>{{::_("What kind of work do you do?")}}</label> <div class=template-tags> <a href ng-click="$ctrl.templateTag = tag" ng-repeat="tag in $ctrl.templateTags" ng-class="{'active': $ctrl.templateTag === tag}">{{tag}}</a> </div> </div> <button type=submit class="btn btn-cta btn-lg">{{::_("Create your first workspace")}} <i class="fa fa-arrow-right right"></i></button> </form> </div> <div ng-if="$ctrl.steps[$ctrl.step] === 'customize-invite'"> <h2>{{$ctrl.appContext.orgs.length ? _("You have been invited to join {org}", {org: $ctrl.appContext.org.name}) : _("You have been invited to collaborate on workspaces")}}</h2> <p>{{::_("Let's help your team mates know who you are")}}</p> <form ng-submit=$ctrl.finishInvite()> <div class=form-group> <label class=form-label for=userDisplayName>{{::_("Full name:")}}</label> <input type=text class="form-control form-control-lg" ng-model=$ctrl.displayName placeholder="{{::_('This is how you will appear to your team mates')}}" id=userDisplayName> <div class=form-text>{{::_("Your username will always be @{username}", {username: $ctrl.currentUser.username})}}</div> </div> <p ng-show="$ctrl.appContext.orgs.length && $ctrl.appContext.org.permission > 0"> {{::_("On the organization page of {orgname} you will find a list of workspaces you have access to.", {orgname: $ctrl.appContext.org.name})}} </p> <p ng-show="!$ctrl.appContext.orgs.length || $ctrl.appContext.org.permission === 0"> {{::_("On your dashboard you will find the workspaces you have been invited to.")}} </p> <button class="btn btn-cta" type=submit> {{$ctrl.appContext.orgs.length ? _("Explore workspaces in {orgname}", {orgname: $ctrl.appContext.org.name}) : _("Go to your dashboard")}} <i class="fa fa-arrow-right right"></i> </button> </form> </div> <div ng-if="$ctrl.steps[$ctrl.step] === 'customize-observer'"> <h2>{{::_("Let's customize Kantree for you")}}</h2> <p>{{::_("Let's help your team mates know who you are")}}</p> <form ng-submit=$ctrl.finishInvite()> <div class=form-group> <label class=form-label for=userDisplayName>{{::_("Full name:")}}</label> <input type=text class="form-control form-control-lg" ng-model=$ctrl.displayName placeholder="{{::_('This is how you will appear to your team mates')}}" id=userDisplayName> <div class=form-text>{{::_("Your username will always be @{username}", {username: $ctrl.currentUser.username})}}</div> </div> <p> {{::_("You are currently not allowed to create workspaces. Ask your team members to invite you to their workspaces or request the right to create workspaces from your administrator.")}} </p> <button class="btn btn-cta" type=submit> {{::_("Go to your dashboard")}} <i class="fa fa-arrow-right right"></i> </button> </form> </div> </div> `);
  $templateCache.put("/static/app/routes/project/modals/templates/export-modal.html", `<form ng-submit=export()> <div class=modal-header> <h3 class=modal-title>{{::_('Export')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body ng-show="!exporting && !url"> <div class=modal-help-message> <p>{{::_('The export process can take a few minutes. You will receive a link to download your file by email.')}}</p> </div> <div class="form-check form-switch" ng-show=showOnyMatchingCards> <input class=form-check-input type=checkbox role=switch ng-model=onlyMatchingCards id=exportMatchingCardsOnly> <label class=form-check-label for=exportMatchingCardsOnly>{{::_('Only export cards matching the current selection')}}</label> </div> <div class=form-group ng-hide=!templates.length> <label class=form-label for=selectedTemplate>{{::_('Template:')}}</label> <div class=input-group> <select name=template ng-model=template ng-change=useTemplate(template) ng-options="tpl as tpl.name for tpl in templates" class=form-select id=selectedTemplate></select> <a href class="btn btn-danger btn-ghost" ng-show=template ng-click=deleteTemplate(template)>{{::_('Delete this template')}}</a> </div> <span class=form-text>{{::_('Save format and field selection to quickly export with same parameters again')}}</span> </div> <div class=form-group> <label class=form-label for=exportFormat>{{::_('Format:')}}</label> <select name=format ng-model=format ng-change=resetTemplate() ng-options="f as f.title for f in formats" class=form-select id=exportFormat> </select> </div> <div class=form-group ng-show=format.attributes> <label class=form-label>{{::_('Fields')}}</label> <checkbox-list values=attributes sortable=true selected=defaultAttributes on-selection-changed=updateSelectedAttributes($values)></checkbox-list> </div> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=includeDescendants id=exportIncludeDescendants> <label class=form-check-label for=exportIncludeDescendants>{{::_('Include descendant cards')}}</label> </div> </div> <div class=modal-body ng-show="exporting && !url"> <p class=modal-big-message> <i class="fa fa-spin fa-spinner"></i> {{::_('Export in progress...')}} <small>({{::_('You will also receive an email when your export is ready')}})</small> </p> </div> <div class=modal-body ng-show=url> <p>{{::_('Your export is ready. If the download has not started automatically, click the link below')}}</p> <p><a ng-href={{url}} target=_blank>{{url}}</a></p> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost pull-left" type=button ng-click=$dismiss()>{{::_('Close')}}</button> <button class="btn btn-default btn-ghost" type=button ng-click=saveTemplate()>{{::_('Save as template')}}</button> <button class="btn btn-primary" type=submit ng-hide="exporting || url">{{::_('Export')}}</button> </div> </form> `);
  $templateCache.put("/static/app/routes/project/modals/templates/import-errors-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_("There were some errors while importing your workspace")}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <p> {{::_('The following errors occurred while importing')}}: </p> <div class=import-errors> <span class=import-error ng-repeat="error in errors">{{error}}</span> </div> <p> {{::_('Your workspace was still imported but some data may be missing.')}} </p> </div> <div class=modal-footer> <button class="btn btn-default pull-left" type=button ng-click=$dismiss()>{{::_('Close')}}</button> <!-- <button class="btn btn-primary" ng-click="import()" ng-disable="!importData || importing">{{::_('Import')}}</button> --> </div> `);
  $templateCache.put("/static/app/routes/project/modals/templates/convert-context-scope-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Changes to contexts')}}</h3> </div> <div class=modal-body> <div class=convert-scope-modal-p> <p>{{::_('Over the last few months, we have been making contexts easier to use.')}}</p> <p><strong>{{::_('Groups are now managed at the workspace level: top board and sub-boards are sharing the same groups from a context.')}}</strong></p> <p>{{::_('New workspaces have been using this new system for a while and we are now migrating older workspaces.')}}</p> <p>{{::_('Please, review the following changes that will be made to your workspace.')}}</p> </div> <hr> <h3>{{::_('Review the groups for each of your contexts:')}}</h3> <div class=convert-scope-groups> <strong>{{::_('Legend:')}}</strong> <span><span>{{::_('Untouched')}}</span></span> <span class=is-merged><i class="fa fa-share-alt fa-flip-horizontal"></i><span>{{::_('Merged')}}</span></span> <span class=is-added><i class=bi-plus-lg></i><span>{{::_('Added')}}</span></span> <span class=is-deleted><i class="fa fa-minus"></i><span>{{::_('Deleted')}}</span></span> </div> <div class=convert-scope-bulk-actions ng-if=showBulkActions()> <strong>{{::_('Change options on all contexts in bulk:')}}</strong> <button type=button class="btn btn-link" ng-click="changeAllConvertScopeMode('deleteEmpty')"> {{::_('Delete empty')}} </button> <button type=button class="btn btn-link" ng-click="changeAllConvertScopeMode('deleteAll')"> {{::_('Delete all')}} </button> <button type=button class="btn btn-link" ng-click="changeAllConvertScopeMode('')"> {{::_('Keep all (and merge if possible)')}} </button> </div> <div class=panel ng-repeat="gt in convertScopeGroupTypes track by gt.id"> <div class=panel-heading>{{gt.name}}</div> <div class=panel-body> <p ng-show=!gt.groupCount>{{::_('You don\\'t have any group in this context.')}}</p> <div class=convert-scope-groups ng-show=gt.groupCount ng-bind-html=gt.resultingGroupsRecap></div> <hr ng-show=gt.groupCount> <div class=convert-scope-modes ng-show=gt.groupCount> <strong>{{::_('Conversion options:')}}</strong> <div class=form-check> <input class=form-check-input type=radio ng-change="changeConvertScopeMode('deleteEmpty', gt)" ng-model=gt.convertScopeMode value=deleteEmpty id=scopeModeDeleteEmpty> <label class=form-check-label for=scopeModeDeleteEmpty>{{::_('Delete empty groups from sub-boards')}}</label> </div> <div class=form-check> <input class=form-check-input type=radio ng-change="changeConvertScopeMode('deleteAll', gt)" ng-model=gt.convertScopeMode value=deleteAll id=scopeModeDeleteAll> <label class=form-check-label for=scopeModeDeleteAll>{{::_('Delete all groups from sub-boards')}}</label> </div> <div class=form-check> <input class=form-check-input type=radio ng-change="changeConvertScopeMode('', gt)" ng-model=gt.convertScopeMode value id=scopeModeKeepAll> <label class=form-check-label for=scopeModeKeepAll> {{::_('Keep all groups from sub-boards (merge those with the same name)')}}</label> </div> </div> </div> </div> </div> <div class=modal-footer> <div ng-show=loading class=ball-scale-ripple><div></div></div> <a ui-sref=globalHome ng-click=$dismiss()>{{::_('Return to dashboard')}}</a> <button class="btn btn-primary" type=button ng-click=merge()>{{::_('Proceed to conversion and reload page')}}</button> </div> `);
  $templateCache.put("/static/app/routes/project/modals/templates/import-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Import new data into the workspace')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <project-importer project=project on-import-ready=onImportReady($data) force-importer="'spreadsheet'"></project-importer> </div> <div class=modal-footer> <button class="btn btn-default pull-left" type=button ng-click=$dismiss()>{{::_('Close')}}</button> <button class="btn btn-primary" ng-click=import() ng-disable="!importData || importing">{{::_('Import')}}</button> </div> `);
  $templateCache.put("/static/app/routes/project/modals/templates/add-view-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_("Add a view to your {projectType}", {projectType: $ctrl.typeLabel})}}</h3> <help-btn guide=customization anchor=save-views></help-btn> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> {{::_("Views open new perpectives into your data and extend the capabilities of your {projectType}.", {projectType: $ctrl.typeLabel})}} </div> <div class=d-flex style="gap: 10px"> <div class=flex-fill> <div class="d-flex flex-row overflow-hidden position-relative"> <div class=views ng-class="{ 'slide' : $ctrl.showCardsApps, 'me-1': !$ctrl.showCardsApps }"> <button type=button ng-click="$ctrl.showCardsApps = true"> <i class=bi-columns-gap></i> <div> <h4>{{::_("Visualize cards")}}</h4> <p>{{::_("Use different view modes to visualize cards")}}</p> <span><i class="kfi kfi-kanban"></i> Kanban</span> <span><i class="fa fa-table"></i> Table</span> <span><i class="kfi kfi-timeline"></i> Gantt</span> <span>And more...</span> </div> <i class=bi-caret-right-fill></i> </button> <button type=button ng-click=$ctrl.addView(app) ng-repeat="app in $ctrl.apps"> <i ng-class=app.icon|iconClass></i> <div> <h4>{{app.title}}</h4> <p>{{app.description}}</p> </div> </button> </div> <div class=views ng-class="{ 'slide' : $ctrl.showCardsApps }"> <button type=button ng-click="$ctrl.showCardsApps = false" class=back> <i class=bi-arrow-left></i> <h4>{{::_("Back to all views")}}</h4> </button> <button type=button ng-click=$ctrl.addView(app) ng-repeat="app in $ctrl.cardsApps"> <i ng-class=app.icon|iconClass></i> <div> <h4>{{app.title}}</h4> <p>{{app.description}}</p> </div> </button> </div> </div> </div> <div class=suggestions ng-if=::$ctrl.suggestions.length> <span>{{::_('Suggestions')}}</span> <button type=button ng-click=$ctrl.useSuggestion(suggestion) ng-repeat="suggestion in $ctrl.suggestions"> <i ng-class=suggestion.icon|iconClass></i> {{suggestion.title}}</button> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/project/ng-components/templates/project.css.html", " .{{ wrappercls }} .board-filters .filter-shortcut > ul > li.active > a { background-color: {{ color }}; color: {{ textColor }}; } .{{ wrappercls }} .board-filters .filter-shortcut > ul > li.active > a:hover { background-color: {{ darken(color, 10) }}; } .{{ wrappercls }} .mobile-board-menu .btn:active, .{{ wrappercls }} .mobile-board-menu .btn.active { color: {{ darken(color, 20) }}; } body.{{ wrappercls }} nav-members:not(.mod-mobile-menu) .invite-btn { color: {{ getReadableTransparentColor(color, 1, 0.75) }}; background-color: {{ darken(color, 10) }}; } body.{{ wrappercls }} nav-members:not(.mod-mobile-menu) .invite-btn:hover, body.{{ wrappercls }} nav-members:not(.mod-mobile-menu) .invite-btn:focus, body.{{ wrappercls }} nav-members:not(.mod-mobile-menu) .invite-btn.drop-enabled { background-color: {{ darken(color, 15) }}; } body.{{ wrappercls }} .board-empty-notice > i, body.{{ wrappercls }} .board-empty-notice > p > i, body.{{ wrappercls }} .report-view .auto-reports > ul > li > a i { color: {{ color }}; } .{{ wrappercls }} .btn.btn-topbar.active { background-color: {{ isBackgroundDark(color) ? tint(color, 90) : realtint(color, 75) }} } .{{ wrappercls }} .btn.btn-topbar.active:not(.btn-icon) > i, .{{ wrappercls }} .btn.btn-topbar.active span.bi-caret-down-fill { color: {{ isBackgroundDark(color) ? color : shade(color, 50) }}; } .{{ wrappercls }} .btn.btn-topbar.active:hover, .{{ wrappercls }} .btn.btn-topbar.active:active, .{{ wrappercls }} .btn.btn-topbar.active:focus, .{{ wrappercls }} .btn.btn-topbar.active.drop-enabled { background-color: {{ shade(isBackgroundDark(color) ? tint(color, 90) : realtint(color, 75), 5) }}; } .{{ wrappercls }} .btn.btn-topbar.active:not(.btn-icon) > i, .{{ wrappercls }} .btn.btn-topbar.active span.bi-caret-down-fill { color: {{ shade(isBackgroundDark(color) ? color : shade(color, 50), 5) }}; } ");
  $templateCache.put("/static/app/routes/project/ng-components/templates/batch-popover.html", '<i class=bi-check2-all></i> <span>{{_("{count} cards selected", {count: $ctrl.selectedCards.length})}}</span> <button class="btn btn-default" drop-menu=$ctrl.actionsMenuConfig drop-config=$ctrl.dropConfig>{{::_("Actions")}} <span class=bi-caret-up-fill></span></button> <button class="btn btn-default" ng-click=$ctrl.export() ng-if=$ctrl.canExport>{{::_("Export")}}</button> <button class="btn btn-ghost btn-icon" ng-click=$ctrl.onClear()><i class=bi-x-lg></i></button> ');
  $templateCache.put("/static/app/routes/project/ng-components/templates/panel-guide.html", `<div class=loader ng-show=$ctrl.loading><i class="fa fa-spin fa-spinner"></i></div> <div class=error ng-show=$ctrl.error><i class="fa fa-warning"></i></div> <div class=empty ng-if="!$ctrl.project.has_guide && !$ctrl.editing"> <div>{{::_('The workspace has no guide yet. Writing a guide helps your team mates navigate your workspace')}}</div> <button class="btn btn-default" ng-click=$ctrl.edit() ng-show=$ctrl.canEdit> <i class="fa fa-pencil"></i> {{::_('Start writing your guide')}} </button> </div> <div class=editor ng-if=$ctrl.editing> <content-composer content=$ctrl.project.guide on-submit=$ctrl.save(submittedText) on-cancel="$ctrl.editing = false" on-draft-change=$ctrl.refreshDraft() options=$ctrl.guideOptions> </div> <div class=content ng-if="$ctrl.project.has_guide && !$ctrl.editing && !$ctrl.loading"> <div class="markdown mod-project-guide" ng-bind-html=$ctrl.project.guide|markdown></div> <button class="btn btn-default btn-ghost btn-sm edit" type=button ng-if=$ctrl.canEdit ng-hide="!!$ctrl.draft || !$ctrl.isConnected()" ng-click=$ctrl.edit()> <i class="fa fa-pencil"></i> {{::_('Edit')}}</button> <span class=unsaved ng-if=$ctrl.canEdit ng-show=!!$ctrl.draft> <span>{{::_('You have unsaved changes.')}}</span> <button class="btn btn-default btn-ghost btn-sm me-2 unsaved-btn" type=button ng-click=$ctrl.edit()>{{::_('View')}}</button> <button class="btn btn-default btn-ghost btn-sm unsaved-btn" type=button ng-click=$ctrl.edit(true)>{{::_('Discard')}}</button> </span> </div> `);
  $templateCache.put("/static/app/routes/project/ng-components/templates/page.html", `<nav-sidebar config=$ctrl.sidebar with-toggle=true collapsable=true></nav-sidebar> <div class=page-container> <topbar with-auth=true> <project-nav ng-if=$ctrl.context context=$ctrl.context view=$ctrl.view with-settings=$ctrl.isEmbedded()></project-nav> </topbar> <div id=board-view class="board page-container-view" ng-class="{'loading-error': $ctrl.loadingErrorMessage, 'is-template': $ctrl.project.is_template}"> <div class="board-notice board-notice-warning" ng-if=$ctrl.lockedOwner> <i class="fa fa-lock"></i> {{::_('The team this workspace belongs to is locked')}} </div> <div class="board-notice board-notice-warning" ng-if="$ctrl.board && ($ctrl.board.is_archived || $ctrl.board.is_parent_archived)"> <i class="fa fa-archive"></i> {{$ctrl.board.is_archived ? _('This board is archived') : _('A parent of this board has been archived') }} </div> <div class=board-notice ng-if="$ctrl.project && !$ctrl.project.is_template && $ctrl.project.can_join"> <i class="fa fa-sign-in"></i> {{::_('You are not a member of this workspace, join to start editing now')}} <button type=button class="btn btn-cta" ng-click=$ctrl.joinProject()>{{::_('Join')}}</button> </div> <div class="board-notice board-notice-template" ng-if="$ctrl.project && $ctrl.project.is_template"> <i class="fa fa-info-circle"></i> <strong>{{::_('This is a template')}}</strong> <button type=button class="btn btn-primary" ng-if=::$ctrl.isAuthenticated() ng-show=$ctrl.canCreateProjectFromTemplate ng-click=$ctrl.openCreateProjectFromTplModal()><i class=bi-plus-lg></i> {{::_('Create a workspace')}} </button> <button type=button class="btn btn-primary" ng-if=::!$ctrl.isAuthenticated() ng-show=$ctrl.canCreateProjectFromTemplate ng-click=$ctrl.openCreateProjectFromTplModal()> <i class=bi-plus-lg></i> {{::_('Create account with this template')}} </button> <a class="btn btn-primary" ui-sref="templates({demo: demo})" ng-show=!!$ctrl.$state.params.from_tpl_lib> {{::_('Back to library')}} </a> </div> <div class="board-notice board-notice-template" ng-if="$ctrl.project && !$ctrl.project.is_template && !$ctrl.project.is_member && !$ctrl.project.can_join && (!$ctrl.isOwnerOfProjectOwner || !!$ctrl.$state.params.from_tpl_lib)"> <button type=button class="btn btn-primary" ng-if=::$ctrl.isAuthenticated() ng-show=$ctrl.canCreateProjectFromTemplate ng-click=$ctrl.openCreateProjectFromTplModal()>{{::_('Copy to my workspaces')}} </button> <button type=button class="btn btn-primary" ng-if=::!$ctrl.isAuthenticated() ng-show=$ctrl.canCreateProjectFromTemplate ng-click=$ctrl.openCreateProjectFromTplModal()> <i class=bi-plus-lg></i> {{::_('Create account with this workspace')}} </button> <a class="btn btn-primary" ui-sref="templates({demo: demo})" ng-show=!!$ctrl.$state.params.from_tpl_lib> {{::_('Back to library')}} </a> </div> <div class=board-message-overlay ng-if=$ctrl.loadingErrorMessage> <div class="board-message-inner text-danger"> <i class="fa fa-warning"></i> <p>{{$ctrl.loadingErrorMessage}}</p> </div> </div> <div class=board-main ng-if="$ctrl.project && $ctrl.project.id"> <project-side-panel context=$ctrl.context ng-show=$ctrl.$projectSidePanel.panel ng-if="!!$ctrl.context && !$ctrl.isScreensizeXS()"></project-side-panel> <project-placeholder ng-if=$ctrl.projectPlaceholderVisible></project-placeholder> <div class=project-app-container ng-if=$ctrl.context> <dynamic-directive directive={{$ctrl.context.app.component}} context=$ctrl.context on-change=$ctrl.updateView($changes)></dynamic-directive> </div> <project-batch-popover context=$ctrl.context view=$ctrl.view selected-cards=$ctrl.$projectPage.selectedCards on-clear=$ctrl.$projectPage.clearSelectedCards() ng-if=$ctrl.context></project-batch-popover> <card-modal-host resizable=true ng-if=!$ctrl.isScreensizeXS()></card-modal-host> <div class=board-message-overlay ng-if=$ctrl.project.status> <div class=board-message-inner ng-switch=$ctrl.project.status> <i class=fa ng-class="{'fa-cog fa-spin': $ctrl.project.status !== 'error', 'fa-warning text-danger': $ctrl.project.status === 'error'}"></i> <div ng-switch-when=importing> <p>{{::_('Import in progress...')}}</p> <p><small>{{::_('This can take up to a few minutes. You will receive an email when it is completed')}}</small></p> </div> <div ng-switch-when=moving> <p>{{::_('Move in progress...')}}</p> </div> <div ng-switch-when=copying> <p>{{::_('Copy in progress...')}}</p> </div> <div ng-switch-when=converting> <p>{{::_('Converting card to workspace...')}}</p> </div> <div ng-switch-default> <p>{{::_('Creating...')}}</p> </div> <div ng-switch-when=error> <p>{{::_('An error occured while creating your workspace')}}</p> <button class="btn btn-danger" ng-click=$ctrl.importDeleteProject()><i class=bi-trash></i> {{::_('Delete workspace')}}</button> <button class="btn btn-primary" ng-click=$ctrl.importKeepProject()>{{::_('Keep workspace')}}</button> </div> </div> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/project/ng-components/templates/onboarding.html", `<div class=media ng-click=$ctrl.toggleBig() ng-if="$ctrl.step.media || $ctrl.step.icon"> <media-embed src=$ctrl.step.media ng-if=$ctrl.step.media></media-embed> <i ng-class=$ctrl.step.icon|iconClass ng-if=$ctrl.step.icon></i> </div> <div class=body> <h3 ng-bind-html=$ctrl.titleHtml ng-if=$ctrl.titleHtml></h3> <div ng-bind-html=$ctrl.bodyHtml ng-if=$ctrl.bodyHtml></div> </div> <div class=footer> <div class=steps ng-if="$ctrl.step.dots !== false"> <div class=step-dot ng-repeat="step in $ctrl.steps" ng-class="{'active': $ctrl.stepIndex >= $index}"></div> </div> <div class=actions> <button class=btn ng-click=$ctrl.prevStep() ng-if="$ctrl.stepIndex > 0 && $ctrl.step.back !== false">{{::_('Back')}}</button> <button class="btn btn-cta" ng-click=$ctrl.nextStep(true)>{{$ctrl.step.cta.actionLabel ? $ctrl.step.cta.actionLabel : ($ctrl.stepIndex === $ctrl.steps.length - 1 ? _('Close') : _('Next'))}}</button> <button class=btn ng-click=$ctrl.nextStep() ng-if=$ctrl.step.cta.continueLabel>{{$ctrl.step.cta.continueLabel}}</button> </div> </div> <button type=button class=close-btn ng-click=$ctrl.close()>&times;</button> `);
  $templateCache.put("/static/app/routes/project/ng-components/templates/nav.html", `<div class=board-nav> <div class="board-nav-info visible-xs-block" ng-class="{'mod-top-level': !$ctrl.context.board.parent_id}"> <div class=project ng-if=$ctrl.context.board.parent_id> <a ui-sref="project({projectId: $ctrl.context.project.slug})">{{$ctrl.context.project.title}}</a><span>/</span> </div> <div class=board-breadcrumb> <div class="path hidden-xs" ng-if=$ctrl.path.length> <button class=btn drop-menu=$ctrl.pathMenuSpec drop-config=$ctrl.pathMenuDropConfig>...</button><span>/</span> </div> <span class="btn title" title={{$ctrl.context.board.title}}> <span>{{$ctrl.context.board.title}}</span> <span class="ref hidden-xs" ng-if=$ctrl.context.board.parent_id>(#{{$ctrl.context.board.ref}})</span> </span> <i class="fa fa-globe indicator hidden-xs" ng-show=$ctrl.context.project.is_private uib-tooltip="{{::_('Private')}}" tooltip-placement=bottom></i> <i class="fa fa-globe indicator hidden-xs" ng-show=$ctrl.context.project.is_public uib-tooltip="{{::_('Has shareable link')}}" tooltip-placement=bottom></i> <span class="fa-stack indicator unapproved-domain-members" ng-show="$ctrl.notApprovedDomainMembers.length > 0" uib-tooltip="{{::_('Has unapproved members')}}" tooltip-placement=bottom> <i class=bi-person-x-fill></i> </span> </div> </div> <div class=board-nav-view-component-outer> <div class="board-nav-view-component hidden-xs"> <div class=board-nav-view-component-inner ng-if=!$ctrl.view.locked> <span class="btn btn-topbar hidden-xs app-nav-name" ng-show=!$ctrl.context.app.hideAppName> <i ng-class=$ctrl.context.app.icon|iconClass ng-show=$ctrl.context.app.icon></i> {{$ctrl.context.app.title}} </span> <dynamic-directive directive={{$ctrl.context.app.navComponent}} context=$ctrl.context shrinked=$ctrl.shrinked></dynamic-directive> </div> <view-locked-btn ng-if=$ctrl.view.locked context=$ctrl.context locked=$ctrl.view.locked></view-locked-btn> <view-rules-btns class="d-flex gap-2" ng-if="$ctrl.canRunAutomations && $ctrl.context.appOptions.showActions && $ctrl.view.locked" context=$ctrl.context></view-rules-btns> </div> <view-save-btn ng-show="$ctrl.showSaveBtn && !$ctrl.view.locked" ng-if=$ctrl.view view=$ctrl.view shrinked=$ctrl.shrinked></view-save-btn> </div> <div class=board-nav-right ng-if=!$ctrl.isScreensizeXS()> <nav-members context=$ctrl.context ng-if="!$ctrl.context.project.is_template && !$ctrl.context.shareMode"></nav-members> <cards-app-search-btn context=$ctrl.context ng-if=$ctrl.viewMode.searchable></cards-app-search-btn> <button class="btn btn-icon btn-topbar" type=button uib-tooltip="{{::_('Ask Kantree Assistant (ctrl+alt+i)')}}" tooltip-placement=bottom tooltip-popup-delay=0 ng-click=$ctrl.openAssistant() ng-if="$ctrl.isAuthenticated() && $ctrl.assistantEnabled" disable-offline ng-disabled=$ctrl.assistantRunning> <i ng-class="{'fa fa-spin fa-spinner': $ctrl.assistantRunning, 'bi bi-stars': !$ctrl.assistantRunning}"></i> </button> <button class="btn btn-icon btn-topbar" type=button uib-tooltip="{{::_('Add...')}}" tooltip-placement=bottom tooltip-popup-delay=0 drop-menu=$ctrl.createMenu ng-if="$ctrl.isAuthenticated() && $ctrl.createMenu.config.length" disable-offline><i class=bi-plus-lg></i></button> <button class="btn btn-icon btn-topbar" ng-class="{'is-nav-alert': $ctrl.hasNewNotif}" type=button uib-tooltip="{{::_('Notifications in this workspace')}}" tooltip-placement=bottom tooltip-popup-delay=0 open-notifications-dropdown=$ctrl.projectNotificationStore notification-drop-title="{{_('Notifications in {project}', {project: $ctrl.context.project.title})}}" on-mark-all-as-read=$ctrl.markAllNotifsAsRead() ng-show=$ctrl.isAuthenticated() disable-offline> <i class=bi-bell-fill></i> </button> <coach-btn></coach-btn> </div> <button class="btn btn-icon btn-topbar visible-xs-inline-block" drop-menu=$ctrl.mobileMenu drop-config="{classes: 'drop-theme-menu drop-theme-mobile-board-menu', tetherOptions: { resizable: false }}"><i class=bi-gear-fill></i></button> </div> `);
  $templateCache.put("/static/app/routes/org/modals/templates/invite-members-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Invite members to your organization')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class="alert alert-info" ng-show="!$ctrl.billing && $ctrl.maxUserReached"> <i class=bi-info-square-fill></i> {{::_('You have reached the maximum number of allowed users')}} </div> <div class="alert alert-info" ng-show="$ctrl.billing && $ctrl.billing.status !== 'trialing' && $ctrl.billing.auto_adjust_seat_count && $ctrl.nbUsers === $ctrl.maxUsers"> <i class=bi-info-square-fill></i> {{::_('Adding new users will automatically add new seats to your subscription (seats will be charged pro-rated to the remaining of your billing period)')}} </div> <div class="alert alert-info alert-actionnable" ng-show="$ctrl.billing && !$ctrl.billing.auto_adjust_seat_count && $ctrl.maxUserReached && $ctrl.isOwner"> <span><i class=bi-info-square-fill></i> {{::_('All seats are being used.')}}</span> <button class="btn btn-text" ng-click=$ctrl.openManageSeatsModal() ng-if="$ctrl.billing.payment_method === 'stripe'">{{::_('Add seats')}}</button> </div> <div class="alert alert-info" ng-show="$ctrl.billing && !$ctrl.billing.auto_adjust_seat_count && $ctrl.maxUserReached && !$ctrl.isOwner"> <i class=bi-info-square-fill></i> {{::_('All seats are being used. Request an owner of this organization to purchase new seats before adding new users')}} </div> <div class=nav-tabs ng-show=$ctrl.serverConfig.enable_org_invite_link> <div class=nav-tabs-tabs> <a class=nav-tab ng-class="{'active': $ctrl.currentTab === 'invites'}" href ng-click="$ctrl.currentTab = 'invites'">{{::_('Add or invite people')}}</a> <a class=nav-tab ng-class="{'active': $ctrl.currentTab === 'link'}" href ng-click="$ctrl.currentTab = 'link'">{{::_('Share a link')}}</a> </div> </div> <div ng-if="$ctrl.currentTab === 'invites'"> <invite-form on-submit="$ctrl.invite(emailOrUsernames, message, callbacks)" ng-hide=$ctrl.maxUserReached></invite-form> <div ng-show=$ctrl.newMembers.length> <h3>{{::_("New users added")}}</h3> <user-avatar user=member.user ng-repeat="member in $ctrl.newMembers"></user-avatar> </div> <div ng-show=$ctrl.invites.length> <hr> <h3>{{::_("Pending invites")}}</h3> <solidjs-component component=$ctrl.MemberList members=$ctrl.invites roles=$ctrl.availableOrgRoles editable=$ctrl.isAdmin show-remove=true on-remove=$ctrl.removeInvite on-role-change=$ctrl.updateInvitePerm on-resend-invite=$ctrl.resendInvite></solidjs-component> </div> <div class=progress ng-show="$ctrl.maxUsers && (!$ctrl.billing || $ctrl.billing.status !== 'trialing')" style="margin-top: 20px;"> <div class=progress-bar role=progressbar ng-style="{'width': ($ctrl.nbUsers / $ctrl.maxUsers * 100) + '%'}"> {{$ctrl.nbUsers}} / {{$ctrl.maxUsers}} {{$ctrl.billing && $ctrl.billing.auto_adjust_seat_count ? _('seats used (auto managed)') : ($ctrl.billing ? _('seats used') : _('allowed users'))}} </div> </div> </div> <div ng-if="$ctrl.currentTab === 'link' && $ctrl.org.invite_link" class=share-link-tab> <h3>{{::_("Share this link to invite people to this team:")}}</h3> <copyable-readonly-input value=$ctrl.org.invite_link></copyable-readonly-input> <a href drop-menu=$ctrl.linkDefaultPermMenu>{{_("Default role when joining using this link: {perm}", {perm: $ctrl.linkDefaultPermLabel})}} <span class=bi-caret-down-fill></span></a> <a href ng-click=$ctrl.toggleLink()>{{::_("Disable invite via link")}}</a> <a href ng-click=$ctrl.resetLink()>{{::_("Generate a new link")}}</a> </div> <div ng-if="$ctrl.currentTab === 'link' && !$ctrl.org.invite_link" class=share-link-tab> <h3>{{::_("Share a link to invite people to this team")}}</h3> <button class="btn btn-primary" ng-click=$ctrl.toggleLink()>{{::_("Enable link")}}</button> </div> <p class=text-center ng-show="$ctrl.billing && $ctrl.billing.status !== 'trialing' && $ctrl.billing.seat_count > $ctrl.billing.next_period_seat_count"> <small>{{_('{nbSeats} seat(s) will be automatically removed at the end of the billing period', {nbSeats: $ctrl.billing.seat_count - $ctrl.billing.next_period_seat_count})}}</small> </p> <p class=text-center ng-show="$ctrl.billing && $ctrl.billing.status !== 'trialing' && $ctrl.billing.auto_adjust_seat_count && $ctrl.invites.length"> <small>{{_('{nbSeats} seat(s) will be automatically added when invites are accepted', {nbSeats: $ctrl.invites.length})}}</small> </p> </div> `);
  $templateCache.put("/static/app/routes/org/modals/templates/export-modal.html", `<form ng-submit=$ctrl.export()> <div class=modal-header> <h3 class=modal-title>{{::_('Export organization')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class="from-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.withFiles id=exportWithFiles> <label class=form-check-label for=exportWithFiles>{{::_('Include files')}}</label> </div> <div class="from-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.withUserOrgs id=exportWithUserOrgs> <label class=form-check-label for=exportWithUserOrgs>{{::_('Include user organizations')}}</label> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.dismiss()>{{::_('Close')}}</button> <button class="btn btn-primary" type=submit>{{::_('Export')}}</button> </div> </form> `);
  $templateCache.put("/static/app/routes/org/modals/templates/creator-modal.html", '<button class="btn-close position-absolute top-0 end-0 mt-3 me-3" type=button ng-click=$ctrl.dismiss()></button> <org-creator-form class=mod-modal on-success=$ctrl.onCreated($org) on-cancel=$ctrl.dismiss() on-payment-needed=$ctrl.onCreated($org) show-cancel=true is-modal=true></org-creator-form> ');
  $templateCache.put("/static/app/routes/org/modals/templates/team-settings-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Team settings')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class=panel> <div class=panel-heading> {{::_("Options")}} </div> <div class=panel-body> <form name=$ctrl.nameForm ng-submit=$ctrl.update()> <div class=form-group> <label class=form-label for=teamName>{{::_('Team name:')}}</label> <input class=form-control type=text required ng-model=$ctrl.name id=teamName> </div> <div class=form-group> <label class=form-label>{{::_('Color:')}}</label> <color-picker-palette color=$ctrl.color on-change="$ctrl.color = $color"></color-picker-palette> </div> <div class=form-group> <label class=form-label>{{::_('Icon:')}}</label> <icon-picker icon=$ctrl.icon on-change="$ctrl.icon = $icon"></icon-picker> </div> <div class=form-group> <label class=form-label for=teamDesc>{{::_('Description:')}}</label> <content-editor ng-model=$ctrl.description></content-editor> </div> <button type=submit class="btn btn-primary" ng-disabled="$ctrl.nameForm.$invalid || $ctrl.updateStatus.processing" disable-offline>{{::_('Save')}}</button> <processing-status status=$ctrl.updateStatus></processing-status> </form> </div> </div> <div class=panel> <div class=panel-heading> {{::_("Access")}} </div> <div class=panel-body> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.orgMembersCanObserve ng-change=$ctrl.updateAccessSettings() id=membersCanObserve> <label class=form-check-label for=membersCanObserve>{{::_('Organization members can access this team')}}</label> </div> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.orgMembersCanAutoJoin ng-change=$ctrl.updateAccessSettings() ng-disabled=!$ctrl.team.org_members_can_observe id=membersCanAutojoin> <label class=form-check-label for=membersCanAutojoin>{{::_('Organization members can join this team by themselves')}}</label> </div> </div> </div> <div class=panel> <div class=panel-heading> {{::_("Delete")}} </div> <div class=panel-body> <button type=button ng-click=$ctrl.delete() class="btn btn-danger"><i class="fa fa-trash"></i> Delete team</button> </div> </div> </div> `);
  $templateCache.put("/static/app/routes/org/modals/templates/add-members-to-modal.html", `<form ng-submit=$ctrl.export()> <div class=modal-header> <h3 class=modal-title>{{$ctrl.resolve.modalTitle}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <input type=text class=form-control ng-model=$ctrl.filter ng-attr-placeholder="{{::_('Filter')}}"> <div ng-repeat="member in $ctrl.members track by member.id" ng-hide=!$ctrl.matchFilter(member)> <user-avatar user=member.user></user-avatar> <span> {{::member.user.display_name}} <small ng-show="::member.user.display_name !== member.user.username">@{{::member.user.username}}</small> </span> <button type=button class="btn btn-primary" ng-click=$ctrl.resolve.onAddCallback(member) ng-hide=$ctrl.resolve.isMemberAddedFunc(member)>{{::_('Add')}}</button> </div> </div> <div class=modal-footer> <div ng-show=$ctrl.resolve.team class="form-check form-switch form-check-inline pull-left"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.onlyShowTeamMember ng-change=$ctrl.refreshMemberStore();$ctrl.refreshMembers() id=onlyShowTeamMember> <label class=form-check-label for=onlyShowTeamMember>{{::_('Only show {team} members', {team: $ctrl.resolve.team.name})}}</label> </div> <button class="btn btn-default" type=button ng-click=$ctrl.goToMembersPage() ng-show=$ctrl.canManageMembers> {{::_('Manage {team} members', {team: $ctrl.resolve.team ? $ctrl.resolve.team.name : $ctrl.resolve.org.name})}} </button> <button class="btn btn-default" type=button ng-click=$ctrl.dismiss()>{{::_('Close')}}</button> </div> </form> `);
  $templateCache.put("/static/app/routes/org/modals/templates/create-team-modal.html", `<form ng-submit=$ctrl.create() name=$ctrl.teamForm> <div class=modal-header> <h3 class=modal-title>{{::_('Create a new team in {org}', {org: $ctrl.resolve.org.name})}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class=form-group> <label class=form-label for=teamName>{{::_('Team name:')}}</label> <input type=text ng-model=$ctrl.name class="form-control form-control-lg" id=teamName required auto-focus> </div> <div class=form-group> <label class=form-label>{{::_('Easily identify your team with a color and icon:')}}</label> <color-picker-palette color=$ctrl.color on-change="$ctrl.color = $color"></color-picker-palette> <icon-picker icon=$ctrl.icon on-change="$ctrl.icon = $icon"></icon-picker> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-cta" type=submit ng-disabled=$ctrl.teamForm.$invalid>{{::_('Create')}}</button> </div> </form> `);
  $templateCache.put("/static/app/routes/org/ng-components/templates/topbar.html", `<topbar class=org-page-topbar> <quick-global-search-toggle cover-toggle=true filter-scopes=$ctrl.filterScopes></quick-global-search-toggle> <div class=navbar-filler></div> <button class="btn btn-topbar hidden-xs" ng-show=$ctrl.showUseAsHomeBtn ng-click=$ctrl.useAsHome() tooltip-popup-delay=0 tooltip-placement=bottom uib-tooltip="{{::_('Make this page your home when you click the Kantree logo in the upper left corner')}}"><i class=bi-house></i> {{::_("Use as home")}}</button> <button class="btn btn-icon btn-topbar" type=button uib-tooltip="{{::_('Add new...')}}" tooltip-placement=bottom tooltip-popup-delay=0 drop-menu=$ctrl.addNewMenu disable-offline><i class=bi-plus-lg></i></button> <button class="btn btn-icon btn-topbar" ng-class="{'is-nav-alert': $ctrl.notificationStore.query().length}" type=button uib-tooltip="{{::_('Notifications in this organization')}}" tooltip-placement=bottom tooltip-popup-delay=0 open-notifications-dropdown=$ctrl.notificationStore notification-drop-title="{{_('Notifications in {org}', {org: $ctrl.org.name})}}" on-mark-all-as-read=$ctrl.markAllNotificationsAsRead() disable-offline> <i class=bi-bell-fill></i> </button> <coach-btn></coach-btn> </topbar> `);
  $templateCache.put("/static/app/routes/org/ng-components/templates/creator-form.html", `<form name=$ctrl.orgForm ng-submit=$ctrl.create()> <div ng-show="$ctrl.activeStep === 'create-org'" class=org-creator-team-name-step> <div class=org-creator-img-container> <img ng-src="{{'/static/assets/welcome.png'|baseUrl}}"> </div> <h2 class=org-creator-title ng-if=::!$ctrl.withoutTitle> {{::_('Create a new organization')}} </h2> <p class="org-creator-p mod-secondary"> {{::_("Organizations are where you and your team mates will be able to collaborate on workspaces.")}} </p> <div class="form-group clearfix"> <label class=form-label for=name>{{::_('Name:')}}</label> <input id=name class=form-control type=text ng-model=$ctrl.orgName required ng-attr-placeholder="{{::_('EX. Acme or Acme Marketing')}}" auto-focus="$ctrl.activeStep === 'create-org'"> </div> </div> <div ng-show="$ctrl.activeStep === 'find-org'" class=org-creator-join-step> <h2 class=org-creator-title>{{::_('Your team is already on Kantree?')}}</h2> <p class=org-creator-p> {{::_('Ask them for an invite to start working together. You will receive it by email.')}} </p> <div class=org-creator-img-container> <img ng-src="{{'/static/assets/send-invite.png'|baseUrl}}" style="width: 105px;"> </div> <p class="org-creator-p mod-small" ng-bind-html=$ctrl.joinHelpLinkText></p> </div> <div ng-show="$ctrl.activeStep === 'members-invite'" class=members-invite> <div class=org-creator-img-container> <img ng-src="{{'/static/assets/invite-members.png'|baseUrl}}"> </div> <h2 class=org-creator-title> {{::_('Invite your team members')}} </h2> <p class="org-creator-p mod-secondary"> {{::_("We'll send them an invitation to join your new team.")}}<br> {{::_("Don't worry, you can invite them later anytime.")}} </p> <fieldset> <input ng-repeat="i in $ctrl.invites track by $index" type=text class=form-control ng-model=$ctrl.invites[$index] ng-change=$ctrl.onInviteInputChange($index) ng-attr-placeholder="{{::_('email or Kantree username')}}"> </fieldset> <fieldset> <textarea class=form-control ng-model=$ctrl.message ng-show=$ctrl.showMessage ng-attr-placeholder="{{::_('Add a custom message to the invite')}}" rows=5></textarea> <a href ng-click="$ctrl.showMessage = true" ng-show=!$ctrl.showMessage>{{::_('Add a custom message to the invite')}}</a> </fieldset> </div> <div class=org-creator-actions ng-class="::{'modal-footer': $ctrl.isModal}"> <button class="btn btn-default btn-ghost" ng-class="{'btn-lg': !$ctrl.isModal}" type=button ng-show="$ctrl.activeStep !== 'create-org' && $ctrl.activeStep !== 'members-invite'" ng-click="$ctrl.activeStep = 'create-org'"><i class="fa fa-angle-double-left"></i> {{::_('Back')}}</button> <button class="btn btn-default btn-ghost" ng-class="{'btn-lg': !$ctrl.isModal}" type=button ng-show="$ctrl.showCancel && $ctrl.activeStep !== 'members-invite'" ng-click=$ctrl.onCancel()>{{::_('Cancel')}}</button> <button class="btn btn-cta" ng-class="{'btn-lg': !$ctrl.isModal}" type=submit ng-show="$ctrl.activeStep === 'create-org'" ng-disabled=$ctrl.orgForm.$invalid>{{::_('Create')}}</button> <button class="btn btn-default btn-ghost" ng-class="{'btn-lg': !$ctrl.isModal}" type=button ng-show="$ctrl.activeStep === 'members-invite'" ng-click=$ctrl.finish()>{{::_('Skip')}}</button> <button class="btn btn-cta" ng-class="{'btn-lg': !$ctrl.isModal}" type=button ng-show="$ctrl.activeStep === 'members-invite'" ng-click=$ctrl.sendInvites()>{{::_('Send invites')}}</button> </div> <div class=already-invited-link ng-show="$ctrl.activeStep === 'create-org' && $ctrl.showFindOrg"> <a href ng-click="$ctrl.activeStep = 'find-org'">{{::_('Click here if your team is already in Kantree')}}</a> </div> </form> `);
  $templateCache.put("/static/app/routes/share/ng-components/templates/share-page.html", `<div class=page-container> <topbar with-auth=true with-logo=true ng-if=!!$ctrl.sharedView> <div class=share-view-nav ng-if=$ctrl.sharedView> <div class=share-header-title>{{::$ctrl.sharedView.name}}</div> <div class=share-header-small>{{::_('from')}}</div> <div class="share-header-small mod-project">{{::$ctrl.sharedView.project.title}}</div> <div class="share-header-actions hidden-xs"> <button class="btn btn-primary btn-sm share-header-action-btn" ng-repeat="form in $ctrl.sharedView.forms" ng-click=$ctrl.openForm(form)>{{::form.name}}</button> </div> </div> </topbar> <div id=share-view class=page-container-view ng-class="{'mod-project': !!$ctrl.sharedView}"> <share-card card=$ctrl.sharedCard ng-if=!!$ctrl.sharedCard></share-card> <share-view view=$ctrl.sharedView ng-if=!!$ctrl.sharedView></share-view> <div class=loader ng-if=$ctrl.loading><i class="fa fa-spinner fa-spin"></i></div> <div class=error ng-if=$ctrl.error>{{$ctrl.error}}</div> </div> </div> `);
  $templateCache.put("/static/app/routes/my-work/ng-components/templates/requests.html", `<topbar> <button type=button class="btn btn-topbar" drop-menu=$ctrl.filterMenu> <i class=bi-filter></i> <span>{{$ctrl.filter.label}}</span> <i class=bi-caret-down-fill></i> </button> </topbar> <div id=mywork-dashboard-requests class=page-container-view> <div class=empty ng-if="!$ctrl.loading && !$ctrl.requests.length">{{::_("You don't have opened requests")}}</div> <a ui-sref="request({requestToken: request.token})" target=_blank ng-repeat="request in $ctrl.requests"> <span class=title ng-show=request.title>{{request.title}}</span> <div> <span> {{request.form.name}} <span ng-if=request.current_group_title class="badge ms-2">{{request.current_group_title}}</span> </span> <span ng-if=request.comments.length><i class=bi-chat-left></i> {{request.comments.length}}</span> <span>{{request.created_at|momentFormat:'lll'}}</span> </div> </a> </div> `);
  $templateCache.put("/static/app/routes/my-work/ng-components/templates/layout.html", "<nav-sidebar config=sidebarConfig></nav-sidebar> <div class=page-container ui-view> </div> ");
  $templateCache.put("/static/app/routes/my-work/ng-components/templates/inbox.html", `<topbar> <user-project-selector-btn class="btn btn-topbar" selected-projects-is-null-for-all=true filter-scopes=$ctrl.filterScopes is-multiple=true readonly=!$ctrl.isConnected show-empty-warning=true on-change=$ctrl.saveFilterScopes($filterScopes)></user-project-selector-btn> <div class=navbar-filler></div> <button class="btn btn-topbar hidden-xs" ng-show=$ctrl.showUseAsHomeBtn ng-click=$ctrl.useAsHome() tooltip-popup-delay=0 tooltip-placement=bottom uib-tooltip="{{::_('Make this page your home when you click the Kantree logo in the upper left corner')}}"><i class=bi-house></i> {{::_("Use as home")}}</button> <button class="btn btn-topbar hidden-xs alert-danger" ng-show=$ctrl.unscopedNotifsStore.query().length open-notifications-dropdown=$ctrl.unscopedNotifsStore notification-drop-title="{{::_('Notifications in hidden workspaces')}}" on-mark-all-as-read=$ctrl.markAllOtherOrgsAsRead()> <i class="fa fa-bell"></i> {{_('{count} unread in hidden workspaces', {count: $ctrl.unscopedNotifsStore.query().length})}} </button> <button class="btn btn-topbar btn-icon hidden-xs" drop-menu=$ctrl.settingsMenu uib-tooltip="{{::_('Inbox options')}}" tooltip-placement=left tooltip-popup-delay=0> <i class="fa fa-sliders"></i> </button> </topbar> <div id=inbox-view class="page-container-view activity-scroll-viewport"> <a href ng-click=$ctrl.refreshFeed() ng-show=$ctrl.refreshFeedNeeded> <i class="fa fa-refresh"></i> {{_('{count} update(s) are available, click to refresh', {count: $ctrl.refreshUnreadCount})}} </a> <div class=inbox-main> <inbox ng-if=$ctrl.hasValidFilterScopes feed=$ctrl.feed loading="$ctrl.loading || $ctrl.loadingFeedPage" unread-ids=$ctrl.unreadIds unread-only=$ctrl.currentUser.app_params.inboxUnreadOnly mark-as-read-when-comment=$ctrl.currentUser.app_params.inboxMarkAsReadWhenComment mark-as-read-on-scrolled=$ctrl.currentUser.app_params.inboxMarkAsReadWhenScrolled on-mark-as-read=$ctrl.markAsRead($activities) on-mark-all-as-read=$ctrl.markAllAsRead()></inbox> <div class=empty-inbox ng-show=!$ctrl.hasValidFilterScopes> <p>{{::_('Please select some workspaces above to get started')}}</p> </div> </div> <div class="inbox-sidebar hidden-xs"> <solidjs-component class=tiny-calendar component=$ctrl.TinyCalendar on-select=$ctrl.doCalendarSearch on-month-changed=$ctrl.queryCalendarCards on-feed-click=$ctrl.showCalendarFeed /> </div> </div> `);
  $templateCache.put("/static/app/routes/my-work/ng-components/templates/dashboard.html", `<topbar> <dynamic-directive directive={{$ctrl.context.app.navComponent}} context=$ctrl.context with-filter-scopes-selector=true></dynamic-directive> <view-save-btn view=$ctrl.view ng-if=$ctrl.originalView.id></view-save-btn> <button class="btn btn-topbar" ng-class="{'btn-icon': $ctrl.isScreensizeXS()}" ng-click=$ctrl.saveAsDashboard() ng-if=!$ctrl.originalView.id> <i class=bi-pencil-square></i> <span class=hidden-xs>{{::_("Edit as dashboard")}}</span> </button> </topbar> <div id=mywork-dashboard-view class=page-container-view> <dynamic-directive directive={{$ctrl.context.app.component}} context=$ctrl.context with-count=true with-empty-notice=$ctrl.withEmptyNotice with-filter-scopes-selector=true></dynamic-directive> </div> `);
  $templateCache.put("/static/app/routes/my-work/ng-components/templates/project-view.html", '<topbar> <a navigate-to={{$ctrl.projectUrl}} class="btn btn-topbar" ng-hide=$ctrl.loading> {{_("Go to {project}", {project: $ctrl.context.project.title})}} <i class=bi-arrow-right-short></i> </a> </topbar> <div class=page-container-view> <loading-indicator class="flex-fill m-5 text-center" ng-if=$ctrl.loading></loading-indicator> <dynamic-directive class=flex-fill ng-show=!$ctrl.loading directive={{$ctrl.context.app.component}} context=$ctrl.context with-count=true with-empty-notice=true></dynamic-directive> <div class=board-message-overlay ng-if=$ctrl.loadingErrorMessage> <div class="board-message-inner text-danger"> <i class="fa fa-warning"></i> <p>{{$ctrl.loadingErrorMessage}}</p> </div> </div> </div> ');
  $templateCache.put("/static/app/routes/template-lib/ng-components/templates/view.html", `<div class=header> <button ng-click=$ctrl.createProject() class="btn btn-cta btn-lg" ng-show=$ctrl.canUse>{{::_('Use this template')}}</button> <h2>{{$ctrl.template.title}}</h2> <div class=tags> <a ui-sref="templates_tag({'tag': tag.replace(' ', '').toLowerCase()})" ng-repeat="tag in $ctrl.template.tags">#{{tag}}</a> </div> </div> <div class=desc ng-bind-html=$ctrl.template.description|markdown></div> <div class=nodesc ng-if="!$ctrl.template.description && !$ctrl.template.preview_media_url">{{::_('No description')}}</div> <media-embed src=$ctrl.template.preview_media_url ng-if=$ctrl.template.preview_media_url></media-embed> `);
  $templateCache.put("/static/app/routes/template-lib/ng-components/templates/library.html", `<nav-sidebar config=$ctrl.sidebarConfig></nav-sidebar> <div class=page-container> <topbar with-auth=true></topbar> <div id=template-library-view class=page-container-view ng-class="{'embedded': $ctrl.$state.params.embed}"> <div class="body tags-section" ng-show="!$ctrl.template && !$ctrl.currentTag"> <div class=onboarding-notice ng-show=$ctrl.onboarding> <span>\u{1F389}</span> <div> <h2>{{::_("Welcome to Kantree! Let's create your first workspace")}}</h2> <p> {{::_("Whether you are organizing data, building a product, planning an event, etc... workspaces will let you work the way you want with your team mates")}} </p> </div> </div> <div ng-if=$ctrl.blankTag> <h2>{{::_('Create a new workspace')}}</h2> <p> {{::_("Workspaces are where work happens, on your own terms. Combine the features you need to customize your space. Templates help you get started quickly but feel free to re-arrange everything, there is no limit!")}} </p> <template-library-tile template=template ng-repeat="template in $ctrl.getTagTemplates($ctrl.blankTag, false)" on-tile-click=$ctrl.onTileClick(template)></template-library-tile> </div> <div ng-if=$ctrl.featuredOrgTemplates class=mt-5> <h2>{{::_('Templates from your organization')}}</h2> <template-library-tile template=template ng-repeat="template in $ctrl.featuredOrgTemplates" on-tile-click=$ctrl.onTileClick(template)></template-library-tile> </div> <div ng-if="$ctrl.onboarding && $ctrl.preferredTag" class=mt-5> <h2>{{::_('{preferred_tag} templates', {preferred_tag: $ctrl.preferredTag})}}</h2> <template-library-tile template=template ng-repeat="template in $ctrl.getTagTemplates($ctrl.preferredTag)" on-tile-click=$ctrl.onTileClick(template)></template-library-tile> </div> <div ng-if="$ctrl.featuredTag && (!$ctrl.onboarding || !$ctrl.preferredTag) && $ctrl.getTagTemplates($ctrl.featuredTag).length" class=mt-5> <h2>{{::_('Featured templates')}}</h2> <template-library-tile template=template ng-repeat="template in $ctrl.getTagTemplates($ctrl.featuredTag)" on-tile-click=$ctrl.onTileClick(template)></template-library-tile> </div> </div> <div class="body tags-section" ng-if="!$ctrl.template && $ctrl.currentTag"> <template-library-tile template=template ng-repeat="template in $ctrl.getTagTemplates($ctrl.currentTag)" on-tile-click=$ctrl.onTileClick(template) can-delete=isOrgManager($ctrl.orgs[$ctrl.currentTag]) on-delete=$ctrl.refreshTemplates()></template-library-tile> <button ng-click=$ctrl.createTemplate($ctrl.orgs[$ctrl.currentTag]) ng-if=isOrgManager($ctrl.orgs[$ctrl.currentTag])><i class=bi-plus-lg></i> {{::_("Create new workspace template")}}</button> </div> <div class=body ng-if=$ctrl.template> <button type=button ng-click="$ctrl.template = null" class="btn btn-default">&laquo; {{::_('Back')}}</button> <template-view template=$ctrl.template org=$ctrl.org team=$ctrl.team can-use=$ctrl.canUse></template-view> </div> <div class=notice-section ng-show=$ctrl.loading> <i class="fa fa-spinner fa-spin"></i> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/icalendar/icalendar-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('iCalendar feed')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=form-group> <label class=form-label>{{::_('Add a Kantree calendar as an external calendar to your calendar app using the following link:')}}</label> <copyable-readonly-input value=url></copyable-readonly-input> </div> </div> <div class=modal-footer> <button class="btn btn-default" type=button ng-click=$dismiss()>{{::_('Close')}}</button> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/image-paste-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Paste image to')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> {{ ::_('You are about to paste an image on your card. Where do you want to paste it?') }} </div> <div class=form-group> <label class=form-label for=pasteOption>{{::_('Image destination')}}</label> <select class=form-select ng-model=pasteOptionSelected ng-options="opt.name for opt in pasteOptions" id=pasteOption></select> </div> <div class=form-group> <label class=form-label>{{::_('Image preview')}}</label> <div class=image-container> <img class=image-preview ng-attr-src="{{ imageSrc }}"> </div> </div> </div> <div class=modal-footer> <span class=image-loading-indicator> <span ng-show=uploading>{{::_('Uploading image')}}</span> <div ng-show=uploading class=ball-scale-ripple><div></div></div> </span> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=paste()>{{::_('Paste')}}</button> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/children.html", `<div class=card-view-children> <div class=progress-indicator> <span class=progress-percent>{{card.nb_completed_pct}}%</span> <div class=progress> <div class=progress-bar ng-style="{'width': card.nb_completed_pct + '%'}"></div> </div> </div> <div class="children js-children-sortable card-tile-list" ui-sortable=sortableOptions ng-model=children scope-on-element> <div card-tile=task edit-on-click=true template-type=task show-children-attributes=showChildrenAttributes show-attributes=showAttributes ng-repeat="task in children track by task.id" editable=directiveEditable class="noactions mod-task"></div> </div> <div ng-show=canCreateChildren> <div class=add-child-container ng-hide=taskCreatorOption.enabled> <button ng-click=startAddTask() class=add-child-btn>{{::_("Add sub-card...")}}</button> <a ui-sref="project_board({projectId: project.slug, cardRef: card.ref})" class="btn btn-default" ng-if="!card.is_template && (card.board_created || (canCreateSubBoards && !card.is_link))" ng-click="onClose({preventLocationChange: true})"><i class="fa fa-sign-in"></i> {{card.board_created ? _('Jump to sub-board') : _('Create sub-board')}}</a> </div> <div class="text-composer card-view-children-input" text-composer=taskCreatorOption ng-if=taskCreatorOption.enabled is-focused=taskCreatorOption.enabled></div> <span class=email-create ng-hide="taskCreatorOption.enabled || !createEmail || project.is_template" ng-bind-html="::_trust('You can also send emails to <a href=mailto:{email}>{email}</a> to create sub-cards', {email: createEmail})"> </span> </div> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/change-history.html", `<div> <span ng-if=loading> <i class="fa fa-spin fa-spinner"></i> {{::_('Loading')}} </span> <span ng-if="!loading && !groupTypes.length"> {{::_('This card has not been moved between groups yet.')}} </span> <div class=nav-tabs ng-if="!loading && groupTypes.length"> <div class=nav-tabs-tabs> <a class=nav-tab ng-repeat="gt in groupTypes" ng-class="{'active': groupType === gt}" href ng-click=select(gt)>{{gt.name}}</a> </div> </div> <table class="table table-condensed table-hover table-striped" ng-if="!loading && groupTypes.length"> <tr> <th>{{::_('Group')}}</th> <th>{{::_('Date')}}</th> <th ng-show=groupType.one_group_per_card>{{::_('Duration')}}</th> <th>{{::_('User')}}</th> </tr> <tr ng-repeat="item in history"> <td>{{item.group}}</td> <td>{{item.created_at.format('L')}}</td> <td ng-show=groupType.one_group_per_card>{{item.duration}}</td> <td>{{item.user ? (item.user.display_name + (item.user.deleted ? ' (' + _('deleted') + ')' : '')) : _('Unknown')}}</td> </tr> </table> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/stream.html", `<div class=card-view-stream ng-class="{'reverse': streamReversed}"> <activities store=store card=target empty-message="{{isConnected ? _('No items') : _('No items / Some items might be missing while offline')}}" actions=activitiesActions show-request-indicator-in-comment=true reversed=streamReversed is-stream=true></activities> <div class=comment-form ng-if="canComment || canLog"> <img class=card-comment-avatar ng-src={{::currentUser|userAvatarUrl}} ng-if=!isScreensizeXS()> <div class=content-composer-wrapper ng-if=isCommentCreating> <content-composer options=newCommentCreatorOptions on-submit="saveComment(submittedText, commentShowInRequest)" on-cancel=closeCommentEditor(cancelledText) on-draft-change=refreshCommentDraft(draftedText) class=inline-buttons></content-composer> <div class="form-check form-check-inline form-switch" ng-show=target.from_request> <input class=form-check-input type=checkbox role=switch ng-model=commentShowInRequest id=showInRequest> <label class=form-check-label for=showInRequest>{{::_('Show in request')}}</label> </div> </div> <div class=card-view-log-composer-wrapper ng-if=isLogCreating> <div class=card-view-log-composer> <h2> {{::_('Log something')}} <a href datepicker-dropdown=logCreator.date datepicker-options=logCreator.datepickerOptions on-date-change="updateLogDate($start, $end)"> {{logCreator.dateLabel}}</a> {{::_('under {logtype}', {logtype: logCreator.type.name})}} </h2> <attribute-form project=project obj=logCreator.obj data=logCreator.data attribute-group=logCreator.attributes attributes-editable=logCreator.editable attributes-movable=logCreator.editable attribute-type-available-for=logs show-empty-notice=true></attribute-form> </div> <button class="btn btn-success" ng-click=submitLog() ng-disabled="logCreator.attributes.length === 0">{{::_('Save')}}</button> <button class="btn btn-cancel btn-icon" ng-click=cancelLogCreator()><i class="fa fa-times"></i></button> </div> <div class=card-view-stream-actions ng-if="!isCommentCreating && !isLogCreating" ng-class="{'has-draft': commentDraft}" ng-click=openCommentEditor()> <a href ng-if=canComment>{{commentButtonLabel}}</a> <span ng-if="canComment && canLog">{{::_('or')}}</span> <a href ng-if=canLog ng-click=$event.stopPropagation() drop-menu=logsDropMenu>{{::_('log something')}} <span class=bi-caret-down-fill></span></a> </div> <span class=email-comment ng-hide="isCommentCreating || isLogCreating || !commentEmail || project.is_template" ng-bind-html="::_trust('You can also send emails to <a href=mailto:{email}>{email}</a> to leave comments', {email: commentEmail})"> </span> </div> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/attribute-group.html", '<div> <attribute-group container="{{ container }}" obj=card attribute-group=attributes project=project class="card-view-attributes-form fluid" editable=editable attributes-editable=attributesEditable show-add=true filter-attributes-using=filterAttributesUsing on-add-attribute="addAttribute($type, $position, $onlyModel)" attr-show-only-model-option=!model.base_model_id show-empty-notice=true></attribute-group> </div> ');
  $templateCache.put("/static/app/modals/card-view/templates/panels.html", `<div class=card-view-panels> <div class=card-view-panels-groups> <div class=card-view-panel-group ng-repeat="panelGroup in panelGroups" ng-class="{'empty': panelGroup.panels.length === 0}"> <div class="card-view-panel-tabs nav-tabs" ng-if=!isScreensizeXS()> <ul class=nav-tabs-tabs card-view-panel-group ng-hide="panelGroups.length === 1 && !panelGroup.panels.length"> <li ng-repeat="panel in panelGroup.panels" class=nav-tab ng-class="{active: panelGroup.current.name === panel.name, 'editing': panel.editing}" ng-click="panelGroup.current = panel" data-panel-name={{panel.name}}> <span ng-dblclick=startEditTab(panel) ng-hide=panel.editing>{{panel.title(target)}}</span> <form ng-submit="updateTab(panelGroup, panel, newPanelName)" ng-if=panel.editing> <input class=form-control type=text ng-model=newPanelName ng-required auto-focus placeholder="{{::_('Tab name')}}" ng-blur=stopEditTab(panel)> </form> <div class=dropdown ng-if="panelGroup.current.name === panel.name && (!!panel.options || attributesEditable)"> <a href class="panel-tabs-btn dropdown-toggle" data-toggle=dropdown ng-hide=panel.editing> <i class=bi-caret-down-square></i> </a> <ul class=dropdown-menu auto-drop-position> <li ng-repeat="opt in panel.options" ng-class="{'divider': opt.divider}"> <a href ng-click="togglePanelOption(panel, opt)" ng-show=!opt.divider> {{opt.title}} <i ng-class="{'fa fa-check': opt.enabled(target)}"></i> </a> </li> <li class=divider ng-show="panel.options.length && attributesEditable"></li> <li ng-show="!panel.builtin && attributesEditable"> <a href ng-click=startEditTab(panel)>{{::_('Rename tab')}}</a> </li> <li class=divider ng-show="!panel.builtin && attributesEditable"></li> <li ng-show="attributesEditable && (panelGroup.panels.length > 1 || panelGroups.indexOf(panelGroup) > 1)"> <a href ng-click="movePanelUpDown(panelGroup, panel, -1)">{{::_('Move to section above this one')}}</a> </li> <li ng-show="attributesEditable && (panelGroup.panels.length > 1 || panelGroups.indexOf(panelGroup) < panelGroups.length - 2)"> <a href ng-click="movePanelUpDown(panelGroup, panel, 1)">{{::_('Move to section under this one')}}</a> </li> <li class=divider ng-show=attributesEditable></li> <li ng-show="!panel.builtin && attributesEditable"> <a href ng-click=removeTab(panel)>{{::_('Delete tab')}}</a> </li> <li ng-show="panel.builtin && attributesEditable"> <a href ng-click="hideTab(panelGroup, panel)">{{::_('Hide tab')}}</a> </li> </ul> </div> </li> </ul> <button class=add-tab-btn drop-menu=addTabMenu ng-click=startAddTab(panelGroup) uib-tooltip="{{::_('Add custom tab to organize fields')}}" tooltip-placement=right ng-show="(panelGroup.panels.length || panelGroups.length === 1) && attributesEditable"><i class="fa fa-ellipsis-v"></i></button> </div> <div class=card-view-panel ng-if="panelGroup.current && !isScreensizeXS()"> <dynamic-directive directive={{panelGroup.current.directive}}></dynamic-directive> </div> <div class=card-view-panel ng-repeat="panel in panelGroup.panels" ng-if=isScreensizeXS()> <h3 class=card-view-panel-header>{{panel.title(target)}}</h3> <dynamic-directive directive={{panel.directive}}></dynamic-directive> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/view.css.html", ".{{ wrappercls }} .card-view-header { background: {{ color }}; color: {{ textColor }}; } .{{ wrappercls }} .card-view-loader div { border-color: {{ mostReadable('#fff', [textColor, color]) }}; } .{{ wrappercls }} .card-view-header-highlight { background-color: {{ getReadableTransparentColor(color, 0.05, 0.08) }}; } .{{ wrappercls }} .card-view-header-highlight > .btn.card-view-header-btn { border-color: {{ getReadableTransparentColor(color, 0.1, 0.2) }}; } .{{ wrappercls }} .card-view-header-inner h2 a:hover, .{{ wrappercls }} .card-view-header-inner h2 a:focus, .{{ wrappercls }} .card-view-header-inner h2 a:active { background-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; } .{{ wrappercls }} .card-view-header-left .parents a:hover, .{{ wrappercls }} .card-view-header-left .parents a:focus, .{{ wrappercls }} .card-view-header-left .parents a:active, .{{ wrappercls }} .card-view-header-left .parents .btn:hover, .{{ wrappercls }} .card-view-header-left .parents .btn:focus, .{{ wrappercls }} .card-view-header-left .parents .btn:active { background-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; } .{{ wrappercls }} .btn.card-view-header-btn { color: {{ textColor }}; } .{{ wrappercls }} .btn.card-view-header-btn:not(.btn-badge):hover, .{{ wrappercls }} .btn.card-view-header-btn:not(.btn-badge):focus, .{{ wrappercls }} .btn.card-view-header-btn:not(.btn-badge):active, .{{ wrappercls }} .btn.card-view-header-btn:not(.btn-badge).drop-enabled, .{{ wrappercls }} .card-view-header-left .btn.btn-icon:hover, .{{ wrappercls }} .card-view-header-left .btn.btn-icon:focus, .{{ wrappercls }} .card-view-header-left .btn.btn-icon:active, .{{ wrappercls }} .card-view-header-left .btn.btn-icon.drop-enabled, .{{ wrappercls }} .card-view-header-left .btn-group.dropdown.open .dropdown-toggle { background-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; } .{{ wrappercls }} .btn.card-view-header-btn.card-model-btn:not(.editable):hover { background-color: transparent; } @media screen and (max-width: 767px) { .{{ wrappercls }} .card-view-header-right { background-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }} }}; } } ");
  $templateCache.put("/static/app/modals/card-view/templates/view.html", `<div class=card-view ng-class=themeName> <div class=card-view-banner ng-if=card.is_link> <span class=ref>#{{card.ref}}</span> <span class=message> {{::card.broken_link ? _('Broken link') : card.link_has_own_attributes ? _('This card points to another card') : _('The card below is the target of your link')}} <span ng-if=card.is_archived>({{::_('The link is archived')}})</span> </span> <a ng-click=openModal(target.link) class="btn mod-card-view-banner" ng-show=target.is_link ng-if=!isShared> {{::_('Go to target')}} <i class="fa fa-sign-in right"></i> </a> <button type=button ng-if="loaded && linkActionsParams && !card.link_has_own_attributes && !card.is_template && !target.is_template" card-actions-menu-toggle=linkActionsParams uib-tooltip="{{::_('Link settings')}}" tooltip-placement=left tooltip-popup-delay=0 class="btn btn-icon mod-card-view-banner"> <i class="fa fa-chain" ng-if=::!card.broken_link></i> <i class="fa fa-chain-broken" ng-if=::card.broken_link></i> </button> </div> <div class=card-view-banner ng-if=project.is_template> <i class="fa fa-magic"></i> <span class=message>{{::_('This card belongs to a workspace template')}}</span> </div> <div class=card-view-banner ng-if="target.is_archived || target.is_parent_archived"> <i class="fa fa-archive"></i> <span class=message>{{::target.is_parent_archived ? _('A parent of this card has been archived') : _('This card is archived') }}</span> <a class=btn ng-if="target.is_archived && canArchiveTarget" ng-click=restore(target)><i class="fa fa-repeat fa-rotate-270"></i> {{::_('Restore')}}</a> </div> <div class=card-view-banner ng-if=target.is_template> <i class="fa fa-refresh fa-rotate-90"></i> <span class=message>{{::_('Template for recurring card')}}</span> </div> <div class=card-view-header ng-class="[target.finished ? 'finished' : '', 'card-state-' + target.state]" auto-focus> <div class=cover-image-container ng-if=imageCoverUrl> <div ng-style="{'background-image': 'linear-gradient(rgba(0, 0, 0, 0.6),rgba(0, 0, 0, 0.6)), url(' + imageCoverUrl + ')'}"></div> </div> <div class=card-view-header-inner ng-class="{'covered': imageCoverUrl}"> <div class=card-view-header-left> <h2 ng-show="!loaded || targetNotLoaded">{{card.title}}</h2> <h2 ng-hide="titleEditorOptions.enabled || !loaded || targetNotLoaded"> <a href ng-if=canRenameTarget ng-click=startEditTitle()>{{ target.title }}</a> <span ng-if=!canRenameTarget>{{ target.title }}</span> </h2> <div class=text-composer ng-if="canRenameTarget && loaded" ng-show=titleEditorOptions.enabled is-focused=titleEditorOptions.enabled init-value=target.title text-composer=titleEditorOptions></div> <a class=ref ng-if="target.ref && !isLocked && !target._temp && !isShared" navigate-to="{{::projectRouteHref(project, target)}}" ng-click=onClose()>#{{::target.ref}}</a> <span class=ref ng-if="target && !target._temp && target.ref && (isLocked || isShared)">#{{::target.ref}}</span> <span class=ref ng-if="target && !target._temp && target.id && (!target.ref && target.ref !== 0)"><i class="fa fa-spin fa-spinner"></i></span> <span class=ref ng-if=target._temp><i class="fa fa-refresh"></i></span> <span class=parents ng-show=target.parent_id> {{::_('in')}} <span ng-repeat="parent in targetPath track by $index"> <a navigate-to={{::parent.href}} ng-if=parent.href ng-click=onClose()>{{::parent.title}}</a> <span ng-if="!parent.href && isShared">{{::parent.title}}</span> <button class="btn btn-link" ng-click="openModal(parent, {showArchived: $scope.showArchived})" ng-if="!parent.href && !isShared">{{::parent.title}}</button> </span> </span> <span class=parents ng-show=!target.parent_id> {{::_("This card represents a workspace")}} </span> <div class="group dropdown" ng-class="{'archived': spec[0].is_archived}" ng-if=!target.is_template ng-repeat="spec in groups"> <a href type=button ng-if=spec[3] groups-menu-toggle=spec[2] ng-style="{'background-color': spec[0].color || '#eee', 'color': textColor(spec[0].color, null, null, '#777')}"> <i ng-class="(spec[0].icon || spec[1].icon)|iconClass" ng-show="spec[0].icon || spec[1].icon"></i> {{spec[0].title}} <span ng-show=spec[0].end_date> <i class="fa fa-clock-o"></i> {{spec[0].end_date|date}} </span> </a> <span type=button ng-if=!spec[3] ng-style="{'background-color': spec[0].color || '#eee', 'color': textColor(spec[0].color, null, null, '#777')}"> <i ng-class="(spec[0].icon || spec[1].icon)|iconClass" ng-show="spec[0].icon || spec[1].icon"></i> {{spec[0].title}} <span ng-show=spec[0].end_date> <i class="fa fa-clock-o"></i> {{spec[0].end_date|date}} </span> </span> </div> <button type=button class="btn btn-icon" ng-if="groupTypesMenuFactoryParams && target.id" group-types-menu-toggle=groupTypesMenuFactoryParams uib-tooltip="{{::_('Add to contexts')}}" hide-offline><i class=bi-plus></i></button> <div class="btn-group dropdown" ng-if="target && !target.is_template && target.id && target.parent_id" hide-offline> <button type=button ng-click="history = true" class="btn btn-icon dropdown-toggle" data-toggle=dropdown uib-tooltip="{{::_('History of group changes')}}" ng-show=!isShared> <i class=bi-clock-history></i> </button> <div class="dropdown-menu change-history" auto-drop-position> <card-change-history card=target in-dropdown=true ng-if=history></card-change-history> </div> </div> <button type=button class="btn btn-icon" ng-if=showSharedIcon drop-menu=shareMenuConfig uib-tooltip="{{::_('This card is being shared using a link')}}"><i class=bi-share-fill></i></button> </div> <div class=card-view-header-right ng-hide=!target> <button type=button class="btn btn-icon card-view-header-btn visible-xs-inline-block" ng-show=showClose ng-click=onClose()><i class="fa fa-arrow-left"></i></button> <button type=button ng-show="target.parent_id && (!isShared || model.model.base_model_type !== 'project')" class="btn card-view-header-btn card-model-btn" ng-class="{'editable': canOpenModelsMenu}" ng-disabled=!canOpenModelsMenu models-menu-toggle=modelsMenuFactoryParams> <i class="fa model-indicator" ng-class=model.indicator|iconClass ng-show=model.indicator> </i>{{model.model.name}}<span class=bi-caret-down-fill ng-if=canOpenModelsMenu></span> </button> <button type=button ng-if="canSubscribeToTarget && loaded" card-subscription-menu-toggle=target ng-class="{'btn-badge': remindersCount}" class="btn card-view-header-btn card-subscription-btn btn-icon" uib-tooltip="{{ _('Subscription and reminders') + (remindersCount ? (' - ' + _n('{count} reminder', '{count} reminders', remindersCount)) : '') }}"> <span ng-if=remindersCount>{{remindersCount}}</span> <i class=fa ng-class="{'fa-bell': subscribedToTarget, 'fa-bell-slash-o': !subscribedToTarget}" style=width:15px;></i> </button> <a ng-if="!target.parent_id && !!project.slug" class="btn btn-default" ui-sref="project({projectId: project.slug})" ng-click=onClose()> {{::_("Go to workspace")}} </a> <button type=button ng-if="!target.is_template && loaded && targetActionsParams" card-actions-menu-toggle=targetActionsParams drop-config="{classes: 'card-actions-menu'}" class="btn btn-icon card-view-header-btn" uib-tooltip="{{::_('More options')}}"><i class=bi-three-dots></i></button> <button type=button class="btn btn-icon card-view-header-btn hidden-xs" ng-show=showClose ng-click=onClose() uib-tooltip="{{::_('Close')}}"><i class=bi-x-lg></i></button> </div> </div> <div class=card-view-header-highlight ng-if=target.from_request> <i class="fa fa-inbox"></i> <span ng-bind-html="_trust('This card is a request from {requester} through {form}', {requester: requesterNameHtml, form: requestFormNameHtml})"></span> <a ng-href={{requestUrl}} target=_blank class="btn card-view-header-btn ms-2" ng-if=!isShared uib-tooltip="{{::_('Request link')}}" tooltip-placement=right><i class="fa fa-external-link"></i>{{::_('Open')}}</a> </div> <div class=card-view-header-highlight ng-if=target.finished> <i ng-class=state.icon|iconClass ng-show=state.icon></i> {{_("This card has been marked as {label} after {time}", {label: _(state.label), time: finishedDuration})}} <button type=button ng-show=canEditTarget class="btn card-view-header-btn ms-2" states-menu-toggle=statesMenuFactoryParams>{{::_('change')}} <span class=bi-caret-down-fill></span></button> </div> <div class=card-view-header-highlight ng-repeat="state in automationStates"> <i class="fa fa-bolt"></i> {{state.error ? _("An error has occured while running automation {rule_name}: {error}", { rule_name: state.rule_name, error: state.error}) : _("Automation {rule_name} is running for this card.", { rule_name: state.rule_name}) }} {{state.step ? _("It will resume when {trigger}", {trigger: state.waiting_on.triggers_when_label}) : ''}} <button type=button ng-show="canEditTarget && (state.step || state.error)" class="btn card-view-header-btn ms-2" ng-click=cancelAutomationState(state)>{{state.error ? _('Dismiss') : _('Cancel')}}</button> </div> <div class="card-view-header-highlight card-toolbar" ng-if=showCardToolbar> <button ng-repeat="action in toolbarActions" type=button class="btn card-toolbar-btn btn-sm btn-action" uib-tooltip="{{ _('Click to run this action') }}" ng-disabled="isTemplateMode() || !action.enabled" ng-hide="!canEditToolbar && !action.enabled" ng-click=runToolbarAction(action) ng-style="isTemplateMode() ? {} : {
          'background-color': action.background_color || '',
          'color': getTextColor(action.background_color)
        }"> <i ng-if="runningRuleId === action.id" class="fa fa-spinner fa-spin"></i> <i ng-if="runningRuleId !== action.id" class="{{ action.icon ? 'fa fa-' + action.icon : 'bi-play' }}"></i> <span>{{ action.name }}</span> </button> <button type=button class="btn card-view-header-btn btn-icon btn-sm" ng-if=canEditToolbar ng-click=openAddAutomationMenu($event) uib-tooltip="{{ _('Add a button triggering an automation') }}"> <i class=bi-plus></i> </button> </div> </div> <div ng-show=!loaded class="card-view-body card-view-body-message"> <i class="fa fa-spin fa-spinner"></i> </div> <div ng-show=targetNotLoaded class="card-view-body card-view-body-message"> <i class="fa fa-warning"></i> <p>{{targetNotLoadedMessage}}</p> </div> <div class=card-view-body ng-class="{'finished': target.finished}" ng-show="loaded && !targetNotLoaded"> <div class=no-internet ng-if="!isConnected() && !isConnectionManagerDisabled()"> <i class="fa fa-warning"></i> {{::_("The information on this card may not be up to date due to lack of Internet connection")}} </div> <div class=no-internet ng-if=target._temp> <i class="fa fa-refresh"></i> {{::_("This card has not been synchronized yet")}} </div> <div class=hidden-attributes ng-if="model.model.only_show_own_attributes && canRevealHiddenAttrs"> <i class=bi-eye-fill></i> <span ng-bind-html="_trust('Only <span>{modelName}</span> card type fields are visible on this card', { modelName: model.model.name})"></span> ( <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=filterAttributesUsing.model.disabled ng-change=updateAttributeGroupFilter() id=showAllAtttributesInCardView> <label class=form-check-label for=showAllAtttributesInCardView>{{::_("Reveal hidden fields")}}</label> </div> ) </div> <div class=card-view-sidebar ng-class="{'empty': isSidebarEmpty}"> <attribute-group ng-if=isScreensizeXS() obj=target editable=directiveEditable attributes-editable=attributesEditable attributes-movable=attributesMovable show-add=true attribute-group=attributes container=__top__ project=project filter-attributes-using=filterAttributesUsing add-btn-position=bottom on-add-attribute="addAttribute($type, '__top__', $position, $onlyModel)" attr-show-only-model-option=!model.model.base_model_id show-empty-notice=!isShared></attribute-group> <attribute-group obj=target attribute-group=attributes editable=directiveEditable filter-attributes-using=filterAttributesUsing attributes-editable=attributesEditable attributes-movable=attributesMovable container show-add=!isSidebarEmpty project=project add-btn-position=bottom on-add-attribute="addAttribute($type, null, $position, $onlyModel)" attr-show-only-model-option=!model.model.base_model_id></attribute-group> </div> <div class=card-view-content> <attribute-group class="card-view-attributes-form fluid" ng-if=!isScreensizeXS() obj=target attribute-group=attributes editable=directiveEditable container=__top__ attributes-editable=attributesEditable attributes-movable=attributesMovable show-add=true project=project filter-attributes-using=filterAttributesUsing on-add-attribute="addAttribute($type, '__top__', $position, $onlyModel)" attr-show-only-model-option=!model.model.base_model_id show-empty-notice=!isShared> </attribute-group> <div class="card-view-panel card-view-panel-pinned-comment" ng-if=pinnedComment> <h3 class="card-view-panel-header visible-xs-inline-block">{{::_('Pinned comment')}}</h3> <div card-comment class="card-comment pinned-comment" comment=pinnedComment card=target store=stream actions=pinnedCommentActions on-add-attribute="addAttribute($type, null, $position, $onlyModel)" attr-show-only-model-option=!model.model.base_model_id></div> </div> <card-view-panels ng-if=loaded></card-view-panels> </div> </div> <ul ng-if="::(isShared || isEmbedded())" class="list-unstyled list-inline powered-by"> <li> <a href=https://kantree.io target=_blank>{{::_('Powered by Kantree')}}</a> </li> <li ng-if=::!isAuthenticated()> <a href ng-click=authentication.login()>{{::_('Login')}}</a> </li> <li ng-if=::!isAuthenticated()> <a href ng-click=authentication.signup()>{{::_('Signup')}}</a> </li> </ul> </div> `);
  $templateCache.put("/static/app/modals/card-view/templates/logs.html", `<div class=card-view-logs> <table class="table table-bordered table-striped" ng-show=!empty> <thead> <tr> <th></th> <th ng-repeat="logType in logTypes" colspan={{countAggregAttrs(logType)}}>{{logType.name}}</th> </tr> <tr> <th>{{::_('User')}}</th> <th ng-repeat="attr in attributes">{{attr.name}}</th> </tr> </thead> <tbody> <tr ng-repeat="user in usersWithLogs"> <td><img class="avatar me-1" ng-src={{::user|userAvatarUrl}}>{{user.display_name}}</td> <td ng-repeat="attr in attributes">{{aggregate(user, attr)}}</td> </tr> </tbody> <tfoot> <tr> <td><strong>{{::_('Total')}}</strong></td> <td ng-repeat="attr in attributes">{{total(attr)}}</td> </tr> </tfoot> </table> <p ng-show=empty>{{::_('No logs yet! Start logging data from the Activity tab')}}</p> </div> `);
  $templateCache.put("/static/app/modals/preview-pdf/pdf-modal.html", '<button type=button class="btn-close btn-close-floating" ng-click=$dismiss()></button> <div class=modal-body> <iframe ng-attr-src={{url}}></iframe> </div> ');
  $templateCache.put("/static/app/modals/share-embed/share-embed-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Share & embed')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class=form-group> <label class=form-label>{{::_('Share the following link:')}}</label> <copyable-readonly-input value=$ctrl.resolve.url show-qrcode=true></copyable-readonly-input> </div> <div class=form-group> <label class=form-label>{{::_('Use the following HTML code to embed on your website:')}}</label> <textarea ng-model=$ctrl.html readonly width=100% rows=5 class=form-control></textarea> </div> </div> <div class=modal-footer> <button class="btn btn-default" type=button ng-click=$ctrl.dismiss()>{{::_('Close')}}</button> </div> `);
  $templateCache.put("/static/app/modals/form-selector/modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Select a form')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=panel ng-repeat="section in sections"> <h2 class=panel-heading>{{section.title}}</h2> <div class=list-group> <span class="list-group-item clickable" ng-click=$close(form) ng-repeat="form in section.forms"> <span class=list-group-item-description>{{form.name}}</span> </span> </div> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> </div> `);
  $templateCache.put("/static/app/modals/project-creator/creator.html", `<form ng-submit=$ctrl.create() name=projectCreator> <div class=project-creator-header ng-class="{'modal-header': !!$ctrl.asModal}"> <h2 ng-class="{'modal-title': !!$ctrl.asModal}">{{::$ctrl.title}}</h2> <button ng-if=!!$ctrl.asModal type=button class=btn-close ng-click=$ctrl.cancel()></button> </div> <div class=project-creator-body ng-class="{'modal-body': !!$ctrl.asModal}"> <div class="alert alert-warning mb-5" ng-if=$ctrl.createTemplate> <p><i class=bi-exclamation-triangle-fill></i> {{::_("Templates can be used to create workspaces using a pre-defined structure. They are not usable workspaces and shouldn't be used to carry your activites. You can also create a template from existing workspaces.")}}</p> </div> <div class=form-group ng-show="$ctrl.teams.length > 1"> <label class=form-label for=team>{{::_('Team:')}}</label> <select ng-options="spec as spec.name for spec in $ctrl.teams track by spec.uuid" ng-model=$ctrl.selectedTeam class=form-select ng-change=$ctrl.selectTeam($ctrl.selectedTeam) id=team></select> </div> <div class=form-group ng-show="!$ctrl.import || $ctrl.forceImporter === 'spreadsheet'"> <label class=form-label for=name>{{::$ctrl.nameFormLabel}}</label> <input class="form-control form-control-lg" type=text required auto-focus auto-focus-select ng-model=$ctrl.projectTitle id=name> </div> <project-importer ng-if="$ctrl.import && $ctrl.forceImporter !== 'spreadsheet'" force-importer=$ctrl.forceImporter hide-importers="['spreadsheet']" on-importer-selected="$ctrl.showSharingSettings = true" on-import-ready=$ctrl.onImportReady($data)></project-importer> <div class=form-group ng-show="$ctrl.showSharingSettings && !ctrl.createTemplate"> <label class=form-label>{{::$ctrl.sharingSettingsFormLabel}}</label> <project-sharing-settings is-template=$ctrl.createTemplate is-portfolio=$ctrl.createPortfolio org=$ctrl.org is-forced-public=$ctrl.isForcedPublic on-settings-changed="$ctrl.sharingSettings = $settings"></project-sharing-settings> </div> <div class=form-group ng-show=$ctrl.showSharingSettings> <label class=form-label>{{::$ctrl.colorFormLabel}}</label> <color-picker-palette color=$ctrl.color on-change="$ctrl.color = $color" empty-color="'#195753'"></color-picker-palette> </div> <project-importer ng-if="$ctrl.import && $ctrl.forceImporter === 'spreadsheet'" force-importer=$ctrl.forceImporter on-import-ready=$ctrl.onImportReady($data)></project-importer> <div class="form-group form-check form-switch mt-4" ng-show="$ctrl.template && $ctrl.template.id && !$ctrl.template.fromScratch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.onlyStructure id=copyOnlyStructure> <label class=form-check-label for=copyOnlyStructure> {{::_("Only use the workspace structure from the template, do not copy cards")}}</label> </div> <div class=form-group ng-if=::$ctrl.createPortfolio> <label class=form-label>{{::_("Select some workspaces to start with your portfolio (this can be done later)")}}</label> <org-project-selector ng-if=::!$ctrl.team org=$ctrl.org selected-projects=$ctrl.portfolioProjects is-multiple=true on-selected="$ctrl.portfolioProjects = $projects"></org-project-selector> <team-project-selector ng-if=::!!$ctrl.team team=$ctrl.team selected-projects=$ctrl.portfolioProjects is-multiple=true on-selected="$ctrl.portfolioProjects = $projects"></team-project-selector> </div> </div> <div class=project-creator-footer ng-class="{'modal-footer': !!$ctrl.asModal}"> <a ng-click=$ctrl.cancel() class="btn btn-default btn-ghost">{{::_('Cancel')}}</a> <button class="btn btn-cta" type=submit ng-disabled="$ctrl.projectCreator.$invalid || ($ctrl.import && !$ctrl.importData) || $ctrl.creating">{{$ctrl.createBtnLabel}}</button> </div> </form> `);
  $templateCache.put("/static/app/modals/project-creator/modal.html", "<project-creator on-created=projectCreated($project) on-cancelled=$dismiss() as-modal=true template=template org=org team=team project-title=projectTitle importer=importer default-view-mode=defaultViewMode create-template=createTemplate create-portfolio=createPortfolio> </project-creator> ");
  $templateCache.put("/static/app/modals/demo-signup/demo-signup-modal.html", `<form ng-submit=$ctrl.signup()> <div class=modal-header> <h3 class=modal-title>{{::_('Signup for Kantree')}}</h3> </div> <div class=modal-body ng-hide=$ctrl.loading> <div class=form-group> <label class=form-label for=signupEmail>Your work email address</label> <input type=email ng-model=$ctrl.email required class=form-control placeholder=you@company.com id=signupEmail> </div> </div> <div class=modal-loader ng-show=$ctrl.loading><i class="fa fa-spin fa-spinner"></i></div> <div class=modal-footer> <a class="btn btn-default btn-ghost" ng-click=$ctrl.onCancel()>{{::_('Cancel')}}</a> <button class="btn btn-cta" type=submit ng-disabled=$ctrl.loading>{{::_('Accept terms and signup')}}</button> </div> </form> `);
  $templateCache.put("/static/app/modals/file-select/file-select-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Select a file')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div ngf-select=$close($file) ngf-drop=$close($file) class=file-drop-zone> <i class="fa fa-cloud-upload"></i> {{::_('Click to select a file or drop your file here')}} </div> </div> `);
  $templateCache.put("/static/app/modals/assistant/modal.html", `<div class=modal-body> <div class=assistant-body ng-class="{'has-response': $ctrl.response}"> <div class="meta flex"> <div class="context flex" uib-tooltip="{{::_('Context that will be provided to the Assistant')}}"> <i class="bi bi-eye"></i> {{::_("Workspace")}} </div> <div class="context flex" ng-repeat="ctx in $ctrl.contextLabels" uib-tooltip="{{::_('Context that will be provided to the Assistant')}}" tooltip-popup-delay=0> <i class="bi bi-eye"></i> {{ctx.label}} <button ng-click=$ctrl.removeContext(ctx.key) uib-tooltip="{{::_('Remove context')}}" tooltip-placement=bottom><i class=bi-x></i></button> </div> <div class="status flex"> <div ng-show=$ctrl.running class=flex> <loading-indicator></loading-indicator> {{$ctrl.runningMessage}} </div> <div ng-show="!$ctrl.running && $ctrl.response.status === 'completed' && !$ctrl.response.error" class=flex> <i class="bi bi-check"></i> {{:: _('Job done') }} </div> <div ng-show="!$ctrl.running && $ctrl.response.status === 'completed' && $ctrl.response.error" class="flex text-danger"> <i class="bi bi-exclamation-octagon-fill"></i> {{:: _('An error occured') }} </div> </div> <button type=button ng-if=$ctrl.speechSupported ng-click=$ctrl.toggleSpeechRecognition() ng-class="{'text-success': $ctrl.speechActive}" uib-tooltip="{{ $ctrl.speechActive ? _('Stop recording') : _('Start voice chat') }}"> <i class=bi ng-class="{'bi-mic': !$ctrl.speechActive, 'bi-mic-fill': $ctrl.speechActive}"></i> </button> <div class=badge>BETA</div> </div> <div class="alert alert-danger" ng-show="$ctrl.response.status === 'completed' && $ctrl.response.error" ng-bind-html=$ctrl.response.error|markdown> </div> <div class=response ng-show="$ctrl.response.status === 'completed' && $ctrl.response.message" ng-bind-html=$ctrl.response.message|markdown> </div> </div> <textarea ng-model=$ctrl.prompt rows=2 ng-keydown=$ctrl.onKeyDown($event) auto-focus ng-disabled=$ctrl.running placeholder={{$ctrl.placeholder}} ng-class="{'continue': $ctrl.response}"></textarea> </div> `);
  $templateCache.put("/static/app/modals/terms/terms-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Update to our terms')}}</h3> </div> <div class=modal-body> <label class=form-label>{{::_('We have updated our terms and they require your validation')}}</label> <textarea class=form-control disabled ng-if=terms.content>{{terms.content}}</textarea> <p ng-if=terms.url><a ng-href={{terms.url}} target=_blank>{{terms.url}}</a></p> </div> <div class=modal-footer> <a class="btn btn-default pull-left" type=button ui-sref=account ng-click=$dismiss()>{{::_('Change or delete my account')}}</a> <button class="btn btn-success" ng-click=accept()>{{::_('Accept')}}</button> </div> `);
  $templateCache.put("/static/app/modals/help/modal.html", `<div class=modal-body> <button type=button class=btn-close ng-click=$dismiss()></button> <h1>{{::_('Help & support')}}</h1> <form ng-submit=$ctrl.doSearch() target=_blank ng-hide=$ctrl.help_site_url> <input class="form-control form-control-lg" ng-model=$ctrl.search placeholder="{{::_('Search for help')}}"> </form> <div class=links-grid> <a ng-href={{$ctrl.links.get_started}} target=_blank ng-hide=$ctrl.help_site_url><i class=bi-star-fill></i> {{::_('Get started')}}</a> <a ng-href={{$ctrl.links.guides}} target=_blank ng-hide=$ctrl.help_site_url><i class=bi-life-preserver></i> {{::_('User guides')}}</a> <a ng-href={{$ctrl.links.faq}} target=_blank ng-hide=$ctrl.help_site_url><i class=bi-question-circle-fill></i> {{::_('FAQ')}}</a> <a ng-href={{$ctrl.links.community}} target=_blank ng-show=$ctrl.links.community><i class=bi-people-fill></i> {{::_('Community')}}</a> <a ng-href={{$ctrl.help_site_url}} target=_blank ng-show=$ctrl.help_site_url><i class=bi-life-preserver></i> {{::_('Documentation')}}</a> </div> <div class=contact> <a ng-href={{$ctrl.ticket_url}} target=_blank class="btn btn-lg btn-primary" ng-show=$ctrl.ticket_url> <i class="fa fa-external-link"></i> {{::_('Open support ticket')}}</a> <a ng-href=mailto:{{$ctrl.serverConfig.support_email}} target=_blank class="btn btn-lg btn-primary" ng-show=$ctrl.serverConfig.support_email> <i class=bi-envelope></i> {{::_('Contact us at {email}', {email: $ctrl.serverConfig.support_email})}}</a> </div> <div class=small-links> <a href ng-click=$ctrl.showKeyboardShortcuts()>{{::_('Keyboard shortcuts')}}</a> <a ng-href={{$ctrl.demo_url}} target=_blank ng-if=$ctrl.serverConfig.payments_enabled>{{::_('Book a demo')}}</a> <a href=https://kantree.io/leave-review target=_blank>{{::_('Leave us a review')}}</a> </div> </div> `);
  $templateCache.put("/static/app/modals/camera/modal.html", "<div class=modal-header> <h3 class=modal-title>{{::_('Take a picture')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <camera-capture on-capture=onCapture($file)></camera-capture> </div> ");
  $templateCache.put("/static/app/modals/camera/capture.html", `<video width={{$ctrl.width}} height={{$ctrl.height}} autoplay></video><br> <button type=button ng-click=$ctrl.capture() class="btn btn-primary">{{::_('Capture')}}</button> <button type=button ng-if=$ctrl.withSwitchButton ng-click=$ctrl.switchCamera() class="btn btn-icon btn-lg btn-default"><i class=bi-arrow-repeat></i></button> <canvas></canvas> `);
  $templateCache.put("/static/app/modals/project-selector/modal.html", `<div class=modal-header> <h3 class=modal-title>{{::(options.isMultiple ? _('Select workspaces in {dir}', {dir: directoryBreadcrumb}) : _('Select a workspace in {dir}', {dir: directoryBreadcrumb}) )}}</h3> <button class=btn-close type=button ng-click=$dismiss()></button> </div> <div class=modal-body> <org-project-selector ng-if=::!options.team org=options.org selected-projects=projects is-multiple=options.isMultiple readonly=options.readonly on-selected=select($projects)></org-project-selector> <team-project-selector ng-if=::!!options.team team=options.team selected-projects=projects is-multiple=options.isMultiple readonly=options.readonly on-selected=select($projects)></team-project-selector> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=add() ng-disabled=!projects.length>{{::_('Select')}}</button> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/group-types.html", `<div class=project-settings-group-types-panel> <div ng-if=!selected> <div class=modal-help-message> <p> {{::_("Cards can be organized in groups. Each group belongs to a context.")}} </p> </div> <div class=panel> <div class=panel-heading> {{::_("Contexts specific to this workspace:")}} <button class="btn btn-primary btn-sm" ng-show=canManageGrouptypes() ng-click=create()> <i class=bi-plus-lg></i> {{::_('Create')}} </button> </div> <div class=panel-body ng-show=!projGroupTypes.length> <p class=panel-empty-message>{{::_('No contexts.')}}</p> </div> <ul class=list-group> <li class=list-group-item ng-repeat="groupType in projGroupTypes track by groupType.id"> <div class=list-group-item-description>{{::groupType.name}}</div> <button type=button class="btn btn-icon btn-sm btn-default" ng-click=select(groupType) ng-show=canManageGrouptypes() uib-tooltip="{{::_('Edit')}}"> <i class="fa fa-pencil"></i> </button> <button type=button class="btn btn-icon btn-sm btn-danger" ng-click="toggleGrouptype($event, groupType)" ng-show=canManageGrouptypes() uib-tooltip="{{::_('Delete')}}"> <i class="fa fa-trash"></i> </button> </li> </ul> </div> <div class=panel ng-show=hasOrgContexts> <div class=panel-heading> {{::_('Contexts shared by all workspaces:')}} <a class="btn btn-link" ui-sref="org.hub({slug: project.owner.slug, '#': 'contexts'})" ng-show="project.owner.type === 'org' && isOwnerOfProjectOwner" ng-click=$close(true)> <i class="fa fa-cog"></i> {{::_('Manage')}} </a> </div> <div class=panel-body ng-show=!orgGroupTypes.length> <p class=panel-empty-message>{{::_('No contexts.')}}</p> </div> <ul class=list-group> <li class=list-group-item ng-repeat="groupType in orgGroupTypes track by groupType.id"> <div class=list-group-item-description>{{::groupType.name}}</div> <kt-form-check ng-show=canManageGrouptypes() value=groupType.used_by.includes(project.id) switch=true on-change="toggleGrouptype(groupType, $isChecked)" tooltip="{{::_('Activate/Deactivate in this workspace')}}"> </li> </ul> </div> </div> <form ng-if=selected name=groupTypeForm> <h2>{{selected.id ? _('Edit a context') : _('Create a new context')}}</h2> <card-group-type-editor group-type=selected project=project></card-group-type-editor> <div class="d-block text-end"> <button class="btn btn-default btn-ghost" type=button ng-click=select()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-disabled=groupTypeForm.$invalid ng-click=save()>{{::_('Save')}}</button> </div> </form> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/members.html", `<div class=project-settings-members-panel> <div class=panel ng-if=members.owners.length> <div class=panel-heading> {{::_("Owner of the workspace")}} </div> <div class=panel-body> <solidjs-component component=MemberList members=members.owners></solidjs-component> </div> </div> <div class=panel ng-if=isOrgProject> <div class=panel-heading> {{::_("Members from the organization")}} </div> <div class=panel-body ng-if=!members.org.length> <p class=panel-empty-message>{{::_('No members.')}}</p> </div> <div class=panel-body ng-if=members.org.length> <solidjs-component component=MemberList members=members.org roles=roles.org filterable=true editable=canManageMembers show-remove=true on-remove=removeMember on-role-change=updateMemberRole></solidjs-component> <div class=mt-3 ng-show="isUserOrgMember && canManageMembers"> <button class="btn btn-primary" ng-click=openAddMemberModal()> <i class="fa fa-user-plus"></i> {{::_('Add members')}} </button> <button class="btn btn-link" ng-show=project.team_members_can_autojoin drop-menu=defaultRoleMenu>{{_('Default role: {0}', defaultRoleName())}} <i class=bi-caret-down></i></button> <button class="btn btn-link" ng-if=::!project.is_portfolio ng-click="switchPanel('roles')">{{::_('Manage roles')}}</button> </div> </div> </div> <div class=panel> <div class=panel-heading> {{isOrgProject ? _("Guests from outside the organization") : _("Guests")}} </div> <div class=panel-body ng-if="!members.guests.length && !invites.length"> <p class=panel-empty-message>{{::_("You haven't invited any guests yet")}}</p> <invite-form class=mt-3 on-submit="invite(emailOrUsernames, message, callbacks)" ng-show=canManageMembers auto-focus-input=false></invite-form> </div> <div class=panel-body ng-if="invites.length || members.guests.length"> <solidjs-component ng-show=members.guests.length component=MemberList members=members.guests roles=roles.guests editable=canManageMembers show-remove=true show-header=true on-remove=removeMember on-role-change=updateMemberRole></solidjs-component> <solidjs-component component=MemberList ng-show=invites.length members=invites roles=roles.guests editable=canManageMembers show-remove=true show-header=!members.guests.length can-edit-roles=false on-remove=removeInvite on-role-change=updateMemberRole on-resend-invite=resendInvite></solidjs-component> <invite-form class=mt-3 on-submit="invite(emailOrUsernames, message, callbacks)" ng-show=canManageMembers></invite-form> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/pii.html", `<div class=project-settings-pii-panel> <div class=modal-help-message> <p> {{::_("If you are using Kantree to store Personally Identifiable Information (PII), you may need to provide reports for privacy compliance.")}} </p> <p> {{::_("Kantree allows you to mark fields containing such information and extract all the data contained in them as a report.")}} </p> </div> <div class=panel ng-show="attributes.length > 0"> <div class=panel-heading> {{::_('Fields containing PII')}} </div> <table class=table> <thead> <tr> <th>{{::_('Name')}}</th> <th>{{::_('Description')}}</th> </tr> </thead> <tbody> <tr ng-repeat="attr in attributes"> <td>{{attr.name}}</td> <td>{{attr.description}}</td> </tr> </tbody> </table> </div> <div class=panel> <div class=panel-heading> {{::_('PII Report')}} </div> <div class=panel-body> <p> {{::_("Download a report of all the personally identifiable information stored in this workspace.")}} </p> <p ng-hide="attributes.length > 0"> <em>{{::_("To generate a report, check the option in fields containing such data.")}}</em> </p> <p ng-show="attributes.length > 0"> <select ng-model=format ng-options="format as format.title for format in formats track by format.name" class="form-select format-selector"></select> <button class="btn btn-primary" ng-click=generate()>{{::_('Download report')}}</button> </p> </div> </div> <div class=panel ng-show=canManageProjectOptions> <div class=panel-heading> {{::_('PII grouping field')}} </div> <div class=panel-body> <p> {{::_('Select a field to group personally identifiable information of a single person across cards.')}} </p> <div class=form-group> <label class=form-label for=piiIdAttr>{{::_('Field to use as common identifier across cards')}}</label> <select class=form-select ng-options="attr.id as attr.name group by attr.model_name for attr in attributes track by attr.id" ng-model=identifierAttributeId ng-disabled="identifierAttributeStatus === 'updating'" id=piiIdAttr> <option value></option> </select> <span class="badge-loading-success me-2"> <div ng-show="identifierAttributeStatus === 'updating'" class=ball-scale-ripple><div></div></div> <div ng-show="identifierAttributeStatus === 'saved'"><i class=bi-check></i><span>{{::_('Saved')}}</span></div> </span> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/recurring-cards.html", `<div class=project-settings-recurring-cards-panel> <div class=modal-help-message> {{::_("Recurring cards let you schedule and automate the creation of cards that need to be repeated daily, weekly or monthly.")}} </div> <loading-indicator ng-if=loading></loading-indicator> <recurring-card-tile ng-repeat="task in tasks track by task.id" task=task></recurring-card-tile> <div ng-if="(!tasks || !tasks.length) && !loading" class=empty> <p>{{::_('You don\\'t have any recurring cards yet.')}}</p> <p>{{::_('Make one recurring, it\\'s easy.')}}</p> <p><img ng-src="{{'/static/assets/'+ imgName + '.png'|baseUrl}}"></p> </div> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/models.html", `<div class=project-settings-models-panel> <div ng-if="!selectedModel && !selectedAttributes"> <div class=modal-help-message> <p>{{::_("Fields are like columns in a table, they let you define something specific on each card (eg.: assigned members).")}}</p> <p>{{::_("Cards can also have a type which can add additional fields.")}}</p> </div> <div class=form-group> <label class=form-label for=modelDefaultChildModel>{{::_("Default type for new cards:")}}</label> <select ng-options="model.id as model.name for model in availableDefaultModels" ng-model=$parent.defaultChildCardModelId class=form-select id=modelDefaultChildModel ng-disabled="defaultModelStatus === 'updating' || !canManageProjectOptions()"> </select> <span class="badge-loading-success me-2"> <div ng-show="defaultModelStatus === 'updating'" class=ball-scale-ripple><div></div></div> <div ng-show="defaultModelStatus === 'saved'"><i class=bi-check></i><span>{{::_('Saved')}}</span></div> </span> </div> <div class=panel ng-show=canManageProjectAttributes()> <div class=panel-heading> {{::_("Fields shared by all cards in the workspace")}} </div> <div class=panel-body> <p> <button class="btn btn-primary" ng-click=editProjectAttributes()> <i class="fa fa-pencil"></i> {{::_("Edit the workspace's fields")}} </button> </p> <div class="form-check form-switch" ng-show="project.owner.type === 'org'"> <input class=form-check-input type=checkbox role=switch ng-model=project.use_org_attributes ng-change=toggleUseOrgAttributes() id=projectUseOrgAttr> <label class=form-check-label for=projectUseOrgAttr>{{::_('Include fields shared by all workspaces')}}:</label> <span class=org-attributes-label ng-repeat="attr in orgBaseAttributesFormatted track by attr.id" uib-tooltip="{{attr.name + ' (' + attr.typeTitle + ')'}}"><i class={{attr.typeIcon|iconClass}}></i> {{attr.name}}</span> </div> </div> </div> <div class=panel> <div class=panel-heading> {{::_("Card types specific to the workspace:")}} </div> <div class=panel-body ng-show=!projModels.length> <p class=panel-empty-message>{{::_('No types have been created yet.')}}</p> </div> <ul class=list-group> <model-list-item ng-repeat="model in projModels track by model.id" model=model project=project show-duplicate=true></model-list-item> </ul> <button class="btn btn-primary btn-sm" ng-show=canCreateModel() ng-click=create()> <i class=bi-plus-lg></i> {{::_('Create')}} </button> </div> <div class=panel ng-if="project.owner.type === 'org'"> <div class=panel-heading> {{::_("Card types shared by all workspaces:")}} </div> <div class=panel-body ng-show=!orgModels.length> <p class=panel-empty-message>{{::_('No types have been created yet.')}}</p> </div> <ul class=list-group> <model-list-item ng-repeat="model in orgModels track by model.id" model=model project=project></model-list-item> </ul> <a class="btn btn-default btn-ghost" ui-sref="org.hub({slug: project.owner.slug, '#': 'models'})" ng-click=$close(true) ng-show="project.owner.type === 'org' && isOwnerOfProjectOwner"> <i class="fa fa-cog"></i> {{::_('Manage in organization')}} </a> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/roles.html", `<div class=project-settings-roles-panel> <div class=modal-help-message> <p> {{::_("Roles allow you to limit which user can interact with which parts of your workspaces.")}} </p> <p> {{::_("Kantree provides you with 4 non-modifiable default roles.")}} </p> <p> {{::_("You can create as many as you want and customize them for each workspace.")}} </p> </div> <div ng-show=!selectedRole> <div class="role-list mb-3"> <role-item ng-repeat="role in roles" editable="canManageMembers && isUserOrgMember && !project.is_archived" role=role on-role-open=selectRole($role) overriden="role.project_ids_with_specific_permissions.indexOf(project.id) >= 0"> </role-item> </div> <a class="btn btn-default btn-ghost" ui-sref="org.hub({slug: project.owner.slug, '#': 'roles'})" ng-click=$close(true) ng-show=isUserOrgMember> <i class="fa fa-cog"></i> {{::_('Manage in organization')}} </a> </div> <form name=roleForm class=role-infos ng-if=selectedRole> <h2 ng-if=!$parent.selectedRole.is_builtin>{{_('Customize {role} for this workspace', {role: $parent.selectedRole.name})}}</h2> <role-editor role=$parent.selectedRole project=project editable="isUserOrgMember && !project.is_archived"></role-editor> <role-exceptions class="d-block mt-3 mb-3" role=$parent.selectedRole project=project editable="isUserOrgMember && !project.is_archived"></role-exceptions> <button class="btn btn-success" type=submit ng-if="!$parent.selectedRole.is_builtin && isUserOrgMember && !project.is_archived" ng-disabled=roleForm.$invalid ng-click=saveRole()> {{::_('Save')}}</button> <button class="btn btn-default" ng-click=resetRole() ng-if="!$parent.selectedRole.is_builtin && $parent.selectedRole.project_ids_with_specific_permissions.indexOf(project.id) >= 0 && isUserOrgMember && !project.is_archived"> {{::_('Reset')}}</button> <button class="btn btn-default btn-ghost" ng-click=cancelEditRole()> {{::_('Back')}}</button> </form> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/ai.html", `<div class=project-settings-ai-panel> <div class=modal-help-message> <p> {{::_("Configure AI settings for this Workspace")}} </p> </div> <div class=panel> <div class=form-group> <label class=form-label>{{::_("Custom context:")}}</label> <textarea class=form-control ng-model=customContext rows=10></textarea> </div> <button class="btn btn-primary" ng-click=save()>{{::_('Save')}}</button> </div> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/appearance.html", `<div class=project-settings-appearance-panel> <div class=form-group> <label class=form-label>{{::_("Main theme color:")}}</label> <color-picker-palette color=project.color on-change=setBgColor($color) empty-color="'#195753'"></color-picker-palette> </div> <div class=form-group ng-show=image_cover_url> <label class=form-label>{{::_('Cover image:')}}</label> <div class=image> <div class=img> <img ngf-thumbnail=image_cover_url> </div> <button class="btn btn-default" ng-click=resetImageCover(null)>{{::_('Reset')}}</button> </div> </div> <div class=form-group> <label class=form-label>{{::_('Background image:')}}</label> <upload-image-field value=project.image_cover_url upload-url=uploadImageUrl upload-field-name=image_cover editable=true on-upload=setImageBg($data) on-reset=setImageBg(null)></upload-image-field> </div> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/model-list-item.html", `<li class=list-group-item> <div class=list-group-item-description> <span> {{::$ctrl.model.name}} <small ng-show=$ctrl.model.copied_from> <i class="fa fa-files-o"></i> {{ $ctrl.model.copied_from ? _('copied') : ''}} </small> </span> <p ng-show=$ctrl.model.concat_attributes> {{::_('Fields:')}} {{ $ctrl.model|formatModelAttributes:$ctrl.project }} </p> <div class=model-use-infos ng-if="!$ctrl.model.is_project_specific && $ctrl.canEditModel && $ctrl.isOwnerOfProjectOwner"> <button class="btn btn-link" ng-show=$ctrl.isNotUsed drop-menu=$ctrl.sharingMenu> {{::_('not used in any workspace')}} <span class=bi-caret-down-fill></span></button> <button class="btn btn-link" ng-show=$ctrl.isOnlyUsedInThisProject drop-menu=$ctrl.sharingMenu> {{::_('only used in this workspace')}} <span class=bi-caret-down-fill></span></button> <span ng-show=$ctrl.isUsedInOtherProjects>{{::_('used in other workspaces')}}</span> </div> </div> <button class="btn btn-icon btn-sm btn-default" ng-click=$ctrl.share() ng-show=$ctrl.canShareModel uib-tooltip="{{::_('Share this type with other workspaces')}}"> <i class="fa fa-share"></i> </button> <button type=button class="btn btn-icon btn-sm btn-default" ng-if=$ctrl.model.is_project_specific ng-click=$ctrl.edit() ng-show=$ctrl.canEditModel uib-tooltip="{{::_('Edit this type')}}"> <i class="fa fa-pencil"></i> </button> <button class="btn btn-icon btn-sm btn-default" ng-click=$ctrl.duplicate() ng-show="$ctrl.canCreateModel && $ctrl.showDuplicate" uib-tooltip="{{::_('Duplicate this type')}}"> <i class="fa fa-clone"></i> </button> <button type=button class="btn btn-icon btn-sm btn-danger" ng-if=$ctrl.model.is_project_specific ng-click=$ctrl.toggleModel(false) ng-show=$ctrl.canDeleteModel uib-tooltip="{{::_('Delete this type')}}"> <i class="fa fa-trash"></i> </button> <kt-form-check value=$ctrl.model.used_by.includes($ctrl.project.id) switch=true on-change=$ctrl.toggleModel($isChecked) ng-show=$ctrl.canToggleModel tooltip="{{::_('Activate/Deactivate in this workspace')}}" ng-if=!$ctrl.model.is_project_specific></kt-form-check> </li> `);
  $templateCache.put("/static/app/modals/project-settings/templates/modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Settings')}}</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class="modal-body modal-body-flex"> <ul class=modal-body-flex-sidebar> <li ng-repeat="panel in panels"> <button type=button class="btn btn-modal-nav" ng-class="{active: currentPanel === panel}" ng-click=switchPanel(panel.name)> {{::panel.title }} <i class="bi-chevron-right hidden-xs"></i> <i class="bi-chevron-down visible-xs-inline-block"></i> </button> </li> </ul> <p class=modal-help-message ng-show=!currentPanel> {{::_("No settings available")}} </p> <dynamic-directive directive="{{currentPanel && currentPanel.directive}}"></dynamic-directive> </div> `);
  $templateCache.put("/static/app/modals/project-settings/templates/options.html", `<div class=project-settings-options-panel> <div class="alert alert-danger" ng-if=project.is_archived> {{::_("This {projectType} is archived", {projectType: typeLabel})}} </div> <div class=panel> <div class=panel-heading>{{::uppercaseFirstLetter(typeLabel)}}</div> <div class=panel-body> <div class=form-group> <label class=form-label for=projectName>{{::_('{projectType} name', {projectType: typeLabel})}}</label> <div class="input-group title-input"> <input type=text class=form-control ng-model=title ng-required ng-change="titleChanged = true" id=projectName> <button type=button ng-click=rename(title) ng-disabled="!titleChanged && !canEditOptions" class=btn ng-class="{'btn-primary': titleChanged, 'btn-default': !titleChanged}">{{::_('Rename')}}</button> </div> </div> <div class=form-group> <p ng-if="project.owner.type === 'org'"> {{::_('This {projectType} belongs to', {projectType: typeLabel})}} <a ui-sref="org.hub({slug: project.owner.slug})" ng-click=$uibModalInstance.dismiss()><strong>{{project.owner.name}}</strong></a> <span ng-show=project.team>/ <a ui-sref="org.team.hub({slug: project.owner.slug, teamSlug: project.team.slug})" ng-click=$uibModalInstance.dismiss()><strong>{{project.team.name}}</strong></a></span> </p> <p ng-if="project.owner.type === 'user'"> {{::_('This is a personal {projectType}', {projectType: typeLabel})}} </p> <button ng-click=copyProject() class="btn btn-default" ng-if=::!project.is_template>{{::_("Copy {projectType}", {projectType: typeLabel})}}</button> <button ng-click=moveProject() class="btn btn-default" ng-if="::(!project.is_template && !project.is_portfolio)">{{::_("Move {projectType}", {projectType: typeLabel})}}</button> <button ng-click=saveAsTemplate() class="btn btn-default" ng-if="::(!project.is_template && !project.is_portfolio && project.owner.type === 'org')">{{::_('Save as a template')}}</button> </div> <div class=form-group ng-if="canManageMembers && !project.is_archived"> <label class=form-label>{{::_("Who can access")}}:</label> <project-sharing-settings org=org project=project sharing-settings-expanded=true can-select-default-role=false on-settings-changed="updateSharingSettings($settings, $isFirst)"></project-sharing-settings> </div> </div> </div> <div class=panel ng-show="canEditOptions && canPublishTemplate"> <div class=panel-heading> {{::_("Public template library")}} </div> <div class=panel-body> <p class=form-text> {{::_('Publish your {projectType} as part of the template library so anybody on Kantree can use it', {projectType: typeLabel})}} </p> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=publishTemplate ng-change=togglePublishTemplate() id=templatePublished> <label class=form-check-label for=templatePublished> {{::_("Published in the template library")}}</label> </div> <div ng-show=publishTemplate> <div class=form-group> <label class=form-label for=templateDesc>{{::_('Description:')}}</label> <textarea ng-model=templateDescription class=form-control ng-change=savePublishTemplateDebounced() id=templateDesc></textarea> </div> <div class=form-group> <label class=form-label>{{::_('Thumbnail image:')}}</label> <upload-image-field value=project.top_level_card.image_cover_url upload-url=uploadThumbnailUrl upload-field-name=image_cover on-upload=setTemplateThumbnail($data) on-reset=setTemplateThumbnail(null)></upload-image-field> </div> <div class=form-group> <label class=form-label>{{::_('Preview media (image or video):')}}</label> <upload-image-field value=project.template_preview_media_url upload-url=uploadImageUrl upload-field-name=template_preview_media on-upload=setTemplatePreviewMedia($data) on-reset=setTemplatePreviewMedia(null)></upload-image-field> </div> <div class=form-group> <label class=form-label for=templateLang>{{::_('Language:')}}</label> <select ng-model=templateLocale ng-change=savePublishTemplate() class=form-select ng-options="locale.code as locale.label for locale in availableLocales" id=templateLang></select> </div> <div class=form-group> <label class=form-label>{{::_('Tags:')}}</label> <ui-select multiple tagging tagging-label="({{::_('new tag')}})" ng-model=$parent.templateTags on-remove=savePublishTemplate() on-select=savePublishTemplate()> <ui-select-match>{{$item}}</ui-select-match> <ui-select-choices repeat="tag in (availableTags | filter: $select.search)">{{tag}}</ui-select-choices> </ui-select> </div> </div> </div> </div> <div class=panel> <div class=panel-heading> {{::_('Notifications')}} </div> <div class=panel-body> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=send_emails ng-change=toggleNotificationEmails() id=projectNotifEmail> <label class=form-check-label for=projectNotifEmail>{{::_('Email notifications enabled')}}</label> </div> </div> </div> <div class=panel> <div class=panel-heading> {{::_('Lock structure')}} </div> <div class=panel-body> <p class=form-text>{{::_('The structure of your {projectType} can be locked.', {projectType: typeLabel})}}</p> <span class=form-text>{{::_('While this option is enabled, these action are disabled:')}}</span> <ul> <li class=form-text>{{::_('Creating, editing, moving or deleting card fields and types (field values are still editable though)')}}</li> <li class=form-text>{{::_('Creating, editing, moving or deleting views (except private views)')}}</li> <li class=form-text>{{::_('More to come...')}}</li> </ul> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=locked_structure ng-change=toggleLockedStructure() id=projectLockedStructure> <label class=form-check-label for=projectLockedStructure>{{::_('Lock the structure of your {projectType}', {projectType: typeLabel})}}</label> </div> </div> </div> <div class=panel ng-show=isManager> <div class=panel-heading> {{project.is_template ? _('Delete') : _('Archive')}} </div> <div class=panel-body> <button class="btn btn-default" ng-click=archive() ng-show="!project.is_template && !project.is_archived"><i class=bi-archive></i> {{::_('Archive')}}</button> <button class="btn btn-default" ng-click=restore() ng-show=project.is_archived><i class=bi-arrow-return-left></i> {{::_('Restore')}}</button> <button class="btn btn-danger" ng-click=delete()><i class="fa fa-trash"></i> {{::_('Delete')}}</button> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/preview-video/video-modal.html", '<button type=button class="btn-close btn-close-floating" ng-click=$dismiss()></button> <div class=modal-body> <videogular vg-theme=theme vg-auto-play=true> <vg-media vg-src=sources vg-native-controls=true> </vg-media> </videogular> </div> ');
  $templateCache.put("/static/app/modals/release/versions/templates/v10.0.0-en.html", '<div class=modal-header> <h3 class=modal-title>Kantree v10 \u{1F389}</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> We are proud to release the 10th version of Kantree with <strong>major improvements in terms of interface, navigation and ease of use</strong>. </p> <p> This release is a stepping stone towards new developments to realize <a href=https://kantree.io/blog/company/the-future-of-kantree-after-version-9-0 target=_blank>our vision of a poweful collaborative work management platform for teams everywhere</a>. </p> <div class=feature-grid> <div> <i class=bi-inbox-fill></i> <span>Introducing the Inbox to follow the work your involved in across all projects</span> </div> <div> <i class=bi-layout-sidebar></i> <span>New sidebar and navigation flow</span> </div> <div> <i class=bi-plus-square-fill></i> <span>New way to add & manage views in workspaces</span> </div> <div> <i class=bi-columns-gap></i> <span>Renaming <em>projects</em> to <em>workspaces</em></span> </div> <div> <i class=bi-card-text></i> <span>Renaming <em>card models</em> to <em>card types</em></span> </div> <div> <i class=bi-speedometer2></i> <span>Renaming <em>reports</em> to <em>dashboards</em></span> </div> <div> <i class=bi-building></i> <span>Improved organization hub</span> </div> <div> <i class=bi-bullseye></i> <span>Work across only one or multiple organization at a time</span> </div> <div> <i class="fa fa-rocket"></i> <span>New way to create workspaces via the template library</span> </div> <div> <i class=bi-list-check></i> <span>Improved list view & form editor in workspaces</span> </div> <div> <i class="fa fa-superscript"></i> <span>New formula editor</span> </div> </div> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/blog target=_blank rel=noopener ng-click=$close()>Learn more on our blog</a> <button class="btn btn-default" type=button ng-click=$close()>Close</button> </div> ');
  $templateCache.put("/static/app/modals/release/versions/templates/v10.0.0-fr.html", `<div class=modal-header> <h3 class=modal-title>Kantree v10 \u{1F389}</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> Cette version est un jalon vers de nouveaux d\xE9veloppements pour r\xE9aliser <a href=https://kantree.io/fr/blog/societe/futur-de-kantree-apres-version-9-0 target=_blank>notre vision d'une plateforme de gestion du travail puissante et collaborative pour toutes les \xE9quipes</a>. </p> <div class=feature-grid> <div> <i class=bi-inbox-fill></i> <span>L'Inbox est le nouvel endroit vous permettant de suivre toutes vos conversations \xE0 travers toutes vos cartes</span> </div> <div> <i class=bi-layout-sidebar></i> <span>Nouvelle barre lat\xE9rale et nouvelle navigation</span> </div> <div> <i class=bi-plus-square-fill></i> <span>Nouvelle fa\xE7on de cr\xE9er et g\xE9rer les vues dans les workspaces</span> </div> <div> <i class=bi-columns-gap></i> <span>Renommage de <em>projets</em> en <em>workspaces</em></span> </div> <div> <i class=bi-card-text></i> <span>Renommage de <em>mod\xE8le de carte</em> en <em>type de carte</em></span> </div> <div> <i class=bi-speedometer2></i> <span>Renommage de <em>rapports</em> en <em>dashboards</em></span> </div> <div> <i class=bi-building></i> <span>Am\xE9lioration des pages d'organisation</span> </div> <div> <i class=bi-bullseye></i> <span>Travaillez \xE0 travers une ou plusieurs organisation</span> </div> <div> <i class="fa fa-rocket"></i> <span>Nouvelle fa\xE7on de cr\xE9er des projets \xE0 travers la biblioth\xE8que de gabarits</span> </div> <div> <i class=bi-list-check></i> <span>Am\xE9lioration de la vue liste et de l'\xE9diteur de formulaires dans les workspaces</span> </div> <div> <i class="fa fa-superscript"></i> <span>Nouvel \xE9diteur de formule</span> </div> </div> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/fr/blog target=_blank rel=noopener ng-click=$close()>En savoir plus sur notre blog</a> <button class="btn btn-default" type=button ng-click=$close()>Fermer</button> </div> `);
  $templateCache.put("/static/app/modals/release/versions/templates/v7.0.0-fr.html", `<div class=modal-header> <h3 class=modal-title>Introduction d'une nouvelle navigation dans Kantree</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> La navigation \xE0 travers l'application ainsi qu'un nouveau syst\xE8me de th\xE8me viennent d'\xEAtre mis \xE0 jour. Naviguer d'un projet \xE0 l'autre est maintenant beaucoup plus rapide et facilite les workflows multi-projets. </p> <hr> <div class="release-modal-section-container mod-side-screenshot"> <div class=release-modal-section> <h2>Nouvelle barre lat\xE9rale</h2> <p> L'ancien panneau de changement de projet a disparu! La nouvelle barre lat\xE9rale affiche maintenant tous vos projets \xE0 travers vos organisations, vos favoris et une liste bien pratique des derniers projets consult\xE9s. </p> <p> Quand vous ouvrez un projet, elle glissera pour afficher les vues de ce dernier. </p> <p> Vous pouvez ancrer n'importe quelle section (ex: projets r\xE9cemment ouvert) en bas de la barre lat\xE9rale pour facilement ouvrir ses projets depuis n'importe o\xF9. </p> </div> <img class=release-modal-screenshot ng-src="{{'/static/assets/releases/new-nav/new-sidebar.png'|baseUrl}}" alt="New sidebar" style="height: 230px"> </div> <hr> <div class=release-modal-section> <h2>Choisissez votre th\xE8me</h2> <p> Kantree propose maintenant 2 modes de couleur: l'un mettant l'emphase sur la barre lat\xE9rale et un autre sur la barre sup\xE9rieure, comme avant. </p> <div class=release-modal-widget-container ng-show="screensize !== 'xs'"> <div class=release-modal-widget-title>Essayez par vous-m\xEAme !</div> <div class=release-modal-widget> <span class="form-check mod-user-theme"> <label class="nav-theme-thumbnail mod-sidebar" ng-class="{'is-selected': theme === 'sidebar'}" for=themeSidebar> <div class=nav-theme-thumbnail-sidebar ng-style="{'background-color': getBoardColor()}"></div> <div class=nav-theme-thumbnail-right-container> <div class=nav-theme-thumbnail-topbar></div> <div class=nav-theme-thumbnail-content></div> </div> </label> <input class=form-check-input type=radio ng-model=theme value=sidebar ng-change=updateTheme() name=themeSidebar id=themeSidebar> <label class=form-check-label for=themeSidebar>Barre lat\xE9rale</label> </span> <span class="form-check mod-user-theme"> <label class="nav-theme-thumbnail mod-topbar" ng-class="{'is-selected': theme === 'topbar'}" for=themeTopbar> <div class=nav-theme-thumbnail-topbar ng-style="{'background-color': getBoardColor()}"></div> <div class=nav-theme-thumbnail-bottom-container> <div class=nav-theme-thumbnail-sidebar></div> <div class=nav-theme-thumbnail-content></div> </div> </label> <input class=form-check-input type=radio ng-model=theme value=topbar ng-change=updateTheme() name=themeTopbar id=themeTopbar> <label class=form-check-label for=themeTopbar>Barre sup\xE9rieure</label> </span> </div> </div> <p> Vous pouvez aussi facilement changer la couleur principale de Kantree <a ui-sref="account({'#': 'appearance'})" ng-click=$close()></a>depuis votre compte.</a> </p> </div> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/fr/blog target=_blank rel=noopener ng-click=$close()>En apprendre plus sur notre blog</a> <button class="btn btn-default" type=button ng-click=$close()>Fermer</button> </div> `);
  $templateCache.put("/static/app/modals/release/versions/templates/v7.0.0-en.html", `<div class=modal-header> <h3 class=modal-title>Introducing a new navigation in Kantree</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> We have released a major upgrade to the navigation in the application as well as a new theming system. Switching between projects is now much faster and will make multi-project workflows easier to work with. </p> <hr> <div class="release-modal-section-container mod-side-screenshot"> <div class=release-modal-section> <h2>New sidebar</h2> <p> The old project switcher is gone! The new sidebar now displays all of your projets across your teams, favorites and a very convenient list of recently opened projects. </p> <p> When you open a project, the sidebar will slide to display project views. </p> <p> You can dock any sections (eg.: recently opened projects) to the bottom of the sidebar to open them easily from anywhere. </p> </div> <img class=release-modal-screenshot ng-src="{{'/static/assets/releases/new-nav/new-sidebar.png'|baseUrl}}" alt="New sidebar" style="height: 230px"> </div> <hr> <div class=release-modal-section> <h2>Choose your own theme</h2> <p> Kantree now comes with two color layouts : one putting the emphasis on the sidebar and another one on the top bar as it was before. </p> <div class=release-modal-widget-container ng-show="screensize !== 'xs'"> <div class=release-modal-widget-title>Try it !</div> <div class=release-modal-widget> <span class="form-check mod-user-theme"> <label class="nav-theme-thumbnail mod-sidebar" ng-class="{'is-selected': theme === 'sidebar'}" for=themeSidebar> <div class=nav-theme-thumbnail-sidebar ng-style="{'background-color': getBoardColor()}"></div> <div class=nav-theme-thumbnail-right-container> <div class=nav-theme-thumbnail-topbar></div> <div class=nav-theme-thumbnail-content></div> </div> </label> <input class=form-check-input type=radio ng-model=theme value=sidebar ng-change=updateTheme() name=themeSidebar id=themeSidebar> <label class=form-check-label for=themeSidebar>Sidebar</label> </span> <span class="form-check mod-user-theme"> <label class="nav-theme-thumbnail mod-topbar" ng-class="{'is-selected': theme === 'topbar'}" for=themeTopbar> <div class=nav-theme-thumbnail-topbar ng-style="{'background-color': getBoardColor()}"></div> <div class=nav-theme-thumbnail-bottom-container> <div class=nav-theme-thumbnail-sidebar></div> <div class=nav-theme-thumbnail-content></div> </div> </label> <input class=form-check-input type=radio ng-model=theme value=topbar ng-change=updateTheme() name=themeTopbar id=themeTopbar> <label class=form-check-label for=themeTopbar>Topbar</label> </span> </div> </div> <p> You can also easily change the main color of Kantree from <a ui-sref="account({'#': 'appearance'})" ng-click=$close()>your user account.</a> </p> </div> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/blog target=_blank rel=noopener ng-click=$close()>Learn more on our blog</a> <button class="btn btn-default" type=button ng-click=$close()>Close</button> </div> `);
  $templateCache.put("/static/app/modals/release/versions/templates/v7.2.0-en.html", '<div class=modal-header> <h3 class=modal-title>Renaming attributes and organizations</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> After careful deliberation, <strong>we have decided to rename "attributes" to "fields" and "organizations" to "teams".</strong> </p> <hr> <div class="release-modal-section-container mod-side-screenshot"> <div class=release-modal-section> <h2>Renaming "attributes" to "fields"</h2> <p> Renaming "attributes" to "fields" feels like an obvious decision. At the beginning, "attribute" came from the fact that not all of them could be user input. Some of them will be buttons, special values, etc... We thought that "field" may have been confusing. In the end, "attribute" is far more confusing overall and "field" should have always been the only term. </p> </div> </div> <hr> <div class="release-modal-section-container mod-side-screenshot"> <div class=release-modal-section> <h2>Renaming "organizations" to "teams"</h2> <p> We are also renaming "organizations" to "teams". Our original plan included adding "teams" under "organizations". In the end we have decided to consider current "organizations" as "teams" and we will add a new concept on top of these new teams for multi-teams organizations. </p> </div> </div> <hr> <p> We are sorry for any disturbance this renaming may cause. However, we are convinced that this new terms are more aligned with current usage of Kantree. </p> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/blog target=_blank rel=noopener ng-click=$close()>Learn more on our blog</a> <button class="btn btn-default" type=button ng-click=$close()>Close</button> </div> ');
  $templateCache.put("/static/app/modals/release/versions/templates/v8.12.0-fr.html", `<div class=modal-header> <h3 class=modal-title>Mise \xE0 jour de l'interface</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> Nous profitons de l'\xE9t\xE9 pour faire quelques mises \xE0 jour de design et de navigation. </p> <hr> <div class=release-modal-section-container> <img class=release-modal-screenshot ng-src="{{'/static/assets/releases/moving-user-nav/moving-user-nav.png'|baseUrl}}" alt="D\xE9placement du menu utilisateur"> <div class=release-modal-section> <h2>Le menu utilisateur</h2> <p> Le menu utilisateur et le menu d'aide sont maintenant disponibles depuis la sidebar. Cela permet de lib\xE9rer un peu d'espace dans la barre de navigation pour les outils de projets. </p> </div> </div> <hr> <div class=release-modal-section-container> <img class=release-modal-screenshot ng-src="{{'/static/assets/releases/moving-user-nav/merging-searches.png'|baseUrl}}" alt="Fusionner les recherches"> <div class=release-modal-section> <h2>Fusion des recherches de projets et de cartes</h2> <p> Nous avons \xE9galement fusionn\xE9 la recherche globale de cartes avec la recherche de projets. Tous se passe maintenant dans le coin sup\xE9rieur droit de l'\xE9cran, rendant le tout plus intuitif est accessible. </p> </div> </div> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/fr/blog target=_blank rel=noopener ng-click=$close()>En apprendre plus sur notre blog</a> <button class="btn btn-default" type=button ng-click=$close()>Fermer</button> </div> `);
  $templateCache.put("/static/app/modals/release/versions/templates/v7.2.0-fr.html", `<div class=modal-header> <h3 class=modal-title>Renommage de "attribut" et "organisation"</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> Apr\xE8s une m\xFBre r\xE9flexion, <strong>nous avons pris la d\xE9cision de renommer les termes "attribut" en "champ" et "organisation" en "\xE9quipe".</strong> </p> <hr> <div class="release-modal-section-container mod-side-screenshot"> <div class=release-modal-section> <h2>Renommage de "attribut" vers "champ"</h2> <p> Renommer "attribut" en "champ" nous parait une d\xE9cision \xE9vidente. A l'origine, le terme "attribut" a \xE9t\xE9 choisi parce que tous les champs ne sont pas forc\xE9ment des champs de donn\xE9es utilisateurs. Certains peuvent \xEAtre des boutons, avoir des valeurs sp\xE9ciales, etc.... Dans ce contexte, nous pensions que le terme "champ" porterait \xE0 confusion. Avec l'exp\xE9rience, il en ressort que le terme "champ" est bien plus comprehensible que celui d'"attribut" et de ce fait nous revenons sur notre d\xE9cision initiale. </p> </div> </div> <hr> <div class="release-modal-section-container mod-side-screenshot"> <div class=release-modal-section> <p> <h2>Renommage de "organisation" vers "\xE9quipe"</h2> Nous avons aussi d\xE9cid\xE9 de renommer "organisation" en "\xE9quipe". Notre plan originel incluait l'ajout de la notion d'\xE9quipe \xE0 l'int\xE9rieur des organisations. Au final, nous pr\xE9f\xE9rons consid\xE9rer les organisations actuelles comme des \xE9quipes et nous ajouterons un nouveau concept au dessus de ces \xE9quipes pour les organisations souhaitant du multi-\xE9quipe. </p> </div> </div> <hr> <p> Nous sommes d\xE9sol\xE9s des perturbations que ce renommage pourrait engendrer. Cependant, nous sommes convaincus que ces nouveaux termes sont plus en phase avec l'utilisation actuelle de Kantree. </p> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/fr/blog target=_blank rel=noopener ng-click=$close()>En apprendre plus sur notre blog</a> <button class="btn btn-default" type=button ng-click=$close()>Fermer</button> </div> `);
  $templateCache.put("/static/app/modals/release/versions/templates/v8.12.0-en.html", `<div class=modal-header> <h3 class=modal-title>Small UI Updates</h3> <button type=button class=btn-close ng-click=$close()></button> </div> <div class=modal-body> <p> We took advantage of the summer to release small UI updates to Kantree. </p> <hr> <div class=release-modal-section-container> <img class=release-modal-screenshot ng-src="{{'/static/assets/releases/moving-user-nav/moving-user-nav.png'|baseUrl}}" alt="Moving User Nav"> <div class=release-modal-section> <h2>User menu</h2> <p> The user menu and the help menu are now accessible from the bottom of the sidebar. It frees some space in the navbar for project tools and buttons. </p> </div> </div> <hr> <div class=release-modal-section-container> <img class=release-modal-screenshot ng-src="{{'/static/assets/releases/moving-user-nav/merging-searches.png'|baseUrl}}" alt="Merging searches"> <div class=release-modal-section> <h2>Merging projects search with cards search</h2> <p> We've also merged the cards global search with the project switcher. Everything is now happening in the top right corner of your screen, making it more intuitive to find cards and projects. </p> </div> </div> </div> <div class=modal-footer> <a class=pull-left href=https://kantree.io/blog target=_blank rel=noopener ng-click=$close()>Learn more on our blog</a> <button class="btn btn-default" type=button ng-click=$close()>Close</button> </div> `);
  $templateCache.put("/static/app/modals/org-settings/templates/billing-panel.html", `<div ng-if=$ctrl.remoteBilling> <p>{{::_('Manage your billing information from our website')}}</p> <a href=https://kantree.io target=_blank class="btn btn-primary"> {{::_('Open in your browser')}} <i class="right fa fa-external-link"></i> </a> </div> <div class=panel ng-if=$ctrl.currentUser.is_kantree_admin> <div class=panel-heading> {{::_("Admin")}} </div> <form class=panel-body ng-submit=$ctrl.updateFromAdmin()> <div class=form-group ng-show=$ctrl.paymentsEnabled> <label class=form-label for=accountPaiementMethod>{{::_('Payment method:')}}</label> <select ng-model=$ctrl.adminAccount.payment_method class=form-select id=accountPaiementMethod> <option value>{{::_('No payment required')}}</option> <option value=stripe>{{::_('Handled via Stripe')}}</option> <option value=manual>{{::_('Handled manually')}}</option> </select> </div> <div class=form-group> <label class=form-label for=accountStatus>{{::_('Status:')}}</label> <select ng-model=$ctrl.adminAccount.status class=form-select id=accountStatus> <option value=trialing>{{::_('Trialing')}}</option> <option value=active>{{::_('Active')}}</option> <option value=unpaid>{{::_('Unpaid')}}</option> <option value=canceled>{{::_('Canceled')}}</option> <option value=locked>{{::_('Locked')}}</option> </select> </div> <div class=form-group ng-show="$ctrl.adminAccount.payment_method === 'stripe'"> <label class=form-label>{{::_('Stripe customer id:')}}</label> <div class=form-control-plaintext ng-hide=!$ctrl.account.stripe_customer_id> <a ng-href=https://dashboard.stripe.com/customers/{{$ctrl.account.stripe_customer_id}} target=_blank> {{$ctrl.account.stripe_customer_id}}</a> </div> <button type=button class="btn btn-default" ng-click=$ctrl.createStripeCustomer() ng-show=!$ctrl.account.stripe_customer_id> {{::_('Create stripe customer')}}</button> </div> <div class=form-group ng-show="$ctrl.adminAccount.status === 'trialing'"> <label class=form-label for=accountTrialEnd>{{::_('Trial ends at:')}}</label> <input type=text class=form-control ng-model=$ctrl.adminAccount.current_period_end id=accountTrialEnd> </div> <div class=form-group ng-show="$ctrl.adminAccount.payment_method && $ctrl.adminAccount.payment_method !== 'stripe' && $ctrl.adminAccount.status === 'active'"> <label class=form-label for=accountPaidUntil>{{::_('Paid until:')}}</label> <input type=text class=form-control ng-model=$ctrl.adminAccount.current_period_end id=accountPaidUntil> </div> <div class=form-group ng-show="$ctrl.adminAccount.payment_method && $ctrl.adminAccount.payment_method !== 'stripe'"> <label class=form-label for=accountSeatCount>{{::_('Number of licenses:')}}</label> <input type=text class=form-control ng-model=$ctrl.adminAccount.seat_count id=accountSeatCount> </div> <button type=submit class="btn btn-primary">{{::_('Save')}}</button> <hr> <button type=button class="btn btn-default" ng-click=$ctrl.forceUpdateStripe() ng-show="$ctrl.account.payment_method === 'stripe' && $ctrl.account.stripe_customer_id"> {{::_('Force update stripe')}}</button> <button type=button class="btn btn-default" ng-click=$ctrl.forceUpdateFromStripe() ng-show="$ctrl.account.payment_method === 'stripe' && $ctrl.account.stripe_customer_id"> {{::_('Force update from stripe')}}</button> <button type=button class="btn btn-default" ng-click=$ctrl.chargeStripeInvoiceItems() ng-show="$ctrl.account.payment_method === 'stripe' && $ctrl.account.stripe_customer_id"> {{::_('Charge stripe invoice items now')}}</button> <button type=button class="btn btn-danger" ng-click=$ctrl.deleteAccount()> {{::_('Delete billing account')}}</button> </form> </div> <div class=panel ng-if="!$ctrl.remoteBilling && !$ctrl.account.payment_method"> <div class=panel-heading> {{::_("Billing")}} </div> <div class=panel-body> <p>{{::_("You won't be charged for your usage of Kantree!")}}</p> <p> {{::_("Feel free to contact us at sales@kantree.io")}} </p> </div> </div> <div class="alert alert-info" ng-if="!$ctrl.remoteBilling && $ctrl.account.status === 'trialing'"> <i class=bi-info-square-fill></i> {{::_("Your free trial ends on {date} ({days} days left)", $ctrl.trialFormatParams)}} </div> <div class="alert alert-danger" ng-if=$ctrl.account.stripe_payment_method_requires_action> <i class=bi-exclamation-triangle-fill></i> {{::_("We need your attention to process your latest payment")}} <button type=button class="btn btn-danger" ng-click=$ctrl.performStripePaymentMethodAction() ng-show=$ctrl.account.stripe_payment_method_requires_action>{{::_('Confirm payment')}}</button> </div> <div class=panel ng-if="$ctrl.paymentsEnabled && !$ctrl.remoteBilling"> <div class=panel-heading> {{::_("Plans")}} </div> <div class=panel-body> <billing-plan-selector plan=$ctrl.account.plan period=$ctrl.account.plan_period currency=$ctrl.account.currency readonly="$ctrl.account.payment_method !== 'stripe' && !$ctrl.currentUser.is_kantree_admin " on-change="$ctrl.switchPlan($plan, $period)" trialing="$ctrl.account.status === 'trialing'"></billing-plan-selector> </div> </div> <div ng-hide=$ctrl.showForm ng-if="!$ctrl.remoteBilling && $ctrl.account.payment_method"> <div class=panel> <div class=panel-heading> {{::_("Seats")}} </div> <div class=panel-body> <div class=progress> <div class=progress-bar role=progressbar ng-style="{'width': ($ctrl.ngOrgUsers / $ctrl.account.seat_count * 100) + '%'}"> {{$ctrl.ngOrgUsers}} / {{$ctrl.account.seat_count}} {{$ctrl.account.auto_adjust_seat_count ? _('seats used (auto managed)') : _('seats used')}} </div> </div> <div ng-hide="$ctrl.account.payment_method !== 'stripe'"> <p class=text-center ng-show="$ctrl.account.seat_count > $ctrl.account.next_period_seat_count"> <small>{{_('{nbSeats} seat(s) will be automatically removed at the end of the billing period', {nbSeats: $ctrl.account.seat_count - $ctrl.account.next_period_seat_count})}}</small> </p> <hr> <p class=text-muted> {{::_("Each time you add a user, a seat is consumed and each time you remove a user, a seat is freed up. Your subscription amount is based on the number of seats, which may be higher than the number of users in your organization.")}} </p> <p class=text-muted> <strong>{{::_("Seats are billed for the whole billing period. When added during a period, they are pro-rated based on the remaining time in the period.")}}</strong> </p> <p class=text-muted> {{::_("When removing seats, the seats become available for re-use. If auto management is enabled, the seat will be automatically removed at the end of the billing period.")}} </p> <div class="form-group form-check form-switch text-center"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.account.auto_adjust_seat_count ng-change=$ctrl.toggleAutoAdjustSeatCount() ng-disabled=!$ctrl.canDisableAutoAdjust id=accountAutoAdjustSeat> <label class=form-check-label for=accountAutoAdjustSeat>{{::_("Automatically adjust seats when adding/removing members")}}</label> </div> <p ng-show="$ctrl.account.auto_adjust_seat_count && !$ctrl.canDisableAutoAdjust" class="text-center text-danger"> {{::_("Auto seat management cannot be disabled at the moment. When manually managing seats, seats are needed to cover pending invites. Cancel some invites first.")}} </p> <p ng-show=!$ctrl.account.auto_adjust_seat_count class="text-center text-danger"> {{::_("Seats will need to be purchased by owners. Admins won't be able to add members if no seats are available")}} </p> <p ng-show=!$ctrl.account.auto_adjust_seat_count class=text-center> <button class="btn btn-primary" ng-click=$ctrl.openManageSeatCountModal()>{{::_("Add or remove seats")}}</button> </p> </div> </div> </div> <div class=panel ng-show=$ctrl.paymentsEnabled> <div class=panel-heading> {{::_("Billing cycle")}} </div> <div class=panel-body ng-show="['trialing', 'active', 'past_due', 'incomplete'].includes($ctrl.account.status)"> <div class=form-group ng-show="$ctrl.account.status === 'trialing'"> <label class=form-label>{{::_('Trialing until:')}}</label> <div class=form-control-plaintext> {{$ctrl.account.current_period_end_formatted}} </div> </div> <div class=form-group ng-hide="$ctrl.account.status === 'trialing'"> <label class=form-label>{{::_('Current period:')}}</label> <div class=form-control-plaintext ng-if=$ctrl.account.current_period_start> {{::_('From {start} to {end}', {start: $ctrl.account.current_period_start_formatted, end: $ctrl.account.current_period_end_formatted})}} </div> <div class=form-control-plaintext ng-if=!$ctrl.account.current_period_start> {{::_('Paid until {end}', {end: $ctrl.account.current_period_end_formatted})}} </div> </div> <div class=form-group ng-show="$ctrl.account.next_charge_at && $ctrl.account.payment_method === 'stripe'"> <label class=form-label>{{::_('Next invoice due:')}}</label> <div class=form-control-plaintext>{{$ctrl.account.next_charge_at|momentFormat:'LL'}}</div> </div> <div class=form-group ng-show="$ctrl.account.payment_method === 'stripe'"> <label class=form-label>{{::_('Next invoice expected amount (excl. VAT):')}}</label> <div class=form-control-plaintext>{{$ctrl.nextInvoiceAmount}}</div> </div> <div class=form-group ng-show="$ctrl.account.last_invoice_at && $ctrl.account.payment_method === 'stripe'"> <label class=form-label>{{::_('Last invoice:')}}</label> <div class=form-control-plaintext> {{_('{currency}{amount} on {date}', { currency: $ctrl.account.currency === 'EUR' ? '\u20AC' : '$', amount: $ctrl.account.last_invoice_amount, date: $ctrl.account.last_invoice_at_formatted })}} </div> </div> <div ng-show="$ctrl.account.cancel_at_period_end && $ctrl.account.payment_method === 'stripe' && $ctrl.account.has_stripe_payment_method"> <strong>{{::_("Your subscription will be cancelled at the end of the period")}}</strong> <button type=button class="btn btn-primary" ng-click=$ctrl.continueSubscription()>{{::_('Continue subscription')}}</button> </div> <div ng-show="!$ctrl.account.cancel_at_period_end && $ctrl.account.payment_method === 'stripe' && $ctrl.account.has_stripe_payment_method"> <button type=button class="btn btn-danger" ng-click=$ctrl.cancelSubscription()>{{::_('Suspend subscription')}}</button> </div> </div> <div class=panel-body ng-show="['unpaid', 'canceled'].includes($ctrl.account.status)"> <p> {{::_("Your subscription has been canceled.")}} </p> <p> {{::_("Feel free to contact us at sales@kantree.io")}} </p> <div ng-show="$ctrl.account.payment_method === 'stripe'"> <button type=button class="btn btn-primary" ng-click=$ctrl.toggleForm(true)>{{::_('Re-activate subscription')}}</button> </div> </div> </div> <div class=panel> <div class=panel-heading> {{::_("Billing information")}} </div> <div class=panel-body> <div class=form-group ng-show="$ctrl.account.payment_method !== 'stripe'"> <label class=form-label>{{::_('Payment method:')}}</label> <p class=form-text> {{::_('Contact us at sales@kantree.io for any questions regarding your subscription')}} </p> </div> <div class=form-group ng-show=$ctrl.account.eu_vat_number> <label class=form-label>{{::_('VAT number:')}}</label> <div class=form-control-plaintext>{{$ctrl.account.eu_vat_number}}</div> </div> <div class=form-group ng-show="$ctrl.account.payment_method === 'stripe' && $ctrl.account.stripe_payment_method_type === 'card'"> <label class=form-label>{{::_('Card:')}}</label> <div class=form-control-plaintext> **** **** **** {{$ctrl.account.card_last4}} ({{$ctrl.account.card_brand}})<br> {{$ctrl.account.card_exp_month}}/{{$ctrl.account.card_exp_year}} </div> </div> <div class=form-group ng-show="$ctrl.account.payment_method === 'stripe' && $ctrl.account.stripe_payment_method_type === 'sepa_debit'"> <label class=form-label>{{::_('IBAN:')}}</label> <div class=form-control-plaintext> **** **** **** **** {{$ctrl.account.sepa_last4}}<br> </div> </div> <div class=form-group ng-show=$ctrl.account.billing_address_country> <label class=form-label>{{::_('Billing address:')}}</label> <div class=form-control-plaintext> <div>{{$ctrl.account.company}}</div> <div>{{$ctrl.account.billing_name}}</div> <div ng-show=$ctrl.account.billing_address_line1>{{$ctrl.account.billing_address_line1}}</div> <div ng-show=$ctrl.account.billing_address_line2>{{$ctrl.account.billing_address_line2}}</div> <div> <span ng-show=$ctrl.account.billing_address_zip>{{$ctrl.account.billing_address_zip}}</span> <span ng-show=$ctrl.account.billing_address_city>{{$ctrl.account.billing_address_city}}</span> </div> <div> <span ng-show=$ctrl.account.billing_address_state>{{$ctrl.account.billing_address_state}}</span> <span ng-show=$ctrl.account.billing_address_country>{{$ctrl.account.billing_address_country}}</span> </div> <div>{{$ctrl.account.billing_email}}</div> <div ng-show=$ctrl.account.billing_phone>{{$ctrl.account.billing_phone}}</div> </div> </div> <button type=button class="btn btn-default" ng-click=$ctrl.performStripePaymentMethodAction() ng-show=$ctrl.account.stripe_payment_method_requires_action>{{::_('Finish activating your payment method')}}</button> <button type=button class="btn btn-default" ng-click=$ctrl.toggleForm() ng-show="$ctrl.account.payment_method === 'stripe'">{{::_('Update payment method')}}</button> </div> </div> <div class=panel ng-if="$ctrl.account.payment_method === 'stripe' && $ctrl.invoices"> <div class=panel-heading> {{::_("Invoices")}} </div> <ul class="list-group invoice-list"> <li ng-repeat="invoice in $ctrl.invoices" class=list-group-item> <a ng-href={{invoice.url}} target=_blank> <span class=period>{{invoice.period_end|momentFormat:"LL"}}</span> <span class=amount>{{invoice.total|formatAmount:invoice.currency}}</span> </a> </li> </ul> </div> </div> <div ng-if=$ctrl.showForm> <div class=panel> <div class=panel-heading> {{::!$ctrl.account.has_stripe_payment_method ? _("Your payment details") : _("Upgrade now")}} </div> <div class=panel-body> <billing-form account=$ctrl.account payment-method-required="['unpaid', 'canceled'].includes($ctrl.account.status)" on-submit="$ctrl.onFormSubmit($plan, $period, $billingDetails, $paymentMethod, $coupon, $callback)" on-cancel=$ctrl.toggleForm()> </billing-form> </div> </div> </div> `);
  $templateCache.put("/static/app/modals/org-settings/templates/settings.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Organization settings')}}</h3> <button type=button class=btn-close ng-click=$ctrl.close()></button> </div> <div class="modal-body modal-body-flex"> <ul class=modal-body-flex-sidebar> <li ng-repeat="panel in $ctrl.panels"> <button type=button class="btn btn-modal-nav" ng-class="{active: $ctrl.currentPanel === panel}" ng-click=$ctrl.openPanel(panel)> {{::panel.title }} <feature-flag-label org=$ctrl.org flag={{panel.featureFlag}} ng-if="panel.featureFlag && panel.upgradeForFeatureFlag"></feature-flag-label> <span class=badge ng-show=panel.beta>BETA</span> <i class="bi-chevron-right hidden-xs"></i> <i class="bi-chevron-down visible-xs-inline-block"></i> </button> </li> </ul> <p class=modal-help-message ng-show=!$ctrl.currentPanel> {{::_("No settings available")}} </p> <dynamic-directive directive="{{$ctrl.currentPanel && $ctrl.currentPanel.component}}" org=$ctrl.org close=$ctrl.close dismiss=$ctrl.dismiss></dynamic-directive> </div> `);
  $templateCache.put("/static/app/modals/org-settings/templates/billing-form.html", `<form name=$ctrl.billingForm ng-submit=$ctrl.onFormSubmit()> <fieldset ng-show=$ctrl.showPlanSelector> <legend>{{::_('Your plan')}}</legend> <billing-plan-selector plan=$ctrl.plan period=$ctrl.period currency=$ctrl.account.currency on-load="$ctrl.selectPlan($plan, $period, $pricing)" on-change="$ctrl.selectPlan($plan, $period, $pricing)"></billing-plan-selector> </fieldset> <fieldset> <legend>{{::_('Billing details')}}</legend> <p class=help> {{::_("All fields are required. Billing address must be the one associated with the card used. If the country from the billing address is different than the country of the card's bank, Kantree will use the bank's country for VAT calculation purposes.")}} </p> <div class=form-group> <label class=form-label for=billingName>{{::_("Full name:")}}</label> <input type=text class=form-control required ng-model=$ctrl.billingDetails.name id=billingName> </div> <div class=form-group> <label class=form-label for=billingCompany>{{::_("Company:")}}</label> <input type=text class=form-control ng-model=$ctrl.company id=billingCompany> </div> <div class=form-group> <label class=form-label for=billingEmail>{{::_("Email:")}}</label> <input type=email class=form-control required ng-model=$ctrl.billingDetails.email id=billingEmail> </div> <div class=form-group> <label class=form-label for=billingPhone>{{::_("Phone:")}}</label> <input type=text class=form-control ng-model=$ctrl.billingDetails.phone id=billingPhone> </div> <div class=form-group> <label class=form-label for=billingAddress>{{::_('Address:')}}</label> <input type=text class=form-control placeholder="{{::_('Address')}}" required ng-model=$ctrl.billingDetails.address.line1 id=billingAddress> </div> <div class=form-group> <input type=text class=form-control ng-model=$ctrl.billingDetails.address.line2> </div> <div class=row> <div class="col-md-6 form-group"> <input type=text class=form-control placeholder="{{::_('City')}}" required ng-model=$ctrl.billingDetails.address.city> </div> <div class="col-md-6 form-group"> <input type=text class=form-control placeholder="{{::_('State')}}" ng-model=$ctrl.billingDetails.address.state> </div> </div> <div class=row> <div class="col-md-6 form-group"> <input type=text class=form-control placeholder="{{::_('Zipcode')}}" required ng-model=$ctrl.billingDetails.address.postal_code> </div> <div class="col-md-6 form-group"> <select ng-model=$ctrl.billingDetails.address.country pvp-country-picker=alpha2 required class=form-select ng-change=$ctrl.refreshVAT()></select> </div> </div> </fieldset> <fieldset ng-show=$ctrl.isEUCountry> <legend>{{::_('European Union VAT')}}</legend> <p class="alert alert-warning"> <i class=bi-exclamation-triangle-fill></i> {{::_("As an EU business, Kantree must collect VAT for customers located in the EU. The country you have selected being an EU country, you will be billed in Euros with your country's VAT added unless you provide a valid EU VAT number.")}} </p> <div class=form-group> <label class=form-label for=billingVAT>{{::_("EU Vat Number:")}}</label> <input type=text class=form-control ng-model=$ctrl.EUVATNumber ng-change=$ctrl.refreshVAT() id=billingVAT ng-class="{'is-valid': $ctrl.EUVATInfo.is_vat_number_valid, 'is-invalid': $ctrl.EUVATNumber && !$ctrl.EUVATInfo.is_vat_number_valid}"> </div> <div class=vat-rate> <i class="fa fa-spinner fa-spin" ng-show=!$ctrl.EUVATInfo></i> <div ng-show="$ctrl.EUVATInfo && $ctrl.EUVATInfo.should_charge_vat"> {{_('VAT Rate: {rate}%', {rate: $ctrl.EUVATInfo.vat_rate})}}<br> {{_('Price per user including VAT: {currency}{amount}', { currency: $ctrl.currencySymbol, amount: $ctrl.EUVATInfo.amount_with_vat})}} </div> <div ng-show="$ctrl.EUVATInfo && !$ctrl.EUVATInfo.should_charge_vat"> {{::_('Not VAT will be charged')}} </div> <small ng-show="$ctrl.EUVATInfo && $ctrl.EUVATInfo.src_currency != $ctrl.EUVATInfo.currency"> {{_("In your local currency with today's exchange rate: {currency}{amount}/user/month", { currency: $ctrl.currencySymbol, amount: EUVatInfo.exchanged_amount_with_vat})}} </small> </div> </fieldset> <fieldset> <legend>{{::_('Payment method')}}</legend> <div class=payment-method-selector ng-show=$ctrl.isEUCountry> <div class=btn-group> <button type=button class="btn btn-default" ng-class="{'active': $ctrl.paymentType === 'card'}" ng-click="$ctrl.paymentType = 'card'">{{::_('Credit Card')}}</button> <button type=button class="btn btn-default" ng-class="{'active': $ctrl.paymentType === 'sepa_debit'}" ng-click="$ctrl.paymentType = 'sepa_debit'">{{::_('SEPA')}}</button> </div> </div> <div class=stripe-element-card ng-show="$ctrl.paymentType === 'card'"> <div class="form-group stripe-element-card"> <label class=form-label>{{::_('Card details:')}}</label> <div class=form-control style="height: 2.4em; padding-top: .7em;"></div> <div class=form-text ng-show=$ctrl.cardElementError>{{::_('We accept VISA, MasterCard, and American Express')}}</div> <div class=form-text ng-show=$ctrl.cardElementError>{{$ctrl.cardElementError}}</div> </div> </div> <div class=stripe-element-iban ng-show="$ctrl.paymentType === 'sepa_debit'"> <div class=form-group> <label class=form-label>{{::_('IBAN details:')}}</label> <div class=form-control style="height: 2.4em; padding-top: .7em;"></div> <div class=form-text ng-show=$ctrl.ibanElementError>{{$ctrl.ibanElementError}}</div> </div> <div id=mandate-acceptance> By providing your IBAN and confirming this payment, you are authorizing Digicoop SARL. and Stripe, our payment service provider, to send instructions to your bank to debit your account in accordance with those instructions. You are entitled to a refund from your bank under the terms and conditions of your agreement with your bank. A refund must be claimed within eight weeks starting from the date on which your account was debited. </div> </div> </fieldset> <fieldset ng-show="!$ctrl.account || !$ctrl.account.has_stripe_payment_method && ($ctrl.account.status == 'trialing' || $ctrl.account.status == 'unpaid')"> <legend>{{::_('Discount code')}}</legend> <p class=help> {{::_('Enter a coupon code below to apply a discount')}} </p> <div class=form-group> <label class=form-label for=billingCoupon>{{::_("Coupon:")}}</label> <input type=text class=form-control ng-model=$ctrl.coupon id=billingCoupon> </div> </fieldset> <div class="alert alert-success" ng-show="!$ctrl.account || !$ctrl.account.has_stripe_payment_method && $ctrl.account.status !== 'trialing'"> <i class=bi-check-circle-fill></i> {{::_('Your Kantree susbscription will start immediatly.')}}<br> <strong>{{_('You will be charged {currency}{amount} for your first period ({nb_members} member(s))', { currency: $ctrl.currencySymbol, amount: $ctrl.account.seat_count * (EUVatInfo && EUVatInfo.should_charge_vat ? EUVatInfo.amount_with_vat : $ctrl.amount) * ($ctrl.period === 'yearly' ? 12 : 1), nb_members: $ctrl.account.seat_count})}} </strong> </div> <div class="alert alert-success" ng-show="$ctrl.account && !$ctrl.account.has_stripe_payment_method && $ctrl.account.status === 'trialing'"> <i class=bi-check-circle-fill></i> {{::_('Your Kantree susbscription will start at the end of your trial period.')}}<br> </div> <div class="d-block text-end"> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.onCancel() ng-show="$ctrl.account && $ctrl.account.has_stripe_payment_method">{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-disabled="$ctrl.billingForm.$invalid || ($ctrl.EUVATNumber && !$ctrl.EUVATInfo.is_vat_number_valid) || !$ctrl.stripeLoaded || (!$ctrl.account && $ctrl.emptyPaymentMethod) || $ctrl.submitting"> {{$ctrl.account && $ctrl.account.has_stripe_payment_method ? _('Update') : _('Upgrade now')}} </button> </div> </form> `);
  $templateCache.put("/static/app/modals/org-settings/templates/plan-selector.html", `<div class=period> <div class=btn-group> <button type=button class="btn btn-default" ng-class="{'active': $ctrl.period === 'monthly'}" ng-click="$ctrl.selectPeriod('monthly')">{{::_('Monthly')}}</button> <button type=button class="btn btn-default" ng-class="{'active': $ctrl.period === 'yearly'}" ng-click="$ctrl.selectPeriod('yearly')">{{::_('Yearly')}}</button> </div> <span class=promo>{{::_('Save 2 months for any annual subscription')}}</span> </div> <div class=plans> <div class=plan ng-repeat="plan in $ctrl.plans|filter:$ctrl.planFilter" ng-class="{'selected': $ctrl.isCurrent(plan)}" ng-hide="plan.deprecated && $ctrl.selectedPlan !== plan.name"> <span class=title>{{plan.title}}</span> <span class=price>{{$ctrl.pricing.price_format.replace('%s', plan.amounts[$ctrl.period])}} <small>/ {{::_('user / month')}}</small></span> <p class=desc>{{_(plan.desc)}}</p> <button type=button class=btn ng-class="$ctrl.isCurrent(plan) || !$ctrl.trialing ? 'btn-default' : 'btn-cta'" ng-click=$ctrl.select(plan) ng-hide=$ctrl.readonly ng-disabled=$ctrl.isCurrent(plan)> {{$ctrl.isCurrent(plan) ? _('Selected') : ($ctrl.trialing ? _('Try') : _('Select'))}}</button> </div> </div> <div class=details> <p ng-show="$ctrl.period === 'yearly'">{{::_('Annual plans are charged for the full year at once')}}</p> <p>{{::_('Prices exclude VAT.')}} <a href=https://kantree.io/pricing target=_blank>{{::_('Pricing FAQ')}}</a></p> <p ng-bind-html=$ctrl.questionsLabel></p> </div> `);
  $templateCache.put("/static/app/modals/org-settings/templates/manage-seats-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Manage seats')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class="modal-body text-center"> <div class=form-group> <label class=form-label for=seatCount>{{::_("Set the total number of seats for your organization:")}}</label> <input type=number class="form-control form-control-lg" ng-model=$ctrl.seatCount id=seatCount ng-change=$ctrl.computeDelta() min=1 style="max-width: 100px; margin: 10px auto;" ng-disabled=$ctrl.submitting> <a href ng-click=$ctrl.reset()>{{::_("reset")}}</a> </div> <p ng-show=$ctrl.subscriptionTotal> {{_("Your subscription total (excl. VAT): {amount}", {amount: $ctrl.subscriptionTotal})}} </p> <p ng-show="$ctrl.delta > 0" class=text-danger> {{_("{nb} additional seat(s) will be purchased immediatly", {nb: $ctrl.delta})}} </p> <p ng-show="$ctrl.delta < 0" class=text-danger> {{_("{nb} seat(s) will be automatically removed at the end of the billing period", {nb: -$ctrl.delta})}}<br> {{::_("If seats are used at the end of the billing period, their removal will be cancelled")}} </p> <p ng-show="$ctrl.scheduledRemoval > 0" class=text-muted> {{_("{nb} seat(s) are already scheduled for removal at the end of the billing period", {nb: $ctrl.scheduledRemoval})}} (<a href ng-click=$ctrl.cancelRemoval()>{{::_('cancel')}}</a>) </p> <p ng-show="$ctrl.delta > 0"> <strong>{{_("Pro-rated amount for the remaining of the period (excl. VAT): {amount}", {amount: $ctrl.amount})}}</strong><br> <small class=text-muted ng-show="$ctrl.account.plan_period === 'yearly'">{{::_('You will be charged in 48h')}}</small> <small class=text-muted ng-show="$ctrl.account.plan_period === 'monthly'">{{::_('You will be charged as part of your next invoice')}}</small> </p> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.dismiss() ng-disabled=$ctrl.submitting>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.submit() ng-disabled="$ctrl.delta === 0 && $ctrl.scheduledRemoval === $ctrl.currentScheduledRemoval || $ctrl.submitting"> <i class="fa fa-spin fa-spinner" ng-show=$ctrl.submitting></i> {{$ctrl.delta > 0 ? _('Purchase for {amount} (excl. VAT)', {amount: $ctrl.amount}) : _('Update')}} </button> </div> `);
  $templateCache.put("/static/app/modals/org-settings/templates/change-plan-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Change your plan')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class="modal-body text-center"> <p> {{::_("Confirm your new subscription plan:")}} </p> <table class="table table-bordered"> <tr> <td>{{::_('Plan:')}}</td> <td>{{$ctrl.plan.title}}</td> </tr> <tr> <td>{{::_('Period:')}}</td> <td>{{$ctrl.resolve.newPeriod === 'yearly' ? _('Yearly') : _('Monthly')}}</td> </tr> <tr> <td>{{::_('Number of seats:')}}</td> <td>{{$ctrl.account.next_period_seat_count}}</td> </tr> <tr> <td>{{::_('New subscription total (excl. VAT):')}}</td> <td>{{$ctrl.amount}}</td> </tr> </table> <div class=form-group> <input type=text class=form-control ng-model=$ctrl.coupon placeholder="{{::_('Discount code')}}"> </div> <p ng-hide="$ctrl.account.plan_period === 'yearly' && $ctrl.resolve.newPeriod === 'monthly'"> {{::_("You will be refunded (pro-rated) for the unused time on your current plan")}} </p> <p ng-show="$ctrl.account.plan_period === 'yearly' && $ctrl.resolve.newPeriod === 'monthly'" class=text-danger> {{::_("You will NOT be refunded for the unused time on your current plan")}} </p> <p> <strong>{{::_('Your billing period will reset and you will be billed immediatly for the new period')}}</strong> </p> <p>{{::_('Questions ? Contact us at sales@kantree.io')}}</p> <div class="alert alert-danger" ng-show=$ctrl.downgrading> <i class=bi-exclamation-triangle-fill></i> {{::_("Downgrading may result in some data to be lost")}} </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.dismiss() ng-disabled=$ctrl.submitting>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.confirm() ng-disabled=$ctrl.submitting> <i class="fa fa-spin fa-spinner" ng-show=$ctrl.submitting></i>{{::_('Confirm')}}</button> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/group-types.html", `<div class=modal-help-message> <p> {{::_("Contexts allow you to group cards together")}} </p> </div> <div class=panel> <div class=panel-heading> {{::_("Contexts which can be used by any workspaces in the organization")}} </div> <div class=panel-body ng-show="!$ctrl.groupTypes.length && !$ctrl.selected"> <p class=panel-empty-message>{{::_('No contexts.')}}</p> </div> <ul class=list-group ng-hide=$ctrl.selected> <li class=list-group-item ng-repeat="groupType in $ctrl.groupTypes track by groupType.id"> <div class=list-group-item-description> {{::groupType.name}} <div class=attributes>{{::_('Scope: {scope}', {scope: groupType.scope})}}</div> </div> <button type=button class="btn btn-icon btn-sm btn-default" ng-show="$ctrl.isOrgManager && !$ctrl.locked" ng-click=$ctrl.select($ctrl.groupType) uib-tooltip="{{::_('Edit')}}" hide-offline> <i class="fa fa-pencil"></i> </button> <button type=button class="btn btn-icon btn-sm btn-danger" ng-show="$ctrl.isOrgManager && !$ctrl.locked" ng-click=$ctrl.delete($ctrl.groupType) uib-tooltip="{{::('Delete')}}" hide-offline> <i class="fa fa-trash"></i> </button> </li> </ul> <form class=panel-body name=$ctrl.groupTypeForm ng-if=$ctrl.selected> <h2>{{_($ctrl.selected.id ? 'Edit context' : 'Create a new context')}}</h2> <card-group-type-editor group-type=$ctrl.selected></card-group-type-editor> <div class="d-block text-end"> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.select()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-disabled=$ctrl.groupTypeForm.$invalid ng-click=$ctrl.save()>{{::_('Save')}}</button> </div> </form> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/project-attrs.html", `<div class="modal-help-message mb-5"> <p> {{::_("Workspace fields let you customize workspace overview and Portfolio card structure.")}} </p> <p> {{::_("They are shared across all workspaces of your organization.")}} </p> <p> {{::_("In Workspace overview, sidebar fields are displayed below main area fields")}} </p> </div> <div class=d-flex> <div class=flex-fill> <div class=project-attrs-container> <h2 class=mb-4>{{_('Main area')}}</h2> <attribute-group class=fluid attribute-group=$ctrl.topLevelCardModel.attributes attributes-editable=$ctrl.isConnected() attributes-movable=$ctrl.isConnected() container=__top__ show-add=true add-btn-position=bottom></attribute-group> </div> <div class=project-attrs-container ng-repeat="container in $ctrl.topLevelCardModel.attribute_containers"> <h2>{{container}}</h2> <attribute-group class=fluid attribute-group=$ctrl.topLevelCardModel.attributes attributes-editable=$ctrl.isConnected() attributes-movable=$ctrl.isConnected() container="{{ container }}" show-add=true add-btn-position=bottom></attribute-group> </div> </div> <div class=flex-shrink-0 style=width:300px;> <h2 class=mb-4>{{_('Sidebar')}}</h2> <attribute-group attribute-group=$ctrl.topLevelCardModel.attributes attributes-editable=$ctrl.isConnected() attributes-movable=$ctrl.isConnected() container show-add=true add-btn-position=bottom></attribute-group> </div> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/admin.html", `<div class=panel> <div class=panel-heading> {{::_("Admin options")}} </div> <div class=panel-body> <form name=$ctrl.detailsForm ng-submit=$ctrl.update()> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.locked ng-disabled=$ctrl.forceLock id=orgLocked> <label class=form-check-label for=orgLocked> {{::_('Locked')}} </label> <p class=form-text>{{::_('This locks the organization, any aspect of updating it and its content will be locked including workspaces.')}}</p> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.canCreateProjects id=orgCancreateProjects> <label class=form-check-label for=orgCancreateProjects> {{::_('Can create workspaces')}} </label> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.canCreatePrivateProjects id=orgCanCreatePrivateProjects> <label class=form-check-label for=orgCanCreatePrivateProjects> {{::_('Can create private workspaces')}} </label> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.preventDeletion id=orgPreventDeletion> <label class=form-check-label for=orgPreventDeletion> {{::_('Prevent deletion by org admins (only kantree admins can delete)')}} </label> </div> <div class=form-group> <label class=form-label for=orgMaxAllowedUsers>{{::_('Maximum number of allowed users')}}</label> <input type=number class=form-control ng-model=$ctrl.maxAllowedUsers id=orgMaxAllowedUsers> </div> <div class=form-group> <label class=form-label for=orgMaxAllowedUsers>{{::_('Feature flags')}}</label> <ui-select multiple tagging tagging-label="({{::_('new flag')}})" ng-model=$ctrl.featureFlags> <ui-select-match>{{$item}}</ui-select-match> <ui-select-choices repeat="tag in ([] | filter: $select.search)">{{tag}}</ui-select-choices> </ui-select> </div> <button type=submit class="btn btn-primary" ng-disabled=$ctrl.detailsForm.$invalid>{{::_('Save')}}</button> <button type=button class="btn btn-primary btn-ghost" ng-click=$ctrl.export()>{{::_('Export')}}</button> <span class="badge-loading-success me-2"> <div ng-show="$ctrl.savingStatus === 'updating'" class=ball-scale-ripple><div></div></div> <div ng-show="$ctrl.savingStatus === 'saved'"><i class=bi-check></i><span>{{::_('Saved')}}</span></div> </span> </form> </div> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/pii.html", `<div class=panel> <div class=panel-heading> {{::_('PII Report')}} </div> <div class=panel-body> <p> {{::_("Download a report of all the personally identifiable information stored across the organization")}} </p> <p> <select ng-model=$ctrl.format ng-options="format as format.title for format in $ctrl.formats" class="form-select format-selector"></select> <button class="btn btn-primary" ng-click=$ctrl.generate()>{{::_('Download report')}}</button> </p> </div> </div> <div class=panel> <div class=panel-heading> {{::_('Search for PII associated to a person')}} </div> <div class=panel-body> <form ng-submit=$ctrl.search()> <div class=input-group> <input type=text class=form-control ng-model=$ctrl.piiSearch placeholder="{{::_('Identifier')}}" ng-required> <button type=submit class="btn btn-primary">{{::_('Search')}}</button> <button class="btn btn-default" ng-disabled="$ctrl.rows && $ctrl.rows.length > 0" ng-click=$ctrl.generate($ctrl.piiSearch)>{{::_('Download report')}}</button> </div> </form> <p ng-show="$ctrl.rows && $ctrl.rows.length === 0"> <strong>{{::_('No results')}}</strong> </p> </div> <table class=table ng-if="$ctrl.rows && $ctrl.rows.length > 0"> <thead> <tr> <th>{{::_('Card')}}</th> <th ng-repeat="col in $ctrl.cols">{{col}}</th> </tr> </thead> <tbody> <tr ng-repeat="row in $ctrl.rows"> <td>{{row['#']}}</td> <td ng-repeat="col in cols">{{row[col]}}</td> </tr> </tbody> </table> </div> <div class=panel ng-show="$ctrl.privacyURL || $ctrl.dataProcessingAgreementURL"> <div class=panel-heading> {{::_('Compliance')}} </div> <div class=panel-body> <p> <a ng-href={{$ctrl.privacyURL}} target=_blank class="btn btn-default" ng-show=$ctrl.privacyURL>{{::_("Privacy Policy")}}</a> <a ng-href={{$ctrl.dataProcessingAgreementURL}} target=_blank class="btn btn-default" ng-show=$ctrl.dataProcessingAgreementURL>{{::_("Data Processing Agreement")}}</a> </p> </div> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/billing.html", `<div class=loader ng-if=$ctrl.loading><i class="fa fa-spin fa-spinner"></i></div> <billing-panel account=$ctrl.account org=$ctrl.org ng-if=$ctrl.account on-delete="$ctrl.account = null" ng-if=$ctrl.isOwner></billing-panel> <div ng-if=$ctrl.showOwnerAlert> {{::_("Ask your organization owner to manage billing settings")}} </div> <div ng-if="!$ctrl.loading && $ctrl.currentUser.is_kantree_admin && !$ctrl.account"> <select ng-model=$ctrl.currency ng-options="c for c in $ctrl.availableCurrencies" class=form-select style="display: inline-block; width: auto;"></select> <button type=button class="btn btn-primary" ng-click=$ctrl.createBillingAccount() ng-show=!$ctrl.account>{{::_('Create billing account')}}</button> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/models.html", `<div class=modal-help-message> <p> {{::_("Cards can have a type which defines which fields are available. Fields are like columns in a table, they let you define something specific on each card (eg.: assigned members).")}} </p> </div> <div class=panel ng-hide=$ctrl.selectedAttributes> <div class=panel-heading> {{::_("Card types shared across workspaces")}} <!-- <button class="btn btn-primary btn-sm" ng-show="$ctrl.editable && !$ctrl.selectedModel" ng-click="$ctrl.create()">
      <i class="bi-plus-lg"></i> {{::_('Create')}}
    </button> --> </div> <div class=panel-body ng-show="!$ctrl.models.length && !$ctrl.selectedModel"> <p class=panel-empty-message>{{::_('No types.')}}</p> </div> <ul class=list-group ng-hide=$ctrl.selectedModel> <li class=list-group-item ng-repeat="model in $ctrl.models|filter:$ctrl.modelsFilter"> <div class=list-group-item-description> {{::model.name}} <div class=model-use-infos> <span ng-if="model.used_by.length === 0">{{::_('Not used in workspaces')}}</span> <span ng-if="model.used_by.length > 0">{{::_('Used in {nb} workspaces', {nb: model.used_by.length})}}</span> </div> <div class=attributes ng-show=model.attributes.length> {{::_('Fields:')}} {{ model|formatModelAttributes }} </div> </div> <!-- <button type="button" class="btn btn-icon btn-sm btn-default"
        ng-show="$ctrl.editable"
        ng-click="$ctrl.selectModel(model)"
        uib-tooltip="{{::_('Edit')}}" hide-offline>
          <i class="fa fa-pencil"></i>
      </button> --> <button type=button class="btn btn-icon btn-sm btn-default" ng-show=$ctrl.editable ng-click=$ctrl.duplicate(model) uib-tooltip="{{::_('Duplicate')}}" hide-offline> <i class="fa fa-clone"></i> </button> <button type=button class="btn btn-icon btn-sm btn-danger" ng-show="$ctrl.editable && !model.base_model_type" ng-click=$ctrl.delete(model) uib-tooltip="{{::('Delete')}}" hide-offline> <i class="fa fa-trash"></i> </button> </li> </ul> <button class="btn btn-default" ng-show="$ctrl.editable && !$ctrl.selectedAttributes" ng-click=$ctrl.selectAttributes($ctrl.org.attributes) hide-offline> <i class="fa fa-pencil"></i> {{::_('Edit organization fields')}} </button> <form class=panel-body name=$ctrl.modelForm ng-if=$ctrl.selectedModel> <h2>{{$ctrl.selectedModel.id ? _('Edit a card type') : _('Create a new card type')}}</h2> <model-editor model=$ctrl.selectedModel models=$ctrl.models org=$ctrl.org></model-editor> <button class="btn btn-default btn-ghost" type=button ng-click="$ctrl.selectedModel = null">{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-disabled=$ctrl.modelForm.$invalid ng-click=$ctrl.saveModel()>{{::_('Save')}}</button> </form> </div> <div class=panel ng-if=$ctrl.selectedAttributes> <div class=panel-heading> {{::_("Edit organization fields")}} </div> <form class="panel-body org-attributes-editor mb-5" name=$ctrl.attributesForm> <model-attr-list-editor attributes=$ctrl.selectedAttributes org=$ctrl.org></model-attr-list-editor> <button class="btn btn-default btn-ghost" type=button ng-click="$ctrl.selectedAttributes = null">{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-disabled=$ctrl.attributesForm.$invalid ng-click=$ctrl.saveAttributes()>{{::_('Save')}}</button> </form> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/integrations.html", `<div class=panel> <div class=panel-heading> {{::_("Integrations third-party accounts")}} </div> <div class=panel-body> <div class=modal-help-message> {{::_("Some integrations need to be connected to third-party accounts. Below is the list of integrations which are using or can use third-party accounts.")}} </div> </div> <ul class=list-group> <li class=list-group-item ng-repeat="integration in $ctrl.integrations"> <div class=list-group-item-description> <i ng-class=integration.icon|iconClass ng-show=integration.icon></i> {{::integration.title}} </div> <button type=button class="btn btn-default" ng-show="$ctrl.isOrgAdmin && !$ctrl.locked && !integration.org_id" ng-click=$ctrl.activate(integration)> {{::_('Activate')}} </button> <button type=button class="btn btn-default" ng-show="$ctrl.isOrgAdmin && !$ctrl.locked && integration.org_id && integration.needs_authorization" ng-click=$ctrl.reauthorize(integration)> {{::_('Re-authorize')}} </button> <button type=button class="btn btn-danger" ng-show="$ctrl.isOrgAdmin && !$ctrl.locked && integration.org_id" ng-click=$ctrl.remove(integration)> {{::_('Remove')}} </button> </li> </ul> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/roles.html", `<div class=modal-help-message> <p> {{::_("Roles allow you to limit which user can interact with which parts of your workspaces.")}} </p> <p> {{::_("Kantree provides you with 4 non-modifiable default roles.")}} </p> <p> {{::_("You can create as many as you want and customize them for each workspace.")}} </p> </div> <div ng-show=!$ctrl.selected> <div class="role-list mb-3"> <role-item ng-repeat="role in $ctrl.roles" role=role show-delete=true show-duplicate=true on-role-duplicate=$ctrl.duplicateRole($role) on-role-delete=$ctrl.delete($role) on-role-open=$ctrl.selectRole($role) editable=$ctrl.editable></role-item> </div> <button class="btn btn-success" type=button ng-show="$ctrl.editable && !$ctrl.selected" ng-click=$ctrl.create()> <i class=bi-plus-lg></i> {{::_('Create')}}</button> </div> <form name=$ctrl.roleForm ng-if=$ctrl.selected> <h2>{{$ctrl.selected.id ? $ctrl.selected.is_builtin ? _('View a role') : _('Edit a role') : _('Create a new role')}}</h2> <role-editor class=mb-3 role=$ctrl.selected editable=$ctrl.editable></role-editor> <div class="d-block text-end"> <button class="btn btn-default btn-ghost" type=button ng-click="$ctrl.selected = null" ng-if="$ctrl.editable && !$ctrl.selected.is_builtin">{{::_('Cancel')}}</button> <button class="btn btn-default btn-ghost" type=button ng-click="$ctrl.selected = null" ng-if="!$ctrl.isOrgAdmin || $ctrl.locked || $ctrl.selected.is_builtin">{{::_('Back')}}</button> <button class="btn btn-success" type=submit ng-if="$ctrl.editable && !$ctrl.selected.is_builtin" ng-disabled=$ctrl.roleForm.$invalid ng-click=$ctrl.saveRole()>{{::_('Save')}}</button> </div> </form> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/ai.html", `<div class=panel> <div class=panel-heading> {{::_('AI')}} <span class=badge>BETA</span> </div> <div class=panel-body> <p> {{::_("Enabled an AI provider to use AI features in your organization")}} </p> <form name=$ctrl.aiForm class=panel-body ng-submit=$ctrl.submit()> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=$ctrl.aiEnabled ng-value=null id=radioAiDisable ng-change=$ctrl.onAiEnabledChange()> <label class=form-check-label for=radioAiDisable>{{::_('Disable')}}</label> </div> <div class="form-group form-check" ng-show=$ctrl.hasGlobalConfig> <input class=form-check-input type=radio ng-model=$ctrl.aiEnabled ng-value="'$global'" id=radioAiGlobal ng-change=$ctrl.onAiEnabledChange()> <label class=form-check-label for=radioAiGlobal>{{::_('Use default provider')}}</label> </div> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=$ctrl.aiEnabled ng-value="'$custom'" id=radioAiCustom ng-change=$ctrl.onAiEnabledChange()> <label class=form-check-label for=radioAiCustom>{{::$ctrl.hasGlobalConfig ? _('Use custom provider') : _('Enable')}}</label> </div> <div ng-show="$ctrl.aiEnabled === '$custom'"> <div class=form-group> <label class=form-label>{{::_("AI provider")}}*:</label> <select class=form-control ng-model=$ctrl.aiProvider ng-options="p for p in $ctrl.aiProviders" ng-change=$ctrl.onAiProviderChange()> <option value>{{::_("Custom")}}</option> </select> </div> <div class=form-group ng-if=!$ctrl.aiProvider> <label class=form-label for=inputBaseUrl>{{::_("Provider base URL")}}*:</label> <input class=form-control type=url id=inputBaseUrl ng-model=$ctrl.data.ai_base_url ng-required="$ctrl.aiEnabled === '$custom'"> </div> <div class=form-group ng-if=!$ctrl.aiProvider> <label class=form-label for=inputModel>{{::_("Model")}}*:</label> <input class=form-control type=text id=inputModel ng-model=$ctrl.data.ai_model ng-required="$ctrl.aiEnabled === '$custom'"> </div> <div class=form-group> <label class=form-label for=inputApiKey>{{::_("API Key")}}*:</label> <input class=form-control type=text id=inputApiKey autocomplete=off ng-model=$ctrl.data.ai_api_key ng-required="$ctrl.aiEnabled === '$custom'"> </div> </div> <div class="form-group form-check form-switch" ng-show="$ctrl.aiEnabled && $ctrl.aiAssistantServerEnabled"> <input class=form-check-input type=checkbox ng-model=$ctrl.aiAssistantEnabled ng-value=true id=aiAllowAssistant ng-disabled=!$ctrl.aiAssistantServerEnabled ng-change=$ctrl.onAiAssistantEnabledChange()> <label class=form-check-label for=aiAllowAssistant>{{::_('Allow Kantreee Assistant')}}</label> </div> <button type=submit class="btn btn-primary" ng-disabled=$ctrl.aiForm.$invalid disable-offline>{{::_('Save')}}</button> </form> </div> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/appearance.html", `<div class=modal-help-message> <p> {{::_("Customize the way your organization looks like!")}} </p> </div> <div class=form-group> <label class=form-label>{{::_('Interface primary color:')}}</label> <color-picker-palette class=mb-3 color=$ctrl.org.color on-change=$ctrl.setColor($color) empty-color=true></color-picker-palette> <div class="alert alert-info" ng-show=$ctrl.hasCustomColor> <i class=bi-info-square-fill></i> {{::_("You have a custom color defined in your account settings which will override the organization color")}} </div> </div> <div class=form-group> <label class=form-label>{{::_('Banner image:')}}</label> <upload-image-field value=$ctrl.org.image_cover_url upload-url=$ctrl.uploadBannerUrl upload-field-name=image_cover on-upload=$ctrl.setBanner($data) on-reset=$ctrl.setBanner(null)></upload-image-field> </div> <div class=form-group> <label class=form-label>{{::_('Banner background color:')}}</label> <color-picker-palette class=mb-3 color=$ctrl.org.cover_color on-change=$ctrl.setBannerColor($color) empty-color=true></color-picker-palette> </div> `);
  $templateCache.put("/static/app/modals/org-settings/panels/templates/options.html", `<div class=panel> <div class=panel-body> <form name=$ctrl.detailsForm ng-submit=$ctrl.update()> <div class=form-group> <label class=form-label for=orgName>{{::_('Organization name:')}}</label> <input class=form-control type=text required ng-model=$ctrl.name id=orgName> </div> <div class=form-group ng-if=$ctrl.canCustomizeOrg> <label class=form-label>{{::_('Description:')}}</label> <content-editor ng-model=$ctrl.description></content-editor> </div> <button type=submit class="btn btn-primary" ng-disabled="$ctrl.detailsForm.$invalid || $ctrl.locked || $ctrl.updateStatus.processing" disable-offline>{{::_('Save')}}</button> <processing-status status=$ctrl.updateStatus></processing-status> </form> </div> </div> <div class=panel> <div class=panel-heading> {{::_("Logo")}} </div> <div class=panel-body> <div class=form-group> <upload-image-field value=$ctrl.org.logo_url upload-url=$ctrl.uploadLogolUrl upload-field-name=logo on-upload=$ctrl.setLogo($data) on-reset=$ctrl.setLogo(null)></upload-image-field> </div> </div> </div> <div class=panel ng-show="$ctrl.org.can_self_export || $ctrl.currentUser.is_kantree_admin" hide-offline> <div class=panel-heading> {{::_("Export")}} </div> <div class=panel-body> <button type=button class="btn btn-primary" ng-click=$ctrl.exportOrg()>{{::_('Export raw data')}}</button> </div> </div> <div class=panel ng-show="$ctrl.org.billing.status != 'past_due' && ($ctrl.currentUser.is_kantree_admin || !$ctrl.org.prevent_deletion)" hide-offline> <div class=panel-heading> {{::_("Delete")}} </div> <div class=panel-body> <p> {{::_('This will permanently delete the organization, all its teams and all its workspaces. This cannot be recovered.')}} </p> <button type=button class="btn btn-danger" ng-click=$ctrl.deleteOrg()><i class="fa fa-trash"></i> {{::_('Delete this organization')}}</button> </div> </div> `);
  $templateCache.put("/static/app/modals/qrcode/qrcode-modal.html", `<div class=modal-header ng-class="{'no-print': !$ctrl.resolve.title}"> <h3 class=modal-title>{{$ctrl.resolve.title || _('QR Code')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <canvas></canvas> <copyable-readonly-input value=$ctrl.resolve.value></copyable-readonly-input> </div> `);
  $templateCache.put("/static/app/ui/card-models/ng-components/templates/card.css.html", "/********************************************************** * TILE */ .{{wrappercls}}.card-tile.card-tile-model-theme { background-color: {{color}}; color: {{textColor}}; border-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme.is-editable-on-click > .card-tile-inner .title:hover { background-color: {{ getReadableTransparentColor(color, 0.1, 0.2) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme.touched, .{{wrappercls}}.card-tile.card-tile-model-theme.selected, .{{wrappercls}}.card-tile.card-tile-model-theme:hover { background-color: {{darken(color, 5)}}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-title { color: {{textColor}}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-title .ref, .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-title .loader, .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-title .offline, .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-title .state-indicator { color: {{ getReadableTransparentColor(color, 0.75) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-title .model-indicator { color: {{darken(color, 30)}}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .request-indicator { color: {{ getReadableTransparentColor(color, 0.2, 0.1) }}; border-color: {{ getReadableTransparentColor(color, 0.2, 0.1) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-action { background-color: {{color}}; color: {{textColor}}; border-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-inner .card-tile-action:hover { background-color: {{darken(color, 5)}}; color: {{textColor}}; } .{{wrappercls}}.card-tile.card-tile-model-theme > .card-tile-children-list { border-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; background-color: {{color}}; } /********************************************************** * TILE MOD TASK */ .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .title { color: {{textColor}}; } .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task.is-editable-on-click > .card-tile-inner .title:hover { background-color: {{ getReadableTransparentColor(color, 0.1, 0.2) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .ref, .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .loader, .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .offline, .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .state-indicator { color: {{ getReadableTransparentColor(color, 0.75) }}; } .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .ref:hover { color: {{textColor}}; } .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .model-indicator { color: {{darken(color, 30)}}; } .{{wrappercls}}.card-tile.card-tile-model-theme.mod-task > .card-tile-inner .request-indicator { color: {{ getReadableTransparentColor(color, 0.2, 0.1) }}; border-color: {{ getReadableTransparentColor(color, 0.2, 0.1) }}; } /********************************************************** * BROWSER TILE */ card-browser-tile.{{wrappercls}} strong { background-color: {{color}}; } card-browser-tile.{{wrappercls}} .title { color: {{textColor}}; } card-browser-tile.{{wrappercls}} .model-indicator { color: {{darken(color, 30)}}; } /********************************************************** * TABLE ROW */ cards-app-table-row.{{wrappercls}} { background: {{color}}; border-bottom-color: {{darken(color, 5)}}; } cards-app-table-row.{{wrappercls}}:hover { background: {{darken(color, 10)}} !important; } cards-app-table-row.{{wrappercls}} .cards-app-table-cell { color: {{textColor}}; border-right-color: {{darken(color, 5)}}; } cards-app-table-row.{{wrappercls}} .cards-app-table-cell:hover { background: {{darken(color, 15)}} !important; } cards-app-table-row.{{wrappercls}} .cards-app-table-cell.title > *:not(.title):not(.text-composer) { color: {{darken(color, 20)}}; } cards-app-table-row.{{wrappercls}} .cards-app-table-cell.title:hover, cards-app-table-row.{{wrappercls}} .cards-app-table-cell.attribute:not(.not-available):hover { background: {{darken(color, 15)}} !important; } /********************************************************** * TIMELINE */ cards-app-timeline-card.{{wrappercls}} > .timeline-object .cards-app-timeline-card-container { background-color: {{color}}; color: {{textColor}} !important; border-color: {{ realdarken(color, 10) }}; } cards-app-timeline-card.{{wrappercls}} > .timeline-object .cards-app-timeline-card-ref, cards-app-timeline-card.{{wrappercls}} > .timeline-object .state-indicator { color: {{textColor}}; } cards-app-timeline-card.{{wrappercls}} > .timeline-object .model-indicator { color: {{darken(color, 30)}} !important; } cards-app-timeline-card.{{wrappercls}}.hovering-timeline-object > .timeline-object .cards-app-timeline-card-container, cards-app-timeline-card.{{wrappercls}}.dragging-timeline-object > .timeline-object .cards-app-timeline-card-container { border-color: {{ realdarken(color, 20) }}; } cards-app-timeline-card.{{wrappercls}} > .timeline-object .btn-timeline-object-expand-left, cards-app-timeline-card.{{wrappercls}} > .timeline-object .btn-timeline-object-expand-right { background-color: {{ realdarken(color, 20) }}; color: {{mostReadable(realdarken(color, 20), ['#fff', '#000'])}} } /********************************************************** * TIMELINE SIDEBAR */ .{{wrappercls}}.card-tile.mod-timeline { background-color: transparent; color: #666 !important; } .{{wrappercls}}.card-tile.mod-timeline.touched, .{{wrappercls}}.card-tile.mod-timeline.selected, .{{wrappercls}}.card-tile.mod-timeline:hover { background-color: transparent !important; } .{{wrappercls}}.card-tile.mod-timeline.editing { background: transparent !important; } .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner { background-color: {{color}}; color: {{textColor}} !important; } .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner.touched, .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner.selected, .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner:hover { background-color: {{darken(color, 10)}} !important; } .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .title, .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .ref, .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .link, .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .request-indicator, .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .state-indicator { color: {{textColor}}; } .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .model-indicator { color: {{darken(color, 30)}} !important; } .{{wrappercls}}.card-tile.mod-timeline > .card-tile-inner .card-tile-action { border-color: {{darken(color, 40)}}; } /********************************************************** * CHECKLIST */ board-checklist .{{wrappercls}}.card-tile.mod-task > .card-tile-inner .model, cards-app-checklist-group .{{wrappercls}}.card-tile.mod-task > .card-tile-inner .model { background-color: {{color}}; color: {{ getReadableTransparentColor(color, 0.75) }}; } board-checklist .{{wrappercls}}.card-tile.mod-task > .card-tile-inner .model-indicator, cards-app-checklist-group .{{wrappercls}}.card-tile.mod-task > .card-tile-inner .model-indicator { color: {{ getReadableTransparentColor(color, 0.75) }}; } /********************************************************** * CALENDAR */ .{{wrappercls}}.card-event { background-color: {{color}}; color: {{textColor}}; border-color: {{ getReadableTransparentColor(color, 0.1, 0.05) }}; } ");
  $templateCache.put("/static/app/ui/card-models/ng-components/templates/attributes.html", `<div> <ul class=model-attrs-list> <li ng-repeat="(key, attr) in attributes"> <attribute-options attribute=attr on-delete=removeAttribute(key) editable=true org=org project=project show-delete=true></attribute-options> </li> </ul> <button class="btn btn-default" ng-click=addAttribute()> <i class=bi-plus-lg></i> {{::_('Add field')}} </button> </div> `);
  $templateCache.put("/static/app/ui/card-models/ng-components/templates/editor.html", `<div class=model-editor> <div class=form-group> <label class=form-label for=name>{{::_('Name:')}}</label> <input class="form-control d-inline-block" type=text id=name required ng-model=model.name auto-grow min-width=250> </div> <div class=form-group> <label class=form-label for=modelColor>{{::_("Card background color:")}}</label> <input class=form-control type=text color-picker="{allowEmpty: true}" color=model.card_color ng-model=model.card_color id=modelColor> <p class=form-text> {{::_("All cards using this type will use this background color.")}} </p> </div> <div class=form-group> <label class=form-label>{{::_("Icon:")}}</label> <indicator-dropdown indicator=model.indicator></indicator-dropdown> <p class=form-text> {{::_("This icon will be displayed on card tiles")}} </p> </div> <div class=advanced ng-show=display.showMoreOpts> <div class=form-group ng-if=model.extends_id> <label class=form-label for=modelExtendsFrom>{{::_("Extends from:")}}</label> <select class="form-select d-inline-block" name=extends ng-model=model.extends_id id=modelExtendsFrom> <option value>--{{::_('Nothing')}}--</option> </select> <p class=form-text> {{::_("This feature is now deprecated. You can click the button below to remove the extend on this type. Inconsistencies may appear in the future if you don't remove it.")}} </p> </div> <div class=form-group> <label class=form-label for=modelDefaultChildModel>{{::_("Default type for sub-cards:")}}</label> <select class="form-select d-inline-block" name=childrenModel ng-model=model.children_default_model_id ng-options="m.id as m.name for m in models | modelsFilter:model" id=modelDefaultChildModel> <option value>--{{::_('This one')}}--</option> </select> <p class=form-text> {{::_("New child cards of a card which is using this type, will use the type selected above as their default one.")}} </p> </div> </div> <a class="d-block text-muted" href ng-click="display.showMoreOpts = !display.showMoreOpts"> {{display.showMoreOpts ? _('Hide advanced options') : _('Show advanced options')}} <i ng-class="{'bi-caret-down-fill': !display.showMoreOpts, 'bi-caret-up-fill': display.showMoreOpts}"></i> </a> <div class=attributes-editor> <div> <h4 class="d-inline-block me-2">{{::_('Fields')}}</h4> <small class=text-muted ng-show=extendedAttributes.length> <span class="form-check form-switch d-inline-block"> <input class=form-check-input type=checkbox role=switch ng-model=display.showInheritedAttr> <label class=form-check-label>{{::_('show inherited fields')}}</label> </span> </small> <small class=text-muted ng-show=!extendedAttributes.length> ({{::_("will inherit from the workspace's fields")}}) </small> </div> <ul ng-if="extendedAttributes && display.showInheritedAttr" class=model-attrs-list> <li class=from-extended ng-repeat="attr in extendedAttributes"> <attribute-options attribute=attr editable=false project=project org=org></attribute-options> </li> </ul> <hr ng-show="display.showInheritedAttr && model.extends_id"> <model-attr-list-editor model=model project=project org=org></model-attr-list-editor> </div> <div ng-if="!model.is_project_specific && model.id" class="alert alert-warning"> <p> <i class=bi-exclamation-triangle-fill style="margin-right: 5px;"></i>{{::_('This type is available for any workspace/template in your team.')}} </p> <p> <span ng-if="!model.used_by || !model.used_by.length">{{::_('No workspace/template is currently using it')}}</span> <span ng-if="model.used_by && model.used_by.length">{{::_n('{count} workspace/template is using it. The changes will be applied to it.', '{count} workspaces/templates are using it. The changes will be applied to all of them.', model.used_by.length)}}</span> </p> <button class="btn btn-default see-projects" ng-if="model.used_by && model.used_by.length" ng-click=loadProjects() ng-show=!showProjects>{{::_('See workspaces/templates')}}</button> <ul class=using-projects ng-if=showProjects> <li ng-repeat="project in projects"> <i ng-if=project.is_template class="fa fa-magic"></i> <i ng-if=!project.is_template class="fa fa-columns"></i> {{project.title}} (<span ng-if=project.is_template>{{::_("template")}}</span><span ng-if=!project.is_template>{{::_("workspace")}}</span>) </li> </ul> </div> </div> `);
  $templateCache.put("/static/app/ui/editors/filter-editor/templates/filter-editor-node.html", `<pretty-select ng-if=!$ctrl.isKQL ng-model=$ctrl.nodeType options=$ctrl.nodeTypes label-prop=label group-by=category filterable=true on-change=$ctrl.onNodeTypeChange()></pretty-select> <div ng-if="$ctrl.nodeType && $ctrl.nodeType.operators"> <pretty-select ng-model=$ctrl.cmpOperator options=$ctrl.nodeType.operators label-prop=label value-prop=op is-required=true on-change=$ctrl.onOperatorChange()></pretty-select> <input ng-if="!$ctrl.nodeType.options || $ctrl.nodeType.options[$ctrl.cmpOperator] === undefined" type=text ng-model=$ctrl.value ng-attr-placeholder={{$ctrl.nodeType.placeholder}} ng-change=$ctrl.notifyChangeDebounced() required> <pretty-select ng-if="$ctrl.nodeType.options &&
    $ctrl.nodeType.options[$ctrl.cmpOperator] !== undefined &&
    $ctrl.nodeType.options[$ctrl.cmpOperator] !== false" ng-model=$ctrl.value options=$ctrl.nodeType.options[$ctrl.cmpOperator] label-prop=label value-prop=value menu-item-prop=menu is-required=true placeholder={{$ctrl.nodeType.placeholder}} filterable=$ctrl.nodeType.optionsFilterable group-by=category on-change=$ctrl.notifyChange()></pretty-select> </div> <div ng-if="$ctrl.nodeType && !$ctrl.nodeType.operators && $ctrl.nodeType.options"> <pretty-select ng-model=$ctrl.value options=$ctrl.nodeType.options label-prop=label value-prop=value is-required=true placeholder={{$ctrl.nodeType.placeholder}} on-change=$ctrl.notifyChange()></pretty-select> </div> <div ng-if="!$ctrl.nodeType || (!$ctrl.nodeType.noValue && !$ctrl.nodeType.operators && !$ctrl.nodeType.options)"> <input type=text ng-model=$ctrl.value ng-attr-placeholder="{{$ctrl.nodeType ? $ctrl.nodeType.placeholder : ''}}" ng-change=$ctrl.notifyChangeDebounced() required> </div> `);
  $templateCache.put("/static/app/ui/editors/filter-editor/templates/filter-editor.html", `<div class=header> <span><i class=bi-filter></i> {{::_('Filter cards')}}</span> <div class=btn-group> <button ng-click="$ctrl.toggleEditor('visual')" ng-class="{'active': $ctrl.editor === 'visual'}" ng-disabled=!$ctrl.group> {{::_('Filter')}} </button> <button ng-click="$ctrl.toggleEditor('ask')" ng-class="{'active': $ctrl.editor === 'ask'}" ng-show=$ctrl.askAvailable> {{::_('Ask')}} <i class=bi-question-circle-fill uib-tooltip="{{::_('Use AI to generate a filter')}}" tooltip-popup-delay=0 tooltip-placement=bottom></i> </button> <button ng-click="$ctrl.toggleEditor('kql')" ng-class="{'active': $ctrl.editor === 'kql'}"> KQL <i class=bi-question-circle-fill uib-tooltip="{{::_('KQL is the Kantree Query Language and helps you copy filters and customize them in advanced ways')}}" tooltip-popup-delay=0 tooltip-placement=bottom></i> </button> </div> <button ng-click=$ctrl.clear() ng-hide="!$ctrl.source && !$ctrl.askQuestion"> <i class=bi-x></i> {{::_("Clear")}} </button> </div> <div class=loader ng-if="$ctrl.loading && $ctrl.editor === 'visual'"><loading-indicator></loading-indicator></div> <filter-editor-group ng-if="!$ctrl.loading && $ctrl.editor === 'visual'" fields=$ctrl.fields stores=$ctrl.stores node=$ctrl.group on-change=$ctrl.notifyChange($source)></filter-editor-group> <div ng-if="$ctrl.editor === 'ask'" class=ask-editor> <textarea ng-model=$ctrl.askQuestion rows=2 ng-keydown=$ctrl.onAskEditorKeyDown($event) placeholder="{{::_('Ask Kantree what cards you would like to see. Press enter to validate')}}" auto-focus ng-disabled=$ctrl.askProcessing></textarea> <div ng-show=$ctrl.askProcessing> <loading-indicator></loading-indicator> {{::_("Thinking...")}} </div> <div ng-show=$ctrl.askError class=text-danger> <i class=bi-exclamation-octagon-fill></i> {{$ctrl.askError}} </div> </div> <kql-editor ng-if="$ctrl.editor === 'kql'" ng-model=$ctrl.source on-validate="$ctrl.parse($value, $callback)" placeholder="{{::_('Type a KQL filter')}}" autocomplete-fields=$ctrl.fields save-on-enter=true save-btn="{{::_('Filter')}}" on-change=$ctrl.notifyChange($value) on-save=$ctrl.notifyChange($value)></kql-editor> `);
  $templateCache.put("/static/app/ui/editors/filter-editor/templates/filter-editor-group.html", `<div ng-repeat="node in $ctrl.nodes" class=node-container> <div class=op> <span ng-if=$first>{{::_('Where')}}</span> <select ng-options="o for o in ['and', 'or']" ng-model=$ctrl.op ng-if="$index === 1" ng-change=$ctrl.notifyChange()></select> <span ng-if="$index > 1">{{$ctrl.op}}</span> </div> <div class=node> <filter-editor-node fields=$ctrl.fields stores=$ctrl.stores node=node ng-if="!['And', 'Or'].includes(node[0])" on-change="$ctrl.notifyNodeChange(node, $source)"></filter-editor-node> <filter-editor-group fields=$ctrl.fields stores=$ctrl.stores node=node ng-if="['And', 'Or'].includes(node[0])" on-change="$ctrl.notifyNodeChange(node, $source)"></filter-editor-group> </div> <button ng-click="$ctrl.removeNode(node); $event.stopPropagation()"><i class="fa fa-trash"></i></button> </div> <div class=actions> <button ng-click=$ctrl.addNode()><i class=bi-plus></i> {{::_('Add condition')}}</button> <button ng-click=$ctrl.addGroup() ng-show="$ctrl.nodes.length > 0"><i class=bi-plus></i> {{::_('Add condition group')}}</button> </div> `);
  $templateCache.put("/static/app/ui/editors/sharing-editor/templates/sharing-editor.html", `<div class=sharing-editor-container> <div ng-if=!$ctrl.link>{{::$ctrl.emptyLabel}}</div> <div ng-if=$ctrl.link> <div class=form-group> <label class=form-label>{{::$ctrl.linkLabel}}</label> <copyable-readonly-input value=$ctrl.link show-qrcode=true on-qrcode=$ctrl.onEmbed() qrcode-modal-title="{{$ctrl.object.title || $ctrl.object.name}}"></copyable-readonly-input> </div> <div class=form-group ng-if="$ctrl.requestForms && $ctrl.requestForms.length && $ctrl.canEdit"> <label class=form-label>{{::_('Include a link to the following public forms:')}}</label> <div class="row row-cols-auto" ng-repeat="form in $ctrl.requestForms"> <kt-form-check value=$ctrl.selectedRequestFormIds.includes(form.id) switch=true on-change="$ctrl.toggleForm(form, $isChecked)">{{form.name}}</kt-form-check> <i ng-if=form.description class="fa fa-question-circle form-text" uib-tooltip={{form.description}} tooltip-placement="auto top"></i> </div> </div> <hr> <div class=form-group> <label class=form-label>{{::_('Sharing options:')}}</label> <kt-form-check value=$ctrl.shareOptions.only_show_request_comments switch=true ng-disabled=!$ctrl.canEdit on-change="$ctrl.updateOptions('only_show_request_comments', $isChecked)"> {{::_('Only show comments visible in form requests')}}</kt-form-check> <kt-form-check ng-if=$ctrl.canSelectShowFieldOption value=$ctrl.shareOptions.only_show_fields_from_view_settings switch=true ng-disabled=!$ctrl.canEdit on-change="$ctrl.updateOptions('only_show_fields_from_view_settings', $isChecked)"> {{::_('In cards, only show fields selected in view settings')}}</kt-form-check> </div> </div> </div> <div class=sharing-editor-controls> <button class="btn btn-danger" ng-click=$ctrl.unshare() ng-show="$ctrl.link && $ctrl.canEdit">{{::_('Unshare')}}</button> <button class="btn btn-default" ng-click=$ctrl.embed()><i class="fa fa-code"></i> {{::_('Embed')}}</button> </div> `);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-editor-action.html", `<div class=main-track> <div class=action> <div class=type> <i class="fa fa-magic"></i> <span>{{$ctrl.actionType ? ($ctrl.cardProvided ? _('Action on card') : _('Action')) : _('Add a new action')}}</span> <button drop-menu=$ctrl.descMenu ng-if=$ctrl.descMenu.config.length><i class=bi-info-circle></i></button> <button type=button ng-click=$ctrl.onDelete() ng-show=!$ctrl.actionType><i class=bi-trash3-fill></i></button> </div> <div class=header ng-class="{'unselected': !$ctrl.actionType, 'no-options': $ctrl.actionType && !$ctrl.actionType.options.length}"> <div class=dropdown> <a href drop-menu=$ctrl.dropMenu ng-if="::$ctrl.actionType && $ctrl.dropMenu" drop-config=$ctrl.dropConfig> <i ng-class=$ctrl.actionType.icon|iconClass></i> {{$ctrl.actionType.title}} <span class=bi-caret-down-fill></span> </a> <a href drop-menu=$ctrl.dropMenu ng-if=$ctrl.dropMenu ng-hide=::$ctrl.actionType drop-config=$ctrl.dropConfig> <i ng-class=$ctrl.actionType.icon|iconClass></i> {{_('Do action...')}} <span class=bi-caret-down-fill></span> </a> </div> <button ng-click=$ctrl.onDelete() ng-show=!!$ctrl.onDelete><i class=bi-trash3-fill></i></button> </div> <div class=options ng-if="$ctrl.actionType && ($ctrl.actionType.description || $ctrl.actionType.options.length)"> <div class=desc ng-if=$ctrl.actionType.description ng-bind-html=$ctrl.actionType.description|markdown></div> <options-editor options=$ctrl.actionType.options values=$ctrl.action.options project=$ctrl.project on-change="$ctrl.onChange({$block: $ctrl.action})"></options-editor> </div> </div> <div class=line ng-if="$ctrl.actionType && $ctrl.actionType.has_block"></div> </div> <div class=sub-track ng-if="$ctrl.actionType && $ctrl.actionType.has_block"> <div class=label>{{::$ctrl.actionType.has_block}}</div> <div class=line-h></div> <div class=line-v></div> <automation-rule-editor-sequence sequence=$ctrl.action.sequence card-provided=$ctrl.actionType.provides_card user-provided=$ctrl.userProvided project=$ctrl.project on-change="$ctrl.onChange({$block: this.action})" provided-variables=$ctrl.sequenceProvidedVariables error-states=$ctrl.errorStates></automation-rule-editor-sequence> </div> `);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-tile.html", `<div ng-click="$ctrl.canManageAutomations && $ctrl.onRuleClick(rule)" ng-disabled=!$ctrl.canManageAutomations> <i ng-class=$ctrl.icon|iconClass></i> <div class=inner> <span class=title> {{$ctrl.rule.name}} <span class="badge badge-sm ms-2 bg-danger" ng-show=$ctrl.rule.is_erroring><i class=bi-exclamation-triangle-fill></i> {{::_("Error")}}</span> <span class="badge badge-sm ms-2" ng-show=!$ctrl.rule.active><i class=bi-pause></i> {{::_("Paused")}}</span> </span> <span class=trigger>{{$ctrl.rule.trigger_title}}</span> <span ng-if=$ctrl.rule.last_trigger_at class=date>{{_('Last triggered {ago}', {ago: $ctrl.fromNow($ctrl.rule.last_trigger_at)})}}</span> <button type=button ng-click="$event.stopPropagation(); $ctrl.run()" ng-show=$ctrl.runnable class="btn btn-default btn-sm mt-2" ng-disabled=$ctrl.running> <i ng-class="$ctrl.running ? 'fa fa-spin fa-spinner' : 'bi-play-fill'"></i> {{::_('Run now')}} </button> </div> </div> <button drop-menu=$ctrl.dropMenu ng-if=$ctrl.canManageAutomations><i class=bi-three-dots-vertical></i></button> `);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-editor-branches.html", `<div class=warning ng-if=!$ctrl.cardProvided> <div class=line-label><i class=bi-info-circle-fill></i> {{_("This tests a condition across the workspace. Use a loop to test a condition and execute actions on individual cards instead")}}</div> <div class=line-v></div> </div> <div class=branches> <div ng-repeat="branch in $ctrl.branches.branches"> <div class=line-h ng-if="$ctrl.branches.branches.length > 1"></div> <div class=line-v></div> <div class=condition> <div class=header> <i class=bi-funnel-fill></i> <span>{{branch[0] === '__otherwise__' ? _("If no other condition matches...") : ($ctrl.cardProvided ? _("If the card matches...") : _("If any card in the workspace matches..."))}}</span> <button drop-menu=$ctrl.descMenu ng-if=$ctrl.descMenu.config.length><i class=bi-info-circle></i></button> </div> <div class=input> <filter-editor-input stores=$ctrl.stores ng-model=branch[0] placeholder="{{::_('KQL Condition')}}" ng-if="::(branch[0] !== '__otherwise__')" on-change=$ctrl.onChange()></filter-editor-input> <button ng-click=$ctrl.delete($index)><i class=bi-trash3-fill></i></button> </div> <div class=add ng-if=!!$last> <div class=line></div> <button drop-menu=::$ctrl.addMenu ng-hide=$ctrl.hasOtherwise><i class=bi-plus-lg></i></button> <button ng-click=$ctrl.add() ng-show=$ctrl.hasOtherwise><i class=bi-plus-lg></i></button> </div> </div> <automation-rule-editor-sequence sequence=branch[1] card-provided=$ctrl.cardProvided user-provided=$ctrl.userProvided project=$ctrl.project on-change="$ctrl.onChange({$block: this.branches})" provided-variables=$ctrl.providedVariables error-states=$ctrl.errorStates></automation-rule-editor-sequence> </div> </div> `);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-editor-query.html", `<div class=main-track> <div class=query> <div class=type> <i class=bi-search></i> <span>{{$ctrl.queryType ? _('Query') : _('Add a new query')}}</span> <button type=button ng-click=$ctrl.onDelete() ng-show=!$ctrl.queryType><i class=bi-trash3-fill></i></button> </div> <div class=header ng-class="{'unselected': !$ctrl.queryType, 'no-options': $ctrl.queryType && !$ctrl.queryType.options.length}"> <div class=dropdown> <a href data-toggle=dropdown ng-if=::$ctrl.queryType> <i ng-class=$ctrl.queryType.icon|iconClass></i> {{$ctrl.queryType.title}} <span class=bi-caret-down-fill></span> </a> <div class=dropdown-menu> <a ng-repeat="queryType in ::$ctrl.queryTypes" href ng-click=$ctrl.select(queryType)> <i ng-class=::(queryType.icon|iconClass)></i> {{::queryType.title}} </a> </div> </div> <button ng-click=$ctrl.onDelete() ng-show=!!$ctrl.onDelete><i class=bi-trash3-fill></i></button> </div> <div class=options ng-if="$ctrl.queryType && ($ctrl.queryType.description || $ctrl.queryType.options.length)"> <div class=desc ng-if=$ctrl.queryType.description ng-bind-html=$ctrl.queryType.description|markdown></div> <options-editor options=$ctrl.queryType.options values=$ctrl.query.options project=$ctrl.project on-change="$ctrl.onChange({$block: $ctrl.query})"></options-editor> </div> </div> <div class=line></div> </div> <div class=sub-track> <div class=label>{{$ctrl.queryType.block_label || _('for each item')}}</div> <div class=line-h></div> <div class=line-v></div> <automation-rule-editor-sequence sequence=$ctrl.query.sequence card-provided=$ctrl.queryType.provides_card project=$ctrl.project on-change="$ctrl.onChange({$block: this.query})" provided-variables=$ctrl.sequenceProvidedVariables error-states=$ctrl.errorStates></automation-rule-editor-sequence> </div> `);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-editor-sequence.html", `<div> <div class=line></div> <button drop-menu=$ctrl.addMenu ng-click="$ctrl.addAfterIndex = -1"><i class=bi-plus-lg></i></button> </div> <div ng-repeat="block in $ctrl._sequence"> <div class=line></div> <automation-rule-editor-event ng-if=::!!block.event event=block project=$ctrl.project on-delete=$ctrl.delete($index) on-change=$ctrl.notifyChange() provided-variables=$ctrl.stepProvidedVariables[$index]></automation-rule-editor-event> <automation-rule-editor-action ng-if=::!!block.action action=block card-provided=$ctrl.cardProvided user-provided=$ctrl.userProvided project=$ctrl.project on-delete=$ctrl.delete($index) on-change=$ctrl.notifyChange() provided-variables=$ctrl.stepProvidedVariables[$index] error-states=$ctrl.errorStates ng-class="{'has-error': $ctrl.hasError(block)}"></automation-rule-editor-action> <automation-rule-editor-branches ng-if=::!!block.branches branches=block card-provided=$ctrl.cardProvided user-provided=$ctrl.userProvided project=$ctrl.project on-delete="$ctrl.delete($index, $deletedBranch)" on-change=$ctrl.notifyChange() provided-variables=$ctrl.stepProvidedVariables[$index] error-states=$ctrl.errorStates ng-class="{'has-error': $ctrl.hasError(block)}"></automation-rule-editor-branches> <automation-rule-editor-query ng-if=::!!block.query query=block card-provided=$ctrl.cardProvided project=$ctrl.project on-delete=$ctrl.delete($index) on-change=$ctrl.notifyChange() provided-variables=$ctrl.stepProvidedVariables[$index] error-states=$ctrl.errorStates></automation-rule-editor-query> <div class=line ng-show=$ctrl.canAddAfter(block)></div> <button drop-menu=::$ctrl.addMenu ng-show=$ctrl.canAddAfter(block) ng-click="$ctrl.addAfterIndex = $index"><i class=bi-plus-lg></i></button> </div> `);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-editor.html", `<form name=$ctrl.ruleForm> <div> <input type=text class="form-control form-control-lg" ng-model=$ctrl.rule.name ng-attr-placeholder="{{::_('Rule name')}}" ng-change=$ctrl.triggerOnChange() required> <button drop-menu=$ctrl.appearanceDropMenu class="btn btn-icon btn-lg btn-default" uib-tooltip="{{::_('Edit appearance')}}"> <i ng-if=$ctrl.rule.icon ng-class=$ctrl.rule.icon|iconClass ng-style="{'color': $ctrl.rule.background_color && $ctrl.rule.background_color !== 'transparent' ? $ctrl.rule.background_color : null}"></i> <div ng-if=!$ctrl.rule.icon class=color-dot ng-style="{'background-color': $ctrl.rule.background_color,
                    'border': $ctrl.rule.background_color === 'transparent' || !$ctrl.rule.background_color ? '1px dashed #aaa' : null}"></div> </button> </div> <automation-rule-editor-event event=$ctrl.triggerEvent project=$ctrl.project is-trigger=true trigger-event-name={{$ctrl.rule.trigger_event}} is-new=$ctrl.isNew on-change="$ctrl.onTriggerEventChange(true, $isFirstEventTypeSelection)"> </automation-rule-editor-event> <automation-rule-editor-sequence ng-if=!!$ctrl.triggerEvent.event sequence=$ctrl.rule.sequence card-provided=$ctrl.cardProvided user-provided=!!$ctrl.triggerEventType.provides_user project=$ctrl.project on-change=$ctrl.triggerOnChange() provided-variables=$ctrl.providedVariables error-states=$ctrl.errorStates></automation-rule-editor-sequence> </form> <div class=rule-meta> <div class=active-states ng-if=$ctrl.activeStates> <loading-indicator></loading-indicator> {{_("{nbActiveRules} triggers are currently being processed", {nbActiveRules: $ctrl.activeStates})}} </div> <div class=errors ng-if=$ctrl.errorStates.length> <button ng-click=$ctrl.toggleShowErrors()> <i class=bi-exclamation-triangle-fill></i> {{::_("This rule has encountered errors")}} <span class=bi-caret-down-fill></span> </button> <div class=error-list ng-show=$ctrl.showErrors> <loading-indicator ng-if=$ctrl.loadingStates></loading-indicator> <a ng-repeat="state in $ctrl.errorStates" href ng-click="state.card && $ctrl.$cardModal.open(state.card)"> <span ng-if=state.card>#{{state.card.ref}}</span> {{state.error}} </a> <a href ng-click=$ctrl.clearErrors()><i class=bi-trash></i> {{::_('Clear all errors')}}</a> </div> </div> </div>`);
  $templateCache.put("/static/app/ui/editors/automation-rule-editor/templates/rule-editor-event.html", `<div class=type> <i class=bi-hourglass-split></i> <span>{{::$ctrl.isTrigger ? _('Trigger') : _('Wait for user action')}}</span> <button drop-menu=$ctrl.descMenu ng-if=$ctrl.descMenu.config.length><i class=bi-info-circle></i></button> <button type=button ng-click=$ctrl.onDelete() ng-show=!$ctrl.eventType><i class=bi-trash3-fill></i></button> </div> <div class=header ng-class="{'unselected': !$ctrl.eventType, 'no-options': $ctrl.eventType && !$ctrl.eventType.options.length}"> <div class=dropdown> <span class=rule-title ng-if="::$ctrl.eventType && (!$ctrl.dropMenu || !$ctrl.dropMenu.config.length)"> <i ng-class=$ctrl.eventType.icon|iconClass></i> {{$ctrl.eventType.title}} </span> <a href drop-menu=$ctrl.dropMenu ng-if="::$ctrl.eventType && $ctrl.dropMenu.config.length" drop-config=$ctrl.dropConfig> <i ng-class=$ctrl.eventType.icon|iconClass></i> {{$ctrl.eventType.title}} <span class=bi-caret-down-fill></span> </a> <a href drop-menu=$ctrl.dropMenu ng-if="$ctrl.dropMenu && $ctrl.dropMenu.config && $ctrl.dropMenu.config.length && !$ctrl.eventType" drop-config=$ctrl.dropConfig> <i class=bi-hourglass-split></i> {{_('Triggers when...')}} <span class=bi-caret-down-fill></span> </a> </div> <button ng-click=$ctrl.onDelete() ng-show=!!$ctrl.onDelete><i class=bi-trash3-fill></i></button> </div> <div class=options ng-if="!!$ctrl.eventType && ($ctrl.eventType.description || $ctrl.eventType.options.length)"> <div class=desc ng-if=$ctrl.eventType.description ng-bind-html=$ctrl.eventType.description|markdown></div> <options-editor options=$ctrl.eventType.options values=$ctrl.event.options project=$ctrl.project on-change=$ctrl.onOptionsChanged($values)></options-editor> </div> `);
  $templateCache.put("/static/app/ui/editors/kql-editor/templates/kql-editor.html", `<form ng-submit="$ctrl.onSave({$value: $ctrl.value})" ng-class="{'has-error': !$ctrl.isValid}"> <div> <textarea ng-model=$ctrl.value ng-attr-placeholder={{::$ctrl.placeholder}} auto-focus required ng-change=$ctrl.validate() ng-keypress=$ctrl.notifyEnterPress($event)></textarea> <div class=hint ng-show="$ctrl.isValid && $ctrl.showHint"> {{$ctrl.result !== null ? '= ' + $ctrl.result : ''}} </div> <div class=error ng-show=!$ctrl.isValid> <i class="fa fa-warning"></i> {{$ctrl.validationError}} </div> </div> <button type=submit class="btn btn-default" ng-disabled="!$ctrl.value || !$ctrl.isValid" ng-if=$ctrl.saveBtn>{{::$ctrl.saveBtn}}</button> </form> <div class=doc ng-show="$ctrl.autocompleteFields.length || $ctrl.autocompleteFuncs.length"> <div class=doc-list> <div class=header ng-show=$ctrl.autocompleteFields.length>{{::_('Fields')}}</div> <button class=btn ng-click=$ctrl.insertField(field) ng-mouseover=$ctrl.showFieldDoc(field) ng-repeat="field in $ctrl.autocompleteFields">{{field.name}}</button> <div class=header ng-show=$ctrl.autocompleteFuncs.length>{{::_('Functions')}}</div> <button class=btn ng-click=$ctrl.insertFunc(func) ng-mouseover=$ctrl.showDoc(func.doc) ng-repeat="func in $ctrl.autocompleteFuncs">{{func.name}}</button> </div> <div class=doc-content ng-bind-html=$ctrl.doc|markdown></div> </div> <a href=https://kantree.io/help/guides/kql target=_blank><i class="fa fa-external-link"></i> {{::_('Learn more about KQL')}}</a> `);
  $templateCache.put("/static/app/ui/editors/content-editor/templates/content-editor.html", `<div ng-if="$ctrl.activeEditor === 'prosemirror'" class=content-editor-prosemirror ng-prosemirror=$ctrl.editorType on-change=$ctrl._onChange($text) text=$ctrl.text hotkeys=$ctrl.hotkeys editor-data=$ctrl.editorData focus-on-load=$ctrl.focusOnLoad></div> <div ng-if="$ctrl.activeEditor === 'markdown'" class="content-editor-textarea markdown-editor"> <textarea class=form-control markdown-editor=$ctrl.editorType on-change=$ctrl._onChange($text) text=$ctrl.text hotkeys=$ctrl.hotkeys editor-data=$ctrl.editorData ng-attr-placeholder={{::$ctrl.placeholder}} focus-on-load=$ctrl.focusOnLoad></textarea> </div> <div class=content-editor-switcher> <button ng-click="$ctrl.switchEditor('markdown');" ng-class="{active: $ctrl.activeEditor === 'markdown'}">{{::_('Markdown')}}</button> <span>|</span> <button ng-click="$ctrl.switchEditor('prosemirror');" ng-class="{active: $ctrl.activeEditor === 'prosemirror'}">{{::_('Rich text')}}</button> </div> `);
  $templateCache.put("/static/app/ui/editors/content-editor/templates/content-composer.html", '<content-editor content=$ctrl.text editor-type={{$ctrl.composerOptions.type}} editor-data=$ctrl.composerOptions.data placeholder={{$ctrl.composerOptions.placeholder}} on-change=$ctrl.onTextChange($text) hotkeys=$ctrl.hotkeys force-editor={{$ctrl.composerOptions.defaultActiveEditor}} class=content-editor focus-on-load=true></content-editor> <button ng-repeat="button in $ctrl.composerOptions.buttons" uib-tooltip={{button.label}} ng-click="$ctrl.triggerHandlers(button.on, $event)" ng-class=button.class ng-disabled="button.whenTextChange.disabled && !$ctrl.contentChanged || $ctrl.disableButtons" ng-hide="button.whenTextChange.hide && !$ctrl.contentChanged" ng-bind-html=button.content> </button> ');
  $templateCache.put("/static/app/ui/editors/content-editor/templates/text-composer.html", `<textarea class=form-control ng-attr-placeholder="{{ options.placeholder }}" ng-attr-rows="{{ ::options.rows }}"></textarea> <button class="btn btn-success js-submit ms-1" type=button ng-show=isFocused ng-if=options.saveBtn ng-disabled=isSaving> {{::options.saveBtnLabel}} <i class=right ng-class=options.saveBtnIcon|iconClass ng-if=options.saveBtnIcon></i> </button> <button class="btn btn-icon js-close ms-1" type=button ng-show=isFocused ng-if=options.cancelBtn uib-tooltip={{::options.cancelBtnLabel}}><i class="fa fa-times"></i></button> <a href=https://help.github.com/articles/github-flavored-markdown/ target=_blank ng-show=isFocused ng-if=options.markdownSupport class=markdown-notice> {{::_('Github markdown supported.')}} </a> `);
  $templateCache.put("/static/app/ui/editors/recurrence-editor/templates/recurrence-editor.html", `<label class=form-label>{{::_('Repeats')}}</label> <div class=btn-group> <button ng-repeat="frequency in $ctrl.frequencies track by $index" class="btn btn-default" ng-class="{'active': $ctrl.isFrequencySelected(frequency.name)}" ng-attr-aria-pressed="{{ $ctrl.isFrequencySelected(frequency.name) ? 'true' : 'false'}}" ng-click=$ctrl.selectFrequency(frequency.name) ng-bind=frequency.label></button> </div> <div ng-if="$ctrl.isFrequencySelected('monthly')"> <label class=form-label>{{::_('On')}}</label> <div class="btn-group recurrence-monthdays"> <button ng-repeat="monthday in $ctrl.monthdays track by $index" class="btn btn-default" ng-class="{'active': $ctrl.isMonthdaySelected($index+1)}" ng-attr-aria-pressed="{{ $ctrl.isMonthdaySelected($index+1) ? 'true' : 'false'}}" ng-click=$ctrl.toggleMonthdays($index+1) ng-bind=monthday></button> </div> </div> <div ng-if="$ctrl.isFrequencySelected('weekly')"> <label class=form-label>{{::_('On')}}</label> <div class="btn-group recurrence-weekdays"> <button ng-repeat="weekday in $ctrl.weekdays track by $index" class="btn btn-default" ng-class="{'active': $ctrl.isWeekdaySelected($index)}" ng-attr-aria-pressed="{{ $ctrl.isWeekdaySelected($index) ? 'true' : 'false'}}" ng-click=$ctrl.toggleWeekdays($index) ng-bind=weekday></button> </div> </div> <div ng-if="!$ctrl.isFrequencySelected('hourly')"> <label class=form-label for=recurrenceHour>{{::_('At')}}</label> <div class=hours> <select class=form-select ng-model=$ctrl.recurrence.hour ng-options="hour as hour for hour in $ctrl.hours" ng-change=$ctrl.updateEditor() id=recurrenceHour></select> : <select class=form-select ng-model=$ctrl.recurrence.minutes ng-options="minutes as minutes for minutes in $ctrl.minutes" ng-change=$ctrl.updateEditor()></select> <div class="btn-group recurrence-amPm" ng-if=!$ctrl.isHours24Selector> <button ng-repeat="amPm in $ctrl.amPm track by $index" class="btn btn-default" ng-class="{'active': $ctrl.isAmPmSelected(amPm)}" ng-attr-aria-pressed="{{ $ctrl.isAmPmSelected(amPm) ? 'true' : 'false'}}" ng-click=$ctrl.selectAmPm(amPm) ng-bind=amPm></button> </div> </div> </div> `);
  $templateCache.put("/static/app/ui/activities/ng-components/templates/activity.html", `<div class=card-activity ng-class="{'is-comment': $ctrl.isComment}"> <span class=activity-header> <span class=activity-icon> <img ng-if="::$ctrl.actor.id || $ctrl.actor.special" class=avatar ng-src={{::$ctrl.actor|userAvatarUrl}} user-avatar-popover=$ctrl.actor> <span class=bullet ng-if="::!$ctrl.actor.id && !$ctrl.actor.special"></span> </span> <span class=activity-message> <span class=activity-title compile-html=::$ctrl.htmlMessage></span> <span class=activity-date uib-tooltip={{::$ctrl.activity.formatted_date_complete}} tooltip-popup-delay=0 tooltip-enable="$ctrl.hoursOnly !== 'true'">{{::($ctrl.hoursOnly === 'true' ? $ctrl.activity.date_hours_only : ($ctrl.activity.date|fromNow)) }}</span> <a href ng-click=$ctrl.markAsRead() ng-show=$ctrl.showMarkAsRead uib-tooltip="{{::_('Mark as read')}}" tooltip-popup-delay=0><i class=bi-eye-fill></i></a> </span> </span> <div ng-if=::$ctrl.isComment class="comment-message markdown" ng-bind-html=::$ctrl.commentHtmlMessage> </div> </div> `);
  $templateCache.put("/static/app/ui/activities/ng-components/templates/activities-line.html", `<li ng-class="[isUnread ? 'unread' : '', item.stream_type]"> <div card-comment class=card-comment ng-if="::item.stream_type === 'comment'" ng-class="{'pinned-comment': item.is_pinned}" comment=item store=store card=card actions=filteredActions show-request-indicator=showRequestIndicatorInComment></div> <card-log ng-if="::item.stream_type === 'log'" log=item card=card actions=filteredActions></card-log> <activity ng-if="::item.stream_type === 'activity'" activity=item card=card hours-only="{{ hoursOnly }}" show-mark-as-read=isUnread on-mark-as-read=onMarkAsRead() mark-as-read-on-scroll=markAsReadOnScroll is-stream=isStream></activity> </li> `);
  $templateCache.put("/static/app/ui/activities/ng-components/templates/log.html", `<div class="card-activity card-log"> <span class=activity-header> <span class=activity-icon> <img ng-if=::log.user class=avatar ng-src={{::user|userAvatarUrl}} uib-tooltip={{::user.display_name}}> </span> <span class=activity-message> <span class=activity-title ng-bind-html=::getLogMessage()></span> <span class=activity-date uib-tooltip={{::log.formatted_date_complete}} tooltip-popup-delay=0 tooltip-placement=right>{{::(log.date|fromNow)}}</span> </span> </span> <div class=card-log-attributes> <div class=card-log-attributes-header> {{logType.name}} <a href ng-if="can('delete')" ng-click=openDeletePopup()><i class="fa fa-trash-o"></i></a> </div> <attribute-table obj=log attribute-group=attributes></attribute-table> </div> </div> `);
  $templateCache.put("/static/app/ui/activities/ng-components/templates/comment.html", `<img class="card-comment-avatar hidden-xs" ng-src={{::user|userAvatarUrl}} alt={{::user.display_name}} user-avatar-popover=user> <div class=comment-wrapper ng-hide="isCommentEditing && isEditingEnabled()"> <span class=comment-header ng-class="{'is-expanded': isExpanded}"> <img class=visible-xs-inline-block ng-src={{::user|userAvatarUrl}} alt={{::user.display_name}}> <span class=comment-title> <span class=comment-owner>{{::user.display_name}}</span> <span class=comment-date uib-tooltip={{::comment.formatted_date_complete}} tooltip-popup-delay=0 tooltip-placement=right ng-if=!comment.offline> {{::(comment.date|fromNow)}} </span> </span> <span class=comment-actions ng-if=card> <span class=needs-sync ng-show=comment.offline uib-tooltip="{{::_('Waiting for synchronization')}}"> <i class="fa fa-refresh"></i> </span> <span class=request-indicator ng-show="showRequestIndicator && comment.show_in_request" uib-tooltip="{{::_('Visible in request')}}"> <i class="fa fa-inbox"></i> </span> <button class="btn btn-icon btn-sm" ng-class="{'disabled': isEditButtonDisabled()}" ng-if="can('edit', 'edit_temporarily')" ng-click=openCommentEditor() uib-tooltip="{{ getEditButtonTooltip() }}"><i class="fa fa-pencil"></i></button> <button class="btn btn-icon btn-sm" ng-if="can('pin')" ng-click=togglePin() ng-class="{active: comment.is_pinned}" uib-tooltip="{{comment.is_pinned ? _('unpin from the top') : _('pin to the top')}}"><i class="fa fa-bookmark"></i></button> <button class="btn btn-icon btn-sm" ng-if="can('delete')" ng-click=openDeletePopup() uib-tooltip="{{::_('Delete')}}"><i class="fa fa-trash-o"></i></button> <button class="btn btn-icon btn-sm" ng-if="comment.is_pinned && can('collapse')" uib-tooltip="{{isExpanded ? _('collapse') : _('expand')}} this comment" ng-click=toggleExpanded()> <i class=fa ng-class="{'fa-minus-square': isExpanded, 'fa-plus-square': !isExpanded}"></i> </button> </span> </span> <div ng-show=isExpanded class="comment-message markdown" ng-bind-html=htmlMessage></div> </div> <content-composer class=focus ng-if="isEditingEnabled() && isCommentEditing" options=commentEditorOptions content=comment.message on-submit=saveComment(submittedText) on-cancel=closeCommentEditor()></content-composer> `);
  $templateCache.put("/static/app/ui/activities/ng-components/templates/activities.html", `<div class=activity-stream> <div ng-if="$ctrl.groupedByDate === 'true'"> <div ng-repeat="dailyActivities in $ctrl.displayedActivities" class=daily-activity-stream> <h3 class=daily-activity-stream-header>{{ dailyActivities.formattedDate }}</h3> <ul class="activities list-unstyled" ng-class="{'reverse': $ctrl.reversed, 'is-stream': $ctrl.isStream}"> <activities-line ng-repeat="item in dailyActivities.activities track by item.id" item=item store=$ctrl.store card=$ctrl.card actions=$ctrl.actions show-request-indicator-in-comment=$ctrl.showRequestIndicatorInComment hours-only=$ctrl.hoursOnly is-unread="$ctrl.unreadIds === true || $ctrl.unreadIds && $ctrl.unreadIds.includes(item.id)" on-mark-as-read="$ctrl.onMarkAsRead({$activity: item})" mark-as-read-on-scroll=$ctrl.markAsReadOnScroll is-stream=$ctrl.isStream></activities-line> </ul> </div> <ul class="activities list-unstyled" ng-show="$ctrl.emptyMessage && !$ctrl.activitiesCount"> <li class=empty> {{$ctrl.emptyMessage}} </li> </ul> <ul class="activities list-unstyled" ng-show=$ctrl.loading> <li class="action loader"> <i class="fa fa-spinner fa-spin"></i> {{::_('Loading...')}} </li> </ul> </div> <ul ng-if="!$ctrl.groupedByDate || $ctrl.groupedByDate === 'false'" class="activities list-unstyled" ng-class="{'reverse': $ctrl.reversed, 'is-stream': $ctrl.isStream}"> <li class=action ng-show="!$ctrl.showAll && $ctrl.activitiesCount > $ctrl.limit && !$ctrl.loading"> <button class="activities-action-btn mb-2" type=button ng-click=$ctrl.toggleShowAll()> <i class=fa ng-class="{'fa-arrow-up' : !$ctrl.reversed, 'fa-arrow-down' : $ctrl.reversed}"></i> {{ _('Show all ({0} more)', $ctrl.activitiesCount - $ctrl.limit) }} </button> </li> <li class="action loader" ng-show=$ctrl.loading> <i class="fa fa-spinner fa-spin"></i> {{::_('Loading...')}} </li> <li class=empty ng-show="$ctrl.emptyMessage && !$ctrl.activitiesCount"> {{$ctrl.emptyMessage}} </li> <activities-line ng-repeat="item in $ctrl.displayedActivities track by item.id" item=item store=$ctrl.store card=$ctrl.card actions=$ctrl.actions show-request-indicator-in-comment=$ctrl.showRequestIndicatorInComment hours-only=$ctrl.hoursOnly is-unread="$ctrl.unreadIds && $ctrl.unreadIds.includes(item.id)" show-mark-as-read=$ctrl.onMarkAsRead on-mark-as-read="$ctrl.onMarkAsRead({$activity: item})" mark-as-read-on-scroll=$ctrl.markAsReadOnScroll is-stream=$ctrl.isStream></activities-line> </ul> </div> `);
  $templateCache.put("/static/app/ui/utils/ng-components/templates/lightbox.html", '<button class="btn-close btn-close-floating" aria-hidden=true ng-click=$dismiss()></button> <div class=modal-body ng-swipe-left=Lightbox.nextImage() ng-swipe-right=Lightbox.prevImage()> <img lightbox-src={{Lightbox.imageUrl}}> <div class=lightbox-nav> <a ng-click=Lightbox.prevImage() ng-if="Lightbox.images && Lightbox.images.length > 1"> <i class="fa fa-chevron-left"></i> </a> <a class=open ng-href={{Lightbox.imageUrl}} target=_blank></a> <a ng-click=Lightbox.nextImage() ng-if="Lightbox.images && Lightbox.images.length > 1"> <i class="fa fa-chevron-right right"></i> </a> </div> </div> ');
  $templateCache.put("/static/app/ui/system/ng-components/templates/search-drop.html", `<div class=drop-wrapper> <div class=dropdown-header> <form ng-submit=$ctrl.search()> <button type=button class="dropdown-header-btn js-drop-close me-sm-1 ms-3 ms-sm-0" ng-click=$ctrl.openSearchPage()><i class=bi-search></i></button> <input type=text class=js-search-input ng-model=$ctrl.filter ng-keyup=$ctrl.onKeyUp($event) ng-keydown=$ctrl.onKeyDown($event) placeholder={{$ctrl.searchPlaceholder}}> <button type=button class="dropdown-header-btn js-drop-close me-sm-1" ng-show=$ctrl._showOpenSearchBtn ng-click=$ctrl.openSearchPage()><i class=bi-box-arrow-up-right></i></button> <button type=button class="btn-close order-first order-sm-last" ng-class="{'js-drop-close': !$ctrl.filter}" ng-click=$ctrl.clear($event)></button> </form> </div> <div class=drop-body> <div ng-hide="$ctrl.loading || $ctrl.cards" class=board-results> <div class=results ng-if="::$ctrl.searchObjTypes.includes('project')"> <p class=help> {{::_('Quickly switch between workspaces or press enter to search for cards')}} </p> <ul> <li ng-repeat="project in $ctrl.matchingProjects track by project.id"> <search-drop-board-link ng-class="{'is-selected': $ctrl.selectedProject === project}" ng-mouseenter="$ctrl.selectedProject = project" item=project before-open-board="$ctrl.beforeOpenBoard(project, $event)"></search-drop-board-link> </li> </ul> <p class=help ng-hide="$ctrl.matchingProjects.length === 0">{{::_('Use \u2191\u2193 to select a workspace, CTRL + ENTER to open.')}}</p> </div> <div class=searches> <h3>{{::_('Suggested Searches:')}}</h3> <a href ng-repeat="search in $ctrl.suggestedSearches" ng-click="$ctrl.onSuggestedSearchClick(search, $event)">{{::search.title}}</a> </div> </div> <div class=loading ng-if=$ctrl.loading><i class="fa fa-spin fa-spinner"></i></div> <div ng-if="!$ctrl.loading && $ctrl.cards"> <div class="results card-tile-list"> <div ng-repeat="card in $ctrl.cards track by card.id" card-tile=card no-context-menu=true modal-load=true template-type=task show-project=true show-checkbox=false class="mod-task no-checkbox" load-related=true></div> </div> <div class=empty ng-if=!$ctrl.cards.length> <p>{{::_('No card found')}}</p> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/ui/system/ng-components/templates/notifications-drop.html", `<div class=drop-wrapper> <div class=dropdown-header> <h3 class=dropdown-header-title>{{$ctrl.dropTitle}}</h3> <button type=button class="btn-close js-drop-close"></button> </div> <div class=drop-body-top ng-show=$ctrl.showNewNotifsButton> <button type=button class="btn btn-primary btn-show-new-notifs" ng-click=$ctrl.showNewNotifs()> <i class="fa fa-arrow-up"></i> {{::_('New notifications are available')}} </button> </div> <div class=drop-body> <activities items=$ctrl.notifs reversed=true on-update=$ctrl.update() aggregate=false empty-message="{{::_('No notifications')}}" unread-ids=true on-mark-as-read=$ctrl.$notifications.markAsRead([$activity])></activities> </div> <div class=dropdown-footer> <button ng-show=$ctrl.notifs.length class="btn btn-default js-drop-close" ng-click=$ctrl.onMarkAllAsRead()>{{::_('Mark all as read')}}</button> </div> </div> `);
  $templateCache.put("/static/app/ui/requests/ng-components/templates/links-menu-component.html", `<div class=form-group> <label class=form-label>{{::_('The form is publicly accessible using this link')}}:</label> <copyable-readonly-input value=$ctrl.url show-qrcode=true qrcode-modal-title={{$ctrl.form.name}} on-qrcode=$ctrl.onClose()></copyable-readonly-input> </div> <div class=form-group ng-if=$ctrl.form.allow_request_via_email> <label class=form-label>{{::_('Requests can be sent by email at this address')}}:</label> <copyable-readonly-input value=$ctrl.form.inbound_email></copyable-readonly-input> </div> <button class="btn btn-default" ng-click=$ctrl.embed()><i class="fa fa-code"></i> {{::_('Embed')}}</button> `);
  $templateCache.put("/static/app/ui/requests/ng-components/templates/request.html", `<div class=request-form-header custom-bgcolor={{$ctrl.form.header_color}}> <h1>{{$ctrl.form.name}}</h1> <p ng-show=$ctrl.form.description>{{$ctrl.form.description}}</p> </div> <div class=request-form-tracking ng-if="$ctrl.form.tracking_groups && !$ctrl.request.closed"> <div ng-repeat="g in $ctrl.form.tracking_groups track by g.id" ng-class="{'active': $ctrl.activeGroups.indexOf(g.id) !== -1}"> <span class=dot><i class=fa ng-class="{
      'fa-arrow-right': !$last && $ctrl.activeGroups.indexOf(g.id) === -1,
      'fa-flag-checkered': $last && $ctrl.activeGroups.indexOf(g.id) === -1,
      'fa-check': $ctrl.activeGroups.indexOf(g.id) !== -1
    }"></i></span> <span class=title>{{g.title}}</span> </div> </div> <div class=request-form-content ng-if=!$ctrl.request.closed> <div class=request-form-control> <span ng-show=$ctrl.hasChanged>{{::_('Unsaved changes*')}}</span> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.startEdit() ng-if="$ctrl.form.editable_after_submit && !$ctrl.editing">{{::_("Edit my responses")}}</button> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.cancelEdit() ng-if=$ctrl.editing>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.update() ng-if=$ctrl.editing> <i class="fa fa-spin fa-spinner" ng-show=$ctrl.submitting></i>{{$ctrl.submitting ? _('Saving...') : _('Save')}}</button> </div> <div ng-if="$ctrl.request.email && $ctrl.form.anonymous_email_field_idx === null && $ctrl.form.email_required" class=form-group> <label class=form-label>{{::_('Your email:')}}</label> <input class=form-control type=email ng-model=$ctrl.request.email disabled> </div> <attribute-group obj=$ctrl.obj attribute-group=$ctrl.attributes ng-if=!$ctrl.editing></attribute-group> <attribute-form obj=$ctrl.editing.obj data=$ctrl.editing.data attribute-group=$ctrl.attributes ng-if=$ctrl.editing></attribute-form> </div> <div class=request-form-comments ng-if=!$ctrl.request.closed> <activities items=$ctrl.request.comments ng-show=$ctrl.request.comments.length></activities> <div class=comment-form ng-if=$ctrl.form.allow_comments ng-class="{'has-comments': $ctrl.request.comments.length}"> <content-composer options="{'buttons': [{'label': _('Comment'), 'whenTextChange' : {'disabled': true}}], 'on': {'blur': null}, 'uuid': 'request-comment-' + $ctrl.request.id, 'draftDelay': 200}" on-submit=$ctrl.postComment(submittedText) on-cancel="$ctrl.isCommentCreating = false" ng-if=$ctrl.isCommentCreating></content-composer> <button class=comment-placeholder ng-hide=$ctrl.isCommentCreating ng-click="$ctrl.isCommentCreating = true"> {{::_('Write a message')}} </button> </div> </div> <div class="request-form-content error" ng-if=$ctrl.request.closed> <p>{{::_('This request has been closed')}}</p> </div> `);
  $templateCache.put("/static/app/ui/requests/ng-components/templates/form.html", `<div class=request-form> <div class=request-form-header ng-hide=hideHeader custom-bgcolor={{form.header_color}}> <h1>{{form.name}}</h1> <p class="alert alert-error" ng-if=disableSubmitMessage>{{disableSubmitMessage}}</p> <p ng-show=form.description>{{form.description}}</p> </div> <div class=request-form-content> <div ng-if="!isAuthenticated() && form.anonymous_email_field_idx === null && form.email_required" class=request-form-email-input> <label class=form-label for=email>{{::_('Your email')}} ({{::_('required')}}):</label> <input class=form-control type=email id=email ng-model=$parent.email ng-required> </div> <attribute-form data=data obj=formObj attribute-group=attributes></attribute-form> </div> <div class=request-form-footer> <button class="btn btn-default btn-ghost btn-lg" type=button ng-click=onCancel() ng-show=onCancel>{{::_('Cancel')}}</button> <button class="btn btn-lg" type=submit ng-click=submit() ng-hide=!attributes.length custom-bgcolor="{{form.header_color || '#508fc7'}}" ng-disabled=disableSubmitBtn ng-attr-title="{{disableSubmitMessage || null}}"> <i class="fa fa-spin fa-spinner" ng-show=submitting></i> {{submitting ? _('Submitting...') : _('Submit')}} </button> </div> </div> `);
  $templateCache.put("/static/app/ui/card-groups/modals/templates/copy-group-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Copy {grouptype} to', {grouptype: groupType.singular_name})}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> <p>{{::_('Choose a workspace or a board where you want to copy your {grouptype}:', {grouptype: groupType.singular_name})}}</p> </div> <project-browser default-selected-card=parent on-changed=selectBoard(card)></project-browser> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=copyCards id=copyCards> <label class=form-check-label for=copyCards>{{::_('Copy cards')}}</label> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=copyTo(selectedBoard) ng-disabled=!selectedBoard>{{::_('Copy')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card-groups/modals/templates/group-type-groups-modal.html", `<div class=modal-header> <h4 class=modal-title>{{::groupType.name + (groupType.scope !== 'card' ? (groupType.scope === 'project' ? _(' (for the whole workspace)') : _(' (for the whole team)')) : '')}}</h4> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div ng-show=!settingsSelected> <div class=modal-body> <div class=nav-tabs> <div class=nav-tabs-tabs> <a class=nav-tab ng-class="{'active': section===0}" href ng-click="groups=openedGroups; section=0"> {{ _('{0} Open', groups.length) }} </a> <a class=nav-tab ng-class="{'active': section===1}" href ng-click="groups=archivedGroups; section=1"> {{ _('{0} Archived', archivedGroups.length) }} </a> </div> </div> <div class=empty-indicator ng-show="groups.length === 0"> {{::_('No groups')}} </div> <ul class=groups> <li ng-repeat="group in groups track by group.id"> <div class=infos> <span class="badge badge-lg" ng-class="{'has-color': group.color}" ng-style="{'background': group.color, 'color': textColor(group.color)}"> <i ng-class=group.icon|iconClass ng-if=group.icon></i> {{group.title}} </span> <div> <span class=actions ng-show=canEditGroup(group)> <a href class="btn btn-xs btn-default btn-icon" card-group-actions-menu-toggle group=group parent=parent uib-tooltip="{{::_('Options')}}"> <i class=bi-three-dots-vertical></i> </a> </span> <span class="date start" ng-if=group.start_date> <i class="fa fa-play"></i> {{ _('Starts on {0}', $ctrl.formatDate(group.start_date)) }} </span> <span class="date end" ng-if=group.end_date> <i class="fa fa-calendar"></i> {{ _('Due on {0}', $ctrl.formatDate(group.end_date)) }} </span> <span class="date end" ng-if="!group.start_date && !group.end_date"> {{::_('No due date')}} </span> </div> </div> <div class=status> <div class=progress> <div class=progress-bar ng-style="{'width': group.progress + '%'}"></div> </div> <span><strong>{{group.progress}}%</strong> {{::_('complete')}}</span> <span><strong>{{group.nb_cards - group.nb_finished_cards}}</strong> {{::_('open')}}</span> <span><strong>{{group.nb_finished_cards}}</strong> {{::_('finished')}}</span> </div> </li> <li ng-if=creating> <h3> <form ng-submit=create(titleInput)> <input class=form-control type=text ng-model=titleInput ng-required ng-blur=create(titleInput) auto-focus> </form> </h3> </li> </ul> </div> <div class=modal-footer> <button type=button class="btn btn-default pull-left" ng-click=startCreate() ng-show=canCreateGroups> <i class=bi-plus-lg></i> {{::_('Add new {grouptype}', {grouptype: groupType.singular_name})}} </button> <button type=button class="btn btn-default pull-left" ng-click=showSettings() ng-show=canEditGroupType> <i class=bi-sliders2></i> {{::_('Settings')}} </button> <button type=button class="btn btn-default pull-left" ng-click=deleteGroupType() ng-show="canManageGrouptype && !groupType.attribute_id"> <i class="fa fa-trash"></i> {{groupType.is_project_specific ? _('Delete this context') : _('Disable this context')}} </button> <button type=button class="btn btn-default" ng-click=$dismiss()> {{::_('Close')}} </button> </div> </div> <form name=groupTypeForm ng-if=settingsSelected> <div class=modal-body> <h2>{{_('Settings')}}</h2> <card-group-type-editor group-type=groupTypeEdit project=project></card-group-type-editor> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=cancelSettings()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-click=saveSettings() ng-disabled=groupTypeForm.$invalid>{{::_('Save')}}</button> </div> </form> `);
  $templateCache.put("/static/app/ui/card-groups/modals/templates/move-group-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Move {grouptype} to', {grouptype: groupType.singular_name})}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> <p>{{::_('Choose a workspace or a board where you want to move your {grouptype}:', {grouptype: groupType.singular_name})}}</p> </div> <project-browser default-selected-card=card on-changed=selectBoard(card)></project-browser> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=relocateCards id=relocateCards> <label class=form-check-label for=relocateCards>{{::_('Relocate cards')}}</label> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=moveTo(selectedBoard) ng-disabled=!selectedBoard>{{::_('Move')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card-groups/ng-components/templates/type-editor.html", `<div class=card-group-type-editor> <div class=form-group ng-hide=groupType.attribute_id> <label class=form-label for=gtName>{{::_('Name:')}}</label> <input type=text id=gtName name=gtName required ng-model=groupType.name min-width=250 class=form-control auto-focus> </div> <div class=form-group ng-hide="groupType.attribute_id || groupType.scope === 'project' || scopes.length === 1"> <label class=form-label for=gtScope>{{::_('Scope:')}}</label> <select class=form-select ng-model=groupType.scope ng-disabled=groupType.id ng-options="scope.id as scope.label for scope in scopes" id=gtScope> </select> <p class=form-text> {{::_("The scope defines to what parent groups will be bound to and which cards can the group contain.")}} </p> </div> <div class=form-group ng-hide=groupType.attribute_id> <label class=form-label for=gtDesc>{{::_('Description:')}}</label> <textarea ng-model=groupType.description class=form-control id=gtDesc></textarea> </div> <div class=form-group ng-hide=groupType.attribute_id> <label class=form-label>{{::_("Icon:")}}</label> <indicator-dropdown indicator=groupType.icon></indicator-dropdown> </div> <div class=form-group ng-hide=groupType.attribute_id> <label class=form-label for=gtSingularName>{{::_('Singular name:')}}</label> <input type=text id=gtSingularName name=gtSingularName required ng-model=groupType.singular_name min-width=250 class=form-control ng-class="::{'autofill': !groupType.singular_name}"> <p class=form-text> {{::_("The context name in singular form for display purposes")}} </p> </div> <div class=form-group ng-hide=groupType.attribute_id> <label class=form-label for=gtPluralName>{{::_('Plural name:')}}</label> <input type=text id=gtPluralName name=gtPluralName required ng-model=groupType.plural_name min-width=250 class=form-control ng-class="::{'autofill': !groupType.plural_name}"> <p class=form-text> {{::_("The context name in plural form for display purposes")}} </p> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=groupType.one_group_per_card id=gtOneGroupPerCard> <label class=form-check-label for=gtOneGroupPerCard>{{::_("Cards can only be in one group of this type at a time")}}</label> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=groupType.auto_random_color id=gtRandomColor> <label class=form-check-label for=gtRandomColor>{{::_("Automatically apply a random color to new groups")}}</label> </div> <div class=form-group> <label class=form-label for=gtPeriod>{{::_("Automatically set start date and end date with the following interval:")}}</label> <input type=text ng-model=groupType.auto_assign_period min-width=250 class=form-control id=gtPeriod> <p class=form-text> {{::_("To specify the period, you can either input the number of days or a number suffixed with 'h' for hours, 'w' for weeks or 'm' for months.")}} </p> </div> <div ng-if="!groupType.is_project_specific && !groupType.attribute_id && groupType.id" class="alert alert-warning"> <p> <i class=bi-exclamation-triangle-fill></i>{{::_('This context is available for any workspace/template in your team.')}} </p> <p> <span ng-if="!groupType.used_by || !groupType.used_by.length">{{::_('No workspace/template is currently using it')}}</span> <span ng-if="groupType.used_by && groupType.used_by.length">{{::_n('{count} workspace/template is using it. The changes will be applied to it.', '{count} workspaces/templates are using it. The changes will be applied to all of them.', groupType.used_by.length)}}</span> </p> <button class="btn btn-default see-projects" ng-if="groupType.used_by && groupType.used_by.length" ng-click=loadProjects() ng-show=!showProjects>{{::_('See workspaces/templates')}}</button> <ul class=using-projects ng-if=showProjects> <li ng-repeat="project in projects track by project.id"> <i ng-if=project.is_template class="fa fa-magic"></i> <i ng-if=!project.is_template class="fa fa-columns"></i> {{project.title}} (<span ng-if=project.is_template>{{::_("template")}}</span><span ng-if=!project.is_template>{{::_("workspace")}}</span>) </li> </ul> </div> </div> `);
  $templateCache.put("/static/app/ui/card-groups/ng-components/templates/group-selector.html", `<div class=group ng-repeat="formattedGroup in $ctrl.groupsFormatted track by formattedGroup.obj.id" ng-style="::{
    'background-color': formattedGroup.obj.color || '#eee',
    'color': $ctrl.textColor(formattedGroup.obj.color, null, null)
  }" ng-class="{
    'has-dark-background': $ctrl.isReadable(formattedGroup.obj.color, '#fff')
  }"> <button class=group-button groups-menu-toggle=formattedGroup.menuSpec drop-config=$ctrl.dropConfig> <div class=group-button-grouptype-label ng-if=::formattedGroup.groupType ng-style="::{
        'color': $ctrl.textColor(formattedGroup.obj.color, 'rgba(0,0,0,0.5)', 'rgba(255,255,255,0.5)', '#777')
      }" ng-bind=::formattedGroup.groupType.singular_name></div> <i ng-if=::formattedGroup.obj.icon ng-class=formattedGroup.obj.icon|iconClass></i> <span ng-bind=::formattedGroup.obj.title></span> </button> <button class=remove-group-button ng-click="$ctrl.handleGroupRemove(formattedGroup.obj, $event)" ng-style="::{
      'color': $ctrl.textColor(formattedGroup.obj.color, 'rgba(0,0,0,0.5)', 'rgba(255,255,255,0.5)', '#777')
    }"><i class="fa fa-times"></i></button> </div> <button class=add-group-button group-types-menu-toggle=$ctrl.groupTypesMenuFactoryParams drop-config=$ctrl.dropConfig><i class=bi-plus-lg></i></button> `);
  $templateCache.put("/static/app/ui/inbox/ng-components/templates/inbox.html", `<div class=inbox> <div class=unread-notice ng-if=$ctrl.hasUnread> <div> <span><i class="fa fa-arrow-down"></i> {{_n('You have {count} unread item', 'You have {count} unread items', $ctrl.unreadIds.length)}} <i class="fa fa-arrow-down"></i></span> </div> <span>(<a href ng-click=$ctrl.markAllAsRead()>{{::_('Mark all as read')}}</a>)</span> </div> <div ng-repeat="item in $ctrl.feed track by item.id"> <span ng-if="item.separator && !item.unread" class="date-separator daily-activity-stream-header"> {{item.separator}} </span> <span ng-if="item.separator && item.unread && $ctrl.hasUnread" class=unread-separator> <span>{{::_('End of unread items')}}</span> </span> <activities ng-if="!item.separator && !item.card" items=item.activities reversed=true limit=false aggregate=false is-stream=true unread-ids=$ctrl.unreadIds on-mark-as-read=$ctrl.markAsRead([$activity])></activities> <card-stream-box ng-if="!item.separator && item.card" card=item.card activities=item.activities unread-ids=$ctrl.unreadIds on-mark-as-read=$ctrl.markAsRead($activities) mark-as-read-when-comment=$ctrl.markAsReadWhenComment mark-as-read-on-scroll=$ctrl.markAsReadWhenScrolled></card-stream-box> </div> <div class=loading ng-if=$ctrl.loading> <div class=title></div> <div class=message></div> <div class=message></div> </div> <div class=empty-inbox ng-if="!$ctrl.feed.length && !$ctrl.loading"> <h2 class=daily-activity-stream-header>{{::_('Your Inbox is empty')}}</h2> <p ng-hide=$ctrl.unreadOnly> {{::_("Once you have subscribed to some cards or received notifications, you will be able to read and reply to comments here")}} </p> <p ng-show=$ctrl.unreadOnly> {{::_("Congrats! You have no unread activities")}} </p> </div> </div> `);
  $templateCache.put("/static/app/ui/base/ng-components/templates/invite-form.html", `<div class=invite-form> <h3>{{::_('Add existing members or send email invites to new members:')}}</h3> <form name=inviteForm ng-submit=submit() ng-disabled=submitting> <div class=input-group> <input class=form-control type=text placeholder={{::placeholder}} ng-model=emailOrUsernames auto-focus=autoFocusInput required uib-typeahead="contact.email as contact.name for contact in autocomplete($viewValue)" typeahead-wait-ms=300> <button type=submit class="btn btn-primary" ng-disabled=inviteForm.$invalid> <i class="fa fa-spin fa-spinner" ng-show=submitting></i> {{submitting ? _('Sending...') : _('Send invite')}} </button> </div> <textarea class="form-control mt-3" ng-model=message ng-show=showMessage placeholder="{{::_('Add a custom message to the invite')}}" rows=5></textarea> <a class="btn btn-sm btn-link" href ng-click="showMessage=true" ng-show=!showMessage>{{::_('Add a custom message to the invite')}}</a> </form> </div> `);
  $templateCache.put("/static/app/ui/base/ng-components/templates/date-navigator.html", `<button ng-disabled=$ctrl.activeRangeIsBeforeMinDate class="btn btn-icon arrow" ng-click="$ctrl.updateRange('prev')" ng-if=$ctrl.showArrows><i class=bi-chevron-left></i> </button> <button class="btn picker needsclick" ng-if=$ctrl.showDatepicker datepicker-dropdown=$ctrl.activeRange datepicker-options=$ctrl.pickerOptions datepicker-range=true on-date-change="$ctrl.updateRange({start: $start, end: $end})"> <span class=formatted-range><i class=bi-calendar></i>{{ $ctrl.formattedActiveRange }}</span> <span class=range-label ng-if="$ctrl.showSpecialLabels && $ctrl.activeRangeLabel">{{ $ctrl.activeRangeLabel }}</span> </button> <div class=picker ng-if=!$ctrl.showDatepicker> <span class=formatted-range><i class=bi-calendar></i>{{ $ctrl.formattedActiveRange }}</span> <span class=range-label ng-if="$ctrl.showSpecialLabels && $ctrl.activeRangeLabel">{{ $ctrl.activeRangeLabel }}</span> </div> <button ng-disabled=$ctrl.activeRangeIsAfterToday class="btn btn-icon arrow" ng-click="$ctrl.updateRange('next')" ng-if=$ctrl.showArrows><i class=bi-chevron-right></i> </button> `);
  $templateCache.put("/static/app/ui/base/ng-components/templates/files.html", '<ul class=file-gallery> <li ng-repeat="f in displayFiles"> <file-thumb file=f card=card store=store show-delete={{showDelete}} deleted="deleted({file: f})" show-cover={{showCover}}></file-thumb> </li> </ul>');
  $templateCache.put("/static/app/ui/base/ng-components/templates/file-thumb.html", `<div class=file-thumb ng-class="{'image': imageUrl}"> <a href ng-click=open($event) uib-tooltip={{file.name}}> <div class=thumb ng-style="{'background-image': imageUrl ? 'url(' + imageUrl + ')' : null}"> <i class=fa ng-class=file.fileTypeIcon></i> </div> <div class=name>{{ file.name }}</div> </a> <button class="btn btn-icon" drop-menu=menuConfig> <i class="fa fa-ellipsis-v"></i> </button> </div> `);
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/menu-panel.html", `<div class=menu-panel-header ng-class="{'mod-tabs': $ctrl.panel.tabs.length > 1}" ng-if=$ctrl.panel.title> <span class=menu-button ng-click=$event.stopPropagation();$ctrl.menu.back() ng-if="$ctrl.panel.level.length > 1" ng-class="{'mod-text': $ctrl.panel.title}"> <i class="fa fa-chevron-left"></i> <i ng-class=$ctrl.panel.icon|iconClass ng-if=$ctrl.panel.icon></i> <span class=menu-panel-title ng-if=$ctrl.panel.title>{{ $ctrl.panel.title }}</span> </span> <span ng-if="$ctrl.panel.title && $ctrl.panel.level.length <= 1" class=menu-panel-title><i ng-class=$ctrl.panel.icon|iconClass ng-if=$ctrl.panel.icon></i> {{ $ctrl.panel.title }}</span> <button class=menu-button ng-if=$ctrl.panel.settings ng-click=$ctrl.panel.settings($event) uib-tooltip="{{::_('Settings')}}"> <i class=bi-three-dots-vertical></i> </button> <button class=menu-button ng-if=$ctrl.sortable ng-click=$ctrl.toggleSort() uib-tooltip="{{::_('Sort')}}"> <i ng-class="{'bi-sort-alpha-down': $ctrl.sortAsc === true,
                  'bi-sort-alpha-down opacity-50': $ctrl.sortAsc === null,
                  'bi-sort-alpha-up': $ctrl.sortAsc === false}"></i> </button> </div> <div class=menu-panel-tabs ng-if="$ctrl.panel.tabs.length > 1"> <span class=menu-panel-tab ng-repeat="tab in $ctrl.panel.tabs track by tab.id" ng-if="$ctrl.panel.tabs && $ctrl.panel.tabs.length" ng-class="{'is-selected': tab.id === $ctrl.selectedTab.id, 'mod-inline': tab.isInline }" ng-click="$ctrl.selectTab(tab, $event)" ng-disabled="!$ctrl.isConnected() && !tab.offline"> <i ng-if=tab.icon class=menu-panel-tab-icon ng-class=tab.icon|iconClass></i> <span ng-if=tab.title class=menu-panel-tab-title ng-show="!tab.showTitleOnlyWhenSelected || tab.id === $ctrl.selectedTab.id">{{ tab.title }}</span> </span> </div> <div class=menu-panel-filter ng-if=$ctrl.defaultFilterEnabled> <div class=menu-item-input> <form ng-class="{'is-focused': $ctrl.filterFocused}"> <input class=form-control type=text ng-model=$ctrl.filter ng-attr-placeholder="{{::_('Filter')}}" ng-change=$ctrl.onFilterChange() ng-focus="$ctrl.filterFocused = true" ng-blur="$ctrl.filterFocused = false"> </form> </div> </div> <div class=menu-panel-content ng-class=$ctrl.selectedTab.classes> <menu-panel-items items=$ctrl.selectedTab.items></menu-panel-items> </div> <div class=menu-panel-help ng-if=$ctrl.panel.help> <help-link guide={{$ctrl.panel.help.guide}} anchor={{$ctrl.panel.help.anchor}}> <i class="bi bi-question-circle-fill menu-icon"></i> {{$ctrl.panel.help.label || _('Help')}} <i class="bi bi-box-arrow-up-right"></i> </help-link> </div> `);
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/items/selectbox.html", '<select ng-model=$ctrl.value ng-disabled=$ctrl.disabled() class=form-select ng-options="opt[$ctrl.item.optionsLabelProperty] group by opt.optGroup for opt in $ctrl.item.selectOptions"> </select> ');
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/items/input.html", `<form ng-submit=$ctrl.onSubmit($event) ng-class="{'is-content': $ctrl.item.content, 'is-number': $ctrl.item.type === 'number', 'is-focused': $ctrl.formFocused, 'is-disabled': $ctrl.disabled()}"> <button class="btn-menu-input btn-menu-input-focus" ng-if=$ctrl.item.icon ng-click=$ctrl.onFocusBtn($event) ng-disabled=$ctrl.disabled()> <i ng-class=$ctrl.item.icon|iconClass></i> </button> <input class=form-control ng-if=$ctrl.item.input ng-attr-type="{{$ctrl.item.type ||\xA0'text'}}" ng-disabled=$ctrl.disabled() ng-attr-placeholder="{{ $ctrl.placeholder }}" ng-model=$ctrl.value ng-change=$ctrl.handleInputChange()> <textarea class=form-control ng-if=$ctrl.item.content ng-attr-placeholder="{{ $ctrl.placeholder }}" ng-model=$ctrl.value ng-change=$ctrl.handleInputChange() ng-keydown=$ctrl.onKeydown($event) ng-disabled=$ctrl.disabled()></textarea> <button type=submit class="btn-menu-input btn-menu-input-submit" ng-show=$ctrl.submitable() uib-tooltip="{{::_('Save')}}"> <span ng-if=$ctrl.item.content>{{::_('Shift +')}}</span> <span class="fa-stack fa-lg icon-enter"> <i class="fa fa-square-o fa-stack-2x"></i> <i class="fa fa-level-down fa-rotate-90 fa-stack-1x"></i> </span> </button> <button class="btn-menu-input btn-menu-input-reset" ng-show=$ctrl.resetable() ng-click=$ctrl.onResetBtn($event)> <i class="fa fa-times-circle"></i> </button> </form> <button ng-if="$ctrl.item.buttons && $ctrl.item.buttons.length" class="btn btn-sm btn-text menu-item-additional-button" ng-repeat="button in $ctrl.item.buttons" ng-class=button.classes ng-style="{'color': button.color || null}" ng-click=button.action($event) ng-show="!button.enabled || button.enabled()"> <i ng-class=button.icon|iconClass ng-if=button.icon></i> <span ng-if=button.label>{{button.label}}</span> </button> `);
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/items/colorpicker.html", `<ul class=menu-colorpicker-content> <li ng-repeat="color in $ctrl.displayedColors"> <button class=menu-colorpicker-color-button ng-click="$ctrl.item.action($event, color)" ng-class="{'is-selected': $ctrl.isSelected(color)}"> <span ng-if="color || $ctrl.item.noColorColor" ng-style="{'background-color': color || $ctrl.item.noColorColor}"> <i class="fa fa-check" ng-if=$ctrl.isSelected(color)></i> </span> <span ng-if="!color && !$ctrl.item.noColorColor" class=no-color> <i class="fa fa-check" ng-if=$ctrl.isSelected(color)></i> </span> </button> </li> <li ng-if=$ctrl.item.submenu class=menu-colorpicker-more> <button class="btn btn-default btn-sm btn-text menu-item-additional-button" ng-class="{'btn-icon': !$ctrl.item.submenuLabel}" ng-click=$ctrl.item.openSubmenu($event) uib-tooltip={{$ctrl.item.submenuTooltip}} tooltip-enable=!!$ctrl.item.submenuTooltip> <span ng-if=$ctrl.item.submenuLabel>{{$ctrl.item.submenuLabel}}</span> <i class=fa ng-class=$ctrl.item.submenuIcon|iconClass ng-if=$ctrl.item.submenuIcon></i> </button> </li> </ul> `);
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/items/default.html", `<button type=button class=menu-item-main-action-button ng-click=$ctrl.item.action($event) ng-if=::!!$ctrl.item.label ng-style="::{'background-color': $ctrl.item.bgColor || null,
              'color': $ctrl.item.textColor || null}"> <div class=color-dot ng-style="::{'background-color': $ctrl.item.color,
                'border': $ctrl.item.color === 'transparent' ? '1px dashed #aaa' : null}" ng-if="::!!($ctrl.item.color && !$ctrl.item.icon)"></div> <div class=color-rectangle ng-style="::{'background-color': $ctrl.item.rectangleColor,
                'border': $ctrl.item.rectangleBorder || '1px solid #000'}" ng-if=::!!($ctrl.item.rectangleColor)></div> <div class=color-diamond ng-style="::{'background-color': $ctrl.item.diamondColor,
                'border': $ctrl.item.diamondBorder || '1px solid #000'}" ng-if=::!!($ctrl.item.diamondColor)></div> <div class=enter-arrow ng-if=::!!$ctrl.item.arrowColor> <div class=arrow-stem ng-style="::{'background-color': $ctrl.item.arrowColor || '#000'}"></div> <div class=arrow-branch ng-style="::{'background-color': $ctrl.item.arrowColor || '#000'}"></div> <div class=arrow-head ng-style="::{'border-color': 'transparent transparent transparent ' + ($ctrl.item.arrowColor || '#000')}"></div> </div> <i class=menu-icon ng-class=::($ctrl.item.icon|iconClass) ng-style="::{'color': $ctrl.item.color && $ctrl.item.color !== 'transparent' ? $ctrl.item.color : null}" ng-if=::!!$ctrl.item.icon></i> <img class=menu-img ng-if=::!!$ctrl.item.img ng-src="{{ ::$ctrl.item.img }}"> <span class=menu-item-label> {{::$ctrl.item.label}} <feature-flag-label org=::$ctrl.item.featureFlag[0] flag={{::$ctrl.item.featureFlag[1]}} ng-if=::$ctrl.item.featureFlag></feature-flag-label> </span> <small class=menu-item-default-small ng-if=::!!$ctrl.item.small>{{::$ctrl.item.small}}</small> <i class="fa fa-check menu-item-selected" ng-if=$ctrl.item.selected()></i> </button> <i class="fa fa-question-circle menu-item-help" ng-if=::!!$ctrl.item.help uib-tooltip={{::$ctrl.item.help}} tooltip-placement="auto top"></i> <button type=button ng-repeat="button in ::$ctrl.item.buttons" class="btn btn-sm menu-item-additional-button {{button.classes}}" ng-if="::!!($ctrl.item.buttons && $ctrl.item.buttons.length)" ng-class="{
    'is-selected': button.selected(),
    'btn-icon': !button.label,
    'btn-default btn-text': !button.classes
  }" ng-style="::{'color': button.color && button.color !== 'transparent' ? button.color : null}" ng-click=button.action($event) ng-show="!button.enabled || button.enabled()" ng-disabled=button.disabled() uib-tooltip={{::button.tooltip}} tooltip-enable=::!!button.tooltip> <div class=color-dot ng-style="::{'background-color': button.color,
              'border': button.color === 'transparent' ? '1px dashed #aaa' : null}" ng-if="::!!(button.color && !button.icon)"></div> <i class=menu-icon ng-class=::(button.icon|iconClass) ng-style="::{'color': button.color && button.color !== 'transparent' ? button.color : null}" ng-if=::!!button.icon></i> <span class=menu-item-button-label ng-if=::!!button.label>{{::button.label}}</span> <small class=menu-item-default-small ng-if=::!!button.small>{{::button.small}}</small> <i class="fa fa-check menu-item-selected" ng-if=button.selected()></i> </button> `);
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/items/iconpicker.html", `<ul class=menu-iconpicker-content ng-class="{'menu-iconpicker-completeset': $ctrl.item.completeSet}"> <li ng-repeat="icon in $ctrl.displayedIcons"> <button class=menu-iconpicker-icon-button ng-click="$ctrl.select($event, icon)" ng-class="{'is-selected': $ctrl.isSelected(icon)}"> <span class={{icon|iconClass}} ng-class="{'is-selected': $ctrl.isSelected(icon), 'no-icon': !icon}" ng-style="{'background-color': $ctrl.isSelected(icon) && $ctrl.item.color ? $ctrl.item.color : null,
          'color': $ctrl.isSelected(icon) && $ctrl.textColor ? $ctrl.textColor : null}"> <i class="fa fa-check" ng-if=$ctrl.isSelected(icon)></i> </span> </button> </li> <li ng-if=$ctrl.item.submenu class=menu-iconpicker-more> <button class="btn btn-default btn-sm btn-icon btn-text menu-item-additional-button" ng-click=$ctrl.item.openSubmenu($event)> <i class="fa fa-chevron-right"></i> </button> </li> </ul> `);
  $templateCache.put("/static/app/ui/base/ng-components/pretty-menu/templates/items/filepicker.html", `<div class=menu-filepicker-dropzone ngf-drop="$ctrl.pickFile($event, $files)" ngf-drag-over-class=dragover ngf-drop-disabled=$ctrl.item.readOnly> <span class=menu-filepicker-dropzone-label-main ng-hide="$ctrl.item.getIsLoading() || $ctrl.pickedFile"> {{::_('Drag an image here')}} </span> <span class=menu-filepicker-progress-bar ng-show=$ctrl.item.getIsLoading()> <i class="fa fa-spin fa-spinner"></i> <span ng-show=$ctrl.item.getProgress()>{{$ctrl.item.getProgress()}}%</span> </span> <img class=menu-filepicker-thumbnail ngf-thumbnail=$ctrl.pickedFile ng-hide=$ctrl.item.getIsLoading()> <div class=menu-filepicker-input ng-hide="$ctrl.item.readOnly || $ctrl.pickedFile || $ctrl.item.getIsLoading()"> <input class=form-control type=file id=file ngf-select="$ctrl.pickFile($event, $files)"> <label class="btn btn-primary btn-sm" for=file><i class="fa fa-upload menu-icon"></i> {{::_('Select from your computer')}}</label> </div> <button class=menu-filepicker-delete-button ng-click=$ctrl.unpickFile($event) ng-hide="$ctrl.item.readOnly || (!$ctrl.pickedFile && !$ctrl.item.getIsLoading())"> <i class="fa fa-times menu-icon"></i> </button> </div> `);
  $templateCache.put("/static/app/ui/base/ng-components/sidebar/templates/project-page-header.html", `<div> <div class=project-back-link ng-if=$ctrl.board.parent_id> <a ui-sref="project({projectId: $ctrl.project.slug})">{{$ctrl.project.title}}</a> <span>/</span> </div> <div class=page-breadcrumb> <div class="path hidden-xs" ng-if=$ctrl.path.length> <button class=btn type=button drop-menu=$ctrl.pathMenu drop-config=$ctrl.pathMenuDropConfig>...</button> <span>/</span> </div> <span class=page-title title="{{$ctrl.board ? $ctrl.board.title : $ctrl.project.title}}"> <span class=title ng-show=$ctrl.board.parent_id>{{$ctrl.board.title}}</span> <a class=title href drop-menu=$ctrl.settingsMenu drop-config=$ctrl.settingsMenuDropConfig ng-show="!$ctrl.board || !$ctrl.board.parent_id"> <i ng-class=$ctrl.project.icon|iconClass></i> {{$ctrl.project.title}} <span class=bi-caret-down-fill></span> </a> <span class="ref hidden-xs" ng-if=$ctrl.board.parent_id>(#{{$ctrl.board.ref}})</span> </span> </div> </div> <i class="fa fa-lock indicator hidden-xs" ng-show=$ctrl.project.is_private uib-tooltip="{{::_('Private')}}" tooltip-placement=bottom tooltip-popup-delay=0></i> <i class="fa fa-globe indicator hidden-xs" ng-show=$ctrl.project.is_public uib-tooltip="{{::_('Has shareable link')}}" tooltip-placement=bottom tooltip-popup-delay=0></i> <span class="fa-stack indicator unapproved-domain-members" ng-show=$ctrl.hasNotApprovedDomainMembers uib-tooltip="{{::_('Has unapproved members')}}" tooltip-placement=bottom tooltip-popup-delay=0> <i class=bi-person-x-fill></i></span> `);
  $templateCache.put("/static/app/ui/base/ng-components/sidebar/templates/view.html", `<a class="nav-sidebar-btn js-sortable-item-handle" ng-class="{'untitled': !$ctrl.view.name}" href uib-tooltip="{{$ctrl.name + ($ctrl.isDraftView ? '*' : '')}}" tooltip-placement={{$ctrl.tooltipPlacement}} tooltip-popup-delay=0 tooltip-enable="$ctrl.mode === 'icon'" ng-click=$ctrl.activate()> <i ng-if="$ctrl.view.icon || $ctrl.view.default_icon" ng-class="($ctrl.view.icon || $ctrl.view.default_icon)|iconClass"></i> <span class=title ng-show="!$ctrl.mode || (!$ctrl.view.icon && !$ctrl.view.default_icon)" ng-bind="($ctrl.mode === 'icon' ? ($ctrl.name|limitTo:2) : $ctrl.name) + ($ctrl.isDraftView ? '*' : '')"></span> <i class="bi-share-fill indicator" ng-if=!!$ctrl.showSharedIcon title="{{::_('This view has been shared using a link')}}"></i> </a> <button class="nav-sidebar-btn btn-draft" type=button ng-if="!$ctrl.view.locked && $ctrl.editable && !$ctrl.isDraftView && $ctrl.draftView" view-menu-toggle=$ctrl.draftView uib-tooltip="{{::_('Unsaved changes')}}" tooltip-placement=right tooltip-popup-delay=0><i class="fa fa-asterisk"></i></button> <button class="nav-sidebar-btn btn-settings" type=button ng-if="( !$ctrl.isDraftView && !$ctrl.draftView ) || $ctrl.view.locked" view-menu-toggle=$ctrl.view><i class=bi-three-dots></i></button> <button class="nav-sidebar-btn btn-save" type=button ng-if="$ctrl.editable && $ctrl.isDraftView" view-menu-toggle=$ctrl.view ng-show=$ctrl.active>{{::_('Save')}}</button> <button class="nav-sidebar-btn btn-delete" type=button ng-if=!!$ctrl.isDraftView uib-tooltip="{{::_('Delete')}}" tooltip-placement=right tooltip-popup-delay=0 ng-click=$ctrl.delete()><i class=bi-trash></i></button> `);
  $templateCache.put("/static/app/ui/base/ng-components/forms/templates/upload-field.html", `<div class=img ng-model=$ctrl.file ngf-drop=$ctrl.upload($ctrl.file)> <span ng-hide="$ctrl.uploadProgress || $ctrl.file || $ctrl.value || !$ctrl.editable">{{::_('Drop file here')}}</span> <span ng-show=$ctrl.uploadProgress>{{$ctrl.uploadProgress}}%</span> <img ngf-thumbnail="$ctrl.file || $ctrl.value" ng-hide=$ctrl.uploadProgress> </div> <button class="btn btn-default" ng-model=$ctrl.file ngf-select=$ctrl.upload($ctrl.file) ng-show=$ctrl.editable> {{::_('Select from your computer')}} </button> <button class="btn btn-default" ng-click=$ctrl.reset() ng-show="$ctrl.editable && ($ctrl.file || $ctrl.value)">{{::_('Reset')}}</button> `);
  $templateCache.put("/static/app/ui/base/ng-components/forms/templates/indicator-dropdown.html", `<div class="btn-group indicator-dropdown"> <button type=button class="btn btn-default dropdown-toggle" data-toggle=dropdown> <i class=fa ng-class=indicator|iconClass ng-hide="hideSelection === 'true' || !indicator || !indicator.length"></i> <span class=bi-caret-down-fill></span> </button> <div class=dropdown-menu> <a href ng-click=setIndicator(i) ng-repeat="i in availableIndicators"> <i class=fa ng-class=i|iconClass></i> </a> <a class=clear href ng-click=setIndicator(null)>{{::_('None')}}</a> </div> </div> `);
  $templateCache.put("/static/app/ui/base/ng-components/forms/templates/checkbox-list.html", `<div> <div class="list-group list-group-scrollable list-group-form-check" ui-sortable=sortableOptions ng-model=items ng-class="{'sortable': sortable}"> <div class=list-group-item ng-repeat="item in items"> <i class=bi-grip-vertical></i> <div class=form-check> <input class=form-check-input type=checkbox ng-model=item.selected ng-change=update() id=formCheckListItem{{$index}}> <label class=form-check-label for=formCheckListItem{{$index}}>{{item.label}}</label> </div> </div> </div> <a href class="btn btn-link" ng-click=toggleAll()>{{::_('Toggle select all / unselect all')}}</a> </div> `);
  $templateCache.put("/static/app/ui/attributes/modals/templates/attribute-options-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Field options')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <attribute-options project=project attribute=attribute obj=obj editable=true></attribute-options> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=save()>{{::_('Save')}}</button> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/input.html", `<div class=attribute-type-input> <span ng-if="!loading && (!editable || options.readonly) && !edit && !hasError && isEmpty && !label" class=attribute-widget-badge>{{::_('Empty')}}</span> <span class="attribute-widget-badge value" ng-if=!edit ng-show="label || label === 0 || hasError || loading" ng-click=toggleEdit(true) ng-class="{'has-action': options.action && !loading,
               'has-clear': options.clearable && editable && !isEmpty && !loading,
               'has-error': hasError,
               'is-empty': isEmpty && !hasError && !loading,
               'has-editor-opener': !!options.editorOpener && editable}" ng-style="{'background-color': bgColor, 'color': fgColor}"> <span class=label ng-if="!loading && !hasError">{{label|ellipsis:100}}</span> <span class=label ng-if="!loading && hasError">{{errorMessage}}</span> <span ng-if="loading && !hasError"><i class="fa fa-spinner fa-spin"></i></span> <a class=attribute-widget-badge-btn ng-if="options.showActionIcon() && !loading" href ng-click="callAction(); $event.stopPropagation()" uib-tooltip={{_(options.actionTooltip)}}> <i class=fa ng-class=options.actionIcon></i> </a> <a class=attribute-widget-badge-btn href ng-show="options.clearable && editable && !options.readonly && !isEmpty && !loading" ng-click="clearValue(); $event.stopPropagation()" ng-style="{'color': fgColor}"> <i class="fa fa-times"></i> </a> </span> <attribute-type-input-editor obj=obj attribute=attribute attribute-group=attributeGroup value=data ng-if=edit on-done=toggleEdit(false) no-auto-focus={{isEmpty}}> </attribute-type-input-editor> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/attribute-required-options-content.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Field configuration')}}</h3> <button type=button class=btn-close ng-click=close()></button> </div> <div class=modal-body> <div class=form-group> <label class=form-label for=attrName>{{::_('Name:')}}</label> <input type=text name=name required ng-model=attributeName class=form-control id=attrName> </div> <options-editor options=typeOptions values=attrOptions project=project card=card editable=true ng-hide=attribute.is_from_integration></options-editor> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=close()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-disabled=!canSave ng-click=save()>{{::_('Save')}}</button> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/attribute-group.html", `<div class=attribute-group ng-class="{'empty': attributes.length === 0, 'sortable': attributesMovable,
  'hidden': !showEmptyNotice && !attributesMovable && attributes.length === 0}"> <div class=attribute-group-inner ui-sortable=sortableOptions ng-model=attributes> <attribute-widget ng-repeat="attr in attributes" ng-show="!isAttributeMatches || isAttributeMatches(attr)" obj=obj editable=editable attribute=attr attribute-group=attributeGroup project=project container={{container}} directive-property={{directiveProperty}} attribute-editable=attributesEditable attribute-movable=attributesMovable is-template=isTemplate> </attribute-widget> </div> <div class=attribute-group-empty ng-if="!attributes.length && showEmptyNotice"> {{::_("You don't have any fields here yet. Click the button below to add some")}} </div> <div class=add-attribute ng-show=attributesEditable ng-class="{'hover': addAttributeHover || addAttributeDropOpen, 'no-line': !attributes.length}"> <button class=btn add-attribute-menu-toggle="addAttr(attrType, onlyModel)" attr-available-for={{attributeTypeAvailableFor}} show-only-model-option=attrShowOnlyModelOption ng-mouseenter="addAttributeHover = true" ng-mouseleave="addAttributeHover = false" on-drop-opened=onAddDropOpen() on-drop-closed=onAddDropClosed() uib-tooltip="{{::_('Add field')}}" tooltip-placement=top> <i class=bi-plus-lg></i> </button> </div> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/attribute-options.html", `<div class="attribute-options clearfix"> <div class="alert alert-info" ng-show=attribute.is_from_integration> <i class=bi-info-square-fill></i> {{::_('This field is provided by an integration. Its options cannot be modified and it cannot be removed.')}} </div> <div class=row> <div class=col-sm-8> <div class=form-group> <label class=form-label for=attrName>{{::_('Name:')}}</label> <input type=text name=name required ng-model=attribute.name ng-disabled=!editable class=form-control id=attrName> </div> </div> <div class=col-sm-4> <div class=form-group> <label class=form-label>{{::_('Type:')}}</label> <div class="dropdown attr-type-selector"> <button class="form-select dropdown-toggle" ng-class="{'text-muted': !attribute.type}" type=button data-toggle=dropdown ng-disabled="!editable || attribute.id"> <i class=fa-fw ng-class=currentType.icon|iconClass></i> {{currentType.title || _('Select type')}} </button> <ul class="dropdown-menu dropdown-menu-right attribute-types-dropdown-menu"> <li ng-repeat="type in types" ng-class="{'active': type.name === attribute.type}"> <a href ng-click=selectType(type.name)> <span><i class=fa-fw ng-class=type.icon|iconClass></i> {{type.title}}</span> <p class=mb-0>{{type.description}}</p> </a> </li> </ul> </div> </div> </div> </div> <div class="form-group attr-desc"> <label class=form-label for=formDesc>{{::_('Description:')}}</label> <textarea ng-model=attribute.description ng-disabled=!editable class=form-control rows=1 id=formDesc></textarea> </div> <div class=form-group ng-if="currentType.canHaveDefaultValue && !attribute.is_from_integration"> <label class=form-label for=attrDefaultVal>{{::_('Default value (only applied on created cards):')}}</label> <input name=default_value ng-model=attribute.default_value type=text class=form-control ng-disabled=!editable id=attrDefaultVal> </div> <options-editor options=typeOptions values=attribute.options org=org project=project card=card editable=editable ng-hide=attribute.is_from_integration></options-editor> <div class="form-check form-switch" ng-show=model> <input class=form-check-input type=checkbox role=switch ng-model=attribute.is_pii id=attrIsPii> <label class=form-check-label for=attrIsPii> {{::_('Contains personally identifiable information')}} (<a href=https://kantree.io/help/guides/gdpr target=_blank>{{::_('learn more')}}</a>) </label> </div> <button class="btn btn-danger btn-sm float-end" type=button ng-click=onDelete() ng-show="showDelete && editable && !attribute.is_from_integration"> <i class=bi-trash-fill></i>{{::_('Remove')}}</button> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/input-editor.html", `<div class=attribute-type-input-editor> <input type={{options.inputType}} placeholder={{options.inputPlaceholder}} ng-model=inputValue ng-class="{'has-error': hasError, 'pe-5': !!options.color}" class=form-control> <a drop-menu=colorPickerMenu ng-style="{'background-color': color}" ng-class="{'has-color': color}" title="{{::_('Background color')}}" ng-show=::!!options.color></a> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/attribute-widget.html", `<div class=attribute-widget ng-class="{
    'top': container === 'top',
    'block': attributeType.widgetBreakline,
    'settings-layout-enabled': _attributeEditable ||
                               canManageRolePerms ||
                               canMoveAttr
  }" data-attr-id={{attribute.id}}> <a ng-if=optionsMenuSpec class="attribute-widget-settings-btn move-handle hidden-xs" drop-menu=optionsMenuSpec on-drop-opened=onDropMenuOpen() on-drop-closed=onDropMenuClose() uib-tooltip="{{::_('Click for more options')}}" tooltip-popup-delay=500> <span>{{getOptionsMenuLabel(attribute)}}</span> <span class=bi-caret-down-fill></span> </a> <span class=debug-attribute-position ng-show=isDebugModeEnabled>{{ getPosition(attribute) }}</span> <label ng-hide="hideHeader || attributeType.widgetHideAttributeName" ng-class="{'move-handle': attributeMovable, 'has-desc': attribute.description}"> <span ng-hide=nameEditing ng-dblclick=handleNameDoubleClick() title={{attribute.name}} uib-tooltip="{{attributeMovable ? _('Double-click to edit') : ''}}" tooltip-popup-delay=700> {{attribute.name}} {{attribute.required ? ('(' + _('required') + ')') : ''}} </span> <input type=text class=attribute-widget-label-form-control value={{$parent.attributeName}} required ng-if=nameEditing placeholder="{{::_('Field name')}}"> <i class="fa fa-question-circle" uib-tooltip={{attribute.description}} tooltip-popup-delay=0 ng-if=attribute.description ng-hide=nameEditing></i> <i class="fa fa-arrows" ng-show=canMoveAttr uib-tooltip="{{::_('Click to drag & move field')}}" tooltip-popup-delay=700></i> </label> <div ng-if=messageDisabled class=attribute-widget-message-disabled> <i class="fa fa-warning"></i> <span ng-bind-html=messageDisabled></span> </div> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/select.html", `<div class=attribute-type-select> <span ng-if="!loading && !editable && !selected.length" class=attribute-widget-badge>{{::_('No selection')}}</span> <div class=d-inline-block ng-if=!!options.multi> <div class="attribute-widget-badge me-1 mb-1" ng-repeat="item in selected track by item[0]" ng-style="{'background-color': item[2] || '#eee', 'color': textColor(item[2] || '#eee', null, null, '#777')}"> <i class="me-2 opacity-50" ng-class=(item[3]|iconClass ng-if="item[3] && !loading"></i> <span class=label>{{item[1]|ellipsis:80}}</span> </div> </div> <button type=button class="attribute-widget-btn me-1 mb-1" ng-class="{'btn-icon': loading || options.multi || !selected.length, 'colored': !options.multi && selected[2]}" attribute-editor-opener obj=obj attribute=attribute attribute-group=attributeGroup value=value editable=editable attribute-editable=attributeEditable ng-style="{'background-color': !options.multi && selected[2] ? selected[2] : null}" ng-disabled="!editable || loading" ng-hide="!editable && (options.multi || !selected.length)"> <span class=label ng-show="!options.multi && !loading"> <i class=fa ng-class=selected[3]|iconClass ng-if=selected[3]></i> <span>{{selected[1]|ellipsis:80}}</span> <span class="caret bi-caret-down-fill" ng-show=editable></span> </span> <i class=bi-plus-lg ng-show="!loading && !!options.multi"></i> <i class="fa fa-spin fa-spinner" ng-show=loading></i> </button> <a ng-if="!options.multi && options.action && (!options.actionDisabled || !options.actionDisabled(attribute)) && value" href ng-click=callAction() uib-tooltip={{_(options.actionTooltip)}}> <i class=fa ng-class=options.actionIcon></i> </a> </div> `);
  $templateCache.put("/static/app/ui/attributes/ng-components/templates/attribute-table.html", `<table class="table table-bordered table-condensed attribute-table"> <tr ng-repeat="attr in attributes"> <td>{{attr.name}}</td> <td class=attribute-table-cell ng-class="'is-' + attr.type"> <attribute-repr-widgets attribute-group=attributeGroup attribute=attr obj=obj options=attrReprWidgetsOptions></attribute-repr-widgets> </td> </tr> </table> `);
  $templateCache.put("/static/app/ui/project/modals/templates/move-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Move {project} to', {project: $ctrl.project.title})}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()><i class="fa fa-arrow-left visible-xs-inline-block"></i> </button> </div> <div class=modal-body> <div class=org-selector> <label class=form-label>{{::_('The workspace will be moved in:')}}</label> <options-widget-orgs options=$ctrl.selectorOptions ng-model=$ctrl.selected></options-widget-orgs> </div> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.withCopy id=moveWithCopy> <label class=form-check-label for=moveWithCopy>{{::_('Keep a copy in {org}', {org: $ctrl.orgName})}}</label> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.openCardMoveModal()>{{::_('Convert to card')}}</button> <button class="btn btn-success" ng-class="{'disabled': $ctrl.isMoveDisabled}" type=button ng-click=$ctrl.moveTo() uib-tooltip={{$ctrl.moveDisabledTooltip}} tooltip-enable=$ctrl.isMoveDisabled> {{$ctrl.withCopy ? _('Copy here') : _('Move here')}}</button> </div> `);
  $templateCache.put("/static/app/ui/project/modals/templates/role-obj-exceptions.html", `<div class=modal-header> <h3 class=modal-title>{{::title}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> <p> {{::_('Roles allow you to limit which user can interact with which parts of your workspaces.')}} </p> <p> {{::_('Here you can override a role default permissions on a per item basis.')}} </p> </div> <div class=scrollable-container> <table class="table roles-actions-table"> <thead> <tr> <th class=show-builtins ng-show=!showBuiltinRoles> <a href ng-click="showBuiltinRoles = true">{{::_('Show builtin roles')}}</a> </th> <th ng-show=showBuiltinRoles></th> <th ng-repeat="role in builtinRoles" ng-show=showBuiltinRoles> {{::role.name}} <i class="fa fa-lock role-item-lock" uib-tooltip="{{::_('This role is not editable')}}"></i> </th> <th ng-repeat="role in orgRoles"> {{::role.name}} </th> </tr> </thead> <tbody> <tr ng-repeat="obj in visibleObjects"> <td>{{obj.name}}</td> <td ng-repeat="role in builtinRoles" ng-show=showBuiltinRoles> <perm-item actions=actions permissions=permissions[role.id][obj.id] project=project object-id=obj.id editable=false allow-as-toggle=true></perm-item> </td> <td ng-repeat="role in orgRoles"> <perm-item actions=actions permissions=permissions[role.id][obj.id] project=project object-id=obj.id editable=true on-update="update(role, obj, $perms)" allow-as-toggle=true></perm-item> </td> </tr> </tbody> </table> </div> <p class=clearfix> <button ng-click=showAllObjects() class="btn btn-default" ng-show="visibleObjects.length < objects.length">{{::_('Show all')}}</button> <button ng-click=openProjectSettings() class="btn btn-default pull-right"><i class="fa fa-cog"></i> {{::_('Manage members')}}</button> <button ng-click=openProjectSettings() class="btn btn-default pull-right" ng-if=isOrgMember><i class="fa fa-cog"></i> {{::_('Manage roles')}}</button> </p> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/perm-item.html", `<div ng-class="[$ctrl.editable ? '' : 'disabled', $ctrl.mode.class, $ctrl.isToggleOnly ? 'toggle-only' : '', $ctrl.isOverriden() ? 'overriden' : '']" ng-click=$ctrl.toggleOnly() class=perm-item-header uib-tooltip="{{$ctrl.isToggleOnly && $ctrl.editable ? _('Click here to toggle permission') : ''}}"> <i ng-class=$ctrl.mode.icon|iconClass></i> {{::$ctrl.label}} </div> <div class=perm-item-actions ng-if=!$ctrl.isToggleOnly> <div ng-repeat="action in $ctrl.actions" ng-class="{overriden: $ctrl.isOverriden(action)}"> <kt-form-check ng-disabled=!$ctrl.editable value=$ctrl.isAllowed(action) on-change="$ctrl.toggle(action, $isChecked)">{{::action.label}}</kt-form-check> </div> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/project-selector.html", `<div class=project-selector> <button class="clear-button btn btn-default" style=width:100% type=button ng-if="$ctrl.selectedProjects.length > 0" ng-click=$ctrl.clearSelection()> {{::_('Clear selection')}} </button> <div class=shortcuts ng-if="::(!!$ctrl.isMultiple && !!$ctrl.showAutoSelect)"> <div class=form-check> <input class=form-check-input type=radio ng-model=$ctrl.autoSelect value=all name=projectAutoSelect ng-change=$ctrl.selectAuto() id=projectAutoSelectAll> <label class=form-check-label for=projectAutoSelectAll>{{::_('All')}}<i class="form-text bi-question-circle ms-2 fs-small" uib-tooltip="{{::_('Auto select all the workspaces you are member of')}}"></i> </label> </div> <div class=form-check> <input class=form-check-input type=radio ng-model=$ctrl.autoSelect value=favorites name=projectAutoSelect ng-change=$ctrl.selectAuto() id=projectAutoSelectFav> <label class=form-check-label for=projectAutoSelectFav>{{::_('Favorites')}}<i class="form-text bi-question-circle ms-2 fs-small" uib-tooltip="{{::_('Auto select all the workspaces you marked as favorite')}}"></i> </label> </div> <div class=form-check> <input class=form-check-input type=radio ng-model=$ctrl.autoSelect value=pinned name=projectAutoSelect ng-change=$ctrl.selectAuto() id=projectAutoSelectPinned> <label class=form-check-label for=projectAutoSelectPinned> {{::_('From selected organizations')}}<i class="form-text bi-question-circle ms-2 fs-small" uib-tooltip="{{::_('Auto select all the workspaces from the organizations you selected to be displayed in your left sidebar')}}"></i> </label> </div> <div class=form-check> <input class=form-check-input type=radio ng-model=$ctrl.autoSelect value=custom name=projectAutoSelect ng-change=$ctrl.selectAuto() id=projectAutoSelectCustom> <label class=form-check-label for=projectAutoSelectCustom>{{::_('Custom')}}</label> </div> </div> <hr ng-if="::(!!$ctrl.isMultiple && !!$ctrl.showAutoSelect)"> <div class=controls> <kt-form-check ng-if=::!!$ctrl.isMultiple value=$ctrl.allProjectsSelected ng-indeterminate=$ctrl.allProjectsIndeterminate on-change=$ctrl.toggleAll() ng-disabled=$ctrl.readonly></kt-form-check> <div class=input-control> <input class=form-control type=text ng-model=$ctrl.filter ng-change=$ctrl.doFilter() ng-attr-placeholder="{{::_('Filter...')}}"> <button type=button class="btn btn-icon" ng-show="$ctrl.filter && $ctrl.filter.length" ng-click=$ctrl.resetFilter() uib-tooltip="{{::_('Clear filter')}}"><i class=bi-x></i></button> </div> </div> <ul class="sections list-unstyled"> <li class=section ng-repeat="section in $ctrl.sections track by section.id"> <kt-form-check ng-if="::(!!$ctrl.isMultiple && section.showHeader !== false)" value=$ctrl.isSectionSelected(section) ng-indeterminate=!!$ctrl.isSectionIndeterminate(section) ng-disabled=$ctrl.readonly on-change=$ctrl.toggleSectionSelection(section)> <strong>{{section.label}}</strong> <small class=ms-1>({{$ctrl.countSelectedProjectsInSection(section)}}/{{section.projects.length}})</small> </kt-form-check> <span ng-if="::(!$ctrl.isMultiple && section.showHeader !== false)"> <strong>{{section.label}}</strong> <small class=ms-1>({{$ctrl.countSelectedProjectsInSection(section)}}/{{section.projects.length}})</small> </span> <hr ng-if="::(section.showHeader !== false)"> <ul class=list-unstyled> <li ng-repeat="project in section.filtered track by project.id"> <kt-form-check ng-if=::!!$ctrl.isMultiple class="{{$ctrl.isProjectSelected(project) ? 'selected' : null}}" value=$ctrl.isProjectSelected(project) on-change=$ctrl.toggleProject(project) ng-disabled=$ctrl.readonly> <project-list-item project=project></project-list-item> </kt-form-check> <button class=btn type=button ng-if=::!$ctrl.isMultiple ng-class="{'selected': $ctrl.isProjectSelected(project)}" ng-click=$ctrl.select([project])> <project-list-item project=project></project-list-item> </button> </li> </ul> </li> </ul> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/menu-header.html", `<div> <div class=project>{{$ctrl.params.project.title}}</div> <div class=owner> {{::_("In")}} <a href ng-click=$ctrl.gotoOwner($event)>{{$ctrl.ownerName}}</a> <button ng-click="$ctrl.openSubmenu({$event: $event})" uib-tooltip="{{::_('Move / copy / archive workspace')}}" tooltip-placement=right ng-show="$ctrl.editable && !$ctrl.isEmbedded()"><span class=fa-stack> <i class="fa fa-folder-o fa-stack-2x"></i> <i class="fa fa-mail-forward fa-stack-1x"></i> </span></button> </div> </div> <button ng-show=$ctrl.canFavorite ng-click=$ctrl.toggleFavorite() uib-tooltip="{{$ctrl.favorited ? _('Remove from favorites') : _('Add to favorites')}}" class="btn btn-icon"> <i ng-class="{'bi-star-fill': $ctrl.favorited, 'bi-star': !$ctrl.favorited}"></i> </button> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/project-browser.html", `<div class=panel ng-if="$ctrl.teams.length > 1"> <div class=panel-heading>{{::_('Team')}}</div> <div class=panel-body> <div class="dropdown list-dropdown"> <a class="form-select dropdown-toggle" data-toggle=dropdown> {{ $ctrl.selected.org.name || '-' }} {{ $ctrl.selected.team ? (' / ' + $ctrl.selected.team.name) : ''}} </a> <ul class=dropdown-menu> <li ng-repeat="spec in $ctrl.teams track by spec.uuid" ng-click=$ctrl.selectTeam(spec) ng-class="{current: $ctrl.isCurrentSelection(spec)}"> {{::spec.name}} </li> </ul> </div> </div> </div> <div class=panel> <div class=panel-heading>{{::_('Browse workspaces and cards')}}<i class=panel-heading-tooltip ng-attr-title={{$ctrl.browserTooltip}}></i></div> <div class=panel-body> <card-browser projects=$ctrl.projects default-selected-card=$ctrl.defaultSelectedCard on-changed="$ctrl.selectCard(project, card)" with-leaves={{$ctrl.withLeaves}} with-links={{$ctrl.withLinks}} with-save-option="{{$ctrl.saveOption ? 'true' : ''}}" default-icon={{$ctrl.defaultIcon}} ng-if=$ctrl.selected.org> </card-browser> </div> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/sharing-settings.html", `<div class="card-sharing-settings form-group"> <div ng-show=!$ctrl.isTemplate> <div class="dropdown mb-4"> <a href class="form-select dropdown-toggle perm-level-item" data-toggle=dropdown> <i ng-class=$ctrl.permLevel.icon|iconClass></i> <div> <span>{{$ctrl.permLevel.name}}</span> <p>{{$ctrl.permLevel.description}}</p> </div> </a> <div class=dropdown-menu> <a class=perm-level-item ng-repeat="permLevel in $ctrl.permLevels" href ng-hide=!!permLevel.disabled ng-click=$ctrl.selectLevel(permLevel)> <i ng-class=permLevel.icon|iconClass></i> <div> <span>{{permLevel.name}}</span> <p>{{permLevel.description}}</p> </div> </a> </div> </div> <div class=mb-4> <solidjs-component component=$ctrl.Tip ng-if=$ctrl.permLevelUnchanged></solidjs-component> </div> <div class="form-group form-check form-switch" ng-show=$ctrl.sharingSettingsExpanded> <label class=form-check-label ng-show="$ctrl.isOrgProject && $ctrl.settings.team_members_can_observe"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.settings.team_members_can_autojoin ng-change=$ctrl._onSettingsChanged()> {{::_("Team members can join this {projectType} by themselves.", {projectType: $ctrl.typeLabel})}} </label> <a href ng-click="$ctrl.showDefaultRoleSelection = true" ng-show="$ctrl.canSelectDefaultRole && $ctrl.settings.team_members_can_autojoin && !$ctrl.showDefaultRoleSelection">{{::_('Set default role')}}</a> </div> <div class=form-group ng-show="$ctrl.showDefaultRoleSelection && $ctrl.isOrgProject && $ctrl.settings.team_members_can_observe"> <label class=form-label for=membersDefaultRole>{{::_("Default role for team members:")}}</label> <select ng-model=$ctrl.settings.default_org_member_role_id ng-options="role.id as role.name for role in $ctrl.roles" ng-change=$ctrl._onSettingsChanged() class=form-select id=membersDefaultRole></select> </div> <div class=form-group ng-show="$ctrl.showDefaultRoleSelection && $ctrl.settings.is_public"> <label class=form-label for=guestsRole>{{::_("Role for guests (authenticated users):")}}</label> <select ng-model=$ctrl.settings.public_role_id ng-options="role.id as role.name for role in $ctrl.roles" ng-change=$ctrl._onSettingsChanged() class=form-select id=guestsRole></select> </div> </div> <div class="form-group form-check form-switch" ng-show=$ctrl.isTemplate> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.settings.is_public ng-change=$ctrl._onSettingsChanged() id=publicTemplate> <label class=form-check-label for=publicTemplate>{{::_("Make this template public (anybody with the link can access)")}}</label> </div> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/role-exceptions.html", `<label class=form-label ng-if="$ctrl.permissions.length > 0">{{::_('Specific rules:')}}</label> <ul class=list-group> <li class=list-group-item ng-repeat="perm in $ctrl.permissions"> <div class=list-group-item-description> <span ng-if="perm.object_type == 'view'"> {{_('{viewName} view is hidden from this role', {viewName: $ctrl.getViewName(perm.object_id)})}} </span> <span ng-if="perm.object_type != 'view'"> {{$ctrl.getTypeName(perm.object_type) }} : {{perm.actions.length ? _('Modification is allowed on') : _('Modification is not allowed on')}} {{$ctrl.getObjectName(perm.object_type, perm.object_id)}} </span> </div> <button class="btn btn-icon btn-sm btn-danger" ng-click=$ctrl.reset(perm) ng-show=$ctrl.editable><i class="fa fa-trash"></i></button> </li> </ul> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/importer.html", `<div ng-hide=$ctrl.importer> <label class=form-label>{{::_("Import from:")}}</label> <div class=importers-list> <a ng-repeat="imp in $ctrl.importers" ng-class="{'active': imp.name === $ctrl.importer.name}" href ng-click=$ctrl.selectImporter(imp)> <span class=img ng-style="{'background-image': 'url(' + imp.logo + ')'}"></span> <span class=name>{{imp.title}}</span> <span class=desc ng-if=imp.description>{{imp.description}}</span> </a> </div> </div> <div ng-if="$ctrl.importer && !$ctrl.showMapping"> <div ng-if="$ctrl.importer.import_from === 'remote'"> <label class=form-label>{{::_("Select a workspace to import:")}}</label> <ul class=projects-list> <li ng-if="!$ctrl.authorized || $ctrl.projects === null"> <div> <span class=name><i class="fa fa-spin fa-spinner"></i></span> </div> </li> <li ng-repeat="proj in $ctrl.projects track by proj[0]" ng-click="$ctrl.selectRemoteImport(proj[0], proj[1])" ng-class="{'active': $ctrl.importRemoteId === proj[0]}"> <div> <span class=name>{{proj[1]}}</span> </div> </li> </ul> </div> <div ng-if="$ctrl.importer.import_from === 'file'"> <div ngf-select=$ctrl.selectFileImport($file) ngf-drop=$ctrl.selectFileImport($file) class=file-drop-zone ng-hide=$ctrl.uploading> <i class="fa fa-cloud-upload"></i> {{::_('Click to select a file or drop your file here')}} </div> <div class=loader ng-show=$ctrl.uploading><i class="fa fa-spin fa-spinner"></i></div> </div> <div ng-if="$ctrl.importer.options.length && !$ctrl.importer.require_mapping"> <options-editor options=$ctrl.importer.options values=$ctrl.options></options-editor> </div> </div> <div ng-if=$ctrl.showMapping> <label class=form-label>{{::_('Map {0} to workspace items:', _($ctrl.importer.mapping_word))}}</label> <p class=form-text> {{::_('Tell Kantree how to treat the value from {0}. When mapping to fields, you can select the type of the field. Make sure the value is compatible with the chosen type.', _($ctrl.importer.mapping_word))}} </p> <button type=button class="btn btn-link btn-apply-mapping" ng-click=$ctrl.applyPreviousMapping()>{{_('Apply previous mapping')}}</button> <div class="alert alert-error" ng-repeat="error in $ctrl.errors" ng-if=$ctrl.errors.length> <i class=bi-x-circle-fill></i> {{::error}} </div> <table class="table table-bordered table-striped mapping-table"> <tr ng-show=!$ctrl.fields><td><i class="fa fa-spin fa-spinner"></i></td></tr> <tr ng-if=$ctrl.fields ng-repeat="field in $ctrl.fields track by field[0]"> <td>{{field[1]}}</td> <td> <select class=form-select ng-model=$ctrl.fieldMap[field[0]] ng-options="item as item.display_name group by item.section for item in $ctrl.mapChoices" ng-change=$ctrl.onMappingChange()> <option value>{{::_('Ignore')}}</option> </select> <div class=custom-field ng-show=$ctrl.isCustomField(field[0])> <select class=form-select ng-model=$ctrl.customTypeMap[field[0]] ng-options="t.name as t.title for t in $ctrl.attributeTypes" ng-show="$ctrl.fieldMap[field[0]].type === 'custom_attr'" ng-change=$ctrl.onMappingChange()></select> <input type=text ng-model=$ctrl.customMap[field[0]] class=form-control placeholder="{{::_('Name')}}" ng-change=$ctrl.onMappingChange()> </div> <div class=form-check ng-show="$ctrl.canUpdate && $ctrl.canBeUpdateField(field[0])"> <input class=form-check-input type=radio ng-model=$ctrl.updateField ng-value=field[0] ng-change=$ctrl.onMappingChange() id=matchField{{$index}}> <label class=form-check-label for=matchField{{$index}}>{{::_("Use this field to match existing card when updating")}}</label> </div> </td> </tr> </table> <div class=form-check ng-show=$ctrl.canUpdate> <input class=form-check-input type=radio ng-model=$ctrl.updateField ng-value=null ng-change=$ctrl.onMappingChange() id=matchNoField> <label class=form-check-label for=matchNoField>{{::_("Do not update existing cards")}}</label> </div> <div class="form-check form-switch" ng-show=$ctrl.updateField> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.updateOnly ng-change=$ctrl.onMappingChange() id=importUpdateOnly> <label class=form-check-label for=importUpdateOnly>{{::_("Do not create new cards when none matches")}}</label> </div> <div class="form-check form-switch" ng-show=$ctrl.updateField> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.suppressActivities ng-change=$ctrl.onMappingChange() id=importSuppressActivities> <label class=form-check-label for=importSuppressActivities>{{::_("Do not log activities when updating cards")}}</label> </div> <options-editor ng-if=$ctrl.importer.options.length options=$ctrl.importer.options values=$ctrl.options on-change=$ctrl.debounceImportReady()></options-editor> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/role-item.html", `<div class=role-item-inner ng-class="{overriden: $ctrl.overriden}" ng-click=$ctrl.onClick()> <h2 class=role-item-title>{{$ctrl.role.name}}<i class="fa fa-lock role-item-lock" uib-tooltip="{{::_('This role is built-in and cannot be modified')}}" ng-show=$ctrl.role.is_builtin></i></h2> <div class=role-item-desc>{{$ctrl.role.description}}</div> <span class=role-item-overriden ng-show=$ctrl.overriden>{{::_('modified for this workspace')}}</span> <div class=role-item-actions ng-show=$ctrl.editable> <button type=button class="btn btn-icon btn-sm" ng-if="$ctrl.showDuplicate === 'true'" ng-click=$ctrl.duplicate($event) uib-tooltip="{{::_('Duplicate')}}"> <i class="fa fa-files-o"></i> </button> <button type=button class="btn btn-icon btn-sm" ng-if="!$ctrl.role.is_builtin  && $ctrl.showDelete === 'true'" ng-click=$ctrl.delete($event) uib-tooltip="{{::('Delete')}}"> <i class="fa fa-trash"></i> </button> </div> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/nav-members.html", `<button type=button class="btn invite-btn" ng-click=$ctrl.openSharingSettingsModal() ng-show="$ctrl.canManageMembers && !$ctrl.hideInviteButton && $ctrl.displayedMembers.length <= 1" hide-offline hide-embedded> <i class=bi-person-plus-fill></i> {{::_('Invite')}} </button> <ul class=nav-members-list drop-menu=$ctrl.menuSpec> <li ng-repeat="member in $ctrl.displayedMembers track by member.id" class=nav-members-list-item> <user-avatar user=member.user show-presence=true connected="!!$ctrl.presenceManager && $ctrl.presenceManager.isUserConnected(member.user) && !$ctrl.isEmbedded()"></user-avatar> </li> </ul> <span class=nav-members-remaining-count> <span ng-show="$ctrl.remainingMembersCount > 0">+{{$ctrl.remainingMembersCount}}</span> </span> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/view-locked-btn-content.html", `<div class=content> <p>{{::_("Viewing cards as")}} <i ng-class=$ctrl.icon|iconClass></i> {{$ctrl.titleMode}}</p> <p ng-if=$ctrl.showGroups><i class=bi-collection></i> {{$ctrl.groupByText}}</p> <p ng-if=$ctrl.showFilters><i class=bi-filter></i> {{$ctrl.filterText}}</p> <p ng-if=$ctrl.showSort><i class=bi-sort-down></i> {{$ctrl.sortText}}</p> </div> <div class=action> <div class=desc>{{::_("The configuration of this view has been locked")}}</div> <button class="btn btn-default mt-2" ng-click=$ctrl.toggle() ng-if=$ctrl.canUnlock> <i class="fa fa-unlock"></i> <span>{{::_('Unlock')}}</span> </button> </div> `);
  $templateCache.put("/static/app/ui/project/ng-components/templates/role-editor.html", `<div class=role-editor> <div class=form-group> <label class=form-label for=roleName>{{::_('Name:')}}</label> <input type=text id=roleName required ng-model=role.name auto-grow min-width=250 ng-disabled="role.is_builtin || !editable || project" class=form-control> </div> <div class=form-group> <label class=form-label for=roleDescription>{{::_("Description:")}}</label> <input type=text id=roleDescription ng-model=role.description auto-grow min-width=250 ng-disabled="role.is_builtin || !editable || project" class=form-control> </div> <div class=permissions-editor> <div class=permissions-editor-header> <h4>{{::_('Permissions:')}}</h4> <small> <i ng-if=role.is_builtin class="fa fa-lock"></i> <span ng-if=role.is_builtin>{{::_('This a built-in role, you can\\'t edit its permissions')}}</span> <i ng-if="project && !role.is_builtin" class="fa fa-info-circle overriden"></i> <span class=overriden ng-if="project && !role.is_builtin">{{::_('Specific rights for this workspace are displayed in red')}}</span> </small> </div> <div class=permissions-list> <perm-item label={{perm.label}} actions=perm.actions permissions=role.permissions on-update=updatePerm($perms) editable="editable && !role.is_builtin" project=project ng-repeat="perm in permissions"></perm-item> </div> </div> </div> `);
  $templateCache.put("/static/app/ui/card/modals/templates/self-attributes-modal.html", `<div class=modal-header> <h3 class=modal-title>{{_('Fields for {title}', {title: card.title})}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <form name=attributesForm> <div class=modal-body> <div class=modal-help-message> <p> {{::_("Each card is associated to a card type which defines a set of base attributes. You are free to add more attributes on each card.")}} </p> </div> <div class=self-attributes> <model-attr-list-editor model=selfModel card=card></model-attr-list-editor> </div> </div> <div class=modal-footer> <button class="btn btn-default" type=button ng-click=$dismiss()>{{::_('Close')}}</button> <button class="btn btn-primary" type=submit ng-disabled=attributesForm.$invalid ng-click=save()>{{::_('Save')}}</button> </div> </form> `);
  $templateCache.put("/static/app/ui/card/modals/templates/add-link-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Create a link to')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> <p>{{::_('Choose a card you want to create a link to :')}}</p> </div> <project-browser default-selected-card=card with-leaves=true with-links=true on-changed=selectCard(card)></project-browser> <div class=panel> <span class=panel-heading>{{::_('Options:')}}</span> <div class=form-check> <input class=form-check-input type=radio ng-model=mirroredCard ng-value=true ng-disabled="::(dynamicGroups && dynamicGroups.length)" name=mirroredCardTrue id=mirroredCardTrue> <label class=form-check-label for=mirroredCardTrue>{{::_('Card mirror')}}</label> <span class=form-text>{{::_('The new card shares its fields with its target')}}</span> <span class="alert alert-error" ng-show="::(dynamicGroups && dynamicGroups.length)">{{::_('You cannot create mirrored card with fields. Try to create it from another column or lane')}}</span> </div> <div class=form-check> <input class=form-check-input type=radio ng-model=mirroredCard ng-value=false name=mirroredCardFalse id=mirroredCardFalse> <label class=form-check-label for=mirroredCardFalse>{{::_('Card link')}}</label> <span class=form-text>{{::_('The new card has its own fields')}}</span> </div> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=addLink(selectedCard) ng-disabled=!selectedCard>{{::_('Create')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card/modals/templates/browser-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Browse card')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <project-browser default-selected-card=card org=org with-leaves=true on-changed=selectCard(card)></project-browser> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$close(selectedCard) ng-disabled=!selectedCard>{{::_('Select')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card/modals/templates/move-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Move card to')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> <p>{{::_('Choose a workspace or a board where you want to move your card :')}}</p> </div> <project-browser default-selected-card=defaultSelectedCard with-save-option=true with-leaves=true on-changed="handleSelectionUpdate(card, project, org, team)"></project-browser> <div class=panel> <h4 class=panel-heading>{{::_('Options')}}</h4> <div class=form-group ng-if=canSelectGroups> <label class=form-label>{{::_('Contexts:')}}</label> <group-selector groups=selectedGroups card=card board=selectedBoard project=selectedProject on-update=handleGroupSelect($groups)></group-selector> </div> <div class="form-check form-switch" ng-hide="isCardTopLevelAndSelectedBoardHasSameOwner || disableWithCopy"> <input class=form-check-input type=checkbox role=switch ng-model=withCopy id=moveWithCopy> <label class=form-check-label for=moveWithCopy>{{::_('Keep a copy in this board')}}</label> </div> </div> <div class="modal-help-message mb-3" ng-show=isCardTopLevelAndSelectedBoardHasSameOwner> <p class="alert alert-warning"><i class=bi-exclamation-triangle-fill></i>{{::_('The workspace already exists in this team')}}</p> </div> <div class="modal-help-message mb-3" ng-show=isCardInSelectedBoardPath> <p class="alert alert-warning"><i class=bi-exclamation-triangle-fill></i>{{::_('You can\\'t move a card inside itself')}}</p> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=moveTo() ng-disabled=isMoveDisabled>{{withCopy ? _('Duplicate then move') : _('Move')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card/modals/templates/save-as-tpl-modal.html", "<project-creator ng-if=!loaded on-cancelled=$dismiss() on-created=$dismiss() as-modal=true template=project org=project.owner create-template=true> </project-creator> ");
  $templateCache.put("/static/app/ui/card/modals/templates/target-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Choose a target')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <div class=modal-help-message> <p>{{::_('Choose a workspace or a board :')}}</p> </div> <project-browser default-selected-card=defaultSelectedCard with-leaves=true on-changed="handleSelectionUpdate(card, project, org, team)"></project-browser> <div ng-if=canSelectGroups> <label class=form-label>{{::_('Contexts:')}} </label> <group-selector groups=selectedGroups card=card board=selectedBoard project=selectedProject on-update=handleGroupSelect($groups)></group-selector> </div> </div> <div class=modal-footer> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=select() ng-disabled=isMoveDisabled>{{_('Select')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/recurring-card-editor.html", `<div class=recurring-card-editor-container> <div class=form-group> <label class=form-label>{{::_('Repeats')}}</label> <div class="d-flex flex-wrap gap-1"> <button ng-repeat="frequency in $ctrl.frequencies track by $index" class="btn btn-sm {{$ctrl.isFrequencySelected(frequency.name) ? 'btn-success' : 'btn-default btn-ghost'}}" ng-attr-aria-pressed="{{ $ctrl.isFrequencySelected(frequency.name) ? 'true' : 'false'}}" ng-click=$ctrl.selectFrequency(frequency.name)>{{frequency.label}}</button> </div> </div> <div class=form-group ng-show="$ctrl.isFrequencySelected('monthly')"> <label class=form-label>{{::_('On')}}</label> <div class="btn-group recurring-card-editor-monthdays"> <button ng-repeat="monthday in $ctrl.monthdays track by $index" class="btn btn-sm {{$ctrl.isMonthdaySelected($index+1) ? 'btn-success' : 'btn-default btn-ghost'}}" ng-attr-aria-pressed="{{ $ctrl.isMonthdaySelected($index+1) ? 'true' : 'false'}}" ng-click=$ctrl.toggleMonthdays($index+1)>{{monthday}}</button> </div> <div class="alert alert-warning mt-3" ng-show="$ctrl.isFrequencySelected('monthly') && $ctrl.isSelectedMonthdaysPotentiallyUnavailable()"> <i class="fa fa-warning"></i> {{::_('No card will be created on the 29th, 30th or 31th if the current month doesn\\'t have these days')}} </div> </div> <div class=form-group ng-show="$ctrl.isFrequencySelected('weekly')"> <label class=form-label>{{::_('On')}}</label> <div class="btn-group d-flex recurring-card-editor-weekdays"> <button ng-repeat="weekday in $ctrl.weekdays track by $index" class="btn btn-sm {{$ctrl.isWeekdaySelected($index) ? 'btn-success' : 'btn-default btn-ghost'}} flex-fill" ng-attr-aria-pressed="{{ $ctrl.isWeekdaySelected($index) ? 'true' : 'false'}}" ng-click=$ctrl.toggleWeekdays($index)>{{weekday}}</button> </div> </div> <div class=form-group ng-show="$ctrl.isFrequencySelected('custom')"> <label class=form-label>{{::_('Every')}}</label> <div class="input-group input-group-sm"> <input type=number class=form-control min=1 ng-model=$ctrl.selected.customDays ng-change=$ctrl.handleCustomDaysChange()> <span class=input-group-text>{{::_('days')}}</span> </div> </div> <div class=form-group ng-show="$ctrl.isFrequencySelected('annually')"> <label class=form-label>{{::_('In')}}</label> <select class="form-select form-select-sm" ng-model=$ctrl.selected.annualMonth ng-options="month.value as month.label for month in $ctrl.months" ng-change=$ctrl.handleAnnualMonthChange()></select> </div> <div class=form-group> <label class=form-label for=selectedHours>{{::_('At')}}</label> <div class="input-group input-group-sm"> <select class="form-select flex-fill" ng-model=$ctrl.selected.hour ng-options="hour as hour for hour in $ctrl.hours" ng-change=$ctrl.handleTimeSelect() id=selectedHours></select> <select class="form-select flex-fill" ng-model=$ctrl.selected.minutes ng-options="minutes as minutes for minutes in $ctrl.minutes" ng-change=$ctrl.handleTimeSelect()></select> <button ng-repeat="amPm in $ctrl.amPm track by $index" ng-show=!$ctrl.isHours24Selector class="btn {{$ctrl.isAmPmSelected(amPm) ? 'btn-success' : 'btn-default btn-ghost'}}" ng-attr-aria-pressed="{{ $ctrl.isAmPmSelected(amPm) ? 'true' : 'false'}}" ng-click=$ctrl.selectAmPm(amPm)>{{amPm}}</button> </div> </div> <div class=form-group> <label class=col-form-label>{{::_('In groups')}}</label> <group-selector groups=$ctrl.selected.groups card=$ctrl.template board=$ctrl.board project=$ctrl.project on-update=$ctrl.handleGroupSelect($groups) with-attributes=true></group-selector> </div> </div> <div class=recurring-card-editor-recap ng-bind-html=$ctrl.recap></div> <div class=recurring-card-editor-controls> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.cancel()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.save()>{{::_('Save')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/browser.html", `<form ng-submit=$ctrl.search()> <input class=form-control type=text ng-model=$ctrl.query ng-attr-placeholder="{{::_('Search...')}}" auto-focus> <i class="fa fa-spinner fa-spin" ng-show=$ctrl.searching></i> <button class="btn btn-form-control btn-clear btn-icon" ng-show="$ctrl.query && $ctrl.query.length" type=button ng-click=$ctrl.clearQuery() ng-attr-title="{{::_('Clear')}}"> <i class="fa fa-times-circle"></i> </button> <button class="btn btn-form-control btn-search btn-icon" ng-show="$ctrl.query && $ctrl.query.length" type=submit ng-attr-title="{{::_('Search')}}"> <i class=bi-search></i> </button> <button class="btn btn-toggle" ng-class="{'enabled': !!$ctrl.resultsOptionsVisible}" ng-show=$ctrl.results type=button ng-click="$ctrl.resultsOptionsVisible = !$ctrl.resultsOptionsVisible"> {{::_('Options')}} </button> </form> <div class=search-results-options ng-if=$ctrl.results ng-show=$ctrl.resultsOptionsVisible> <span class=search-results-option> <button class="btn btn-drop" drop-menu=$ctrl.groupByMenuSpec> {{::_('Grouped by {label}', {label: $ctrl.activeGroupBy.label})}} <i class="bi-caret-down-fill right"></i> </button> </span> <span class=search-results-option> <button class="btn btn-drop" drop-menu=$ctrl.sortByMenuSpec> {{::_('Sorted by {label}', {label:$ctrl.activeSortBy.label})}} <i class="fa fa-{{$ctrl.activeSortBy.reverse ? 'long-arrow-up' : 'long-arrow-down'}} right"></i> <i class="bi-caret-down-fill right"></i> </button> </span> </div> <section ng-if=$ctrl.results> <div data-simplebar data-simplebar-auto-hide=false> <ul class="list-unstyled search-results"> <li class=search-results-group ng-repeat="resultsGroup in $ctrl.results track by resultsGroup.id"> <h4 ng-show=::resultsGroup.title> <button type=button class="btn btn-expand btn-icon" ng-click="resultGroup.collapsed = !resultGroup.collapsed"> <i class="{{resultGroup.collapsed ? 'bi-caret-right-fill' : 'bi-caret-down-fill'}}"></i> </button> <strong>{{::resultsGroup.title}}</strong> <small>({{::resultsGroup.cards.length}})</small> </h4> <ul class=list-unstyled ng-show=!resultGroup.collapsed> <li class=search-results-item ng-repeat="card in resultsGroup.cards track by card.id" ng-attr-title="{{card.is_archived ? _('Archived. Can\\'t be selected') : null}}"> <card-browser-tile card=::card selectable=true selected-cards-ids=$ctrl.selectedCardsIds on-select=$ctrl.select($card) show-project="$ctrl.activeGroupBy.id === 'nothing'"></card-browser-tile> </li> </ul> </li> </ul> </div> <div class=search-results-count> <span>{{$ctrl.resultsCountLabel}}</span> <button class="btn btn-switch-section" ng-click=$ctrl.clearResults()> {{::_('Back to tree view')}} </button> </div> </section> <section ng-if=!$ctrl.results> <div data-simplebar data-simplebar-auto-hide=false> <card-tree-view projects=$ctrl.projects default-selected-card=$ctrl.defaultSelectedCard on-changed="$ctrl.select(card, project)" with-leaves={{$ctrl.withLeaves}} with-links={{$ctrl.withLinks}} with-save-option="{{$ctrl.withSaveOption ? 'true' : ''}}" default-icon={{$ctrl.defaultIcon}}></card-tree-view> </div> </section> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/browser-tile.html", `<div ng-click=$ctrl.select($ctrl.card);$event.stopPropagation() class=card-browser-tile__inner ng-class="{
    'selected': $ctrl.selected,
    'archived': $ctrl.card.is_archived,
    'with-parents': !!$ctrl.parents.length
  }"> <div class="d-flex flex-grow-1 align-items-baseline" ng-class="::{'flex-row-reverse overflow-hidden': !$ctrl.fullDisplay}"> <i class=ref>#{{::$ctrl.card.ref}}</i> <div class="d-flex flex-column" ng-class="::{'flex-grow-1 overflow-hidden': !$ctrl.fullDisplay}" uib-tooltip={{::$ctrl.card.title}} tooltip-enable=::!$ctrl.fullDisplay> <div class="d-flex align-items-baseline"> <strong class=font-weight-normal ng-class="::{'overflow-hidden': !$ctrl.fullDisplay}"> <i ng-if="::($ctrl.model && $ctrl.model.indicator)" class="model-indicator {{::$ctrl.model.indicator|iconClass}}"></i> <span ng-class="::{
              'text-decoration-line-through': $ctrl.card.finished,
              'd-block text-overflow': !$ctrl.fullDisplay
            }">{{::$ctrl.card.title}}</span> </strong> <i ng-if=::$ctrl.state class="text-muted fs-small mx-1" ng-class=::$ctrl.state.icon|iconClass title={{::$ctrl.state.label}}></i> <span ng-if=::$ctrl.card.children.length class=children style="margin-right: 5px" ng-style="$ctrl.simpleDisplay && {'margin-left':'auto'}" ng-attr-title="{{::(_('Number of sub-cards') + ($ctrl.card.nb_completed_pct > 0 ? _(' ({pct}% completed)', {pct: card.nb_completed_pct}) : ''))}}" ng-click=$ctrl.toggleChildrenList();$event.stopPropagation()> <i class="fa fa-{{::($ctrl.card.board_created ? 'columns': 'list')}}"></i> {{($ctrl.card.nb_finished_children > 0 ? $ctrl.card.nb_finished_children + '/' : '') + $ctrl.card.children.length}} <span class=attr-widget-drop-icon ng-if="$ctrl.card.children.length > 0"> <i ng-class="$ctrl.childrenToggleState ? 'bi-caret-up-fill' : 'bi-caret-down-fill'"></i> </span> </span> <span ng-if=::$ctrl.card.is_link class=link-indicator ng-class="::{'fa-stack': $ctrl.card.broken_link}" title={{::$ctrl.linkTooltip}}> <i class="fa fa-chain" ng-class="::{
              'fa-chain': !$ctrl.card.broken_link,
              'fa-chain-broken': $ctrl.card.broken_link
            }"></i> </span> </div> <div class="d-flex text-muted fs-small" ng-if=$ctrl.parents.length> {{_('in {parents}', {parents: $ctrl.parents})}} </div> </div> </div> <div class="d-flex flex-shrink-0 ms-2" ng-if=$ctrl.showSelectButton> <button type=button class="btn btn-primary" ng-if=!$ctrl.selected ng-click=$ctrl.select($ctrl.card);$event.stopPropagation()> <i class=bi-plus-lg></i> {{::($ctrl.selectButtonLabel || _('Add'))}} </button> <button type=button class="btn btn-danger" ng-if=$ctrl.selected ng-click=$ctrl.select($ctrl.card);$event.stopPropagation()> <i class=bi-dash-lg></i> {{::_('Remove')}} </button> </div> </div> <div ng-if=$ctrl.showChildren> <ul ng-if="$ctrl.childrenToggleState && $ctrl.card.children.length" class="list-unstyled nested ps-2 py-1 mb-1 mt-1"> <li class=search-results-item ng-repeat="childCard in $ctrl.card.children" data-id={{childCard.id}}> <card-browser-tile card=::childCard selectable=true selected-cards-ids=$ctrl.selectedCardsIds on-select=$ctrl.select(childCard) show-select-button=$ctrl.showSelectButton select-button-label=$ctrl.selectButtonLabel show-project=$ctrl.showProject show-children=$ctrl.showChildren> </card-browser-tile> </li> </ul> </div> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/stream-box.html", `<div class=header> <a ui-sref="project({projectId: $ctrl.card.project_slug, '#': $ctrl.card.ref})" ng-click="$event.preventDefault(); $ctrl.openCardModal()"> <span class=ref>#{{::$ctrl.card.ref}}</span> <span class=title>{{::$ctrl.card.title}}</span> <span class=project>{{::_('in {project}', {project: $ctrl.card.project_title})}}</span> </a> <button ng-if=$ctrl.card.subscribed card-subscription-menu-toggle=$ctrl.card subscription-state-only=true uib-tooltip="{{::_('You are subscribed to this card')}}"><i class="fa fa-bell"></i></button> <button ng-click=$ctrl.markAllAsRead() ng-show=$ctrl.hasUnread class=unread uib-tooltip="{{::_('Unread activities in this card. Click to mark as read')}}"><i class="fa fa-asterisk"></i></button> </div> <activities store=$ctrl.activities card=$ctrl.card is-stream=true force-aggregate=true unread-ids=$ctrl.unreadIds on-mark-as-read="$ctrl.onMarkAsRead({$activities: [$activity]})" mark-as-read-on-scroll=$ctrl.markAsReadOnScroll></activities> <div class=start-comment ng-click=$ctrl.toggleCommentEditor() ng-if=!$ctrl.commenting>{{::_('Click to comment')}}</div> <content-composer ng-if=$ctrl.commenting options=$ctrl.commentEditorOptions on-submit=$ctrl.submitComment(submittedText) on-cancel=$ctrl.toggleCommentEditor()></content-composer> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/recurring-card-tile.html", `<div class=recurring-card-tile-container> <div card-tile=$ctrl.template ng-if=::$ctrl.template editable="$ctrl.editable && $ctrl.isConnected()" no-context-menu=false></div> <div class=recurring-card-tile-recap> <i class="fa fa-refresh fa-rotate-90"></i> <span ng-bind-html=$ctrl.recap></span> </div> </div> <div class=recurring-card-tile-controls> <button class=btn drop-menu=$ctrl.projectTaskEditorMenuSpec drop-config=$ctrl.dropConfig ng-if=::$ctrl.project ng-show=!$ctrl.project.is_archived> <i class="fa fa-pencil"></i><span>{{::_('Edit')}}</span> </button> <button class=btn ng-click=$ctrl.delete() ng-show=!$ctrl.project.is_archived ng-if=::$ctrl.project> <i class="fa fa-trash"></i><span>{{::_('Delete')}}</span> </button> </div> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/reminder-editor.html", `<div class=form-group> <label class=form-label>{{::_('Reminder type')}}</label> <div class="btn-group btn-group-sm w-100" role=group> <button type=button class="btn {{$ctrl.isRelativeMode() ? 'btn-success' : 'btn-default btn-ghost'}}" ng-attr-aria-pressed="{{$ctrl.isRelativeMode() ? 'true' : 'false'}}" ng-click="$ctrl.setMode('relative')">{{::_('Relative')}}</button> <button type=button class="btn {{$ctrl.isAbsoluteMode() ? 'btn-success' : 'btn-default btn-ghost'}}" ng-attr-aria-pressed="{{$ctrl.isAbsoluteMode() ? 'true' : 'false'}}" ng-click="$ctrl.setMode('absolute')">{{::_('Fixed date')}}</button> </div> </div> <div ng-show=$ctrl.isRelativeMode()> <div class=form-group> <label class=form-label for=selectedSpan>{{::_('A notification will spawn in:')}}</label> <div class="input-group input-group-sm"> <input class=form-control type=number ng-model=$ctrl.selected.span min=0 step=1 oninput="validity.valid||(value='');" id=selectedSpan auto-focus select-on-focus> <select class=form-select ng-model=$ctrl.selected.spanUnit ng-options="unit.value as unit.label for unit in $ctrl.spanUnits" ng-change=$ctrl.handleSpanUnitSelect()></select> </div> </div> <div class=form-group ng-show=$ctrl.isTimeSelectorAvailable()> <label class=form-label>{{::_('At')}}</label> <div class="input-group input-group-sm"> <select class=form-select ng-model=$ctrl.selected.hours ng-options="hour as hour for hour in $ctrl.hours"></select> <select class=form-select ng-model=$ctrl.selected.minutes ng-options="minutes as minutes for minutes in $ctrl.minutes"></select> <button ng-repeat="amPm in $ctrl.amPm track by $index" class="btn {{$ctrl.isAmPmSelected(amPm) ? 'btn-success' : 'btn-default btn-ghost'}}" ng-attr-aria-pressed="{{ $ctrl.isAmPmSelected(amPm) ? 'true' : 'false'}}" ng-click=$ctrl.selectAmPm(amPm) ng-show=!$ctrl.isHours24Selector>{{amPm}}</button> </div> </div> </div> <div ng-show=$ctrl.isAbsoluteMode()> <div class=form-group> <label class=form-label>{{::_('Select date and time')}}</label> <div id=reminder-datepicker-container></div> </div> </div> <div class=form-group> <label class=form-label>{{::_('For:')}}</label> <div class="form-check form-switch" ng-repeat="target in $ctrl.targets"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.selected[target.value] id=selectedTarget{{$index}}> <label class=form-check-label for=selectedTarget{{$index}}>{{::target.label}}</label> </div> </div> <div class=reminder-editor-controls> <button class="btn btn-default btn-ghost" type=button ng-click=$ctrl.cancel()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.save() ng-disabled=!$ctrl.canSave()>{{::_('Add')}}</button> </div> `);
  $templateCache.put("/static/app/ui/card/ng-components/templates/tile-list.html", `<div class=tile-selector> <div class="dropdown-body relationships-editor"> <div class=relationships-editor__header> <user-project-selector-btn class="form-select project-selector-btn" selected-projects=[$ctrl.currentProject] show-portfolios=false is-disabled=!$ctrl.canChangeProject on-change=$ctrl.onProjectChange($projects)> </user-project-selector-btn> <input type=text class=form-control ng-model=$ctrl.searchInput ng-change=$ctrl.onSearchChange() placeholder="{{::_('Filter...')}}"> <button ng-click=$ctrl.toggleSort() class="btn btn-icon btn-default" aria-label="{{$ctrl.sortBy ? _('Sort A-Z') : _('Sort Z-A')}}"> <i uib-tooltip="{{::_('Sorted by')}} {{$ctrl.sortBy ? 'Z-A' : 'A-Z'}}" ng-class="{'bi-sort-up': $ctrl.sortBy, 'bi-sort-down': !$ctrl.sortBy}"> </i> </button> </div> <div class=tile-selector__body> <ul id=tile-selector-list class="list-unstyled tile-selector__body--overflowing-list px-2 py-1 mb-0 mt-3" role=listbox aria-label="{{::_('Card list')}}"> <li class=search-results-item role=option aria-selected={{$ctrl.selectedCardsIds.includes(cardItem.id)}} ng-repeat="cardItem in (filteredItems = ($ctrl.cardTree | orderBy:['title']:$ctrl.sortBy | filter:$ctrl.filterFn)) track by cardItem.id" data-id={{cardItem.id}}> <card-browser-tile class="reversed simple-display" card=cardItem selectable=true selected-cards-ids=$ctrl.selectedCardsIds on-select=$ctrl.onCardToggled($card);$event.stopPropagation() show-select-button=true select-button-label="$ctrl.isSingleSelect ? _('Select') : null" show-children=true> </card-browser-tile> </li> <li class="action loader text-center" ng-show=$ctrl.loading> <i class="fa fa-spinner fa-spin"></i> {{::_('Loading...')}} </li> <li class="text-center text-danger" ng-show=$ctrl.loadError> {{::_("Error loading cards")}} <button class="btn btn-link" ng-click=$ctrl.loadCards($ctrl.currentProject)> {{::_("Retry")}} </button> </li> <li style="text-align: center" ng-show="(!filteredItems.length || !$ctrl.cardTree.length) && !$ctrl.loading && !$ctrl.loadError"> {{::_("No card found")}} </li> </ul> <div class="d-flex align-items-center px-2 mt-3" hide-offline> <div class="d-flex relationships-editor__addcard--container" ng-hide="$ctrl.loading || $ctrl.showCardCreator"> <button id=create-and-add type=button ng-click=$ctrl.openCardCreator() ng-show=$ctrl.canCreate class="btn relationships-editor__addcard--conditionner"> <i class=bi-plus-lg></i> <label class="form-label ms-1" for=create-and-add> {{$ctrl.placeholder}} </label> </button> </div> <form ng-submit=$ctrl.create() class="dropdown-item relationships-editor__addcard d-flex mt-0" style="max-height: 45px" ng-show="!$ctrl.loading && $ctrl.showCardCreator"> <input id=new-card-input ng-model=$ctrl.newCardTitle class=form-control-plaintext type=text placeholder="{{::_('Name your new card...')}}"> <input ng-click=$ctrl.closeCardCreator() ng-show="$ctrl.newCardTitle.length > 1" class="btn-close me-2" type=reset value> <button uib-tooltip={{$ctrl.placeholder}} ng-disabled="$ctrl.newCardTitle.length < 1 || $ctrl.isCreatingCard" type=submit class="btn btn-primary"> {{::_('Create and add')}} </button> </form> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/extensions/sso/templates/org-settings.html", `<div class=modal-help-message> <p> {{::_("Enable Single-Sign-On to allow users from your company to transparently signup/login to Kantree and automatically join your organization")}} </p> </div> <div class=panel> <form class=panel-body ng-submit=$ctrl.submit() name=$ctrl.ssoForm> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=$ctrl.ssoType ng-value=null id=radioSsoTypeDisable> <label class=form-check-label for=radioSsoTypeDisable>{{::_('Disable')}}</label> </div> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=$ctrl.ssoType ng-value="'$metadata'" id=radioSsoTypeMetadata> <label class=form-check-label for=radioSsoTypeMetadata>{{::_('Provide SAML 2.0 IdP metadata URL')}}</label> </div> <div class=form-group ng-show="$ctrl.ssoType === '$metadata'"> <label class=form-label for=inputSsoTypeUrl>{{::_("URL")}}*:</label> <input class=form-control type=url id=inputSsoTypeUrl ng-model=$ctrl.data.idp_metadata_url ng-required="$ctrl.ssoType === '$metadata'"> </div> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=$ctrl.ssoType ng-value="'$params'" id=radioSsoTypeDetails> <label class=form-check-label for=radioSsoTypeDetails>{{::_('Provide SAML 2.0 IdP details')}}</label> </div> <div ng-show="$ctrl.ssoType === '$params'"> <div class=form-group> <label class=form-label for=inputSsoTypeEntityId>{{::_("Entity ID")}}*:</label> <input class=form-control type=text id=inputSsoTypeEntityId ng-model=$ctrl.data.entity_id ng-required="$ctrl.ssoType === '$params'"> </div> <div class=form-group> <label class=form-label for=inputSsoTypeLoginUrl>{{::_("Login URL")}}*:</label> <input class=form-control type=url id=inputSsoTypeLoginUrl ng-model=$ctrl.data.login_url ng-required="$ctrl.ssoType === '$params'"> </div> <div class=form-group> <label class=form-label for=inputSsoTypeCertificate>{{::_("x509 certificate")}}*:</label> <textarea class=form-control id=inputSsoTypeCertificate ng-model=$ctrl.data.x509_cert ng-required="$ctrl.ssoType === '$params'"></textarea> </div> </div> <div class="form-check form-group" ng-repeat="provider in $ctrl.providers"> <input class=form-check-input type=radio ng-model=$ctrl.ssoType ng-value=provider.name id=radioSsoType{{provider.title}}> <label class=form-check-label for=radioSsoType{{provider.title}}>{{provider.title}}</label> </div> <button type=submit class="btn btn-primary" ng-disabled="$ctrl.ssoForm.$invalid || $ctrl.updateStatus.processing" disable-offline>{{::_('Save')}}</button> <processing-status status=$ctrl.updateStatus></processing-status> </form> </div> <div class=panel> <div class=panel-heading> {{::_("Authentication")}} </div> <div class=panel-body> <div class="form-group row"> <label class="form-label col-sm-4">{{::_("Your domain")}}:</label> <div class=col-sm-8> {{::$ctrl.info.domain}} <i class="fa fa-check text-success" ng-show=$ctrl.info.domain_ownership_validated></i> <i class="fa fa-close text-danger" ng-show=!$ctrl.info.domain_ownership_validated></i> <a href class=text-danger ng-show="!$ctrl.info.domain_ownership_validated && $ctrl.info.can_auto_join_from_domain" ng-click=$ctrl.validateDomain()> {{::_('needs validation, click here')}} </a> </div> </div> <div> <div class="form-group row"> <label class="form-label col-sm-4">{{::_("Login URL")}}:</label> <div class=col-sm-8><a ng-href={{$ctrl.info.kantree_login_url}}>{{$ctrl.info.kantree_login_url}}</a></div> </div> </div> <div class="form-check form-group"> <input class=form-check-input type=radio ng-model=$ctrl.domainLogin ng-value=false ng-change=$ctrl.updateDomainLogin() id=radioSsoDomainLoginFalse> <label class=form-check-label for=radioSsoDomainLoginFalse> {{::_("Users must use the provided Kantree login URL to login using SSO and automatically join your organization")}} </label> </div> <div class="form-check form-group"> <input class=form-check-input type=radio ng-model=$ctrl.domainLogin ng-value=true ng-disabled="!$ctrl.ssoType || !$ctrl.info.domain_ownership_validated" ng-change=$ctrl.updateDomainLogin() id=radioSsoDomainLoginTrue> <label class=form-check-label for=radioSsoDomainLoginTrue> {{::_("Any email address using your domain will use SSO and automatically join your organization")}} </label> </div> </div> </div> <div class=panel ng-show="$ctrl.info.provider.name === 'saml'"> <div class=panel-heading> {{::_("SAML integration")}} </div> <div class=panel-body> <h2>URLs</h2> <table class="table table-bordered"> <tr> <td>Consume URL</td> <td>{{$ctrl.info.acs_url}}</td> </tr> <tr> <td>Metadata URL</td> <td>{{$ctrl.info.metadata_url}}</td> </tr> </table> <h2>Attributes</h2> <p> {{::_("Be sure to configure your identity provider to include the following attributes with its SAML assertions")}} </p> <table class="table table-bordered"> <tr> <th><code>User.email</code></th> <td>{{::_("User's email address")}}</td> </tr> <tr> <th><code>User.FirstName</code></th> <td>{{::_("User's first name")}}</td> </tr> <tr> <th><code>User.LastName</code></th> <td>{{::_("User's last name")}}</td> </tr> </table> <p> {{::_('The username will be computed from the email address')}} </p> </div> </div> `);
  $templateCache.put("/static/app/extensions/emailing/templates/template-editor.html", `<form class=email-template-editor name=emailTemplateForm> <h2>{{template.id ? _('Edit a template') : _('Add a new template')}}</h2> <div class=form-group> <label class=form-label for=tplName>{{::_("Template name:")}}</label> <input type=text ng-model=template.name class=form-control id=tplName> </div> <div class=form-group> <label class=form-label for=tplSubject>{{::_("Subject:")}}</label> <input type=text ng-model=template.subject class=form-control id=tplSubject> </div> <div class=form-group> <label class=form-label for=tplSender>{{::_("Sender name:")}}</label> <input type=text ng-model=template.sender class=form-control placeholder="{{::_('Leave blank to use team name')}}" id=tplSender> </div> <div class=form-group> <label class=form-label for=tplReplyTo>{{::_("Reply to:")}}</label> <input type=text ng-model=template.reply_to class=form-control placeholder="{{::_('Leave blank to discard replies')}}" id=tplReplyTo> <p class=form-text>{{::_("Provide an email address that will receive replies to emails sent using this template")}}</p> </div> <div class=form-group> <label class=form-label>{{::_("Body:")}}</label> <content-editor ng-model=template.body editor-data=contentEditorData></content-editor> </div> <div class="alert alert-danger" ng-show=template.render_error> <h4><i class=bi-exclamation-triangle-fill></i>{{::_('An error occured while rendering the template during the last attempt')}}</h4> <p> {{template.render_error}} </p> </div> <div class="form-group attachments"> <label class=form-label>{{::_("Attachments:")}}</label> <p ng-repeat="attachment in template.attachments"> <input type=text ng-model=attachment.file.name disabled class=form-control> <button class="btn btn-icon btn-danger" ng-click=deleteAttachment(attachment)><i class="fa fa-trash"></i></button> </p> <p ng-repeat="file in newAttachments"> <input type=text ng-model=file.name disabled class=form-control> <button class="btn btn-icon btn-danger" ng-click=deleteNewAttachment(file)><i class="fa fa-trash"></i></button> </p> <button class="btn btn-default" ngf-select=addAttachment($files) ngf-multiple=true>{{::_('Add attachment')}}</button> </div> <div class="d-block text-end"> <button class="btn btn-danger" type=button ng-click=delete() ng-if=template.id>{{::_('Delete')}}</button> <button class="btn btn-default btn-ghost" type=button ng-click=onCancel() ng-if=onCancel>{{::_('Cancel')}}</button> <button class="btn btn-default btn-ghost" type=button ng-click=sendTest() ng-show=template.id>{{::_('Send test')}}</button> <button class="btn btn-success" type=submit ng-disabled=emailTemplateForm.$invalid ng-click=save()>{{::_('Save')}}</button> </div> </form> `);
  $templateCache.put("/static/app/extensions/emailing/templates/template-editor-modal.html", "<div class=modal-body> <email-template-editor project=project template=template on-cancel=$close(template) on-save=$close($template) on-delete=$close()></email-template-editor> </div> ");
  $templateCache.put("/static/app/extensions/emailing/templates/project-settings.html", `<div class=project-settings-email-templates-panel> <div class=modal-help-message> <p> {{::_("Email templates can be used to send emails in custom automation rules")}} </p> <div class="alert alert-info" ng-show="maxEmailTemplateSendPerDay != null"> <i class=bi-info-square-fill></i> {{::_("You can send up to {total} emails per day across all workspaces of your organization", {total: maxEmailTemplateSendPerDay})}} </div> </div> <div class=panel ng-if=!selected> <div class=panel-heading> {{::_('Email templates')}} </div> <div class=panel-body ng-show=!templates.length> <p class=panel-empty-message>{{::_('No templates yet.')}}</p> </div> <ul class=list-group> <li class=list-group-item ng-repeat="template in templates track by template.id"> <div class=list-group-item-description>{{::template.name}}</div> <button type=button class="btn btn-icon btn-sm btn-primary" ng-click=edit(template) ng-show=!project.is_archived uib-tooltip="{{::_('Edit')}}"> <i class="fa fa-pencil"></i> </button> <button type=button class="btn btn-icon btn-sm btn-danger" ng-click=delete(template) ng-show=!project.is_archived uib-tooltip="{{::_('Delete')}}"> <i class="fa fa-trash"></i> </button> </li> </ul> <button class="btn btn-primary" ng-click=add() ng-show=!project.is_archived> <i class=bi-plus-lg></i> {{::_('Add email template')}} </button> </div> <email-template-editor ng-if=selected project=project template=selected on-cancel="$parent.selected = null" on-save="refresh(); $parent.selected = null" on-delete="refresh(); $parent.selected = null"></email-template-editor> <div class=panel ng-show=!selected> <div class=panel-heading> {{::_('Send email using...')}} </div> <form class=panel-body name=smtpForm ng-submit=updateSmtpConnection()> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=useSmtpConnection ng-value=false ng-disabled=!canSendFromKantree name=radioSendFromKantree id=radioSendFromKantree> <label class=form-check-label for=radioSendFromKantree>{{::_('Let Kantree send emails for you')}}</label> <p class=form-text> {{!canSendFromKantree ? _("Only available for paying customers.") : _("Any abuse will result in immediate ban.")}} {{_("Emails are sent from {sender}", {sender: defaultSender})}} </p> </div> <div class="form-group form-check"> <input class=form-check-input type=radio ng-model=useSmtpConnection ng-value=true name=radioUseSmtpConnection id=radioUseSmtpConnection> <label class=form-check-label for=radioUseSmtpConnection>{{::_('Use a custom SMTP connection')}}</label> </div> <div ng-show=useSmtpConnection> <div class=form-group> <label class=form-label for=smtpServer>{{::_("Server")}}*:</label> <input type=text class=form-control ng-model=smtp.server ng-required=useSmtpConnection name=smtpServer id=smtpServer> </div> <div class=form-group> <label class=form-label for=smtpPort>{{::_("Port")}}*:</label> <input type=number class=form-control ng-model=smtp.port ng-required=useSmtpConnection name=smtpPort id=smtpPort> </div> <div class=form-group> <label class=form-label for=smtpUsername>{{::_("Username")}}:</label> <input type=text class=form-control ng-model=smtp.username name=smtpUsername id=smtpUsername> </div> <div class=form-group> <label class=form-label for=smtPwd>{{::_("Password")}}:</label> <input type=password class=form-control ng-model=smtp.password name=smtPwd id=smtPwd> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=smtp.use_tls name=smtpUseTLS id=smtpUseTLS> <label class=form-check-label for=smtpUseTLS>{{::_('Use TLS')}}</label> </div> <div class=form-group> <label class=form-label for=smtpSender>{{::_("Sender")}}:</label> <input type=text class=form-control ng-model=smtp.default_sender ng-attr-placeholder={{defaultSender}} name=smtpSender id=smtpSender> <p class=form-text>{{::_("Email address to send emails from")}}</p> </div> </div> <button type=submit class="btn btn-primary" ng-disabled="smtpForm.$invalid || smtpUpdateStatus.processing" disable-offline>{{::_('Save')}}</button> <processing-status status=smtpUpdateStatus></processing-status> </form> </div> `);
  $templateCache.put("/static/app/apps/portfolio/overview/ng-components/templates/overview.html", `<div class=overview-app-content> <div class="overview-app-widget projects"> <h2 class=overview-app-widget-header> <span class=overview-app-widget-title>{{::_("Workspaces")}}</span> <div class=overview-app-widget-controls> <button type=button class="btn btn-primary btn-ghost" ng-click=$ctrl.addProjects()> <i class=bi-plus-lg></i>{{::_('Add')}}</button> </div> </h2> <div class=project-tile-list> <div class=project-tile-wrapper ng-repeat="project in $ctrl.projects | orderBy:$ctrl.sortBy track by project.id" class=position-relative> <solidjs-component component=$ctrl.ProjectTile project=project show-team=true use-simple-anchor-tag=true></solidjs-component> <button type=button class="btn btn-icon btn-danger btn-ghost" ng-click=$ctrl.removeProject(project) class="position-absolute top-0 right-0" uib-tooltip="{{_('Remove from portfolio')}}"><i class=bi-x></i></button> </div> </div> </div> </div> `);
  $templateCache.put("/static/app/apps/global/report/ng-components/templates/report.html", `<div class=board-empty-notice ng-show="!$ctrl.widgets.length && $ctrl.isConnected()"> <p><i class="fa fa-certificate theme-main-color"></i> {{::$ctrl.titleForEmpty}}</p> <video autoplay loop muted> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-global-report.mp4'|baseUrl}}" type=video/mp4> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-global-report.webm'|baseUrl}}" type=video/webm> </video> <button type=button class=btn ng-click=$ctrl.addWidget()> <i class="bi-plus-lg theme-main-color"></i> <span>{{::_('Add your first widget')}}</span> </button> </div> <div class=auto-reports ng-show="!$ctrl.widgets.length && $ctrl.isConnected() && !!$ctrl.settings.autoReports"> <p> {{::_('Discover our ready to use dashboards:')}} </p> <ul ng-if=!!$ctrl.settings.autoReports> <li ng-repeat="report in $ctrl.settings.autoReports"> <a href ng-click=$ctrl.updateWidgets(report.widgets)> <i class="fa theme-main-color" ng-class=::report.icon|iconClass></i> <span>{{::report.title}}</span> </a> </li> </ul> </div> <div class=board-empty-notice ng-show="!$ctrl.isConnected() && !$ctrl.isConnectionManagerDisabled"> <i class="fa fa-warning"></i> <p>{{::_('Not available while offline')}}</p> </div> <report ng-if="$ctrl.charts && $ctrl.widgets.length && $ctrl.isConnected()" widgets=$ctrl.widgets editable=$ctrl.editable on-widgets-update=$ctrl.updateWidgets($widgets) on-fetch-data-start="$ctrl.fetching = true" on-fetch-data-end="$ctrl.fetching = false"></report> `);
  $templateCache.put("/static/app/apps/global/report/ng-components/templates/nav.html", `<button ng-if=$ctrl.editable class="btn btn-topbar add-btn" type=button ng-click=$ctrl.openChartLibrary() disable-offline><i class=bi-plus-lg></i> {{::_('Add widget')}}</button> <button class="btn btn-topbar" ng-class="{'is-nav-alert': !!$ctrl.context.needFetchCards}" type=button ng-show=$ctrl.editable uib-tooltip="{{::_('There are updates on Workspaces that might change your report.')}}" tooltip-enable=$ctrl.context.needFetchCards tooltip-placement=bottom ng-click=$ctrl.onForceRefreshAllWidgets() ng-disabled=!$ctrl.widgets.length disable-offline><i class=bi-arrow-repeat></i> {{::_('Refresh')}}</button> <button class="btn btn-icon btn-topbar" type=button ng-click=$ctrl.toggleFullscreen() uib-tooltip="{{::_('Toggle full screen')}}" tooltip-placement=bottom ng-disabled=!$ctrl.widgets.length> <i class=bi-fullscreen></i></button> `);
  $templateCache.put("/static/app/apps/global/cards/ng-components/templates/cards.html", `<div class=loading ng-show=$ctrl.context.fetching><i class="fa fa-spin fa-spinner"></i> {{::_("Searching...")}}</div> <div class=results ng-if=!$ctrl.context.fetching> <cards-app ng-if="!$ctrl.withEmptyNotice || $ctrl.resultsCount" store=$ctrl.context.cardStore filter=$ctrl.context.filter filter-scopes=$ctrl.context.filterScopes mode=$ctrl.mode group-by=$ctrl.groupBy options=$ctrl.context.appOptions on-change=$ctrl.updateContext($changes)></cards-app> <p ng-show="!$ctrl.withEmptyNotice || $ctrl.resultsCount" ng-if=::$ctrl.withCount>{{_('{count} cards found', {count: $ctrl.resultsCount || 0})}}</p> <div class=board-empty-notice ng-if="$ctrl.withEmptyNotice && !$ctrl.resultsCount"> <p>{{::_("No card found")}}</p> </div> </div> `);
  $templateCache.put("/static/app/apps/global/cards/ng-components/templates/nav.html", `<global-cards-app-projects-btn ng-if=$ctrl.showFilterScopesSelector context=$ctrl.context></global-cards-app-projects-btn> <cards-app-nav class=hidden-xs ng-if=!$ctrl.context.hideNav store=$ctrl.context.cardStore filter=$ctrl.context.appOptions.filter filter-scopes=$ctrl.context.filterScopes group-by-groups=$ctrl.context.groupByGroups group-by-choices=$ctrl.context.groupByChoices mode=$ctrl.mode group-by=$ctrl.groupBy options=$ctrl.context.appOptions readonly=$ctrl.context.readonly on-change=$ctrl.updateContext($changes) shrinked=$ctrl.shrinked></cards-app-nav> <button ng-if=!$ctrl.context.hideNav class="btn btn-icon btn-topbar" ng-class="{'is-nav-alert': !!$ctrl.context.needFetchCards}" uib-tooltip="{{$ctrl.context.needFetchCards ?
    _('There are updates on Workspaces that might change the matching cards. Refresh cards') : _('Refresh cards')}}" tooltip-placement=bottom ng-click=$ctrl.refreshAll() ng-disabled=!$ctrl.editable> <i class=bi-arrow-repeat></i></button> `);
  $templateCache.put("/static/app/apps/reports/modals/templates/widget-editor-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Widget settings')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class=modal-body> <report-chart-widget-editor ng-if="$ctrl.widget.chart.name !== 'cards'" widget=$ctrl.widget options=$ctrl.editorOptions on-change=$ctrl.onWidgetChange($widget)></report-chart-widget-editor> <report-cards-app-widget-editor ng-if="$ctrl.widget.chart.name === 'cards'" widget=$ctrl.widget options=$ctrl.editorOptions on-change=$ctrl.onWidgetChange($widget)></report-cards-app-widget-editor> </div> <div class=modal-footer> <button class="btn btn-danger me-auto" type=button ng-click=$ctrl.delete()><i class="fa fa-trash"></i> {{::_('Delete')}}</button> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.save() ng-disabled=$ctrl.missingReqs>{{::_('Save')}}</button> </div> `);
  $templateCache.put("/static/app/apps/reports/modals/templates/add-widget-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Add widget')}}</h3> <button type=button class=btn-close ng-click=$dismiss()></button> </div> <div class="modal-body mod-large-padding" ng-if=::!$ctrl.projectScoped ng-show=!$ctrl.widget> <h3>{{::_('Select a type of widget:')}}</h3> <ul class=list-unstyled> <li ng-repeat="type in $ctrl.widgetTypes"> <button type=button class="btn mod-new-widget" ng-click=type.onSelect()> <i ng-class=type.icon|iconClass class=theme-main-color></i> <span>{{type.title}}</span> </button> </li> </ul> <div ng-if=$ctrl.suggestedWidgets.length> <h3> {{::_('Suggested widgets:')}}</h3> <ul class=list-unstyled> <li ng-repeat="widget in $ctrl.suggestedWidgets"> <button type=button class="btn mod-new-widget" ng-click=widget.onSelect()> <i ng-class=widget.icon|iconClass class=theme-main-color></i> <span>{{widget.title}}</span> <p>{{widget.desc}}</p> </button> </li> </ul> </div> </div> <div class=modal-body ng-if=!!$ctrl.widget> <h3 ng-if=::!$ctrl.projectScoped> <button type=button class="btn btn-icon" ng-click=$ctrl.reset()><i class="fa fa-chevron-left"></i></button> {{_('Configure the new widget')}} </h3> <div class=editor-container> <div class=chart-library ng-class="{'collapsed': $ctrl.libCollapsed}" ng-if="$ctrl.widget.chart.name !== 'cards' || $ctrl.projectScoped"> <div class=header> <button type=button class="btn btn-icon btn-sm" ng-click="$ctrl.libCollapsed = !$ctrl.libCollapsed"> <i class=fa ng-class="{'fa-minus-square-o': !$ctrl.libCollapsed, 'fa-plus-square-o': $ctrl.libCollapsed}"></i> </button> <h3>{{_('Charts library')}}</h3> </div> <div class=body> <pretty-menu ng-if=::$ctrl.chartLibraryConfig config=::$ctrl.chartLibraryConfig></pretty-menu> </div> </div> <report-chart-widget-editor ng-if="$ctrl.widget.chart.name !== 'cards'" widget=$ctrl.widget on-change=$ctrl.onWidgetChange($widget)></report-chart-widget-editor> <report-cards-app-widget-editor ng-if="$ctrl.widget.chart.name === 'cards'" widget=$ctrl.widget on-change=$ctrl.onWidgetChange($widget)></report-cards-app-widget-editor> </div> </div> <div class=modal-footer ng-show=!!$ctrl.widget> <button class="btn btn-default btn-ghost" type=button ng-click=$dismiss()>{{::_('Cancel')}}</button> <button class="btn btn-success" type=button ng-click=$ctrl.save() ng-disabled=$ctrl.missingReqs>{{::_('Add')}}</button> </div> `);
  $templateCache.put("/static/app/apps/reports/ng-components/templates/report.html", '<grid-stack ng-hide=$ctrl.expandedWidget on-widget-change=$ctrl.onGridstackUpdate($changes) editable=$ctrl.editable> <gridstack-widget ng-repeat="widget in $ctrl._widgets track by widget.id" widget-id={{widget.id}} position=widget.position> <report-widget widget-title={{widget.title}} chart=widget.chart options=widget.options filter=widget.filter filter-scopes=widget.filter_scopes editable=$ctrl.editable editor-options=$ctrl.widgetEditorOptions chart-config=widget.chartConfig on-change="$ctrl.updateWidget(widget, $widget)" on-remove=$ctrl.removeWidget(widget) on-fetch-data-start="$ctrl.fetching = true" on-fetch-data-end="$ctrl.fetching = false" on-toggle-expand="$ctrl.expandedWidget = widget" show-header=true></report-widget> </gridstack-widget> </grid-stack> <report-widget ng-if=$ctrl.expandedWidget widget-title={{$ctrl.expandedWidget.title}} chart=$ctrl.expandedWidget.chart options=$ctrl.expandedWidget.options filter=$ctrl.expandedWidget.filter filter-scopes=$ctrl.expandedWidget.filter_scopes editable=$ctrl.editable editor-options=$ctrl.widgetEditorOptions chart-config=$ctrl.expandedWidget.chartConfig on-change="$ctrl.updateWidget($ctrl.expandedWidget, $widget)" on-remove=$ctrl.removeWidget($ctrl.expandedWidget) on-toggle-expand="$ctrl.expandedWidget = null" expanded=true show-header=true></report-widget> ');
  $templateCache.put("/static/app/apps/reports/ng-components/templates/table.html", `<table class=table ng-class="{'has-row-labels': !!$ctrl.config.options.rowLabels, 'big-cells': $ctrl.config.options.big,
      'hide-grid': $ctrl.config.options.hideGrid, 'table-bordered table-hover table-striped': !$ctrl.config.options.hideGrid}"> <thead ng-if=$ctrl.config.options.columnLabels> <tr> <th ng-if=$ctrl.config.options.rowLabels>{{$ctrl.config.options.corner}}</th> <th ng-repeat="col in $ctrl.config.options.columnLabels" ng-bind-html="$ctrl.formatLabel(col, $ctrl.config.options.columnLabelFormat)"></th> </tr> </thead> <tbody> <tr ng-repeat="row in $ctrl.config.data track by $index"> <td ng-if=$ctrl.config.options.rowLabels class=row-label ng-bind-html="$ctrl.formatLabel($ctrl.config.options.rowLabels[$index], $ctrl.config.options.rowLabelFormat)"></td> <td ng-repeat="cell in row track by $index">{{$ctrl.formatValue(cell)}}</td> </tr> </tbody> </table>`);
  $templateCache.put("/static/app/apps/reports/ng-components/templates/widget.html", `<div class=report-widget-header ng-if=::$ctrl.showHeader> <h3 ng-class="{'drag-handle': $ctrl.editable}" data-fittext data-fittext-min=8 data-fittext-max=inherit uib-tooltip="{{::$ctrl.chart.description ? $ctrl.chart.description + ' - ' : ''}}{{_('Last updated {updated}, click & drag to move around', {updated: $ctrl.updatedAt || '?'})}}" tooltip-popup-delay=0 tooltip-placement=bottom> {{$ctrl.title}} </h3> <div class=report-widget-actions ng-hide=$ctrl.titleEditing> <button ng-click=$ctrl.onToggleExpand() class="btn btn-icon btn-sm" ng-class="{'btn-primary': $ctrl.expanded, 'btn-default': !$ctrl.expanded}" ng-show=$ctrl.onToggleExpand uib-tooltip="{{::_('Show this widget in fullscreen')}}"><i class=bi-fullscreen></i></button> <button ng-click=$ctrl.openWidgetEditor() ng-show=$ctrl.editable class="btn btn-icon btn-sm btn-default" uib-tooltip="{{::_('Configure')}}"><i class=bi-three-dots></i></button> </div> </div> <div ng-if=::$ctrl.doesWidgetWrapperManageDataFetch class=loader ng-show=$ctrl.loading><i class="fa fa-cog fa-spin"></i></div> <div ng-if=::$ctrl.doesWidgetWrapperManageDataFetch class=report-widget-error ng-show="$ctrl.error && !$ctrl.loading"> <i class="fa fa-exclamation-triangle"></i> <p>{{$ctrl.errorReason}}</p> <button type=button class="btn btn-link" ng-click=$ctrl.fetchData(true) ng-show=$ctrl.loadingInterrupted><i class="fa fa-refresh"></i>{{::_('Reload')}}</button> <button type=button class="btn btn-link" ng-click=$ctrl.openWidgetEditor() ng-show=$ctrl.missingReqs ng-if=$ctrl.editable><i class="fa fa-pencil"></i>{{::_('Edit')}}</button> </div> <div class=report-widget-inner ng-if="(!$ctrl.loading && !$ctrl.error) || !$ctrl.doesWidgetWrapperManageDataFetch"> <dynamic-directive directive=report-widget-{{$ctrl.chartType}} config=$ctrl.chartData options=$ctrl.options filter=$ctrl.filter filter-scopes=$ctrl.filterScopes on-fetch-data-start="$ctrl.loading = true" on-fetch-data-end="$ctrl.loading = false"></dynamic-directive> </div> `);
  $templateCache.put("/static/app/apps/reports/ng-components/templates/chart-editor.html", `<div class=preview> <input class=form-control type=text ng-model=$ctrl.titleInput ng-model-options="{debounce: 100}" ng-change=$ctrl._onChange() ng-attr-placeholder="{{::_('Title required...')}}" ng-required auto-grow min-width=250> <report-widget widget-title={{$ctrl.titleInput}} chart=$ctrl.chart options=$ctrl.options filter-scopes=$ctrl.widget.filter_scopes filter=$ctrl.filter editable=false></report-widget> </div> <div class=editor> <div class=modal-help-message ng-if=::$ctrl.chart.description> <p>{{$ctrl.chart.description}}</p> </div> <div ng-if=::!$ctrl.projectScoped> <div class=form-group ng-if=::$ctrl.showFilterScopesSelector> <label class=form-label>{{::_('Select workspaces')}}</label> <user-project-selector-btn class="btn btn-default btn-ghost" selected-projects-is-null-for-all=true filter-scopes=$ctrl.widget.filter_scopes is-multiple=true show-empty-warning=true force-open-menu="::(!$ctrl.widget.filter_scopes || $ctrl.widget.filter_scopes.length === 0)" drop-config=$ctrl.dropConfig on-change=$ctrl.applyProjectSelection($filterScopes)></user-project-selector-btn> </div> <div class=form-group> <label class=form-label for=chartFilter>{{::_('Filter')}}</label> <textarea class=form-control ng-model=$ctrl.filter ng-model-options="{debounce: 100}" ng-change=$ctrl._onChange() id=chartFilter></textarea> </div> </div> <options-editor options=$ctrl.chartOptions values=$ctrl.options project=$ctrl.project on-change="$ctrl._onChange({options: $values})"></options-editor> </div> `);
  $templateCache.put("/static/app/apps/project/logs/ng-components/templates/nav.html", `<button class="btn btn-topbar" drop-menu=$ctrl.menu ng-if=$ctrl.menu> <i class="fa fa-filter"></i> <span>{{::_('Show logs for category')}} <strong>{{$ctrl.logType.name}}</strong></span> <span class=bi-caret-down-fill></span> </button> <button class="btn btn-topbar" drop-menu=$ctrl.exportMenu ng-show=$ctrl.canExportData hide-offline> <i class="fa fa-download"></i> {{::_('Export')}} </button> `);
  $templateCache.put("/static/app/apps/project/logs/ng-components/templates/logs.html", `<date-navigator range=$ctrl.activeDateRange on-change=$ctrl.updateDateRange($range) show-arrows=!$ctrl.context.shareMode show-datepicker=!$ctrl.context.shareMode ng-show=$ctrl.logTypes.length></date-navigator> <div class=board-logs-view-inner> <div class=activities-log-stream ng-if="$ctrl.dailyLogs.length > 1"> <h3 class=daily-activity-stream-header>{{::_('Total over the period')}}</h3> <table class=totals> <thead> <tr> <th class=user></th> <th class=card></th> <th ng-repeat="attr in $ctrl.logType.attributes">{{attr.type === 'number' ? attr.name : ''}}</th> </tr> </thead> <tbody> <tr ng-repeat="user in $ctrl.users"> <td class=user><img ng-src={{user|userAvatarUrl}} class="avatar me-1">{{user.display_name}}</td> <td class=card></td> <td ng-repeat="attr in $ctrl.logType.attributes">{{$ctrl.getUserSum(user, $ctrl.logs, attr)}}</td> </tr> </tbody> <tfoot> <tr> <td>{{::_('Total')}}</td> <td class=card></td> <td ng-repeat="attr in $ctrl.logType.attributes">{{$ctrl.getSum($ctrl.logs, attr)}}</td> </tr> </tfoot> </table> </div> <div ng-repeat="daily in $ctrl.dailyLogs" class=activities-log-stream> <h3 class=daily-activity-stream-header>{{ daily.formattedDate }}</h3> <table class=logs> <thead> <tr> <th class=user></th> <th class=card></th> <th ng-repeat="attr in $ctrl.logType.attributes">{{attr.name}}</th> </tr> </thead> <tbody> <tr ng-repeat="log in daily.activities" ng-click=$ctrl.openCard(log)> <td class=user ng-bind-html=$ctrl.getUserCell(log)></td> <td class=card ng-bind-html=$ctrl.getCardCell(log)></td> <td ng-repeat="attr in $ctrl.logType.attributes" class=logs-cell ng-class="'is-' + attr.type"> <attribute-repr-widgets attribute=attr obj=log attribute-group=$ctrl.logType.attributes options=$ctrl.attrReprWidgetsOptions></attribute-repr-widgets> </td> </tr> </tbody> <tfoot> <tr> <td>{{$ctrl.hasAggregAttrs ? _('Total') : ''}}</td> <td></td> <td ng-repeat="attr in $ctrl.logType.attributes">{{$ctrl.getSum(daily.activities, attr)}}</td> </tr> </tfoot> </table> </div> <div class=board-empty-notice ng-show="!$ctrl.logs.length && !$ctrl.loading"> <p><i class="fa fa-certificate theme-main-color"></i> {{::_("Logs help you keep track of what's happening in your workspace outside of Kantree. Start logging anything from cards.")}}</p> <video autoplay loop muted> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-logs.mp4'|baseUrl}}" type=video/mp4> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-logs.webm'|baseUrl}}" type=video/webm> </video> </div> <ul class="activities list-unstyled" ng-show=$ctrl.loading> <li class="action loader"> <i class="fa fa-spinner fa-spin"></i> {{::_('Loading...')}} </li> </ul> </div> `);
  $templateCache.put("/static/app/apps/project/report/ng-components/templates/report.html", `<div class=board-empty-notice ng-show="!$ctrl.widgets.length && $ctrl.isConnected()"> <p><i class="fa fa-certificate theme-main-color"></i> {{::_('Create a custom report by adding charts and save it as a view.')}}</p> <video autoplay loop muted> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-report.mp4'|baseUrl}}" type=video/mp4> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-report.webm'|baseUrl}}" type=video/webm> </video> </div> <div class=auto-reports ng-show="!$ctrl.widgets.length && $ctrl.isConnected() && !!$ctrl.autoReports"> <p> {{::_('Discover our ready to use reports:')}} </p> <ul> <li ng-repeat="report in $ctrl.autoReports"> <a href ng-click=$ctrl.createFromAutoReport(report)> <i ng-class=::report.icon|iconClass class=theme-main-color></i> <span>{{::report.title}}</span> </a> </li> </ul> </div> <div class=board-empty-notice ng-show="!$ctrl.isConnected() && !$ctrl.isConnectionManagerDisabled"> <i class="fa fa-warning"></i> <p>{{::_('Not available while offline')}}</p> </div> <report ng-if="$ctrl.widgets.length && ($ctrl.charts && $ctrl.isConnected() || $ctrl.context.shareMode)" widgets=$ctrl.widgets editable=$ctrl.editable on-widgets-update=$ctrl.updateWidgets($widgets)></report> `);
  $templateCache.put("/static/app/apps/project/report/ng-components/templates/nav.html", `<button ng-if="$ctrl.editable && !$ctrl.options.locked" class="btn btn-topbar add-btn" type=button ng-click=$ctrl.openChartLibrary() disable-offline><i class=bi-plus-lg></i> {{::_('Add chart')}}</button> <button class="btn btn-topbar" type=button ng-show=$ctrl.editable ng-click=$ctrl.onForceRefreshAllWidgets() ng-disabled=!$ctrl.widgets.length disable-offline><i class=bi-arrow-repeat></i> {{::_('Refresh')}}</button> <button class="btn btn-icon btn-topbar" type=button ng-click=$ctrl.toggleFullscreen() uib-tooltip="{{::_('Toggle full screen')}}" tooltip-placement=bottom ng-disabled=!$ctrl.widgets.length> <i class=bi-fullscreen></i></button> `);
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/webhooks.html", `<div class=project-integrations-help> {{::_("Use webhooks to call remote URLs when actions occur in Kantree")}} </div> <div ng-if=!$ctrl.selected> <ul class=list-group> <li class=list-group-item ng-repeat="webhook in $ctrl.webhooks track by webhook.id"> <div class=list-group-item-description>{{::webhook.url}}</div> <button type=button class="btn btn-icon btn-sm btn-default" ng-click=$ctrl.edit(webhook) uib-tooltip="{{::_('Edit')}}"><i class=bi-pencil-fill></i></button> <button type=button class="btn btn-icon btn-sm btn-danger btn-ghost" ng-click=$ctrl.delete(webhook) uib-tooltip="{{::_('Delete')}}"><i class=bi-trash-fill></i></button> </li> </ul> <button type=button class="btn btn-primary" ng-click=$ctrl.add()> <i class=bi-plus-lg></i> {{::_('Add webhook')}} </button> </div> <form ng-if=$ctrl.selected name=$ctrl.webhookForm ng-submit=$ctrl.save()> <div class=panel> <h3 class=panel-heading>{{$ctrl.selected.id ? _('Edit a webhook') : _('Add a new webhook')}}</h3> <div class=form-group> <label class=form-label for=webhookUrl>{{::_("URL:")}}</label> <input type=url ng-model=$ctrl.selected.url class=form-control id=webhookUrl> </div> <div class=form-group> <label class=form-label>{{::_("Events related to:")}}</label> <div class="list-group list-group-form-check"> <div class=list-group-item ng-repeat="event in $ctrl.availableEvents"> <div class=form-check> <input class=form-check-input type=checkbox ng-model=$ctrl.events[event[0]] id=webhookEvent{{$index}}> <label class=form-check-label for=webhookEvent{{$index}}>{{event[1]}}</label> </div> </div> </div> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.selected.active id=webhookActive> <label class=form-check-label for=webhookActive>{{::_("Is active")}}</label> </div> <div class="alert alert-info" ng-show=$ctrl.selected.last_called_at> <h4><i class=bi-info-square-fill></i>{{::_('Response from the last time it was called')}}</h4> <hr> <div class=form-group> <label class=form-label>{{::_('Date:')}}</label> {{$ctrl.selected.last_called_at|momentFormat}} </div> <div class=form-group> <label class=form-label>{{::_('Response code:')}}</label> {{$ctrl.selected.last_call_response_code}} </div> <div class=form-group> <label class=form-label>{{::_('Response content:')}}</label><br> <textarea class=form-control disabled ng-model=$ctrl.selected.last_call_response_body width=100%></textarea> </div> </div> <div class="d-block text-end"> <button class="btn btn-default btn-ghost" type=button ng-click="$ctrl.selected = null">{{::_('Cancel')}}</button> <button class="btn btn-success" type=submit ng-disabled=$ctrl.webhookForm.$invalid>{{::_('Save')}}</button> </div> </div> </form> `);
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/feature-embed.html", '<div class=modal-header> <h3 class=modal-title>{{::_("Embed on other web pages")}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <h3>{{::_("Share & embed views")}}</h3> <p> {{::_("You can share and embed individual views. Only the filtered data is exposed through the views. Use it to share reports, embed tables in your website, etc...")}} </p> <h3>{{::_("Share & embed cards")}}</h3> <p> {{::_("Share individual cards with clients and contractors.")}} </p> <h3>{{::_("Share & embed forms")}}</h3> <p> {{::_("Forms can be embeded in websites to collect data seamlessly")}} </p> </div> ');
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/feature-export.html", '<div class=modal-header> <h3 class=modal-title>{{::_("Export your cards data")}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <h3>{{::_("Download as spreadsheet")}}</h3> <p> {{::_("Export to Excel, CSV, OpenOffice and JSON")}} </p> <p> <button type=button class="btn btn-primary" ng-click=$ctrl.openExportModal()>{{::_("Export now")}}</button> </p> <h3>{{::_("Integration with BI tools")}}</h3> <p> {{::_("Use the following URL to add a CSV feed of your cards in your BI tool:")}} </p> <p> <copyable-readonly-input value=$ctrl.url></copyable-readonly-input> </p> <p> {{::_("Large projects (> 1000 cards), the above URL may fail. In this case, use the API.")}} <a href=https://kantree.io/help/guides/powerbi target=_blank>{{::_("Read our PowerBI guide for more information")}}</a> </p> </div> ');
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/services.html", '<h3><i class="fa fa-bolt" style="color: rgb(243, 197, 47);"></i> {{::_("Using the powers of Kantree")}}</h3> <div class=integration-list> <project-integrations-service-tile ng-repeat="integration in $ctrl.integrationFeatures" integration=integration on-open=$ctrl.open(integration) class=golden></project-integrations-service-tile> </div> <div ng-if=$ctrl.projectIntegrations.length> <h3>{{::_("Enabled integrations")}}</h3> <div class=integration-list> <project-integrations-service-tile ng-repeat="integration in $ctrl.projectIntegrations" integration=integration on-open=$ctrl.open(integration)></project-integrations-service-tile> </div> </div> <div ng-if=$ctrl.integrations.length> <h3>{{::_("Using third-party apps")}}</h3> <div class=integration-list> <project-integrations-service-tile ng-repeat="integration in $ctrl.integrations" integration=integration on-open=$ctrl.open(integration)></project-integrations-service-tile> </div> </div> ');
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/feature-form.html", `<div class=modal-header> <h3 class=modal-title>{{::_("Collect data using forms")}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <p> {{::_("Add form views and let people, whether they have access to your workspace or not, create cards inside your workspace.")}} </p> <p> {{::_("You can also enable submitting forms via email from the options of your form.")}} </p> </div> <div class=modal-footer> <button class="btn btn-primary" type=button ng-click=$ctrl.create()>{{::_('Create a form')}}</button> </div> `);
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/integrations.html", `<div class=nav-tabs> <div class=nav-tabs-tabs> <button ng-repeat="panel in $ctrl.panels" ng-click=$ctrl.activate(panel) class=nav-tab ng-class="{'active': $ctrl.currentPanel === panel}">{{panel.title}}</button> </div> </div> <dynamic-directive directive={{$ctrl.currentPanel.component}} context=$ctrl.context></dynamic-directive> `);
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/integration-modal.html", `<form name=$ctrl.serviceForm ng-submit=$ctrl.save()> <div class=modal-header> <h3 class=modal-title>{{::$ctrl.integration.title}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class=markdown ng-bind-html="$ctrl.integration.description.replace('CARD_ID', $ctrl.project.top_level_card.id).replace('PROJECT_ID', $ctrl.project.id)|markdown:true"></div> <div class="alert alert-danger alert-dismissible" ng-show=$ctrl.integration.error> <button type=button class=close data-dismiss=alert ng-click=$ctrl.clearError()>&times;</button> <strong>Error:</strong> {{$ctrl.integration.error}} <a href ng-click=$ctrl.authorize() class="btn btn-danger" ng-show=!$ctrl.integration.authorized> {{::_('Re-authorize')}}</a> </div> <options-editor options=$ctrl.availableOptions values=$ctrl.options></options-editor> </div> <div class=modal-footer> <button class="btn btn-default" type=button ng-click=$ctrl.dismiss()>{{::_('Close')}}</button> <button class="btn btn-danger" type=button ng-show="$ctrl.activable && $ctrl.integration.project_id" ng-click=$ctrl.remove()> <i class="fa fa-trash"></i> {{::_('Disable')}}</button> <button class="btn btn-primary" type=submit ng-show="$ctrl.activable && $ctrl.usable" ng-disabled=$ctrl.serviceForm.$invalid> {{$ctrl.integration.project_id ? _('Update') : _('Activate')}} </button> <button type=button class="btn btn-primary" ng-click=$ctrl.authorize() ng-show="$ctrl.isOwnerOfProjectOwner && $ctrl.activable && !$ctrl.usable"> {{::_('Activate')}} </button> </div> </form> `);
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/feature-email.html", `<div class=modal-header> <h3 class=modal-title>{{::_('Create Cards by email')}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div class=form-group> <label class=form-label>{{::_('Send emails to the following address:')}}</label> <copyable-readonly-input value=$ctrl.url></copyable-readonly-input> </div> <div class=markdown> <p> {{::_("Email subject will be your card title, email content will be a comment in your new card.")}} </p> <p> {{::_("Add @username and #group in your email subject to automatically assign your new card and add it to some groups.")}} </p> </div> <div class="form-group form-check form-switch" ng-if=$ctrl.canManageSettings> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.allowAnon ng-change=$ctrl.updateAllowAnon() id=allowAnon> <label class=form-check-label for=allowAnon>{{::_('Allow creating cards from any email addresses')}}</label> <p class=form-text>{{::_('Otherwise, will be limited to email addresses of the workspace members')}}</p> </div> </div> <div class=modal-footer> <button class="btn btn-default" type=button ng-click=$ctrl.dismiss()>{{::_('Close')}}</button> </div> `);
  $templateCache.put("/static/app/apps/project/integrations/ng-components/templates/feature-external-data.html", '<div class=modal-header> <h3 class=modal-title>{{::_("Connect to external data sources")}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <h3>{{::_("Fetch data from external sources")}}</h3> <p> {{::_("Two fields exist for pulling data from external data sources as a list or as a value")}} </p> <h3>{{::_("Call remote URLs")}}</h3> <p> {{::_("Use Remote Action Buttons or Call Remote URLs from automations to trigger actions on third-party web services")}} </p> </div> ');
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/project-activity-input.html", `<img class=card-comment-avatar ng-if=!$ctrl.isScreensizeXS() ng-src={{::$ctrl.currentUser|userAvatarUrl}}> <div class=content-composer-wrapper ng-if=$ctrl.isCommentCreating> <content-composer class=inline-buttons options=$ctrl.newCommentCreatorOptions on-submit="$ctrl.saveComment(submittedText, commentShowInRequest)" on-cancel=$ctrl.closeCommentEditor(cancelledText) on-draft-change=$ctrl.refreshCommentDraft(draftedText)></content-composer> </div> <div class=card-view-log-composer-wrapper ng-if=$ctrl.isLogCreating> <div class=card-view-log-composer> <h2> {{::_('Log something')}} <a href datepicker-dropdown=$ctrl.logCreator.date datepicker-options=$ctrl.logCreator.datepickerOptions on-date-change="$ctrl.updateLogDate($start, $end)">{{$ctrl.logCreator.dateLabel}}</a> {{::_('under {logtype}', {logtype: $ctrl.logCreator.type.name})}} </h2> <attribute-form project=project obj=$ctrl.logCreator.obj data=$ctrl.logCreator.data attribute-group=$ctrl.logCreator.attributes attributes-editable=$ctrl.logCreator.editable attributes-movable=$ctrl.logCreator.editable attribute-type-available-for=logs show-empty-notice=true></attribute-form> </div> <button class="btn btn-success" type=button ng-click=$ctrl.submitLog() ng-disabled="$ctrl.logCreator.attributes.length === 0">{{::_('Save')}}</button> <button class="btn btn-cancel btn-icon" type=button ng-click=$ctrl.cancelLogCreator()><i class="fa fa-times"></i></button> </div> <div class=card-view-stream-actions ng-class="{'has-draft': $ctrl.commentDraft}" ng-if="!$ctrl.isCommentCreating && !$ctrl.isLogCreating" ng-click=$ctrl.openCommentEditor()> <a href ng-if=$ctrl.canComment>{{$ctrl.commentPlaceholder}}</a> <span ng-if="$ctrl.canComment && $ctrl.canLog">{{::_('or')}}</span> <a href ng-if=$ctrl.canLog drop-menu=$ctrl.logsDropMenu ng-click=$event.stopPropagation()>{{::_('log something')}} <i class=bi-caret-down-fill></i></a> </div> `);
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/overview-stats.html", `<div class=project-overview-app-stats-widget> <button type=button class="btn btn-silent" ng-click=$ctrl.toggleGuide()> <i class=bi-book></i> {{::_("Guide")}} </button> </div> <div class=project-overview-app-stats-widget ng-click=$ctrl.toggleDueCardsView()> <button type=button class="btn btn-silent"><em>{{$ctrl.dueCardsCount}}</em></button> {{::_n('card due', 'cards due', $ctrl.dueCardsCount)}} <button type=button class="btn btn-sm" drop-menu=$ctrl.dropMenuConfig> {{$ctrl.dueCardsTimeSpan}} <i class="bi-caret-down-fill right"></i> </button> </div> <div class=project-overview-app-stats-widget ng-click=$ctrl.toggleUpdatedCardsView()> <button type=button class="btn btn-silent"><em>{{$ctrl.updatedCardsCount}}</em></button> {{::_n('card updated', 'cards updated', $ctrl.updatedCardsCount)}} <button type=button class="btn btn-sm" drop-menu=$ctrl.dropMenuConfig> {{$ctrl.updatedCardsTimeSpan}} <i class="bi-caret-down-fill right"></i> </button> </div> <div class=project-overview-app-stats-widget> activity line placeholder <!-- <project-activity-line-chart project="$ctrl.context.project"></project-activity-line-chart> --> </div> `);
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/overview.html", "<div class=project-overview-app-content> <project-overview-app-header context=$ctrl.context></project-overview-app-header> <project-overview-app-attributes context=$ctrl.context></project-overview-app-attributes> <project-overview-app-members context=$ctrl.context></project-overview-app-members> </div> ");
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/project-inbox.html", `<a href ng-click=$ctrl.refreshFeed() ng-show=$ctrl.refreshFeedNeeded> <i class="fa fa-refresh"></i> {{_('{count} update(s) are available, click to refresh', {count: $ctrl.refreshUnreadCount})}} </a> <inbox feed=$ctrl.feed loading="$ctrl.loading || $ctrl.loadingFeedPage" unread-ids=$ctrl.unreadIds unread-only=false mark-as-read-when-comment=false mark-as-read-on-scrolled=false on-mark-as-read=$ctrl.markAsRead($activities) on-mark-all-as-read=$ctrl.markAllAsRead()></inbox> `);
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/overview-members.html", `<div class=project-overview-app-members-list ng-if="!$ctrl.context.project.is_template && $ctrl.members.owners.length"> <h2 class=project-overview-app-members-list-title>{{::_("Owner")}}</h2> <solidjs-component component=$ctrl.MemberList members=$ctrl.members.owners presence-manager=$ctrl.presenceManager show-presence=true default-view-mode="'tiles'"></solidjs-component> </div> <div class=project-overview-app-members-list ng-if="!$ctrl.context.project.is_template && $ctrl.members.org.length"> <h2 class=project-overview-app-members-list-title>{{::_("Members")}}</h2> <solidjs-component component=$ctrl.MemberList members=$ctrl.members.org roles=$ctrl.roles.org editable=$ctrl.canManageMembers presence-manager=$ctrl.presenceManager show-presence=true show-remove=true default-view-mode="'tiles'" on-remove=$ctrl.removeMember on-role-change=$ctrl.updateMemberRole></solidjs-component> </div> <div class=project-overview-app-members-list ng-if="!$ctrl.context.project.is_template && ($ctrl.invites.length || $ctrl.member.guests.length)"> <h2 class=project-overview-app-members-list-title>{{::_("Guests")}}</h2> <solidjs-component component=$ctrl.MemberList ng-show=$ctrl.members.guests.length members=$ctrl.members.guests roles=$ctrl.roles.guests editable=$ctrl.canManageMembers presence-manager=$ctrl.presenceManager show-presence=true show-remove=true default-view-mode="'tiles'" on-remove=$ctrl.removeMember on-role-change=$ctrl.updateMemberRole></solidjs-component> <solidjs-component component=$ctrl.MemberList ng-show=$ctrl.invites.length members=$ctrl.invites roles=$ctrl.roles.guests editable=$ctrl.canManageMembers presence-manager=$ctrl.presenceManager show-presence=true show-remove=true default-view-mode="'tiles'" on-remove=$ctrl.removeInvite on-role-change=$ctrl.updateMemberRole on-resend-invite=$ctrl.resendInvite></solidjs-component> </div> `);
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/overview-attributes.html", "<attribute-group class=fluid obj=$ctrl.topLevelCard attribute-group=$ctrl.topLevelCardModel.attributes editable=$ctrl.topLevelCardEditable project=$ctrl.context.project></attribute-group> ");
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/overview-inbox.html", "<project-activity-input project=$ctrl.context.project comment-placeholders=::$ctrl.commentPlaceholders></project-activity-input> <project-inbox project=$ctrl.context.project></project-inbox> ");
  $templateCache.put("/static/app/apps/project/overview/ng-components/templates/overview-header.html", "<h1>{{$ctrl.context.project.title}}</h1> ");
  $templateCache.put("/static/app/apps/project/files/ng-components/templates/files.html", "<file-gallery store=$ctrl.files></file-gallery> ");
  $templateCache.put("/static/app/apps/project/files/ng-components/templates/nav.html", `<form class=board-nav-filters-form ng-submit=$ctrl.doFilter()> <i class="fa fa-filter"></i> <input type=text placeholder="{{_('Filter')}}" auto-grow min-width=300 max-width=500 ng-model=$ctrl.filter> <button class="btn btn-icon mod-icon-input reset" ng-class="{'btn-topbar': $ctrl.isScreensizeXS()}" type=button ng-show=$ctrl.filter ng-click="$ctrl.filter = ''; $ctrl.doFilter()"> <i class="fa fa-close" ng-show="$ctrl.filter !== ''"></i> </button> </form> `);
  $templateCache.put("/static/app/apps/project/automations/ng-components/templates/share-modal.html", `<div class=modal-header> <h3 class=modal-title>{{::_("Trigger automation via URL")}}</h3> <button type=button class=btn-close ng-click=$ctrl.dismiss()></button> </div> <div class=modal-body> <div ng-show=$ctrl.runnable class=mb-4> <h4>{{::_("Trigger via a public URL")}}</h4> <p>{{::_("Share a link that automatically triggers this automation when it is visited.")}}</p> <copyable-readonly-input value=$ctrl.url></copyable-readonly-input> </div> <h4>{{::_("Trigger via HTTP POST request")}}</h4> <p>{{::_("Use this automation has a custom API endpoint.")}}</p> <copyable-readonly-input value=$ctrl.url></copyable-readonly-input> <div ng-show=!$ctrl.runnable class="alert alert-info mt-3"> <i class=bi-exclamation-triangle-fill></i> {{::_("You must provide the card_id query parameter to run the rule against a card")}} </div> <p class=mt-3>{{::_("Example usage using cURL while providing variables:")}}</p> <textarea readonly width=100% rows=5 class=form-control>curl -X POST {{$ctrl.url}}{{!$ctrl.runnable ? ' -d card_id=CARD_ID ' : ''}} -d variable1=value1 -d variable2=value2</textarea> </div> <div class=modal-footer> <button type=button class="btn btn-danger" ng-click=$ctrl.invalidate()><i class=bi-trash></i> {{::_("Invalidate all existing URLs")}}</button> <button type=button class="btn btn-default" ng-click=$ctrl.dismiss()>{{::_("Close")}}</button> </div> `);
  $templateCache.put("/static/app/apps/project/automations/ng-components/templates/automations.html", `<solidjs-component component=$ctrl.SolidAutomations rules=$ctrl.rules on-rule-click=$ctrl.editRuleFun on-create-rule=$ctrl.createRuleFun context=$ctrl.context loading=$ctrl.loading editing=$ctrl.editing></solidjs-component> <automation-rule-editor ng-if=!!$ctrl.editing rule=$ctrl.editing project=::$ctrl.context.project on-change="$ctrl.context.trigger('onEditorChange', $valid)" is-new=$ctrl.isNew></automation-rule-editor>`);
  $templateCache.put("/static/app/apps/project/automations/ng-components/templates/nav.html", `<!-- TODO: Use later when app system can handle it: <solidjs-component component="$ctrl.SolidAutomationsNav"></solidjs-component> --> <button class="btn btn-topbar btn-add-automation hidden-xs" ng-if="!$ctrl.editing && $ctrl.canManageAutomations" ng-click=$ctrl.openAddAutomationMenu($event)> <i class=bi-plus-lg></i> {{::_("Add")}} </button> <help-btn guide=workflow-automation ng-if=!$ctrl.editing></help-btn> <button class="btn btn-topbar" ng-click=$ctrl.cancelEdit() ng-show=$ctrl.editing> <i class=bi-arrow-left></i> {{::_("Back to rules")}} </button> <button class="btn btn-topbar" ng-click=$ctrl.saveRule() ng-show=$ctrl.editing ng-disabled="!$ctrl.modified || $ctrl.saveDisabled"> <i class=bi-save></i> {{::_("Save")}} </button> <button class="btn btn-topbar" ng-click=$ctrl.runRule() ng-show="$ctrl.editing && $ctrl.runnable" ng-disabled="$ctrl.saveDisabled || $ctrl.running"> <i ng-class="$ctrl.running ? 'fa fa-spin fa-spinner' : 'bi-play-fill'"></i> {{$ctrl.modified ? _("Save and run") : _("Run now")}} </button> <button class="btn btn-topbar" ng-click=$ctrl.deleteRule() ng-show="$ctrl.editing && $ctrl.editing.id"> <i class=bi-trash></i> {{::_("Delete")}} </button> <button class="btn btn-topbar" ng-class="{'disabled-active-toggle': !$ctrl.editing.active}" ng-click=$ctrl.toggleActive() ng-show="$ctrl.editing && $ctrl.pausable"> <i ng-class="!!$ctrl.editing.active ? 'bi-toggle-on' : 'bi-toggle-off'"></i> {{!!$ctrl.editing.active ? _("Active") : _("This rule is currently paused. Click to enable.")}} </button> <button class="btn btn-topbar" ng-show="$ctrl.editing && $ctrl.shareable" drop-menu=$ctrl.shareMenu> <i class=bi-share></i> {{::_("Share")}} </button> `);
  $templateCache.put("/static/app/apps/project/forms/ng-components/templates/form-editor.html", `<div class=request-form-editor-header> <label class=form-label for=formPublicPerm><i class="fa fa-eye"></i> {{::_('Accessible by')}}</label> <select class="form-select form-select-lg" ng-model=$ctrl.form.public_permission ng-options="p.perm as p.label for p in $ctrl.permissions" id=formPublicPerm></select><br> <kt-form-check value=!$ctrl.form.unlisted on-change="$ctrl.form.unlisted = !$isChecked" ng-show="$ctrl.form.public_permission > 0" switch=true> {{::_("List on organization hub")}} </kt-form-check> </div> <div class=request-form> <div class=request-form-header custom-bgcolor={{$ctrl.form.header_color}} bgcolor-watch=true> <div class=request-form-editor-title> <input type=text ng-required ng-model=$ctrl.form.name class=form-control placeholder="{{::_('Form title')}}" auto-focus custom-fgcolor={{$ctrl.form.header_color}}> <button class="btn btn-icon" drop-menu=$ctrl.colorPickerOptions><i class=bi-palette-fill></i></button> </div> <a href ng-click=$ctrl.showDescription() ng-hide=!$ctrl.hideDescription>{{::_('Add description')}}</a> <textarea ng-model=$ctrl.form.description class=form-control placeholder="{{::_('Introductory text for your form')}}" ng-hide=$ctrl.hideDescription custom-fgcolor={{$ctrl.form.header_color}}></textarea> </div> <div class=request-form-editor-tracking ng-show=$ctrl.form.request_page> <a href class="btn btn-default btn-ghost btn-sm" ng-click="$ctrl.showProcessSteps = true" ng-show=!$ctrl.showProcessSteps> <i class="fa fa-bullhorn"></i> {{::_("Show steps of your process to the user on its request page")}}</a> <div class=request-form-tracking ng-if=$ctrl.form.tracking_group_type_id> <div ng-if=$ctrl.showProcessSteps ng-repeat="g in $ctrl.trackingGroups track by g.id" ng-show=$ctrl.selectedGroups[g.id]> <span class=dot><i class="fa fa-arrow-right"></i></span> <span class=title>{{g.title}}</span> </div> </div> <div class="request-form-editor-tracking-settings input-group input-group-sm" ng-show=$ctrl.showProcessSteps> <select class=form-select ng-model=$ctrl.form.tracking_group_type_id ng-options="gt.id as gt.name for gt in $ctrl.groupTypes track by gt.id" ng-change=$ctrl.refreshGroups(true)> <option value>{{::_('No tracking')}}</option> </select> <button class="btn btn-default btn-icon btn-ghost btn-sm" type=button drop-menu=$ctrl.trackingGroupsMenu ng-show="$ctrl.form.tracking_group_type_id && $ctrl.trackingGroups" uib-tooltip="{{::_('Select which steps to show to the user')}}"><i class=bi-eye></i></a> <button class="btn btn-default btn-icon btn-ghost btn-sm" type=button ng-click=$ctrl.removeTracking() uib-tooltip="{{::_('Hide process steps')}}"><i class=bi-trash-fill></i></a> </div> </div> <div class=request-form-editor-fields ui-sortable=$ctrl.uiSortableOptions ng-model=$ctrl.fields> <div class=request-form-editor-field ng-repeat="field in $ctrl.fields"> <h4> <span class=request-form-editor-field-move-handle><i class="fa fa-sort"></i></span> <span ng-if="field.type === 'title'">{{::_('Field mapped to Title')}}</span> <span ng-if="field.type === 'attribute'">{{_('Field mapped to {attr}', {attr: field.attribute.name})}}</span> <span ng-if="field.type === 'text'">{{::_('Text content')}}</span> <span ng-if="field.type === 'header'">{{::_('Header')}}</span> <span ng-if=$ctrl.dynamicFieldTypes.includes(field.type)>{{::_('Set card field with value of {form_special_field}', {form_special_field: field.label})}}</span> <button type=button class="btn btn-icon btn-text" ng-click=$ctrl.removeField(field)><i class=bi-trash-fill></i></button> </h4> <div ng-if="['title', 'attribute'].includes(field.type)"> <div class="alert alert-info" ng-if="field.type === 'attribute' && field.attribute.type == 'files' && $ctrl.publicUploadRestrictions && $ctrl.form.public_permission === 2"> <p>{{::_("File uploads in public forms have restrictions: {0}", $ctrl.publicUploadRestrictions)}}</p> </div> <div class=form-group> <label class=form-label for=field{{$index}}Label>{{::_('Label:')}}</label> <input type=text ng-model=field.label class=form-control ng-change=$ctrl.onFieldChange() id=field{{$index}}Label> </div> <div class=form-group> <label class=form-label for=field{{$index}}Desc>{{::_('Description:')}}</label> <input type=text ng-model=field.description class=form-control ng-change=$ctrl.onFieldChange() id=field{{$index}}Desc> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=field.required ng-change=$ctrl.onFieldChange() id=field{{$index}}Required> <label class=form-check-label for=field{{$index}}Required>{{::_('Required')}}</label> </div> </div> <div ng-if="field.type === 'text'"> <div class=form-group> <content-editor ng-model=field.description on-change=$ctrl.onFieldChange()></content-editor> </div> </div> <div ng-if="field.type === 'header'"> <div class=form-group> <input type=text ng-model=field.label class=form-control ng-change=$ctrl.onFieldChange()> </div> </div> <div ng-if=$ctrl.dynamicFieldTypes.includes(field.type)> <div class=form-group> <select class=form-select ng-model=field.attribute_id ng-change=$ctrl.onFieldChange() ng-options="attr.id as attr.name for attr in $ctrl.specialFieldAttributes"> <option value>{{::_('Ignored')}}</option> </select> </div> </div> </div> <div class=field-required-message ng-show="!$ctrl.fields || !$ctrl.fields.length">{{::_('Add fields from your workspace to your form using the button below')}}</div> <button type=button class="btn btn-primary btn-icon" drop-menu=$ctrl.addFieldMenu uib-tooltip="{{::_('Add new field')}}"><i class=bi-plus-lg></i></button> </div> </div> <i class=bi-arrow-down></i> <div class=request-form-editor-footer> <h4><a href ng-click=$ctrl.toggleAfterSubmittingCollapse()> <i ng-class="{'bi-caret-down-fill': !$ctrl.afterSubmittingCollapsed, 'bi-caret-right-fill': $ctrl.afterSubmittingCollapsed}"></i> {{::_('Advanced options once the form is submitted')}} </a></h4> <div ng-show=!$ctrl.afterSubmittingCollapsed> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.email_required id=formEmailRequired> <label class=form-check-label for=formEmailRequired>{{::_("Submitter must provide an email address")}}</label> </div> <div class=form-group> <div class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.send_confirmation_email id=formSendConfirmationEmail> <label class=form-check-label for=formSendConfirmationEmail>{{::_('Send a confirmation email')}}</label> </div> <textarea ng-show=$ctrl.form.send_confirmation_email ng-model=$ctrl.form.email_message class=form-control placeholder="{{::_('Message sent to the person after they submitted the form')}}"></textarea> </div> <div class=form-group ng-show=$ctrl.parents.length> <label class=form-label for=formAddToParent>{{::_('Create the card under the following parent:')}}</label> <select class=form-select ng-model=$ctrl.form.add_to_parent_id id=formAddToParent ng-options="c.id as c.full_title for c in $ctrl.parents" ng-disabled=$ctrl.scopedToParent> <option value>{{::_('Top level of workspace')}}</option> </select> </div> <div class=form-group> <label class=form-label for=formAddToGroup>{{::_('Create the card in the following group:')}}</label> <select class=form-select ng-model=$ctrl.form.add_card_to_group_id id=formAddToGroup ng-options="g.id as g.title group by g.group_type for g in $ctrl.groups"> <option value>{{::_('Ungrouped')}}</option> </select> </div> <div class=form-group ng-show="$ctrl.models.length > 1"> <label class=form-label for=formCardModel>{{::_('Create the card using the following type:')}}</label> <select class=form-select ng-model=$ctrl.form.card_model_id id=formCardModel ng-options="m.real_id as m.name for m in $ctrl.models" ng-change=$ctrl.refreshAttributes()> </select> </div> <div class=form-group> <label class=form-label for=formEmailSender>{{::_('Name of the sender in email notifications')}}</label> <input type=text ng-model=$ctrl.form.email_sender class=form-control id=formEmailSender placeholder="{{::_('If left blank, the name of your organization will be used')}}"> </div> <div class=form-group ng-show="$ctrl.form.public_permission === 2"> <label class=form-label for=formAnonEmailField>{{::_('When submitted anonymously, use the following field for email address (must be email type):')}}</label> <select class=form-select ng-model=$ctrl.form.anonymous_email_field_idx id=formAnonEmailField ng-options="f.idx as f.label for f in $ctrl.anonymousEmailFields"> <option value>{{::_('Automatically add an email field at the top of the form')}}</option> </select> </div> </div> <div ng-show=$ctrl.serverConfig.email_inbound_domain> <hr> <h4 class="form-check form-switch" ng-class="{'inactive': !$ctrl.form.allow_request_via_email}"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.allow_request_via_email id=FormAllowRequestViaEmail> <label class=form-check-label for=FormAllowRequestViaEmail>{{::_('Allow receiving requests via email')}}</label> </h4> <div ng-show=$ctrl.form.allow_request_via_email> <p class=form-text> {{::_('Map the subject, body and attachments to form fields. Fields marked as required will be ignored when creating cards by email')}} </p> <div class=form-group> <label class=form-label for=formEmailSubjectField>{{::_('Map the subject to the following field:')}}</label> <select class=form-select ng-model=$ctrl.form.email_subject_field_idx id=formEmailSubjectField ng-options="f.idx as f.label for f in $ctrl.inboundEmailFields"> <option value>{{::_('Ignored')}}</option> </select> </div> <div class=form-group> <label class=form-label for=formEmailBodyField>{{::_('Map the body to the following field:')}}</label> <select class=form-select ng-model=$ctrl.form.email_body_field_idx id=formEmailBodyField ng-options="f.idx as f.label for f in $ctrl.inboundEmailFields"> <option value>{{::_('Ignored')}}</option> </select> </div> <div class=form-group> <label class=form-label for=formEmailFilesField>{{::_('Map attachments to the following field:')}}</label> <select class=form-select ng-model=$ctrl.form.email_attachments_field_idx id=formEmailFilesField ng-options="f.idx as f.label for f in $ctrl.inboundEmailFileFields"> <option value>{{::_('Ignored')}}</option> </select> </div> </div> </div> </div> <i class=bi-arrow-down></i> <div class=request-form-editor-footer> <h4 class="form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.request_page id=formRequestPage> <label class=form-check-label for=formRequestPage>{{::_("Provide a tracking page for the submitter")}}</label> </h4> <div ng-show=$ctrl.form.request_page> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.allow_comments id=formAllowComments> <label class=form-check-label for=formAllowComments> {{::_('Allow requester to post comments after submitting the request')}} </label> </div> <div class="form-group form-check form-switch"> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.editable_after_submit id=formEditableAfterSubmit> <label class=form-check-label for=formEditableAfterSubmit> {{::_('Allow requester to edit fields after submitting the request')}} </label> </div> <div class="form-group form-check form-switch" ng-show=$ctrl.form.tracking_group_type_id> <input class=form-check-input type=checkbox role=switch ng-model=$ctrl.form.notify_requester_of_group_change id=formNotifyRequester> <label class=form-check-label for=formNotifyRequester> {{::_('Notify requester when cards is moved from one group to another')}} </label> </div> </div> </div> `);
  $templateCache.put("/static/app/apps/project/forms/ng-components/templates/form.html", '<div class=board-form-view> <request-form-editor form=$ctrl.editing scoped-to-parent=$ctrl.scopedToParent ng-if=$ctrl.editing></request-form-editor> <request-form form=$ctrl.form ng-if="$ctrl.form && !$ctrl.editing" reset-on-submit=true disable-submit-btn=!$ctrl.canSubmit disable-submit-message=$ctrl.disableSubmitMessage on-submitted=$ctrl.onSubmit(request)></request-form> </div> ');
  $templateCache.put("/static/app/apps/project/forms/ng-components/templates/nav.html", `<button class="btn btn-topbar hidden-xs" ng-click=$ctrl.edit() ng-hide="$ctrl.editing || !$ctrl.canEdit"> <i class=bi-pencil></i> {{::_("Edit form")}} </button> <button class="btn btn-topbar hidden-xs" ng-hide="$ctrl.editing || !$ctrl.canShare" drop-menu=$ctrl.shareMenuConfig drop-config="{classes: 'drop-theme-menu drop-theme-arrow drop-theme-form-links'}"> <i class=bi-share></i> {{::_("Share")}} </button> <button class="btn btn-topbar" ng-click=$ctrl.cancel() ng-show="$ctrl.editing && !$ctrl.isNew"> <i class=bi-arrow-left></i> {{::_("Back to form")}} </button> <button class="btn btn-topbar" ng-click=$ctrl.save() ng-show=$ctrl.editing ng-disabled="!$ctrl.editing.fields.length || !$ctrl.editing.name"> <i class=bi-save></i> {{::_("Save")}} </button> <span ng-if="$ctrl.editing && (!$ctrl.editing.fields.length || !$ctrl.editing.name)" class="align-middle text-danger"> <i class=bi-exclamation-triangle-fill></i> {{::_("The form must have a title and some fields")}} </span> `);
  $templateCache.put("/static/app/apps/project/forms/ng-components/templates/forms.html", `<div class=board-empty-notice ng-show="!$ctrl.requestForms.length && !$ctrl.editingForm && !$ctrl.fillForm"> <p><i class="fa fa-certificate theme-main-color"></i> {{::_('Let external people create cards in your workspace through a form')}}</p> <video autoplay loop muted> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-forms.mp4'|baseUrl}}" type=video/mp4> <source ng-attr-src="{{'/static/assets/tour/videos/placeholder-forms.webm'|baseUrl}}" type=video/webm> </video> <button type=button class=btn ng-show=$ctrl.canCreate() ng-click=$ctrl.create() disable-offline> <i class="bi-plus-lg theme-main-color"></i> <span>{{::_('Create your first form')}}</span> </button> </div> <div ng-hide="!$ctrl.requestForms.length || $ctrl.editingForm || $ctrl.fillForm"> <ul class=board-forms-list> <li ng-repeat="form in $ctrl.requestForms" ng-click=$ctrl.fill(form)> <div class=header custom-bgcolor=form.header_color> <h3> {{form.name}} <i class="fa fa-globe" ng-show="form.public_permission === 2" uib-tooltip="{{::_('Publicly accessible')}}"></i> </h3> <div class=actions> <button type=button class="btn btn-icon btn-sm btn-default" ng-click="$event.stopPropagation(); $ctrl.viewRequests(form)" uib-tooltip="{{::_('View cards created through this form')}}" disable-offline> <i class="fa fa-list"></i> </button> <button type=button class="btn btn-icon btn-sm btn-default" ng-show=$ctrl.canFeatureItem() ng-click="$event.stopPropagation(); $ctrl.addToOrgFeaturedItems(form)" uib-tooltip="{{::_('Feature on organization page')}}" disable-offline> <i class=fa ng-class="{'fa-star-o': !form.featured, 'fa-star': form.featured}"></i> </button> <button type=button class="btn btn-icon btn-sm btn-default" ng-click="$event.stopPropagation(); $ctrl.edit(form)" uib-tooltip="{{::_('Edit')}}" ng-show=$ctrl.canEdit(form) disable-offline> <i class="fa fa-pencil"></i> </button> <button type=button class="btn btn-icon btn-sm btn-danger" ng-click="$event.stopPropagation(); $ctrl.delete(form)" uib-tooltip="{{::_('Delete')}}" ng-show=$ctrl.canDelete(form) disable-offline> <i class="fa fa-trash"></i> </button> </div> </div> <div class=body> <p ng-show=form.description>{{form.description}}</p> <p class=links-label ng-show="form.public_permission == 1"> {{::_("Share the following link with your team mates:")}} </p> <p class=links-label ng-show="form.public_permission == 2"> {{::_("Share the following public link with anybody:")}} </p> <div class=links ng-show="form.public_permission > 0"> <div class=input-group> <span class=input-group-text><i class="fa fa-link"></i></span> <input type=text readonly value={{$ctrl.getFormURL(form)}} class=form-control ng-click="$event.stopPropagation(); $ctrl.focus($event)"> <a href class="btn btn-icon btn-default btn-ghost clipboard" ng-click=$event.stopPropagation() uib-tooltip="{{::_('Copy link')}}" ng-clipboard={{$ctrl.getFormURL(form)}}> <i class="fa fa-clipboard"></i> </a> </div> <div class=input-group ng-if=form.allow_request_via_email> <span class=input-group-text><i class="fa fa-envelope"></i></span> <input type=text readonly value={{form.inbound_email}} class=form-control ng-click="$event.stopPropagation(); $ctrl.focus($event)"> <a href class="btn btn-icon btn-default btn-ghost clipboard" ng-click=$event.stopPropagation() uib-tooltip="{{::_('Copy email')}}" ng-clipboard={{form.inbound_email}}> <i class="fa fa-clipboard"></i> </a> </div> <button ng-click="$event.stopPropagation(); $ctrl.openEmbedModal(form)" class="btn btn-default"> <i class="fa fa-code"></i> {{::_('Embed')}}</button> </div> </div> </li> </ul> <button class="btn create-btn" ng-show=$ctrl.canCreate() ng-click=$ctrl.create() disable-offline> <i class=bi-plus-lg></i> {{::_('Create new form')}} </button> </div> <div class=edit-form ng-if=$ctrl.editingForm> <request-form-editor form=$ctrl.editingForm on-cancel=$ctrl.edit() on-save=edit()></request-form-editor> </div> <div class=fill-form ng-if=$ctrl.fillForm> <request-form form=$ctrl.fillForm show-cancel=true on-cancel=$ctrl.edit() on-submitted=$ctrl.afterSubmit(request)></request-form> </div> `);
  $templateCache.put("/static/app/apps/project/cards/ng-components/templates/cards.html", ` <div class=board-notice ng-if="!$ctrl.isConnected() && !$ctrl.isConnectionManagerDisabled && !!$ctrl.options.filter"> <i class="fa fa-warning"></i> {{::_('Filters are only available while online. The current view is displayed without filtering enabled')}} </div> <div class="board-notice mod-with-close-btn" ng-show="$ctrl.screenizeConstraint && !$ctrl.screensizeConstraintNoticeClosed"> <i class="fa fa-warning"></i> {{::_('You cannot display swimlanes on a small screen')}} <button type=button class=board-notice-close-btn ng-click="$ctrl.screensizeConstraintNoticeClosed = true"> <i class="fa fa-times"></i> </button> </div> <cards-app board=$ctrl.context.board store=$ctrl.context.cardStore filter=$ctrl.options.filter matching-card-ids=$ctrl.context.matchingCardIds mode=$ctrl.mode group-by=$ctrl.groupBy options=$ctrl.options on-change=$ctrl.updateContext($changes)></cards-app> `);
  $templateCache.put("/static/app/apps/cards/common/ui/group-header/ng-components/templates/header.html", `<button class="btn btn-icon clickable group-collapsed" ng-click="$ctrl.collapsed = !$ctrl.collapsed" ng-hide=$ctrl.hideCollapseBtn> <i ng-class="{'bi-dash-square-dotted': !$ctrl.collapsed, 'bi-plus-square-dotted': $ctrl.collapsed}"></i> </button> <button class="btn btn-icon clickable js-group-action-menu group-settings ms-2" type=button ng-click="$ctrl.openGroupActionsMenu(null, $event)" ng-if=$ctrl.canOpenSettings> <i class=bi-three-dots-vertical></i> </button> <h2 class=group-title ng-class="{'editable': $ctrl.canEditTitle, 'clickable': $ctrl.group.onTitleClick}" ng-attr-title={{$ctrl.title}} ng-hide=$ctrl.titleEditorOptions.enabled ng-click="$ctrl.group.onTitleClick && $ctrl.onTitleClick()"> <div> <img ng-src={{::$ctrl.group.avatar}} ng-if=::!!$ctrl.group.avatar class="avatar me-1"> <strong ng-click="$ctrl.canEditTitle && $ctrl.startEditTitle()"> <i class=me-1 ng-class=$ctrl.icon|iconClass ng-show=!!$ctrl.icon></i> {{$ctrl.title}} </strong> <sup ng-if="::(!!$ctrl.group && !$ctrl.group.is_dynamic)" ng-show=$ctrl.$cardGroupSubscriptionStore.isSubscribed($ctrl.group) uib-tooltip="{{::_('You are subscribed to this group')}}"><i class="fa fa-bell"></i></sup> </div> </h2> <div class="group-title text-composer input-text" ng-if=$ctrl.canEditTitle ng-show=$ctrl.titleEditorOptions.enabled text-composer=$ctrl.titleEditorOptions is-focused=$ctrl.titleEditorOptions.enabled init-value=$ctrl.group.title></div> <i class="bi-question-circle ms-2" uib-tooltip-html=$ctrl.desc tooltip-popup-delay=0 ng-show=!!$ctrl.desc></i> <button class="btn cards-counter ms-2" ng-class="{'clickable': !!$ctrl.onCounterToggled}" ng-click="$ctrl.onCounterToggled && $ctrl.onCounterToggled()"> <span class=cards-app-group-cards-counter uib-tooltip={{$ctrl.cardCounterTooltip}} ng-class="{'warning': $ctrl.cardCounterLimitReached, 'editable': !!$ctrl.onCounterToggled}"> <i class=bi-exclamation-triangle-fill></i> <span>{{$ctrl.cardCounterLabel}}</span> </span> </button> <button class="btn btn-icon group-date ms-2" ng-class="{'clickable': $ctrl.canOpenSettings}" type=button ng-if="!!($ctrl.group.start_date || $ctrl.group.end_date)" uib-tooltip="{{ ($ctrl.group.start_date ? $ctrl.formatDate($ctrl.group.start_date) : '?') + ' - ' +
    ($ctrl.group.end_date ? $ctrl.formatDate($ctrl.group.end_date) : '?') }}" ng-click="$ctrl.canOpenSettings && $ctrl.openGroupActionsMenu('calendar', $event)"><i class=bi-calendar></i> </button> <button class="btn btn-icon clickable group-order ms-2" ng-class="{'js-group-action-menu': !$ctrl.canOpenSettings}" type=button uib-tooltip="{{::_('Sort by')}}" ng-click="!$ctrl.sortByDisabled && $ctrl.openGroupActionsMenu('sort by', $event)" ng-if=!!$ctrl.sortBy> <i class=bi-sort-down></i> </button> `);
  $templateCache.put("/static/app/apps/cards/common/ui/ng-components/templates/card-creator.html", "<strong class=card-creator-alert ng-if=$ctrl.filtered> <i class=bi-exclamation-triangle-fill></i> {{::_('Your new card might not match the current active filter. It might be directly hidden after creation.')}} </strong> <div class=text-composer text-composer=$ctrl.creatorOptions custom-template=/static/app/apps/cards/common/ui/ng-components/templates/text-composer-tpl.html is-focused=$ctrl.creatorOptions.enabled></div> <button type=button class=card-creator-btn ng-show=$ctrl.creatorOptions.enabled ng-mousedown=$ctrl.handleLinkCreateClick() hide-offline> {{::_('...or create a card link')}} </button> ");
  $templateCache.put("/static/app/apps/cards/common/ui/ng-components/templates/text-composer-tpl.html", `<form> <textarea class=form-control ng-attr-placeholder="{{ options.placeholder }}"></textarea> <div class=text-composer-actions> <button class="btn btn-success js-submit" type=submit> {{::_('Add')}} <i class=right ng-class=options.saveBtnIcon|iconClass ng-if=options.saveBtnIcon></i> </button> <button class="btn btn-icon js-close" type=button><i class="fa fa-times"></i></button> </div> </form> `);
  $templateCache.put("/static/app/apps/cards/common/ui/ng-components/templates/add-group.html", `<button class=btn type=button ng-hide=$ctrl.creatorOptions.enabled ng-class="{'btn-icon': !!$ctrl.groupsCount && !$ctrl.showLabel}" ng-click="$ctrl.creatorOptions.enabled = true"> <i class=bi-plus-lg></i> <span ng-show="!$ctrl.groupsCount || !!$ctrl.showLabel">{{_('Add new {groupType}', {groupType: $ctrl.groupBy.getLabel()})}}</span> </button> <div class=group-creator-container ng-show=$ctrl.creatorOptions.enabled> <div class="text-composer input-text" text-composer=$ctrl.creatorOptions is-focused=$ctrl.creatorOptions.enabled init-value="$ctrl.capitalize($ctrl.groupBy.getLabel()) + ' ' + ($ctrl.groupsCount + 1)"></div> <p ng-bind-html="::(!$ctrl.closeEditorOnEnter ? _trust('<span>Enter</span> to add cards, <span>Tab</span> to continue adding groups') : _trust('<span>Tab</span> to continue adding groups'))"></p> </div> `);
  $templateCache.put("/static/app/apps/cards/common/ui/ng-components/templates/cardlist.css.html", "cardlist-header.{{ wrappercls }} { background-color: {{ color }}; border-color: {{ darken(color, 10) }}; color: {{ textColor }}; } cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer.input-text input { background: {{ color }}; } cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon { color: {{ textColor }}; } cardlist-header.{{ wrappercls }} .cardlist-title { color: {{ textColor }}; } cardlist-header.{{ wrappercls }} .cardlist-title.is-editable > div > span:hover { background: {{ darken(color, 10) }}; } cardlist-header.{{ wrappercls }} .cardlist-header-desc, cardlist-header.{{ wrappercls }} .cardlist-header-icon { color: {{ darken(color, 30) }}; } /********************************************************** * KANBAN COLUMN */ kanban-column.{{ wrappercls }} .cardlist-viewport, kanban-column.{{ wrappercls }} .cardlist-card-creator-opener { background-color: {{ color }}; border-color: {{ darken(color, 10) }}; color: {{ textColor }}; } kanban-column.{{ wrappercls }} .cardlist-viewport::-webkit-scrollbar-thumb:horizontal, kanban-column.{{ wrappercls }} .cardlist-viewport::-webkit-scrollbar-thumb:vertical { background: {{ mostReadable(color, [darken(color, 25), lighten(color, 25)]) }}; } kanban-column.{{ wrappercls }} .cardlist-cards .ui-sortable-placeholder { background-color: {{ darken(color, 15) }}; } kanban-column.{{ wrappercls }} .cardlist-loading-indicator { background-color: {{ color }}; border-color: {{ darken(color, 10) }}; color: {{ darken(color, 25) }}; } kanban-column.{{ wrappercls }} .cardlist-loading-indicator:last-child { border-color: {{ darken(color, 10) }}; } kanban-column.{{ wrappercls }} .cardlist-card-creator-opener button { color: {{ textColor }}; } kanban-column.{{ wrappercls }} cardlist-card-creator { border-color: {{ darken(color, 10) }}; background: {{color}}; } kanban-column.{{ wrappercls }} cardlist-card-creator .cardlist-create-link { color: {{ textColor }}; background: {{ color }}; } /********************************************************** * TIMELINE SIDEBAR HEADER * First cancel default custom color */ board-checklist cardlist-header.{{ wrappercls }}, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} { background-color: transparent; border-color: #cfcfcf; color: #555; } board-checklist cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer.input-text input, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer.input-text input { background: #f7f7f7; } board-checklist cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon { color: #555; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon:hover, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .btn.drop-enabled, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .btn:hover { color: #333; background: #e2e2e2; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .btn:hover { color: #333; } board-checklist cardlist-header.{{ wrappercls }} .cardlist-title, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-title { color: #000; } board-checklist cardlist-header.{{ wrappercls }} .cardlist-title > div > span, .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-title > div > span { color: {{ textColor }}; } board-checklist cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon:hover, board-checklist cardlist-header.{{ wrappercls }} .cardlist-header-container .btn.drop-enabled, board-checklist cardlist-header.{{ wrappercls }} .cardlist-header-container .btn:hover { background-color: transparent; } board-checklist cardlist-header.{{ wrappercls }} .cardlist-header-container .btn:hover { color: #333; } cardlist-header.{{ wrappercls }} .cardlist-title > div > span { background: {{ color }}; } cardlist-header.{{ wrappercls }} .cardlist-title.is-editable > div > span:hover { background: {{ darken(color, 10) }}; } /********************************************************** * CARDS VIEW TIMELINE SIDEBAR HEADER * First cancel default custom color */ .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} { background-color: transparent; border-color: #cfcfcf; color: #555; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer.input-text input { background: #f7f7f7; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon { color: #555; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .text-composer .btn.btn-icon:hover { background-color: #e2e2e2; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .btn:hover { color: #333; background: #e2e2e2; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-header-container .btn.drop-enabled { background: #e2e2e2; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-title { color: #000; } .cards-app-timeline-sidebar-group-header cardlist-header.{{ wrappercls }} .cardlist-title > div > span { color: {{ textColor }}; } cardlist-header.{{ wrappercls }} .cardlist-title > div > span { background: {{ color }}; } cardlist-header.{{ wrappercls }} .cardlist-title.is-editable > div > span:hover { background: {{ darken(color, 10) }}; } ");
  $templateCache.put("/static/app/apps/cards/common/ui/nav/ng-components/templates/filter-btn.html", `<button class="btn btn-topbar cards-app-filter-btn" ng-class="{'active': !!$ctrl.filter}" ng-disabled=$ctrl.readonly ng-if=!$ctrl.useInput> <i class=bi-filter></i> {{$ctrl.label ? _('Filtered by {filter}', {filter: $ctrl.label}) : _p('filter-by-btn', 'Filter')}} <span class=bi-caret-down-fill ng-hide=$ctrl.readonly></span> </button> <filter-editor-input ng-if=$ctrl.useInput ng-model=$ctrl.filter filter-scopes=$ctrl.filterScopes on-change=$ctrl.notifyChange($value) placeholder="{{::_('Filter')}}"></filter-editor-input> `);
  $templateCache.put("/static/app/apps/cards/common/ui/nav/ng-components/templates/group-by-editor.html", `<div> <label><i ng-class="$ctrl.groupableTwice ? 'bi-distribute-horizontal' : 'bi-distribute-vertical'"></i> {{$ctrl.groupableTwice ? _("Group cards into columns") : _("Group cards together")}}</label> <span>{{::_("Your cards will be grouped together based on the context or field you select")}}</span> <pretty-select ng-model=$ctrl.firstGroupBy menu-builder=$ctrl.columnMenuBuilder drop-config=$ctrl.dropConfig label-formatter=$ctrl.menuLabelFormatter is-required=true on-change="$ctrl.notifyChange(0, $value)" on-drop-closed=$ctrl.onDropClosed({$afterSet})></pretty-select> </div> <div ng-class="{'disabled': !$ctrl.firstGroupBy}" ng-if=$ctrl.groupableTwice> <label><i class=bi-distribute-vertical></i> {{::_("Group cards into rows")}}</label> <span>{{::_("Gives you the possibility to create a matrix representation with columns and rows")}}</span> <pretty-select ng-model=$ctrl.secondGroupBy menu-builder=$ctrl.laneMenuBuilder drop-config=$ctrl.dropConfig label-formatter=$ctrl.menuLabelFormatter is-required=true on-change="$ctrl.notifyChange(1, $value)" on-drop-closed=$ctrl.onDropClosed({$afterSet}) disabled=!$ctrl.firstGroupBy></pretty-select> </div> `);
  $templateCache.put("/static/app/apps/cards/common/ui/nav/ng-components/templates/options-btn.html", `<button class="btn btn-topbar" drop-menu=$ctrl.modeOptionsMenu drop-config="{classes: 'cards-app-mode-option-menu drop-theme-menu drop-theme-arrow'}" ng-if=$ctrl.modeOptionsMenu uib-tooltip="{{_('{mode} options', {mode: $ctrl.title})}}" tooltip-placement=bottom> <i class=bi-eye-fill></i> {{::_('Appearance')}} <span class=bi-caret-down-fill></span> </button> `);
  $templateCache.put("/static/app/apps/cards/calendar/ng-components/templates/calendar.html", `<div class="cards-app-calendar-sidebar hidden-xs" ng-class="{'collapsed': $ctrl.unscheduledCollapsed}" ng-if="!$ctrl.showEmptyNotice || ($ctrl.activeDateAttribute.size > 0)"> <div class=unscheduled-cards ng-click="$ctrl.unscheduledCollapsed ? $ctrl.onUnscheduledHeaderClick($event): null"> <div class=unscheduled-cards-header ng-click=$ctrl.onUnscheduledHeaderClick($event)> <i class=fa ng-class="{
        'bi-caret-left-square': !$ctrl.unscheduledCollapsed,
        'bi-caret-down-square': $ctrl.unscheduledCollapsed
      }"></i> <span>{{::_('Unscheduled cards')}}</span> </div> <ul class="viewport list-unstyled"> <li ng-repeat="u in $ctrl.unscheduled track by u.event.id"> <div class=noactions card-tile=u.card show-parents="($ctrl.options || {}).include_descendants" show-archived="($ctrl.options || {}).include_archived" show-ref=::!$ctrl.project.is_portfolio strike-title-when-done="($ctrl.options || {}).strikeDoneCards" disable-children-toggle=::$ctrl.project.is_portfolio show-board-pattern=::!$ctrl.project.is_portfolio show-board-btn-label=::!$ctrl.project.is_portfolio selector=$ctrl.selector ng-attr-data-event="{{ u.event|json }}"></div> </li> </ul> </div> </div> <div class=cards-app-calendar-container ng-if="!$ctrl.showEmptyNotice || !$ctrl.board || $ctrl.activeDateAttribute.size > 0"> <full-calendar cards=$ctrl.cards groups=$ctrl.groups card-active-date-attributes-names="$ctrl.board ? $ctrl.activeDateAttributeNames : null" strike-done-cards="($ctrl.options || {}).strikeDoneCards" week-numbers="($ctrl.options || {}).weekNumbers" cards-editable=$ctrl.cardsEditable groups-editable=$ctrl.groupsEditable droppable=true selectable-dates=$ctrl.canCreateCard on-change="$ctrl.onCalendarChange(startDate, endDate, event)" on-event-source-update="$ctrl.onEventSourceUpdate(scheduled, unscheduled)" on-select=$ctrl.onEventSelect(event) on-date-selected="$ctrl.onDateSelected(start, stop, event)"></full-calendar> </div> <div class=cards-app-empty-notice ng-if="$ctrl.showEmptyNotice && $ctrl.activeDateAttribute.size === 0"> <i class="fa fa-clock-o"></i> <p>{{::_("Calendar lets you organize your cards through time and keep track of your planning easily.")}}</p> <p ng-show=!!$ctrl.project>{{::_("But first, you need to add a date field in your cards.")}}</p> <p ng-show=!$ctrl.project>{{::_("There isn't any date field in your cards")}}</p> </div> `);
  $templateCache.put("/static/app/apps/cards/table/ng-components/templates/card-creator.html", `<div class="cards-app-table-cell ref"> <button class="btn btn-icon" type=button ng-show=$ctrl.creatorOptions.enabled uib-tooltip="{{::_('Add link')}}" ng-mousedown=$ctrl.handleLinkCreateClick() hide-offline> <i class="fa fa-chain"></i> </button> </div> <div class="cards-app-table-cell stretched"> <span class=card-creator-alert ng-if=$ctrl.filtered> <i class=bi-exclamation-triangle-fill></i> {{::_('Your new card might not match the current active filter. It might be directly hidden after creation.')}} </span> <div class=text-composer text-composer=$ctrl.creatorOptions is-focused=$ctrl.creatorOptions.enabled></div> </div> `);
  $templateCache.put("/static/app/apps/cards/table/ng-components/templates/table-column-header.html", `<span class=cards-app-column-title ng-dblclick=$ctrl.startRename() ng-hide=$ctrl.renaming> <span>{{$ctrl.attrs.label}}</span> <sup ng-hide=$ctrl.renaming ng-if="$ctrl.attrs && $ctrl.attrs.length > 1" uib-tooltip="{{_('This column gathers fields from {nb} different sources', {nb: $ctrl.attrs.length})}}"> <i class=bi-intersect></i> </sup> </span> <form ng-submit=$ctrl.rename() ng-show=$ctrl.renaming> <input type=text ng-model=$ctrl.title ng-blur=$ctrl.rename() auto-focus select-on-focus> </form> <a href drop-menu=$ctrl.headerSettingsMenu ng-hide="$ctrl.renaming || !$ctrl.headerSettingsMenu"> <i class=bi-three-dots-vertical></i> </a> `);
  $templateCache.put("/static/app/apps/cards/table/ng-components/templates/table.html", `<div class=cards-app-table-inner> <div class=cards-app-table-header> <div class=cards-app-table-header-left> <div class="cards-app-table-cell ref"> <span>#</span> </div> <div class="cards-app-table-cell title" ng-style="{'width': $ctrl.getColumWidth('__title__')}"> <span>{{::_('Title')}}</span> <button class="btn btn-resize-column" ng-mousedown="$ctrl.startResizingColumn($event, 0)"></button> </div> </div> <div class="cards-app-table-header-right js-table-cols-sortable" ui-sortable=$ctrl.columnSortableOptions ng-model=$ctrl.visibleAttributes> <div class=cards-app-table-cell ng-repeat="namedAttrGroup in $ctrl.visibleAttributes track by namedAttrGroup.name" ng-style="{'width': $ctrl.getColumWidth(namedAttrGroup.name)}"> <cards-app-table-column-header attrs=namedAttrGroup board=$ctrl.board sort-by=$ctrl.sortBy on-sort-change="$ctrl.setSortBy(namedAttrGroup.name.toLowerCase(), $reverse)" on-toggle-visibility=$ctrl.toggleAttrVisibility(namedAttrGroup.name)> </cards-app-table-column-header> <button class="btn btn-resize-column" ng-mousedown="$ctrl.startResizingColumn($event, $index+1)"></button> </div> </div> <div class="cards-app-table-cell cards-app-table-add-column" ng-hide=!$ctrl.addColumnMenu drop-menu=$ctrl.addColumnMenu drop-config=$ctrl.addColumnDropConfig drop-watchers=$ctrl.addColumnDropWatchers><i class=bi-plus-lg></i></div> </div> <sortable-groups-container class=cards-app-table-body ng-style="{'width': $ctrl.getTableWidth() + 'px'}" groups=$ctrl.groups project=$ctrl.project options=$ctrl.sortableTableGroupsOptions> <cards-app-table-group ng-if=$ctrl.ungroupedCardsVisible ng-show=!$ctrl.isFilteredOnFirstGroupBy custom-title={{$ctrl.ungroupedLabel}} store=$ctrl.ungroupedCardsStore board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices visible-attributes=$ctrl.visibleAttributes hide-header=$ctrl.groupBy[0].isNothing() selector=$ctrl.selector selector-page="{ungrouped: true}" on-change="$ctrl.onChange({$changes: $changes})" open-creator-on-init="!$ctrl.groups.length && !$ctrl.project.status" show-ungrouped-tooltip=true ng-class="{'ungrouped': $ctrl.groupBy[0].isNothing()}"></cards-app-table-group> <div class=ui-sortable-groups-items-container> <cards-app-table-group ng-repeat="group in $ctrl.groups track by group.id" class=ui-sortable-groups-item ng-class="{'is-archived': group.is_archived}" group=group store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices visible-attributes=$ctrl.visibleAttributes selector=$ctrl.selector selector-page="{group: group}" on-change="$ctrl.onChange({$changes: $changes})"></cards-app-table-group> </div> <add-card-group class=cards-app-add-group ng-if=$ctrl.canAddGroup ng-hide=$ctrl.isFilteredOnFirstGroupBy group-by=$ctrl.groupBy[0] board=$ctrl.board close-editor-on-enter=true open-editor-hotkey=$ctrl.addGroupHotkey enable-open-editor-hotkey=true></add-card-group> </sortable-groups-container> </div> `);
  $templateCache.put("/static/app/apps/cards/table/ng-components/templates/table-group-color.css.html", "cards-app-table-group.ui-sortable-helper.{{ wrappercls }}, cards-app-table.boxed-groups cards-app-table-group.{{ wrappercls }} { background-color: {{ color }}; border-color: {{ darken(color, 10) }}; color: {{ textColor }}; } cards-app-table-group.{{ wrappercls }} .header { border-bottom-color: {{ darken(color, 10) }}; } cards-app-table-group.{{ wrappercls }} .header .cards-app-table-cell { border-right-color: {{ darken(color, 10) }}; } cards-app-table-group.{{ wrappercls }} .header .cards-app-table-cell:not(.cards-app-table-cell-header) { color: {{ darken(color, 30) }}; } cards-app-table-group.{{ wrappercls }} .footer { border-bottom-color: {{ darken(color, 10) }}; } cards-app-table-group.{{ wrappercls }} cards-app-group-header .group-title strong { color: {{ textColor }}; } cards-app-table-group.{{ wrappercls }} cards-app-group-header .group-title.editable strong:hover { background-color: {{ getReadableTransparentColor(color, 0.10) }}; } cards-app-table-group.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable, cards-app-table-group.{{ wrappercls }} cards-app-group-header > i.bi-question-circle, cards-app-table-group.{{ wrappercls }} cards-app-group-header .group-title sup, cards-app-table-group.{{ wrappercls }} cards-app-group-header .group-title > div > i { color: {{ getReadableTransparentColor(color, 0.65) }}; } cards-app-table-group.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable:hover, cards-app-table-group.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable:focus { color: {{ textColor }}; } ");
  $templateCache.put("/static/app/apps/cards/table/ng-components/templates/table-group.html", `<sortable-cards-container cards=$ctrl.cards on-drop=$ctrl.handleCardDropped($onDropParams) before-drop=$ctrl.beforeCardDropped($onDropParams) after-drop=$ctrl.afterCardDropped($onDropParams) groups="$ctrl.group || null" board=$ctrl.board sort-by=$ctrl.sortBy editable="$ctrl.canSortCards && !$ctrl.isScreensizeXS()" options=$ctrl.sortableOptions collapsed=!$ctrl.expandedOnce is-filtered=$ctrl.filtered is-card-filtered=$ctrl.isCardFiltered($card)> <div class="cards-app-table-row header" ng-hide=$ctrl.hideHeader ng-class="{'is-archived': $ctrl.group.is_archived}"> <div class="cards-app-table-cell cards-app-table-cell-header"> <cards-app-group-header group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options sort-by=$ctrl.sortBy sort-choices=$ctrl.sortChoices can-free-sort=$ctrl.canFreeSort total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix menu-custom-drop-config=$ctrl.menuCustomDropConfig editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) show-ungrouped-tooltip=$ctrl.showUngroupedTooltip show-icon=true show-desc=true on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> </div> <div class=cards-app-table-cell ng-repeat="namedAttrGroup in $ctrl.visibleAttributes"> <span ng-if=$ctrl.hasAggregation(namedAttrGroup)>{{_('Sum: {value}', {value: $ctrl.getAggregatedValue(namedAttrGroup)})}}</span> </div> </div> <div class="body ui-sortable-cards-items-container" ng-if=!$ctrl.expandedOnce></div> <div class="body ui-sortable-cards-items-container" ng-if=::$ctrl.expandedOnce> <cards-app-table-row ng-repeat="card in $ctrl.cards track by card.id" class=ui-sortable-cards-item ng-show=$ctrl.isCardFiltered(card) card=card visible-attributes=$ctrl.visibleAttributes column-widths="($ctrl.options || {}).column_widths" show-archived="($ctrl.options || {}).include_archived" strike-title-when-done="($ctrl.options || {}).strikeDoneCards" selector=$ctrl.selector></cards-app-table-row> </div> <div class=footer ng-if=$ctrl.canCreateCard ng-hide=$ctrl.isCreatingCard ng-class="{'minimized': !$ctrl.hideHeader && !$ctrl.isCreatingCard}" ng-click=$ctrl.openCreator()> <div class="cards-app-table-cell ref"><i class=bi-plus-lg></i></div> <div class="cards-app-table-cell stretched"> {{::_('Add card')}}</div> </div> </sortable-cards-container> `);
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/kanban-group-color.css.html", " cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header, cards-app-swimlanes-lane-header.{{ wrappercls }}, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header { background-color: {{ color }}; border-color: {{ darken(color, 10) }}; color: {{ textColor }}; } cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .group-title strong, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .group-title strong, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .group-title strong { color: {{ textColor }}; } cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .group-title.editable strong:hover, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .group-title.editable strong:hover, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .group-title.editable strong:hover { background-color: {{ getReadableTransparentColor(color, 0.10) }}; } cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable, cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header > i.bi-question-circle, cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .group-title sup, cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .group-title > div > i, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header > i.bi-question-circle, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .group-title sup, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .group-title > div > i, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .btn.btn-icon.clickable, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header > i.bi-question-circle, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .group-title sup, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .group-title > div > i { color: {{ getReadableTransparentColor(color, 0.65) }}; } cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable:hover, cards-app-swimlanes-column-header.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable:focus, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable:hover, cards-app-swimlanes-lane-header.{{ wrappercls }} cards-app-group-header .btn.btn-icon.clickable:focus, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .btn.btn-icon.clickable:hover, cards-app-kanban-column.{{ wrappercls }}:not(.is-collapsed) cards-app-group-header .btn.btn-icon.clickable:focus { color: {{ textColor }}; } cards-app-kanban-column.{{ wrappercls }} cards-app-group-progress, cards-app-kanban-column.{{ wrappercls }} cards-app-group-misc, cards-app-kanban-column.{{ wrappercls }} cards-app-group-progress, cards-app-kanban-column.{{ wrappercls }} cards-app-group-misc { color: {{ realshade(setAlpha(color, 0.2), 70) }}; } cards-app-swimlanes-cardlist.{{ wrappercls }}, cards-app-swimlanes-column-sub-header.{{ wrappercls }}, cards-app-kanban-column.{{ wrappercls }} sortable-cards-container > div { background-color: {{ setAlpha(color, 0.2) }}; } cards-app-swimlanes-cardlist.{{ wrappercls }} sortable-cards-container .ui-sortable-cards.ui-sortable-current-container, cards-app-kanban-column.{{ wrappercls }} sortable-cards-container > div.ui-sortable-current-container { background-color: {{ setAlpha(color, 0.3) }}; } cards-app-swimlanes-cardlist.{{ wrappercls }}.is-column-collapsed sortable-cards-container, cards-app-swimlanes-cardlist.{{ wrappercls }}.is-lane-collapsed sortable-cards-container { background-image: linear-gradient(45deg, {{ tint(setAlpha(color, 0.2), 5, 2) }} 25%, transparent 25%, transparent 50%, {{ tint(setAlpha(color, 0.2), 5, 2) }} 50%, {{ tint(setAlpha(color, 0.2), 5, 2) }} 75%, transparent 75%, transparent); } cards-app-swimlanes-cardlist.{{ wrappercls }}.is-column-collapsed sortable-cards-container:hover, cards-app-swimlanes-cardlist.{{ wrappercls }}.is-lane-collapsed sortable-cards-container:hover { background-image: linear-gradient(45deg, {{ realshade(tint(setAlpha(color, 0.2), 5, 2), 2) }} 25%, transparent 25%, transparent 50%, {{ realshade(tint(setAlpha(color, 0.2), 5, 2), 2) }} 50%, {{ realshade(tint(setAlpha(color, 0.2), 5, 2), 2) }} 75%, transparent 75%, transparent); } cards-app-swimlanes-cardlist.{{ wrappercls }} .footer > .btn:hover, cards-app-kanban-column.{{ wrappercls }} .footer > .btn:hover { background-color: {{ tint(setAlpha(color, 0.2), 5, 2) }}; } cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header { color: {{ realshade(setAlpha(color, 0.20), 70) }}; } cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .group-title strong { color: {{ realshade(setAlpha(color, 0.20), 70) }}; } cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .group-title.editable strong:hover { background-color: {{ getReadableTransparentColor(setAlpha(color, 0.20), 0.10) }}; } cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .btn.btn-icon.clickable, cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header > i.bi-question-circle, cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .group-title sup, cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .group-title > div > i { color: {{ realshade(setAlpha(color, 0.20), 50) }}; } cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .btn.btn-icon.clickable:hover, cards-app-kanban-column.{{ wrappercls }}.is-collapsed cards-app-group-header .btn.btn-icon.clickable:focus { color: {{ realshade(setAlpha(color, 0.20), 70) }}; } ");
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/swimlanes-cardlist.html", `<sortable-cards-container cards=$ctrl.displayedCards on-drop=$ctrl.handleCardDropped($onDropParams) before-drop=$ctrl.beforeCardDropped($onDropParams) after-drop=$ctrl.afterCardDropped($onDropParams) groups=$ctrl.groups board=$ctrl.board sort-by=$ctrl.sortBy editable=$ctrl.canSortCards options=$ctrl.sortableOptions collapsed=!$ctrl.expandedOnce is-filtered=$ctrl.filtered is-card-filtered=$ctrl.isCardFiltered($card)> <div class="body ui-sortable-cards-items-container" ng-if=!$ctrl.expandedOnce></div> <div class="body ui-sortable-cards-items-container" ng-if=::$ctrl.expandedOnce> <div ng-repeat="card in $ctrl.displayedCards track by card.id" ng-show=$ctrl.isCardFiltered(card) card-tile=card show-project=$ctrl.showProjectOnCards show-archived="($ctrl.options || {}).include_archived" show-parents="($ctrl.options || {}).include_descendants" show-children-attributes="($ctrl.options || {}).children_visible_attributes" show-attributes=$ctrl.visibleAttrNames show-ref=::!$ctrl.project.is_portfolio strike-title-when-done="($ctrl.options || {}).strikeDoneCards" disable-children-toggle=::$ctrl.project.is_portfolio show-board-pattern=::!$ctrl.project.is_portfolio show-board-btn-label=::!$ctrl.project.is_portfolio filter-active-board-group-by=::(true)></div> </div> <div class=footer ng-if=$ctrl.canCreateCard ng-hide=$ctrl.isCreatingCard> <button type=button class=btn ng-click=$ctrl.openCreator()> <i class=bi-plus-lg></i> <span ng-show=!$ctrl.displayedCards.length>{{::_('Add card')}}</span> </button> </div> </sortable-cards-container> `);
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/swimlanes-lane-header.html", `<cards-app-group-header ng-class="{'flow-indicator':  $ctrl.group && $ctrl.group.show_flow_indicator}" group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix menu-custom-drop-config=$ctrl.menuCustomDropConfig show-ungrouped-tooltip=$ctrl.showUngroupedTooltip editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> `);
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/kanban-column.html", `<sortable-cards-container cards=$ctrl.cards on-drop=$ctrl.handleCardDropped($onDropParams) before-drop=$ctrl.beforeCardDropped($onDropParams) after-drop=$ctrl.afterCardDropped($onDropParams) groups="$ctrl.group || null" board=$ctrl.board sort-by=$ctrl.sortBy editable=$ctrl.canSortCards options=$ctrl.sortableOptions collapsed=!$ctrl.expandedOnce is-filtered=$ctrl.filtered is-card-filtered=$ctrl.isCardFiltered($card)> <div class=header ng-class="{'flow-indicator':  $ctrl.group && $ctrl.group.show_flow_indicator}"> <cards-app-group-header group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options sort-by=$ctrl.sortBy sort-choices=$ctrl.sortChoices can-free-sort=$ctrl.canFreeSort total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) on-counter-toggled=$ctrl.toggleStats() hide-collapse-btn=$ctrl.groupBy[0].isNothing() show-ungrouped-tooltip=$ctrl.showUngroupedTooltip on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> </div> <div class=sub-header> <div class=inner> <cards-app-group-progress cards=$ctrl.matchingCards ng-if=$ctrl.showProgress></cards-app-group-progress> <cards-app-group-stats cards=$ctrl.matchingCards project=$ctrl.project ng-if=$ctrl.showStats></cards-app-group-stats> <cards-app-group-misc group=$ctrl.group ng-if=$ctrl.showMisc></cards-app-group-misc> </div> </div> <div class="body ui-sortable-cards-items-container" ng-if=!$ctrl.expandedOnce></div> <div class="body ui-sortable-cards-items-container" ng-if=::$ctrl.expandedOnce> <div ng-repeat="card in $ctrl.cards track by card.id" ng-show=$ctrl.isCardFiltered(card) card-tile=card show-project=$ctrl.showProjectOnCards show-archived="($ctrl.options || {}).include_archived" show-parents="($ctrl.options || {}).include_descendants" show-children-attributes="($ctrl.options || {}).children_visible_attributes" show-attributes=$ctrl.visibleAttrNames show-ref=::!$ctrl.project.is_portfolio strike-title-when-done="($ctrl.options || {}).strikeDoneCards" disable-children-toggle=::$ctrl.project.is_portfolio show-board-pattern=::!$ctrl.project.is_portfolio show-board-btn-label=::!$ctrl.project.is_portfolio selector=$ctrl.selector filter-active-board-group-by=::(true)></div> </div> <div class=footer ng-if=$ctrl.canCreateCard ng-hide=$ctrl.isCreatingCard> <button type=button class="btn add-card" ng-click=$ctrl.openCreator()> <i class=bi-plus-lg></i> <span ng-show=!$ctrl.cards.length>{{::_('Add card')}}</span> </button> </div> </sortable-cards-container> `);
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/swimlanes-column-header.html", `<cards-app-group-header ng-class="{'flow-indicator':  $ctrl.group && $ctrl.group.show_flow_indicator}" group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options sort-by=$ctrl.sortBy sort-choices=$ctrl.sortChoices can-free-sort=$ctrl.canFreeSort total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix hide-collapse-btn=$ctrl.groupBy[0].isNothing() show-ungrouped-tooltip=$ctrl.showUngroupedTooltip editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) on-counter-toggled=$ctrl.toggleStats() on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> `);
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/kanban-simple.html", `<sortable-groups-container groups=$ctrl.groups project=$ctrl.project options=$ctrl.sortableOptions> <cards-app-kanban-column ng-if=$ctrl.ungroupedCardsVisible ng-show=!$ctrl.isFilteredOnFirstGroupBy class=mod-ungrouped ng-class="{'is-archived': false, 'is-stretchable': false }" custom-title={{$ctrl.ungroupedLabel}} store=$ctrl.ungroupedCardsStore board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices visible-attr-names=$ctrl.visibleAttrNames selector=$ctrl.selector open-creator-on-init="!$ctrl.groups.length && !$ctrl.project.status" show-ungrouped-tooltip=true on-change="$ctrl.onChange({$changes: $changes})"></cards-app-kanban-column> <div class="kanban-sortable-columns ui-sortable-groups-items-container"> <cards-app-kanban-column ng-repeat="group in $ctrl.groups track by group.id" ng-show=$ctrl.matchGroup(group) ng-class="{'ui-sortable-groups-item': !group.is_archived,
        'is-archived': !!group.is_archived, 'is-stretchable': $ctrl.isColumnStretchable(group)}" group=group store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices visible-attr-names=$ctrl.visibleAttrNames selector=$ctrl.selector on-change="$ctrl.onChange({$changes: $changes})"></cards-app-kanban-column> </div> <add-card-group class=mod-column ng-if=$ctrl.canAddGroup ng-hide=$ctrl.isFilteredOnFirstGroupBy group-by=$ctrl.groupBy[0] board=$ctrl.board close-editor-on-enter="$ctrl.project && !$ctrl.project.is_template" open-editor-hotkey=$ctrl.addGroupHotkey enable-open-editor-hotkey=true on-group-added=$ctrl.scrollToRight($event) on-editor-opened=$ctrl.scrollToRight()></add-card-group> </sortable-groups-container> `);
  $templateCache.put("/static/app/apps/cards/kanban/ng-components/templates/kanban-swimlanes.html", ` <sortable-groups-container class=swimlanes-columns-headers groups=$ctrl.columnGroups project=$ctrl.project options=$ctrl.sortableColumnsOptions> <div class=swimlanes-columns-headers-first-cell></div> <div class="swimlanes-column-header mod-ungrouped" ng-if=$ctrl.isColumnVisible(0) ng-show=!$ctrl.isFilteredOnFirstGroupBy> <cards-app-swimlanes-column-header store=$ctrl.columnUngroupedStore custom-title={{$ctrl.columnUngroupedLabel}} board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices show-ungrouped-tooltip=true on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-column-header> </div> <div class="swimlanes-sortable-columns-headers ui-sortable-groups-items-container"> <div ng-repeat="columnGroup in $ctrl.columnGroups track by columnGroup.id" class=swimlanes-column-header ng-class="{
        'ui-sortable-groups-item': !columnGroup.is_archived,
        'is-stretchable': $ctrl.isColumnStretchable(columnGroup)
      }" ng-hide=!$ctrl.isColumnVisible($index+1)> <cards-app-swimlanes-column-header ng-class="{'is-archived': columnGroup.is_archived || false}" group=columnGroup store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-column-header> </div> </div> <add-card-group class=mod-column ng-if=$ctrl.canAddGroup($ctrl.groupBy[0]) ng-hide=$ctrl.isFilteredOnFirstGroupBy group-by=$ctrl.groupBy[0] board=$ctrl.board close-editor-on-enter=false enable-editor-auto-opening-on-init=true enable-open-editor-hotkey=false on-group-added=$ctrl.scrollToBottom($event) on-editor-opened=$ctrl.scrollToBottom()></add-card-group> </sortable-groups-container> <div class=swimlanes-columns-sub-headers> <div class=swimlanes-columns-headers-first-cell></div> <div ng-if=$ctrl.isColumnVisible(0) ng-show=!$ctrl.isFilteredOnFirstGroupBy> <cards-app-swimlanes-column-sub-header store=$ctrl.columnUngroupedStore custom-title={{$ctrl.columnUngroupedLabel}} board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-column-header> </div> <div ng-repeat="columnGroup in $ctrl.columnGroups track by columnGroup.id" ng-class="{'is-stretchable': $ctrl.isColumnStretchable(columnGroup) }" ng-hide=!$ctrl.isColumnVisible($index+1)> <cards-app-swimlanes-column-sub-header group=columnGroup store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-column-sub-header> </div> </div> <sortable-groups-container class=swimlanes-lanes groups=$ctrl.laneGroups project=$ctrl.project options=$ctrl.sortableLanesOptions> <div class="swimlanes-lane mod-ungrouped" ng-class="{'is-collapsed': ($ctrl.options || {})['lane_' + $ctrl.laneUngroupedLabel + '_collapsed'],
      'fixed-height': !!($ctrl.options || {}).swimlanes_fixed_height}" ng-if=$ctrl.isLaneVisible(0) ng-show=!$ctrl.isFilteredOnSecondGroupBy> <cards-app-swimlanes-lane-header store=$ctrl.laneUngroupedStore custom-title={{$ctrl.laneUngroupedLabel}} board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices show-ungrouped-tooltip=true on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-lane-header> <div class=swimlanes-cardlists> <cards-app-swimlanes-cardlist ng-if=$ctrl.isColumnVisible(0) ng-show=!$ctrl.isFilteredOnFirstGroupBy lane-store=$ctrl.laneUngroupedStore lane-title=$ctrl.laneUngroupedLabel column-store=$ctrl.columnUngroupedStore column-title=$ctrl.columnUngroupedLabel cards=$ctrl.cards[0][0] board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds visible-attr-names=$ctrl.visibleAttrNames on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-cardlist><cards-app-swimlanes-cardlist ng-repeat="columnGroup in $ctrl.columnGroups track by columnGroup.id" ng-class="{'is-stretchable': $ctrl.isColumnStretchable(columnGroup), 'is-archived': columnGroup.is_archived || false}" lane-store=$ctrl.laneUngroupedStore lane-title=$ctrl.laneUngroupedLabel column-group=columnGroup cards=$ctrl.cards[0][$index+1] board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds visible-attr-names=$ctrl.visibleAttrNames on-change="$ctrl.onChange({$changes: $changes})" ng-hide=!$ctrl.isColumnVisible($index+1)></cards-app-swimlanes-cardlist> </div> </div><div class="swimlanes-sortable-lanes ui-sortable-groups-items-container" ng-show="$ctrl.laneGroups && $ctrl.laneGroups.length"> <div ng-repeat="laneGroup in $ctrl.laneGroups track by laneGroup.id" class=swimlanes-lane ng-class="{
        'ui-sortable-groups-item': !laneGroup.is_archived,
        'is-collapsed': ($ctrl.options || {})['lane_' + laneGroup.title + '_collapsed'],
        'fixed-height': !!($ctrl.options || {}).swimlanes_fixed_height
      }" ng-hide=!$ctrl.isLaneVisible($index+1)> <cards-app-swimlanes-lane-header ng-class="{'is-archived': laneGroup.is_archived || false}" group=laneGroup store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-lane-header> <div class=swimlanes-cardlists> <cards-app-swimlanes-cardlist ng-if=$ctrl.isColumnVisible(0) ng-show=!$ctrl.isFilteredOnFirstGroupBy ng-class="{'is-archived': laneGroup.is_archived || false}" lane-group=laneGroup column-store=$ctrl.columnUngroupedStore column-title=$ctrl.columnUngroupedLabel cards=$ctrl.cards[$index+1][0] board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds visible-attr-names=$ctrl.visibleAttrNames on-change="$ctrl.onChange({$changes: $changes})"></cards-app-swimlanes-cardlist><cards-app-swimlanes-cardlist ng-repeat="columnGroup in $ctrl.columnGroups track by columnGroup.id" ng-class="{'is-stretchable': $ctrl.isColumnStretchable(columnGroup), 'is-archived': laneGroup.is_archived || columnGroup.is_archived || false}" lane-group=laneGroup column-group=columnGroup cards=$ctrl.cards[$parent.$index+1][$index+1] board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds visible-attr-names=$ctrl.visibleAttrNames on-change="$ctrl.onChange({$changes: $changes})" ng-hide=!$ctrl.isColumnVisible($index+1)></cards-app-swimlanes-cardlist> </div> </div> </div> <add-card-group class=mod-lane ng-if=$ctrl.canAddGroup($ctrl.groupBy[1]) ng-hide=$ctrl.isFilteredOnSecondGroupBy group-by=$ctrl.groupBy[1] board=$ctrl.board close-editor-on-enter=false enable-editor-auto-opening-on-init=false enable-open-editor-hotkey=false on-group-added=$ctrl.scrollToBottom($event) on-editor-opened=$ctrl.scrollToBottom()></add-card-group> </div> `);
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/sidebar-group.html", `<div class=header ng-hide=$ctrl.hideHeader> <cards-app-group-header group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options sort-by=$ctrl.sortBy sort-choices=$ctrl.sortChoices can-free-sort=$ctrl.canFreeSort total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) free-sort-disabled=true show-icon=true show-desc=true on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> </div> <div class="body ui-sortable-cards-items-container"> <div ng-repeat="card in $ctrl.cards track by card.id" class=mod-timeline ng-show=$ctrl.isCardFiltered(card) card-tile=card show-archived="($ctrl.options || {}).include_archived" show-parents="($ctrl.options || {}).include_descendants" show-ref=::!$ctrl.project.is_portfolio strike-title-when-done="($ctrl.options || {}).strikeDoneCards" disable-children-toggle=::$ctrl.project.is_portfolio show-board-pattern=::!$ctrl.project.is_portfolio show-board-btn-label=::!$ctrl.project.is_portfolio filter-active-board-group-by=::(true) template-type=timeline force-complete-children-list=true toggle-children-key=project-timeline-card on-toggle-children="$ctrl.onToggleChildren($card, $toggleState)" timeline-spec=$ctrl.timelineSpec></div> </div> <div class=footer ng-if=$ctrl.canCreateCard ng-hide=$ctrl.isCreatingCard> <button type=button class=btn ng-click=$ctrl.openCreator()> <i class=bi-plus-lg></i> <span>{{::_('Add card')}}</span> </button> </div> `);
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/timeline-group-color.css.html", "cards-app-timeline-group.{{ wrappercls }} cards-app-group-header .group-title strong, cards-app-timeline-sidebar-group.{{ wrappercls }} cards-app-group-header .group-title strong { background-color: {{ color }}; color: {{ textColor }}; } cards-app-timeline-group.{{ wrappercls }} cards-app-group-header .group-title.editable strong:hover, cards-app-timeline-sidebar-group.{{ wrappercls }} cards-app-group-header .group-title.editable strong:hover { background-color: {{ shade(color, 10) }}; } ");
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/base-timeline.html", '<div class=timeline-container-outer> <button class="btn btn-primary btn-timeline-back-to-today is-left" ng-show=$ctrl.currentScrolledToLeft ng-click=$ctrl.scrollToCurrent()><i class="fa fa-angle-double-left"></i> {{$ctrl.currentSpanLabel}}</button> <button class="btn btn-primary btn-timeline-back-to-today is-right" ng-show=$ctrl.currentScrolledToRight ng-click=$ctrl.scrollToCurrent()>{{$ctrl.currentSpanLabel}} <i class="fa fa-angle-double-right right"></i></button> <mouse-drag-scrollable-container drag-disabled=$ctrl.isObjectDragging class=timeline-container> <div class=timeline-viewport> <div class=timeline-background></div> <div class=timeline-content ng-transclude></div> <div class=timeline-dates></div> </div> </mouse-drag-scrollable-container> </div> ');
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/timeline-group.html", `<div class=cards-app-timeline-group-header ng-hide=$ctrl.hideHeader> <cards-app-group-header ng-if=$ctrl.timeline.compactMode group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options sort-by=$ctrl.sortBy sort-choices=$ctrl.sortChoices can-free-sort=$ctrl.canFreeSort total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix menu-custom-drop-config=$ctrl.settingsDropConfig editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) free-sort-disabled=true show-icon=true show-desc=true on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> </div> <div class=cards-app-timeline-group-content ng-if=!$ctrl.collapsed ng-style="{'height': $ctrl.contentHeight !== null ? $ctrl.contentHeight + 'px' : 'inherit'}"> <cards-app-timeline-card ng-repeat="obj in $ctrl.timelineObjects track by obj.id" object=obj vertical-position=$ctrl.getCardVerticalPosition(obj) ng-show=$ctrl.isCardFiltered(obj._card)></cards-app-timeline-card> </div> <div class=cards-app-timeline-group-card-creator ng-if=!$ctrl.collapsed ng-show=$ctrl.canCreateCard></div> `);
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/timeline-card.html", `<div class=timeline-object> <div class=timeline-object-container ng-style="{'left': $ctrl.position.left, 'width': $ctrl.position.width }" ng-show=$ctrl.object.dateRange ng-mouseenter=$ctrl.onMouseEnter($event) ng-mouseleave=$ctrl.onMouseLeave($event)> <button class="btn btn-timeline-object-expand-left js-expand-left" ng-show="$ctrl.timeline.editable && $ctrl.objectEditable"> <i class="fa fa-chevron-left"></i> </button> <div class="timeline-object-content cards-app-timeline-card-container" ng-class="{'archived': $ctrl.object._card.is_archived || $ctrl.object._card.is_parent_archived,
                'finished': $ctrl.object._card.finished,
                'struck-title': ($ctrl.cardsAppTimeline.options || {}).strikeDoneCards}" ng-mousedown=$ctrl.handleMouseDown($event) ng-click=$ctrl.handleClick($event)> <span class=cards-app-timeline-card-ref ng-show="$ctrl.object._card.ref > 0">#{{$ctrl.object._card.ref}}</span> <i ng-show=$ctrl.state.icon class=state-indicator ng-class=::$ctrl.state.icon|iconClass ng-attr-title={{$ctrl.state.label}}></i> <i ng-show="$ctrl.model && $ctrl.model.indicator" class="model-indicator {{$ctrl.model.indicator|iconClass}}"></i> <span class=cards-app-timeline-card-title>{{ $ctrl.object._card.title }}</span> <span ng-show=$ctrl.object._card.nb_children ng-click=$ctrl.toggleChildCards($event) class="attribute-repr attribute-repr-widget attribute-repr-widget-label card-tile-children" ng-class="$ctrl.canToggleChildren ? 'is-togglable js-toggle-children' : ''"> <span>{{ ($ctrl.object._card.nb_finished_children > 0 ? $ctrl.object._card.nb_finished_children + '/' : '') + $ctrl.object._card.nb_children }}</span> <span class=attr-widget-drop-icon ng-if=$ctrl.canToggleChildren> <i class=bi-caret-down-fill></i> <i class=bi-caret-up-fill></i> </span> </span> </div> <button class="btn btn-timeline-object-expand-right js-expand-right" ng-show="$ctrl.timeline.editable && $ctrl.objectEditable"> <i class="fa fa-chevron-right"></i> </button> </div> <div class=timeline-object-creation-tooltip ng-show="!$ctrl.object.dateRange && $ctrl.timeline.editable && $ctrl.objectEditable">{{::_('Create new date range')}}</div> </div> <div class=cards-app-timeline-card-children-list ng-style="{'height': $ctrl.contentHeight !== null ? $ctrl.contentHeight + 'px' : 'inherit'}"> <div class=cards-app-timeline-cards-background ng-show=$ctrl.canDisplayBackground> <div class=cards-app-timeline-card-fake-object ng-if=$ctrl.canDisplayFakeObject()> <span class=cards-app-timeline-card-ref>#{{$ctrl.object._card.ref}}</span> <span class=cards-app-timeline-card-title>{{ $ctrl.object._card.title }}</span> <span ng-show=$ctrl.object._card.nb_children ng-mousedown="$ctrl.toggleChildCards($event, true)" class="attribute-repr attribute-repr-widget attribute-repr-widget-label card-tile-children" ng-class="$ctrl.canToggleChildren ? 'is-togglable js-toggle-children' : ''"> <span>{{ ($ctrl.object._card.nb_finished_children > 0 ? $ctrl.object._card.nb_finished_children + '/' : '') + $ctrl.object._card.nb_children }}</span> <span class=attr-widget-drop-icon ng-if=$ctrl.canToggleChildren> <i class=bi-caret-down-fill></i> <i class=bi-caret-up-fill></i> </span> </span> </div> <div class=cards-app-timeline-card-global-date-range-object ng-show=$ctrl.canDisplayGlobalDateRangeObject ng-class="{'faded': !$ctrl.canDisplayBackgroundInner()}"></div> <div class=cards-app-timeline-cards-background-inner ng-show=$ctrl.canDisplayBackgroundInner()></div> </div> <div class=cards-app-timeline-card-children-list-container ng-if="$ctrl.timelineObjects.length && $ctrl.canToggleChildren" ng-show=$ctrl.showChildren> <cards-app-timeline-card ng-repeat="obj in $ctrl.timelineObjects track by obj.id" object=obj vertical-position=$ctrl.getCardVerticalPosition(obj)></cards-app-timeline-card> </div> </div> `);
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/nav.html", `<cards-app-nav-default mode=$ctrl.mode board=$ctrl.board store=$ctrl.store filter=$ctrl.filter filter-repr=$ctrl.filterRepr filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds group-by-groups=$ctrl.groupByGroups group-by-choices=$ctrl.groupByChoices readonly=$ctrl.readonly on-change="$ctrl.onChange({$changes: $changes})" shrinked=$ctrl.shrinked></cards-app-nav-default> <button class="btn btn-topbar" datepicker-dropdown=$ctrl.dateRange datepicker-options=$ctrl.pickerOptions datepicker-range=true on-date-change="$ctrl.updateDate($start, $end)"> <i class="fa fa-calendar-o"></i> {{::_('Go to period')}} <span class=bi-caret-down-fill></span> </button> `);
  $templateCache.put("/static/app/apps/cards/timeline/ng-components/templates/timeline.html", `<div class=cards-app-timeline-body ng-class="{'mod-sidebar':!$ctrl.timelineOptions.compactMode}" ng-if=$ctrl.activeDateAttribute.size> <div class=cards-app-timeline-sidebar ng-class="{'collapsed': !!$ctrl.timelineOptions.compactMode}" ng-if=!$ctrl.isScreensizeXS()> <div class=cards-app-timeline-sidebar-header ng-click=$ctrl.toggleCompactMode() ng-class="{'collapsed': !!$ctrl.timelineOptions.compactMode}"> <i class=fa ng-class="{'fa-toggle-left': !$ctrl.timelineOptions.compactMode, 'fa-toggle-down': $ctrl.timelineOptions.compactMode}"></i> <span>{{::_('All cards')}}</span> </div> <div class=cards-app-timeline-sidebar-container ng-show=!$ctrl.timelineOptions.compactMode> <div class=cards-app-timeline-sidebar-viewport> <cards-app-timeline-sidebar-group ng-if=$ctrl.ungroupedCardsVisible ng-show=!$ctrl.isFilteredOnFirstGroupBy custom-title={{$ctrl.ungroupedLabel}} store=$ctrl.ungroupedCardsStore board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices hide-header=$ctrl.groupBy[0].isNothing() on-change="$ctrl.onChange({$changes: $changes})"></cards-app-timeline-sidebar-group> <cards-app-timeline-sidebar-group ng-repeat="group in $ctrl.groups track by group.id" ng-class="{'is-archived': group.is_archived || false}" group=group store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices on-change="$ctrl.onChange({$changes: $changes})"></cards-app-timeline-sidebar-group> </div> </div> </div> <timeline date-range=$ctrl.timelineOptions.dateRange on-update-object=$ctrl.updateCard($data) on-update-date-range="$ctrl.updateDateRange($scrolledRange, true)" compact-mode=$ctrl.timelineOptions.compactMode editable=$ctrl.datesEditable> <cards-app-timeline-group ng-if=$ctrl.ungroupedCardsVisible ng-show=!$ctrl.isFilteredOnFirstGroupBy custom-title={{$ctrl.ungroupedLabel}} store=$ctrl.ungroupedCardsStore board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices hide-header=$ctrl.groupBy[0].isNothing() on-change="$ctrl.onChange({$changes: $changes})"></cards-app-timeline-group> <cards-app-timeline-group ng-repeat="group in $ctrl.groups track by group.id" ng-class="{'is-archived': group.is_archived || false}" group=group store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices on-change="$ctrl.onChange({$changes: $changes})"></cards-app-timeline-group> </timeline> </div> <div class=cards-app-empty-notice ng-if=!$ctrl.activeDateAttribute.size> <i class="fa fa-clock-o"></i> <p>{{::_("Timeline lets you plan and schedule anything visually and helps you track your progress. Create beautiful roadmaps and meet your deadlines.")}}</p> <p ng-show=!!$ctrl.project>{{::_("But first, you need to add a date field in your cards.")}}</p> <p ng-show=!$ctrl.project>{{::_("There isn't any date field in your cards")}}</p> </div> `);
  $templateCache.put("/static/app/apps/cards/checklist/ng-components/templates/card-creator.html", `<strong class=card-creator-alert ng-if=$ctrl.filtered> <i class=bi-exclamation-triangle-fill></i> {{::_('Your new card might not match the current active filter. It might be directly hidden after creation.')}} </strong> <div class="d-flex align-items-baseline"> <i class=bi-app></i> <div class=text-composer text-composer=$ctrl.creatorOptions custom-template=/static/app/apps/cards/common/ui/ng-components/templates/text-composer-tpl.html is-focused=$ctrl.creatorOptions.enabled></div> </div> <button type=button class=card-creator-btn ng-show=$ctrl.creatorOptions.enabled ng-mousedown=$ctrl.handleLinkCreateClick() hide-offline> {{::_('...or create a card link')}} </button> `);
  $templateCache.put("/static/app/apps/cards/checklist/ng-components/templates/checklist-group.html", `<sortable-cards-container cards=$ctrl.cards on-drop=$ctrl.handleCardDropped($onDropParams) before-drop=$ctrl.beforeCardDropped($onDropParams) after-drop=$ctrl.afterCardDropped($onDropParams) groups="$ctrl.group || null" board=$ctrl.board sort-by=$ctrl.sortBy editable=$ctrl.canSortCards options=$ctrl.sortableOptions collapsed=!$ctrl.expandedOnce is-filtered=$ctrl.filtered is-card-filtered=$ctrl.isCardFiltered($card)> <div class=header ng-hide=$ctrl.hideHeader> <cards-app-group-header group=$ctrl.group custom-title=$ctrl.customTitle board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options sort-by=$ctrl.sortBy sort-choices=$ctrl.sortChoices can-free-sort=$ctrl.canFreeSort total-count=$ctrl.totalCardsCount matching-count=$ctrl.matchingCardsCount mode-options-key-prefix=$ctrl.modeOptionsKeyPrefix menu-custom-drop-config=$ctrl.settingsDropConfig editing-title=$ctrl.editingTitle on-title-edit-start=$ctrl.onTitleEditStart() on-title-edit-end=$ctrl.onTitleEditEnd($event) on-counter-toggled=$ctrl.toggleStats() show-ungrouped-tooltip=$ctrl.showUngroupedTooltip show-icon=true show-desc=true on-change="$ctrl.onChange && $ctrl.onChange({$changes: $changes})"></cards-app-group-header> <cards-app-group-progress ng-if=$ctrl.showProgress cards=$ctrl.matchingCards></cards-app-group-progress> <cards-app-group-stats ng-if=$ctrl.showStats cards=$ctrl.matchingCards project=$ctrl.project></cards-app-group-stats> </div> <div class="body ui-sortable-cards-items-container" ng-if=!$ctrl.expandedOnce></div> <div class="body ui-sortable-cards-items-container card-tile-list" ng-if=::$ctrl.expandedOnce> <div ng-repeat="card in $ctrl.cards track by card.id" class=mod-task ng-show=$ctrl.isCardFiltered(card) card-tile=card show-project=$ctrl.showProjectOnCards show-archived="($ctrl.options || {}).include_archived" show-parents="($ctrl.options || {}).include_descendants" show-children-attributes="($ctrl.options || {}).children_visible_attributes" show-attributes=$ctrl.visibleAttrNames show-ref=::!$ctrl.project.is_portfolio strike-title-when-done="($ctrl.options || {}).strikeDoneCards" disable-children-toggle=::$ctrl.project.is_portfolio show-board-pattern=::!$ctrl.project.is_portfolio show-board-btn-label=::!$ctrl.project.is_portfolio selector=$ctrl.selector filter-active-board-group-by=::(true) template-type=task edit-on-click=true scroll-viewport=.ui-sortable-groups disable-default-model-theme=true></div> </div> <div class=footer ng-if=$ctrl.canCreateCard ng-hide=$ctrl.isCreatingCard> <button type=button class=btn ng-click=$ctrl.openCreator()> <i class=bi-plus-lg></i> <span>{{::_('Add card')}}</span> </button> </div> </sortable-cards-container> `);
  $templateCache.put("/static/app/apps/cards/checklist/ng-components/templates/checklist-group-color.css.html", "cards-app-checklist-group.{{ wrappercls }} cards-app-group-header .group-title strong { background: {{ color }}; color: {{ textColor }}; } cards-app-checklist-group.{{ wrappercls }} cards-app-group-header .group-title.editable strong:hover { background: {{ shade(color, 10) }}; } ");
  $templateCache.put("/static/app/apps/cards/checklist/ng-components/templates/checklist.html", `<sortable-groups-container groups=$ctrl.groups project=$ctrl.project> <cards-app-checklist-group ng-if=$ctrl.ungroupedCardsVisible ng-show=!$ctrl.isFilteredOnFirstGroupBy class=mod-ungrouped ng-class="{'is-archived': false}" custom-title={{$ctrl.ungroupedLabel}} store=$ctrl.ungroupedCardsStore board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices selector=$ctrl.selector visible-attr-names=$ctrl.visibleAttrNames on-change="$ctrl.onChange({$changes: $changes})" open-creator-on-init="!$ctrl.groups.length && !$ctrl.project.status" show-ungrouped-tooltip=true hide-header=$ctrl.groupBy[0].isNothing()></cards-app-checklist-group> <div class="cards-app-checklist-sortable-groups ui-sortable-groups-items-container"> <cards-app-checklist-group ng-repeat="group in $ctrl.groups track by group.id" ng-show=$ctrl.matchGroup(group) class=ui-sortable-groups-item ng-class="{'is-archived': group.is_archived || false}" group=group store=$ctrl.store board=$ctrl.board filter=$ctrl.filter filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds sort-choices=$ctrl.sortChoices selector=$ctrl.selector visible-attr-names=$ctrl.visibleAttrNames on-change="$ctrl.onChange({$changes: $changes})"></cards-app-checklist-group> </div> <add-card-group class=mod-column ng-if=$ctrl.canAddGroup ng-hide=$ctrl.isFilteredOnFirstGroupBy group-by=$ctrl.groupBy[0] board=$ctrl.board close-editor-on-enter="$ctrl.project && !$ctrl.project.is_template" open-editor-hotkey=$ctrl.addGroupHotkey enable-open-editor-hotkey=true on-group-added=$ctrl.scrollToBottom($event) on-editor-opened=$ctrl.scrollToBottom()></add-card-group> </sortable-groups-container> <cards-app-board-progress ng-if=!!$ctrl.options.showProgress store=$ctrl.store group-by=$ctrl.groupBy options=$ctrl.options></cards-app-board-progress> `);
  $templateCache.put("/static/app/apps/cards/quadrant/ng-components/templates/quadrant.html", '<solidjs-component ng-if="$ctrl.options.activeAxisSeries.length > 0" component=$ctrl.QuadrantView class=quadrant-view-wrapper></solidjs-component> <div class=cards-app-empty-notice ng-if="$ctrl.withEmptyNotice && (!$ctrl.options.activeAxisSeries || $ctrl.options.activeAxisSeries.length == 0)" style="max-width: 500px;"> <i class=bi-grid-3x3-gap-fill></i> <p>{{::_("Quadrant helps you visually organize your cards into priority zones, making it easy to focus on what truly matters.")}}</p> <div style="margin-top: 5vh; text-align: center;"> <p>{{::_("Configure your quadrant by selecting the axes you wish to work with")}} <img src=/static/assets/select-axis-quadrant.gif style="max-width: 100%; padding-top: 10px;"> </div> </div> ');
  $templateCache.put("/static/app/apps/cards/quadrant/ng-components/templates/nav.html", '<cards-app-nav-default mode=$ctrl.mode board=$ctrl.board store=$ctrl.store filter=$ctrl.filter filter-repr=$ctrl.filterRepr filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds group-by-groups=$ctrl.groupByGroups group-by-choices=$ctrl.groupByChoices readonly=$ctrl.readonly on-change="$ctrl.onChange({$changes: $changes})" shrinked=$ctrl.shrinked></cards-app-nav-default> ');
  $templateCache.put("/static/app/apps/cards/map/ng-components/templates/map.html", "<solidjs-component component=$ctrl.MapView></solidjs-component>");
  $templateCache.put("/static/app/apps/cards/gantt/ng-components/templates/gantt.html", "<solidjs-component component=$ctrl.GanttView class=timeline-view-wrapper></solidjs-component> ");
  $templateCache.put("/static/app/apps/cards/gantt/ng-components/templates/nav.html", '<cards-app-nav-default mode=$ctrl.mode board=$ctrl.board store=$ctrl.store filter=$ctrl.filter filter-repr=$ctrl.filterRepr filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds group-by-groups=$ctrl.groupByGroups group-by-choices=$ctrl.groupByChoices readonly=$ctrl.readonly on-change="$ctrl.onChange({$changes: $changes})" shrinked=$ctrl.shrinked></cards-app-nav-default> ');
  $templateCache.put("/static/app/apps/cards/planning/ng-components/templates/planning.html", "<solidjs-component component=$ctrl.PlanningView class=timeline-view-wrapper></solidjs-component> ");
  $templateCache.put("/static/app/apps/cards/planning/ng-components/templates/nav.html", '<cards-app-nav-default mode=$ctrl.mode board=$ctrl.board store=$ctrl.store filter=$ctrl.filter filter-repr=$ctrl.filterRepr filter-scopes=$ctrl.filterScopes group-by=$ctrl.groupBy options=$ctrl.options matching-card-ids=$ctrl.matchingCardIds group-by-groups=$ctrl.groupByGroups group-by-choices=$ctrl.groupByChoices readonly=$ctrl.readonly on-change="$ctrl.onChange({$changes: $changes})" shrinked=$ctrl.shrinked></cards-app-nav-default> ');
  $templateCache.put("/static/app/attributes/ng-components/templates/members.html", `<div class=attribute-type-members> <span ng-show="!editable && (!members || !members.length)" class=attribute-widget-badge>{{::_('No one')}}</span> <ul class="list-unstyled d-inline-block"> <li class="d-inline-block mb-1" ng-repeat="member in members"> <a href ng-click=openAttributeEditor()> <img ng-src={{::member|userAvatarUrl}} user-avatar-popover=member> </a> </li> <li class="d-inline-block mb-1 me-0" ng-show=editable> <a href class="attribute-widget-btn btn-icon rounded-circle" attribute-editor-opener obj=obj attribute=attribute attribute-group=attributeGroup value=members editable=editable is-template=isTemplate><i class=bi-plus-lg></i></a> </li> </ul> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/bool.html", "<div class=attribute-type-bool> <input type=checkbox data-toggle=toggle data-size=small> </div> ");
  $templateCache.put("/static/app/attributes/ng-components/templates/relationships.html", `<div class=attribute-type-relationships> <span ng-if="!loading && !editable && !cards.length" class=attribute-widget-badge>{{::_('Empty')}}</span> <div class=cards> <div class=card-tile-wrapper ng-repeat="card in cards track by card.id"> <div ng-if="::(card.ref !== null || !projectStore.tryGetForCard(card))" card-tile=card show-project=true template-type=task class="noactions mod-task" show-checkbox=false modal-load=true></div> <div ng-if="::(card.ref===null || !projectStore.tryGetForCard(card))" class=card-tile> <div class=card-tile-inner> <div class=card-tile-content> <div class=card-tile-title> <span class=title>{{::card.title}}</span> </div> </div> </div> </div> <button ng-if=editable ng-click=removeRelationship(card) class="btn btn-default btn-icon"><i class="fa fa-times"></i></button> </div> </div> <button ng-if=editable attribute-editor-opener attribute-group=attributeGroup attribute=attribute obj=card value=value editable=editable class="attribute-widget-btn btn-icon"><i class=bi-plus-lg></i></button> <button class="attribute-widget-btn btn-icon" ng-class="{'active': showReferencingCards}" uib-tooltip="{{::_('See cards referencing this one')}}" tooltip-placement=right ng-click=toggleShowReferencingCards() ng-show="isAuthenticated() && !!card.id"> <i ng-class="(referencingLoading ? 'fa-spinner fa-spin' : 'bi-arrow-left-right')|iconClass"></i> </button> <span ng-show="showReferencingCards && !referencingLoading && !referencingCards.length">{{::_('No other cards referencing this one')}}</span> <span ng-show="showReferencingCards && !referencingLoading && referencingCards.length">{{_('{count} card(s) referencing this one:', {count: referencingCards.length})}}</span> <div class="cards referencing-cards" ng-show="showReferencingCards && !referencingLoading && referencingCards.length"> <div class=card-tile-wrapper ng-repeat="card in referencingCards track by card.id"> <div card-tile=card show-project=true template-type=task class="noactions mod-task" show-checkbox=false modal-load=true></div></div> </div> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/relationships-editor.html", `<div class="dropdown-header pt-3"> <span class="dropdown-title menu-panel-title">{{::_('Add relationship with')}}</span> <button type=button class=btn-close ng-click=$ctrl.onDone()></button> </div> <div class="dropdown-body relationships-editor"> <card-tile-list card=$ctrl.card attribute=$ctrl.attribute project=$ctrl.project selected-cards=$ctrl.selectedCards filtered-cards-ids=$ctrl.filteredCards widget-options=$ctrl.options on-card-added=$ctrl.handleRelationship($selectedCard) on-card-removed=$ctrl.removeRelationship($selectedCard)> </card-tile-list> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/date-editor.html", `<div class=attribute-type-date-editor> <div id=air-datepicker></div> <div class=relative-interval ng-show=isTemplate> <label class=form-label>{{::_('Or interval relative to setting date:')}}</label> <div class=input-group> <input type=text ng-model=relativeAmount class=form-control placeholder="{{::_('Interval')}}"> <select ng-options="unit[0] as unit[1] for unit in relativeUnits track by unit[0]" ng-model=relativeUnit ng-show=showRelativeUnit class=form-select></select> <button class="btn btn-default" ng-click=setRelativeDate()>{{::_('Set')}}</button> </div> </div> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/encrypted-editor.html", '<div class=attribute-type-input-editor> <input type=text placeholder="Secret value" ng-model=inputValue class=form-control> </div> ');
  $templateCache.put("/static/app/attributes/ng-components/templates/files.html", `<div class=attribute-type-files ngf-drop=upload($files) ngf-allow-dir=false ngf-drag-over-class=dragover ngf-multiple=true ngf-hide-on-drop-not-available=false> <span ng-show="!editable && (!value || !value.length)" class=attribute-widget-badge>{{::_('Empty')}}</span> <file-gallery store=files show-delete="{{editable ? 'true': ''}}" show-cover="{{canShowCoverBtn ? 'true' : ''}}" deleted=removeFile(file) card=obj></file-gallery> <button ng-show=editable class="attribute-editor-opener attribute-widget-btn btn-icon"><i class=bi-plus-lg></i></button> <span class="dnd-label ms-3" ng-show=editable>{{_('or drop {file_type} here', {file_type: fileType}) + (maxFileSize ? _(" (max {file_size})", {file_size: maxFileSize}) : '')}}</span> <div ng-show=uploadInProgress class="uploading mt-3"> {{::_('Uploading:')}} <div class=progress> <div class=progress-bar role=progressbar ng-style="{'width': (progress || 0) + '%'}"> {{progress}}% </div> </div> </div> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/labels.html", `<div class=attribute-type-labels> <span class="badge mod-attr mod-clickable" ng-repeat="label in labels" ng-style="{'background-color': label[1], 'color': label[2]}" title={{::label[0]}}> <a href class=name color-picker=colorPickerOptions color=::label[1]>{{::label[0]}}</a> <a href ng-if=editable ng-click=removeLabel(label)> <i class="fa fa-times"></i></a> </span> <input class=form-control ng-if=editable type=text placeholder="{{::_('Add a label')}}" ng-model=search.input ng-keydown=handleKeys($event)> <script type=text/ng-template id=attribute-type-labels-drop.html>
    <ul resize-dropdown="halfWindow" class="suggestions-list list-unstyled" ng-show="filteredSuggestions.length">
      <li ng-repeat="suggestion in filteredSuggestions = (suggestions | filter: isRelevant)" class="blockSpan" ng-click="addLabel(suggestion[0], suggestion[1])" ng-class="{active : selectedIndex===$index}">
        <span ng-style="{'background-color': suggestion[1], 'color': suggestion[2]}">{{::suggestion[0]}}</span>
      </li>
    </ul>
  <\/script> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/content.html", `<div class=attribute-type-content> <attribute-type-content-editor ng-if=editorEnabled obj=obj attribute=attribute attribute-group=attributeGroup value=value on-done=onEditorDone() default-active-editor=false on-draft-change=refreshDraft(draftedText)></attribute-type-content-editor> <span ng-show="!editable && !value" class=attribute-widget-badge>{{::_('Empty')}}</span> <div class="markdown js-attribute-content" ng-if="!editorEnabled && value" ng-bind-html=value|markdown:true ng-dblclick=edit()></div> <button type=button class=attribute-type-content-add-btn ng-click=edit() ng-hide="editorEnabled || !editable || value || draft"> {{::_('Click to add a {name}', {name: attribute.name}) }} </button> <button type=button class="attribute-widget-btn btn-sm" ng-click=edit() ng-hide="editorEnabled || !editable || !value"> <i class="fa fa-pencil"></i> {{::_('Edit')}} </button> <span class=unsaved ng-hide="editorEnabled || !editable || !draft"> <span class=me-1>{{::_('You have unsaved changes.')}}</span> <button type=button class="attribute-widget-btn btn-sm me-1" ng-click=edit()>{{::_('View')}}</button> <button type=button class="attribute-widget-btn btn-sm" ng-click=edit(true)>{{::_('Discard')}}</button> </span> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/indicators.html", `<div class=attribute-type-indicators> <span class=card-indicator ng-repeat="spec in value"> <a class=name color-picker=colorPickerOptions color=::spec[1] ng-style="{'color': spec[1] ? spec[1] : '#000'}"> <i class=fa ng-class=spec[0]|iconClass></i> </a> </span> <button type=button class="attribute-widget-btn btn-icon" attribute-editor-opener obj=obj attribute=attribute attribute-group=attributeGroup value=value editable=editable attribute-editable=attributeEditable ng-disabled=!editable> <i class=bi-caret-down-fill></i> </button> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/indicators-editor.html", `<div class="dropdown-menu attribute-type-indicators-editor"> <a href ng-click=toggle(indicator) ng-repeat="indicator in choices" ng-class="{'active': isActive(indicator)}"> <i class=fa ng-class=indicator|iconClass></i> </a> </div>`);
  $templateCache.put("/static/app/attributes/ng-components/templates/encrypted.html", `<div class=attribute-type-input> <span class="attribute-widget-badge value" ng-if="value && !edit" ng-click=toggleEdit(true) ng-class="{'has-clear': editable}"> <span class=label><i class="fa fa-lock"></i> ***********</span> <a class=attribute-widget-badge-btn href ng-show=editable ng-click=clearValue()> <i class="fa fa-times"></i> </a> </span> <attribute-type-encrypted-editor obj=obj attribute=attribute attribute-group=attributeGroup value=value ng-if="editable && (edit || !value)" on-done=toggleEdit(false) no-auto-focus="{{!value ? 'true' : ''}}"> </attribute-type-encrypted-editor> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/automation-trigger-btn.html", '<div class=attribute-type-automation-trigger-btn> <button type=button class="btn btn-primary text-wrap" ng-click=call() ng-disabled="disabled || !canRun || calling" uib-tooltip=$scope.disabledTooltip tooltip-enable=!!$scope.disabledTooltip> <i class="fa fa-spin fa-spinner" ng-show=calling></i> <i class=bi-exclamation-triangle-fill ng-show=!canRun></i> {{label}} </button> </div> ');
  $templateCache.put("/static/app/attributes/ng-components/templates/iframe.html", `<div class="attribute-type-input attribute-type-iframe"> <span class="attribute-widget-badge value mb-3" ng-if="!editable || (!isEmpty(value) && !edit)" ng-click=toggleEdit(true) ng-class="{'has-action': editable && isCard, 'has-clear': editable}"> <span class=label ng-if=!isEmpty(value)>{{value}}</span> <span class=label ng-if=isEmpty(value)>{{::_('No URL provided')}}</span> <a class=attribute-widget-badge-btn href ng-show=editable ng-click="$event.stopPropagation(); clearValue()"> <i class="fa fa-times"></i> </a> </span> <attribute-type-input-editor class=mb-3 obj=obj attribute=attribute attribute-group=attributeGroup value=value ng-if="editable && (edit || isEmpty(value))" on-done=toggleEdit(false) no-auto-focus=true> </attribute-type-input-editor> <iframe ng-if=!isEmpty(value) width=100% height="{{ attribute.options.height }}" src="{{ getIframeUrl() }}" sandbox="allow-same-origin allow-scripts allow-modals allow-forms allow-popups allow-downloads"></iframe> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/date.html", `<div class=attribute-type-date> <span ng-show="!editable && !date.value" class=attribute-widget-badge>{{::_('Empty')}}</span> <span class="attribute-widget-badge badge-due-date" ng-class="[!date.value ? '' : 'dd', date.diffLabel[0], editable ? 'clickable' : null]" ng-if="editable || date.value" attribute-editor-opener obj=obj attribute=attribute attribute-group=attributeGroup editable=editable value=value is-template=isTemplate> <span class=label>{{(date.value || _('not set'))}} <span class="fs-small opacity-75" ng-show=date.diffLabel[1]>({{_(date.diffLabel[1])}})</span> </span> <a class=attribute-widget-badge-btn href ng-if="editable && date.value" ng-click=$event.stopPropagation();unsetDate()><i class="fa fa-times"></i></a> </span> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/remote-action-btn.html", `<div class=attribute-type-remote-action-btn> <button type=button class="btn btn-primary" ng-disabled="!editable || !options.url || (value && value.status === 'loading')" ng-click=call()> <i class="fa fa-spin fa-spinner" ng-show="value && value.status === 'loading'"></i> <span ng-hide="value && value.status === 'loading'">{{options.label}}</span> </button> <remote-call-result response=value ng-if="value && value.status !== 'loading'"></remote-call-result> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/group-type.html", `<div class=attribute-type-group-type ng-class="{'one-group-per-card': groupType.one_group_per_card}"> <span ng-show="!_editable() && !groups.length" class=attribute-widget-badge>{{::_('Empty')}}</span> <div class="d-inline-block me-1 mb-1" ng-repeat="group in groups track by group.id"> <span class=attribute-widget-badge ng-class="{'clickable': _editable() && groupType.one_group_per_card,
      'colored': group.color || null, 'archived': group.is_archived}" groups-menu-toggle="_editable() && groupType.one_group_per_card ? groupsMenuFactoryParams : null" ng-style="{'background-color': group.color || null, 'color': textColor(group.color, null, null, null)}"> <i class="me-2 opacity-75" ng-class="(group.icon || groupType.icon)|iconClass" ng-show="group.icon || groupType.icon"></i> <span class=label> {{group.title|ellipsis:80}} <span class="fs-small opacity-50" ng-style="{'color': textColor(group.color, null, null, null)}" ng-if=group.end_date><i class=bi-clock-fill></i> {{group.end_date|date}}</span> </span> <span class="caret bi-caret-down-fill ms-1" ng-style="{'color': textColor(group.color, null, null, null)}" ng-if="groupType.one_group_per_card && _editable()"></span> <a href class=attribute-widget-badge-btn ng-if="_editable() && !groupType.one_group_per_card" ng-click="removeGroup(group); $event.stopPropagation()"><i class="fa fa-times"></i></a> </span> </div> <button class="attribute-widget-btn btn-icon" groups-menu-toggle=groupsMenuFactoryParams ng-disabled=!_editable() ng-if="(!groupType.one_group_per_card || !groups.length) && _editable()"> <i ng-class="{'bi-plus-lg': !groupType.one_group_per_card, 'bi-caret-down-fill': groupType.one_group_per_card}"></i> </button> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/header.html", '<div class=attribute-type-header> <h1 ng-dblclick=edit()> <span ng-hide=editing>{{attribute.name}}</span> <i class="fa fa-question-circle" uib-tooltip={{attribute.description}} tooltip-popup-delay=0 ng-if=attribute.description ng-hide=editing></i> <input type=text class=form-control ng-model=title ng-show=editing ng-blur=save()> </h1> </div> ');
  $templateCache.put("/static/app/attributes/ng-components/templates/likes.html", `<div class=attribute-type-likes> <button type=button class="attribute-widget-btn me-2" ng-click=like() ng-disabled=!editable ng-class="{'focus': liked === true, 'btn-success': value.likes.length > value.dislikes.length}"> <i class="fa fa-thumbs-up"></i> {{value.likes.length}} </button> <button type=button class=attribute-widget-btn ng-click=dislike() ng-disabled=!editable ng-class="{'focus': liked === false, 'btn-danger': value.likes.length < value.dislikes.length}"> <i class="fa fa-thumbs-down"></i> {{value.dislikes.length}} </button> <span>{{_n('{total} voter', '{total} voters', value.total, {total: value.total || 0})}}</span> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/location.html", `<div class="attribute-type-input attribute-type-location"> <span class="attribute-widget-badge value mb-3" ng-if="!editable || (!isValueEmpty() && !edit)" ng-click=toggleEdit(true) ng-class="{'has-action': editable && isCard, 'has-clear': editable}"> <span class=label>{{getAddress()}}</span> <span class="badge bg-light text-muted ms-1" ng-if=hasCoordinates() title="{{_('Coordinates available')}}"> <i class=bi-geo-alt-fill></i> </span> <a class=attribute-widget-badge-btn href ng-show=editable ng-click="$event.stopPropagation(); clearValue()"> <i class="fa fa-times"></i> </a> </span> <attribute-type-input-editor class=mb-3 obj=obj attribute=attribute attribute-group=attributeGroup value=getAddress() ng-if="editable && (edit || isValueEmpty())" on-done=toggleEdit(false) no-auto-focus=true></attribute-type-input-editor> <iframe class="header mb-3" ng-show="!isValueEmpty() && !hideMap" width="{{attribute.position === '' ? '200px' : '700px'}}" height="{{attribute.position === '' ? '100px' : '300px'}}" loading=lazy ng-src={{getUrl()}}></iframe> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/remote-call-result.html", `<i class="fa fa-spin fa-spinner" ng-show="$ctrl.response.status === 'loading'"></i> <div ng-if="$ctrl.response.status === 'success'"> <table ng-if="$ctrl.isDict || $ctrl.isList" class="table table-bordered table-striped"> <tr ng-repeat="item in $ctrl.response.data" ng-if=$ctrl.isList> <td>{{item|jsonToText}}</td> </tr> <tr ng-repeat="(key, value) in $ctrl.response.data" ng-if=$ctrl.isDict> <th>{{key}}</th> <td>{{value|jsonToText}}</td> </tr> </table> <div ng-if="!$ctrl.isDict && !$ctrl.isList">{{$ctrl.response.data}}</div> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/files-editor.html", `<div class="attribute-type-files-editor dropdown-content"> <div class=dropdown-header>{{::_('Attach from:')}}</div> <ul> <li> <input type=file name=file ngf-select=upload($files) ngf-multiple=true> <label class="form-label dropdown-item" for=file>{{::_('Upload from your computer')}}</label> </li> <li ng-if=camera.isAvailable()> <a class=dropdown-item href ng-click=captureWithCamera()>{{::_('Take a picture')}}</a> </li> <li ng-repeat="provider in fileProviders"> <a class=dropdown-item href ng-click=execProvider(provider)>{{provider.label}}</a> </li> <li class=dropdown-divider></li> <li> <form name=attachLinkForm ng-submit=attachLink(attachLinkUrl)> <label class="form-label d-block" for=attachLink>{{::_('Attach a link:')}}</label> <input class="form-control form-control-sm d-inline-block" type=url ng-model=attachLinkUrl placeholder="{{::_('Paste link here')}}" required id=attachLink> <div class=btn-group ng-disabled=attachLinkForm.$invalid> <button type=submit class="btn btn-sm btn-default">{{::_('Add')}}</button> <button type=button class="btn btn-sm btn-default dropdown-toggle" data-toggle=dropdown aria-haspopup=true aria-expanded=false> <span class=bi-caret-down-fill></span> </button> <ul class=dropdown-menu> <li><a href ng-click=attachLinkWithName(attachLinkUrl)>{{::_('Add with name')}}</a></li> </ul> </div> </form> </li> </ul> <div ng-show=uploadInProgress class=uploading> <h3 class=dropdown-header>{{::_('Uploading:')}}</h3> <div class=progress> <div class=progress-bar role=progressbar ng-style="{width: (progress || 0) + '%'}"> {{progress}}% </div> </div> </div> </div> `);
  $templateCache.put("/static/app/attributes/ng-components/templates/state.html", '<div class=attribute-type-state> <div class="btn-group dropdown"> <button class=btn ng-disabled=!editable states-menu-toggle=statesMenuFactoryParams> <i ng-class=state.icon|iconClass ng-if=state.icon></i> {{state.label}} <span class=bi-caret-down-fill></span> </button> <div attribute-editor-opener obj=card attribute=attribute attribute-group=attributeGroup editable=editable ng-if="editable && load"></div> </div> </div> ');
}]);

// public/app/index.js
function bootstrap() {
  render(App, document.getElementById("app-root"));
}
window.kantree = { bootstrap, ngApp, toggleDebugMode };
export {
  bootstrap
};
/*! Bundled license information:

dompurify/dist/purify.js:
  (*! @license DOMPurify 2.4.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.4.3/LICENSE *)

html2canvas/dist/html2canvas.js:
  (*!
   * html2canvas 1.4.1 <https://html2canvas.hertzen.com>
   * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
   * Released under MIT License
   *)
  (*! *****************************************************************************
      Copyright (c) Microsoft Corporation.
  
      Permission to use, copy, modify, and/or distribute this software for any
      purpose with or without fee is hereby granted.
  
      THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
      AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
      LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
      OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
      PERFORMANCE OF THIS SOFTWARE.
      ***************************************************************************** *)

leaflet/dist/leaflet-src.js:
  (* @preserve
   * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com
   * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade
   *)
*/
